content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python code that doesn't work from the command line A module that I have written (test.py) in Python 2.6 can be imported and run perfectly well from with the Python IDLE with the commands: import test test.run_test_suite() However if I use the command "python test.py" at the command line, it crashes apparently (a...
Python code that doesn't work from the command line
A module that I have written (test.py) in Python 2.6 can be imported and run perfectly well from with the Python IDLE with the commands: import test test.run_test_suite() However if I use the command "python test.py" at the command line, it crashes apparently (according to traceback) on the command "import os". As you...
[ "Are you using the same python version in both cases? When starting from the commandline, you get the first Python in your path, while IDLE is most probably executed directly from a shortcut.\nIf you have more than one version of python installed on your machine, this could translate in two complete different envir...
[ 0, 0 ]
[]
[]
[ "command_line", "debugging", "python", "python_idle" ]
stackoverflow_0003790268_command_line_debugging_python_python_idle.txt
Q: Would it be a good idea to make python store compile code in file stream instead of pyc files? I'm wondering if it wouldn't be a better if Python would store the compiled code in a file stream of the original source file. This would work on file systems supporting forks/data-streams, and fall-back if this is not p...
Would it be a good idea to make python store compile code in file stream instead of pyc files?
I'm wondering if it wouldn't be a better if Python would store the compiled code in a file stream of the original source file. This would work on file systems supporting forks/data-streams, and fall-back if this is not possible. On Windows using ADS (Alternative Data Streams) On OS X using resource forks On Linux usin...
[ "One problem I forsee is that it then means that each platform has different behaviour.\nThe next is that not every filesystem OS X supports also supports resource forks (and the way it stores them in non-hfs filesystems is universally hated by everyone else: ._ )\nHaving said that, I have often been bitten by a .p...
[ 1, 1 ]
[]
[]
[ "ads", "fork", "python" ]
stackoverflow_0003793745_ads_fork_python.txt
Q: Django get_object_or_create() not working on deployment server I'm having major trouble with a get_or_create call. I have it working locally absolutely fine, and the same script is working online on another site. Has anyone got an idea what's going on? I get "IntegrityError: (1062, "Duplicate entry '2147483647' f...
Django get_object_or_create() not working on deployment server
I'm having major trouble with a get_or_create call. I have it working locally absolutely fine, and the same script is working online on another site. Has anyone got an idea what's going on? I get "IntegrityError: (1062, "Duplicate entry '2147483647' for key 'PRIMARY'")" whenever I run the script... for tweet in Twitte...
[ "My guess is that you suffer from this: How do I deal with this race condition in django?\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003794428_django_python.txt
Q: does python 2.5 have an equivalent to Tcl's uplevel command? Does python have an equivalent to Tcl's uplevel command? For those who don't know, the "uplevel" command lets you run code in the context of the caller. Here's how it might look in python: def foo(): answer = 0 print "answer is", answer # should ...
does python 2.5 have an equivalent to Tcl's uplevel command?
Does python have an equivalent to Tcl's uplevel command? For those who don't know, the "uplevel" command lets you run code in the context of the caller. Here's how it might look in python: def foo(): answer = 0 print "answer is", answer # should print 0 bar() print "answer is", answer # should print 42 ...
[ "In general, what you ask is not possible (with the results you no doubt expect). E.g., imagine the \"any code\" is x = 23. Will this add a new variable x to your caller's set of local variables, assuming you do find a black-magical way to execute this code \"in the caller\"? No it won't -- the crucial optimizat...
[ 3, 1 ]
[]
[]
[ "python", "tcl", "uplevel" ]
stackoverflow_0003794461_python_tcl_uplevel.txt
Q: why i can't reverse a list of list in python i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): map(lambda row: row.reverse(), figure) i tried this one, but the reversed return an iterator : map(reversed, figure) finally i d...
why i can't reverse a list of list in python
i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): map(lambda row: row.reverse(), figure) i tried this one, but the reversed return an iterator : map(reversed, figure) finally i did something like this , which work for me , but i...
[ "The mutator methods of Python's mutable containers (such as the .reverse method of lists) almost invariably return None -- a few return one useful value, e.g. the .pop method returns the popped element, but the key concept to retain is that none of those mutators returns the mutated container: rather, the containe...
[ 27, 8, 3, 1, 0 ]
[]
[]
[ "list", "map_function", "python", "reverse" ]
stackoverflow_0003794486_list_map_function_python_reverse.txt
Q: Does thread-local mean thread safe? Specifically I'm talking about Python. I'm trying to hack something (just a little) by seeing an object's value without ever passing it in, and I'm wondering if it is thread safe to use thread local to do that. Also, how do you even go about doing such a thing? A: No -- thread...
Does thread-local mean thread safe?
Specifically I'm talking about Python. I'm trying to hack something (just a little) by seeing an object's value without ever passing it in, and I'm wondering if it is thread safe to use thread local to do that. Also, how do you even go about doing such a thing?
[ "No -- thread local means that each thread gets its own copy of that variable. Using it is (at least normally) thread-safe, simply because each thread uses its own variable, separate from variables by the same name that's accessible to other threads. OTOH, they're not (normally) useful for communication between th...
[ 8 ]
[]
[]
[ "multithreading", "python", "thread_local", "thread_safety" ]
stackoverflow_0003794868_multithreading_python_thread_local_thread_safety.txt
Q: Python - how can I override the functionality of a class before it's imported by a different module? I have a class that's being imported in module_x for instantiation, but first I want to override one of the class's methods to include a specific feature dynamically (inside some middleware that runs before module_...
Python - how can I override the functionality of a class before it's imported by a different module?
I have a class that's being imported in module_x for instantiation, but first I want to override one of the class's methods to include a specific feature dynamically (inside some middleware that runs before module_x is loaded.
[ "You should know that each class type (like C in class C: ...) is an object, so you can simply overwrite the class methods. As long as instances don't overwrite their own methods (won't happen too often because that's not really useful for single inntances), each instance uses the methods as inherited from its clas...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003794905_python.txt
Q: Transform game pseudo code into python Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete pr...
Transform game pseudo code into python
Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn i...
[ "Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem. \nI would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like high and low. The way to understand vari...
[ 14, 11, 4, 2, 1, 1, 0 ]
[]
[]
[ "pseudocode", "python" ]
stackoverflow_0000992076_pseudocode_python.txt
Q: Display dynamically added methods and attributes in python help I have a class where I add new methods and properties dynamically. The new properties are handled by overriding __getattr__ and __setattr__ while the new methods are added directly (obj.mymethod = foo). Is there a way to make these show up if I do "he...
Display dynamically added methods and attributes in python help
I have a class where I add new methods and properties dynamically. The new properties are handled by overriding __getattr__ and __setattr__ while the new methods are added directly (obj.mymethod = foo). Is there a way to make these show up if I do "help(inst)" where inst is an instance of my class? Right now I only see...
[ "The issue is that help(inst) provides the information about class from which that instance \"inst\" is derived from.\nsay obj is derived from class A, then instead of doing obj.mymethod = foo, if you did A.mymethod = foo, then this will show up in help(obj)\nLook at the example below and it's output.\nclass A(obje...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003795139_python.txt
Q: how to manage lock-write mechanism in django i've been searching for a while for a way to handle the lock-write mechanism in( whenever user is updating , the record should be locked for the others ) . and i've been told that the web-frame work is responsible for this. check this out : https://serverfault.com/ques...
how to manage lock-write mechanism in django
i've been searching for a while for a way to handle the lock-write mechanism in( whenever user is updating , the record should be locked for the others ) . and i've been told that the web-frame work is responsible for this. check this out : https://serverfault.com/questions/184666/how-to-configure-apache-server my que...
[ "Locks on the Database are provided by your DBMS like MySql or MSSQL Server. Not your framework or webserver.\nhttp://en.wikipedia.org/wiki/Lock_(database)\n" ]
[ 1 ]
[]
[]
[ "django", "locking", "python" ]
stackoverflow_0003795348_django_locking_python.txt
Q: stomp.py based durable client fills up subscribers list in ActiveMQ I have a problem with a durable client on ActiveMQ. I am using stomp.py in Python. conn.start() conn.connect(wait=True, header = {'client-id': 'myhostname' }) conn.subscribe( '/topic/testTopic', ack='auto', headers = { ...
stomp.py based durable client fills up subscribers list in ActiveMQ
I have a problem with a durable client on ActiveMQ. I am using stomp.py in Python. conn.start() conn.connect(wait=True, header = {'client-id': 'myhostname' }) conn.subscribe( '/topic/testTopic', ack='auto', headers = { 'activemq.subscriptionName': 'myhostname', ...
[ "I solved it, the whole thing was due to a simple spelling mistake. The line:\nconn.connect(wait=True, header = {'client-id': 'myhostname' })\n\nShould contain 'headers' in plural form.\n" ]
[ 3 ]
[]
[]
[ "activemq", "python", "stomp" ]
stackoverflow_0003774152_activemq_python_stomp.txt
Q: Finding a Value within a Range in a List of Tuple Values in Python I'm trying to get the Body Mass Index (BMI) classification for a BMI value that falls within a standard BMI range - for instance, if someone's BMI were 26.2, they'd be in the "Overweight" range. I made a list of tuples of the values (see below), al...
Finding a Value within a Range in a List of Tuple Values in Python
I'm trying to get the Body Mass Index (BMI) classification for a BMI value that falls within a standard BMI range - for instance, if someone's BMI were 26.2, they'd be in the "Overweight" range. I made a list of tuples of the values (see below), although of course I'm open to any other data structure. This would be eas...
[ "# bmi = <whatever>\nfound_bmi_range = [bmi_range for bmi_range\n in bmi_ranges\n if bmi_ranges[2] <= bmi <= bmi_ranges[3]\n ][0]\n\nYou can add if clauses to list comprehensions that filter what items are included in the result.\nNote: you may want to adjust you...
[ 2, 0, 0, 0, 0 ]
[ "If you like a lighter original data structure and one import from standard library:\nimport bisect\n\nbmi_ranges = []\nbmi_ranges.append((u'Underweight', u'Severe Thinness', 0, 15.99))\nbmi_ranges.append((u'Underweight', u'Moderate Thinness', 16.00, 16.99))\nbmi_ranges.append((u'Underweight', u'Mild Thinness', 17....
[ -1, -1 ]
[ "python", "search", "sequence", "tuples" ]
stackoverflow_0003795032_python_search_sequence_tuples.txt
Q: How to force execution of a different thread I have one main thread that does some rather CPU intensive operation. The thread has to hold a lock for all its calculations. Then there are some other threads which occasionally require the same lock for brief amounts of time. How can I force the main the main thread t...
How to force execution of a different thread
I have one main thread that does some rather CPU intensive operation. The thread has to hold a lock for all its calculations. Then there are some other threads which occasionally require the same lock for brief amounts of time. How can I force the main the main thread to occasionally allow the other threads to execute ...
[ "Merely releasing the GIL doesn't guarantee that other threads will have a chance to run.\nIn Unix, the call you really want is sched_yield(). There's no interface to that function in the Python standard library; it would be straightforward to add one with a native module.\nusleep(0) and select() are sometimes use...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003795119_python.txt
Q: What are python generators? Possible Duplicate: What can you use Python generator functions for? I tried to read about python generators but did not understand much about the concept as to what we can do with generators, I am new to python please let me know Thank you A: Simply put, a generator in Python is a ...
What are python generators?
Possible Duplicate: What can you use Python generator functions for? I tried to read about python generators but did not understand much about the concept as to what we can do with generators, I am new to python please let me know Thank you
[ "Simply put, a generator in Python is a function that can maintain state between values produced. Read this.\n", "The presentation here explains generators very well:\nhttp://www.dabeaz.com/generators/index.html\nI have yet to find a use for the more advanced pipelining stuff, but I use the general technique all ...
[ 1, 1, 1, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0003795656_generator_python.txt
Q: Python tool for incorporating imported items Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything? Take a library that draws a box called box.py def box(text='Hello, World!') draw the box magic return Now in another program (we'll call it warnin...
Python tool for incorporating imported items
Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything? Take a library that draws a box called box.py def box(text='Hello, World!') draw the box magic return Now in another program (we'll call it warning.py) it says: from box import box box('Warning, ...
[ "It sounds like you're wanting to effectively copy-paste everything into one file to be able to distribute a single file instead of several? \nIn that case, look into using a zipped module instead of copy-pasting everything into one file... This is far more maintainable in the long run.\nPython will execute a zip ...
[ 7, 0 ]
[]
[]
[ "import", "parsing", "python" ]
stackoverflow_0003795629_import_parsing_python.txt
Q: Does Python use a compiler or interpreter or a combination? Possible Duplicate: CPython is bytecode interpreter? My question is: Does Python use a compiler, an interpreter or a combination of them? A: Python uses a virtual machine aproach (as PHP, Ruby, .NET languages etc), python implementation uses a compile...
Does Python use a compiler or interpreter or a combination?
Possible Duplicate: CPython is bytecode interpreter? My question is: Does Python use a compiler, an interpreter or a combination of them?
[ "Python uses a virtual machine aproach (as PHP, Ruby, .NET languages etc), python implementation uses a compiler to create intermediate language that is executed on a virtual machine.\n" ]
[ 2 ]
[ "yes it use an interpreter, just run the .py and then it will be ecxecuted! if you want to compile your script to run on another machine as a .exe program you can compile it with th py2exe library\n" ]
[ -1 ]
[ "compiler_construction", "interpreter", "python" ]
stackoverflow_0003795893_compiler_construction_interpreter_python.txt
Q: Given a Python list, how to write a function that returns a given range of elements? I have def findfreq(nltktext, atitem) fdistscan = FreqDist(nltktext) distlist = fdistscan.keys() return distlist[:atitem] which relies on FreqDist from the NLTK package, and does not work. The problem seems to be the ...
Given a Python list, how to write a function that returns a given range of elements?
I have def findfreq(nltktext, atitem) fdistscan = FreqDist(nltktext) distlist = fdistscan.keys() return distlist[:atitem] which relies on FreqDist from the NLTK package, and does not work. The problem seems to be the part of the function where I try to return only the first n items of the list, using the v...
[ "You need a colon (:) at the end of the def line.\ndef findfreq(nltktext, atitem):\n fdistscan = FreqDist(nltktext)\n distlist = fdistscan.keys()\n return distlist[:atitem]\n\nPython's function declaration syntax is:\ndef FuncName(Args):\n # code\n\n", "operator.itemgetter() will return a function tha...
[ 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003795928_list_python.txt
Q: when we need use sudo python xxx.py or just python xxx.py or xxx.py I have write a website,what confused me is when i run the website,first i need start the the app, so there are 3 ways: sudo python xxx.py python xxx.py xxx.py I didn't clear with how to use each of them,the NO.3 method currently in my computer ...
when we need use sudo python xxx.py or just python xxx.py or xxx.py
I have write a website,what confused me is when i run the website,first i need start the the app, so there are 3 ways: sudo python xxx.py python xxx.py xxx.py I didn't clear with how to use each of them,the NO.3 method currently in my computer dosen't work well
[ "sudo will run the application with superuser permissions. Considering that you're referring to a website, this is certainly not what you want to do. (For a webapp, if it requires superuser permissions, it's broken. That's far, far too big of a security risk to consider actually using.) \nUnder other circumstan...
[ 4 ]
[]
[]
[ "env", "python", "sudo" ]
stackoverflow_0003795942_env_python_sudo.txt
Q: 404 Response in Google Buzz API I'm playing around with Google Buzz API from Python, During the OAuth process when I reach the part of authorizing the token from browser, I go to this URL https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?oauth_token=..., and when I press OK, continue I expect to be directed...
404 Response in Google Buzz API
I'm playing around with Google Buzz API from Python, During the OAuth process when I reach the part of authorizing the token from browser, I go to this URL https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?oauth_token=..., and when I press OK, continue I expect to be directed to a page like this one http://code....
[ "It seems that providing the domain parameter is essential even in Installed Applications, I set it to anonymous since I'm testing and the problem was solved :)\nSorry to bother you but I'm sure this will help others in the future ;)\n" ]
[ 1 ]
[]
[]
[ "google_api", "google_buzz", "http_status_code_404", "python" ]
stackoverflow_0003795941_google_api_google_buzz_http_status_code_404_python.txt
Q: AttributeError: 'NoneType' object has no attribute 'findSongBySize' I'm new to Ubuntu (and the Python scripts that go with it) and I've been hitting this error with the iTunesToRhythm script. **Traceback (most recent call last): File "/home/amylee/iTunesToRhythm.py", line 220, in <module> main(sys.argv) Fi...
AttributeError: 'NoneType' object has no attribute 'findSongBySize'
I'm new to Ubuntu (and the Python scripts that go with it) and I've been hitting this error with the iTunesToRhythm script. **Traceback (most recent call last): File "/home/amylee/iTunesToRhythm.py", line 220, in <module> main(sys.argv) File "/home/amylee/iTunesToRhythm.py", line 48, in main match = correla...
[ "I'm the original developer. I updated the script to throw an exception if the file format is not recognized (I think this is what you are running into). I also incorporated some useful patches from another user.\nPlease download the files again and e-mail me if you still have trouble.\n", "Your problem appears...
[ 7, 1 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0003795143_attributes_python.txt
Q: retrieve application/json document with twill/mechanize in authenticated session I need to retrieve a document with MIME type "application/json". I'm using twill to log in to a site and when I attempt to go to the URL pointing to the JSON document and show it, I get this message: 'The HTTP header field "Accept" wi...
retrieve application/json document with twill/mechanize in authenticated session
I need to retrieve a document with MIME type "application/json". I'm using twill to log in to a site and when I attempt to go to the URL pointing to the JSON document and show it, I get this message: 'The HTTP header field "Accept" with value "text/html; */*" could not be parsed.' I have tried changing the "Accept" fi...
[ "This is by no means the answer I'm looking for, but zope.testbrowser will do what I want.\nThe interface is slightly more complicated than twill, but not by much.\nStill looking for a twill solution!\n", "Looks like you have Accept: text/html; */* which seems syntactically wrong to me: per w3.org, the syntax is\...
[ 0, 0 ]
[]
[]
[ "json", "mechanize", "python", "twill" ]
stackoverflow_0003796009_json_mechanize_python_twill.txt
Q: Can I override Python list displays? I'd like to change the behavior of Python's list displays so that instead of producing a list, they produce a subclass of list that I've written. (Note: I don't think this is a good idea; I'm doing it for fun, not actual use.) Here's what I've done: old_list = list class Call...
Can I override Python list displays?
I'd like to change the behavior of Python's list displays so that instead of producing a list, they produce a subclass of list that I've written. (Note: I don't think this is a good idea; I'm doing it for fun, not actual use.) Here's what I've done: old_list = list class CallableList(old_list): def __init__(self,...
[ "You cannot trivially override the syntactic sugar used for built-in types, since this happens at the compiler level. Always call the constructor explicitly.\n", "You can't change it from within Python. Constructs such as list-comprehensions always use the built-in list type, not whatever you've defined the word...
[ 3, 1 ]
[ " >>> print(x(2)) # works in 2.7\n 3\n >>> type(x)\n <class '__main__.CallableList'>\n >>> y = [1,2,3]\n >>> type(y)\n <type 'list'>\n\nso you haven't really redefined type 'list,' you've only changed your namespace so that the type list's list() method now clashes with your type CallableList type. To...
[ -1 ]
[ "list", "overriding", "python" ]
stackoverflow_0003795591_list_overriding_python.txt
Q: Combine picture and plot with Python Matplotlib I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below...
Combine picture and plot with Python Matplotlib
I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below the plot?
[ "This demo from the matplotlib gallery shows how to insert pictures, draw lines to them, etc. I'll post the image from the gallery, and you can follow the link to see the code.\n\nAnd here's the code (from version 2.1.2):\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.patches import Circle...
[ 26, 19 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003765056_matplotlib_python.txt
Q: Python to check if file status is being uploading Python 2.6 My script needs to monitor some 1G files on the ftp, when ever it's changed/modified, the script will download it to another place. Those file name will remain unchanged, people will delete the original file on ftp first, then upload a newer version. My ...
Python to check if file status is being uploading
Python 2.6 My script needs to monitor some 1G files on the ftp, when ever it's changed/modified, the script will download it to another place. Those file name will remain unchanged, people will delete the original file on ftp first, then upload a newer version. My script will checking the file metadata like file size a...
[ "There is no such attribute. You may be unable to GET such file, but it depends on the server software. Also, file access flags may be set one way while the file is being uploaded and then changed when upload is complete; or incomplete file may have modified name (e.g. original_filename.ext.part) -- it all depends ...
[ 4, 3 ]
[]
[]
[ "ftp", "metadata", "python" ]
stackoverflow_0003795605_ftp_metadata_python.txt
Q: Yahoo BOSS API Python Library Error i've just downloaded the Yahoo BOSS Mashup framework from http://developer.yahoo.com/search/boss/mashup.html, and I have a problem: I'm receiving the following error for all examples. For instance, for example.ex3.py: File "ex3.py", line 33 tb = db.group(by=["ynews$title"], ...
Yahoo BOSS API Python Library Error
i've just downloaded the Yahoo BOSS Mashup framework from http://developer.yahoo.com/search/boss/mashup.html, and I have a problem: I'm receiving the following error for all examples. For instance, for example.ex3.py: File "ex3.py", line 33 tb = db.group(by=["ynews$title"], key="dg$diggs", reducer=lambda d1, d2: d1...
[ "oh, i manage to fix it. What i did is that i changed the key word \"as\" and replace it with some other word.\nI used \"as\" to \"as1\" and reinstalled the framework. Now it works. Hope this helps all other people. \n" ]
[ 0 ]
[]
[]
[ "python", "yahoo_boss_api" ]
stackoverflow_0003796747_python_yahoo_boss_api.txt
Q: Qt uses CSS to color objects? Is there another way to go about this? I am learning PyQt from this site. The tutorial is building a widget that colours a square. In this, they are using CSS to colour the square, rather than give it some sort of concrete property of colour. Why is this? Is there another way to d...
Qt uses CSS to color objects? Is there another way to go about this?
I am learning PyQt from this site. The tutorial is building a widget that colours a square. In this, they are using CSS to colour the square, rather than give it some sort of concrete property of colour. Why is this? Is there another way to do this without CSS or is this the preferred method? It seems awfully stra...
[ "Every widget has QPalette, that can be modified and accessed via QWidget::palette() and QWidget::setPalette(p).\nYou can find some useful details here: QPalette in Qt 4.6. CSS is just more clean and simple (and declarative, which is SOoo popular nowadays :) ) way to determine it.\nNote, that if you want only to mo...
[ 4, 0 ]
[]
[]
[ "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0003695799_pyqt_python_qt_user_interface.txt
Q: object oriented programming basics (python) Level: Beginner In the following code my 'samePoint' function returns False where i am expecting True. Any hints? import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) ...
object oriented programming basics (python)
Level: Beginner In the following code my 'samePoint' function returns False where i am expecting True. Any hints? import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) ...
[ "Looking at your code \ndef samePoint(p, q):\n return (p.cartesian == q.cartesian)\n\np.cartesian, q.cartesian are functions and you are comparing function rather than function result. Since the comparing two distinct functions, the result is False\nWhat you should have been coding is\ndef samePoint(p, q):\n ...
[ 6, 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003797219_oop_python.txt
Q: python script in crontab gets input arguments of another process running at the same time I run 2 python scripts from crontab at the same time each 30 min, e.g. 00,30 6-19 * * 0-5 /.../x.py site1 */3 6-19 * * 0-5 /.../y.py site2 At the beginning the both scripts make import of a module that prints some data to a...
python script in crontab gets input arguments of another process running at the same time
I run 2 python scripts from crontab at the same time each 30 min, e.g. 00,30 6-19 * * 0-5 /.../x.py site1 */3 6-19 * * 0-5 /.../y.py site2 At the beginning the both scripts make import of a module that prints some data to a log, e.g. name = os.path.basename(sys.argv[0]) site = sys.argv[1] pid = os.getpid() Occasiona...
[ "When two scripts \"run at the same time\", the lines that they print can be mixed, depending on how the operating system allocates priority to the processes.\nYou can thus obtain, in your logs, something like:\nx.py: /tmp/x.py\n…\n… # Other processes logging information\n…\ny.py: /tmp/y.py\nx.py: site1 # Not prin...
[ 2, 2, 0, 0 ]
[]
[]
[ "crontab", "logging", "python" ]
stackoverflow_0003744751_crontab_logging_python.txt
Q: Django with multiple database I have a Django application with two configured databases first_DB and second_DB The configurations seems as following DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NA...
Django with multiple database
I have a Django application with two configured databases first_DB and second_DB The configurations seems as following DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME' : 'emonitor', ...
[ "If you don't know where the 500 error is coming from, set DEBUG=True in your settings, and look at the debug stack trace page that is produced. It will show you where the exception is being raised.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003797119_django_python.txt
Q: What does cpython do to help detect object cycles(reference counting)? From what I've read about cpython it seems like it does reference counting + something extra to detect/free objects pointing to each other.(Correct me if I'm wrong). Could someone explain the something extra? Also does this guarantee* no cycle ...
What does cpython do to help detect object cycles(reference counting)?
From what I've read about cpython it seems like it does reference counting + something extra to detect/free objects pointing to each other.(Correct me if I'm wrong). Could someone explain the something extra? Also does this guarantee* no cycle leaking? If not is there any research into an algorithm proven to add to ref...
[ "As explained in the documentation for gc.garbage, there is no guarantee that no leaks occur; specifically, cyclic objects with __del__ methods are not collected by default. For such objects, the cyclic links have to be manually broken to enable further GC.\nFrom what I understand by browsing the CPython sourcecode...
[ 4 ]
[]
[]
[ "cpython", "garbage_collection", "proof", "python", "reference_counting" ]
stackoverflow_0003797220_cpython_garbage_collection_proof_python_reference_counting.txt
Q: Overuse of mixin is evil and what are the alternative solutions? Sometimes using mixin with multiple inheritance can help us improve reusability of our code. For example, the following design class FollowableMixin(object): def get_followers(self): ... ... class User(FollowableMixin): ... may ...
Overuse of mixin is evil and what are the alternative solutions?
Sometimes using mixin with multiple inheritance can help us improve reusability of our code. For example, the following design class FollowableMixin(object): def get_followers(self): ... ... class User(FollowableMixin): ... may be better reused than simply adding get_followers to User: class User(...
[ "Sometimes it can help to collect together related features in a single class if they are often used together.\nclass FooMixin(FollowableMixin, RunnableMixin):\n pass\n\nThen when you come to use it you only have one or two direct base classes instead of many.\nObviously you should only do this if it makes sense...
[ 6, 6, 4, 4 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0003797446_design_patterns_oop_python.txt
Q: python django how can i filter object_set.all by current user in template http://pastebin.com/Aa5rJxv8 i have django problem above, i tried to explain i need to show ratings given by current user to books in user shelves thanks A: One way to do this in the template would be to define a custom filter. This custom...
python django how can i filter object_set.all by current user in template
http://pastebin.com/Aa5rJxv8 i have django problem above, i tried to explain i need to show ratings given by current user to books in user shelves thanks
[ "One way to do this in the template would be to define a custom filter. This custom filter can accept a queryset and the currently logged in user as arguments and do the necessary filtering. \n@register.filter\ndef filter_by_user(queryset, user):\n \"\"\"Filter the queryset by (currently logged in) user\"\"\"\n ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003797774_django_python.txt
Q: How to get around error 304 in urllib2, Python For the openers, opener = urllib2.build_opener(), if I try to add an header: request.add_header('if-modified-since',request.headers.get('last-nodified')) I get the error code: Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> feeddata =...
How to get around error 304 in urllib2, Python
For the openers, opener = urllib2.build_opener(), if I try to add an header: request.add_header('if-modified-since',request.headers.get('last-nodified')) I get the error code: Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> feeddata = opener.open(request) File "C:\Python27\lib\urllib...
[ "Your traceback says: expected string, NoneType found from which I deduce that you've stored a None value as a header. Did you really write 'last-nodified'? The header you mean was probably 'last-modified', but even then you should check that it existed and not re-use it as a header if request.headers.get() returns...
[ 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003797902_python_urllib2.txt
Q: How to select a Radio Button? I am using mechanize and I am trying to select a button from a radio button list. This list has 5 items. How can I select the first item? Docs didn't help me. >>> br.form <ClientForm.HTMLForm instance at 0x9ac0d4c> >>> print(br.form) <form1 POST http://www.example.com application/x-ww...
How to select a Radio Button?
I am using mechanize and I am trying to select a button from a radio button list. This list has 5 items. How can I select the first item? Docs didn't help me. >>> br.form <ClientForm.HTMLForm instance at 0x9ac0d4c> >>> print(br.form) <form1 POST http://www.example.com application/x-www-form-urlencoded <HiddenControl(DD...
[ "It should be as simple as\nbr.form['prodclass'] = ['1']\n\nI prefer the more verbose:\nbr.form.set_value(['1'],name='prodclass')\n\n" ]
[ 13 ]
[]
[]
[ "mechanize", "python", "radio_button" ]
stackoverflow_0003798138_mechanize_python_radio_button.txt
Q: Combining a url with urlunparse I'm writing something to 'clean' a URL. In this case all I'm trying to do is return a faked scheme as urlopen won't work without one. However, if I test this with www.python.org It'll return http:///www.python.org. Does anyone know why the extra /, and is there a way to return this ...
Combining a url with urlunparse
I'm writing something to 'clean' a URL. In this case all I'm trying to do is return a faked scheme as urlopen won't work without one. However, if I test this with www.python.org It'll return http:///www.python.org. Does anyone know why the extra /, and is there a way to return this without it? def FixScheme(website): ...
[ "Problem is that in parsing the very incomplete URL www.python.org, the string you give is actually taken as the path component of the URL, with the netloc (network location) one being empty as well as the scheme. For defaulting the scheme you can actually pass a second parameter scheme to urlparse (simplifying yo...
[ 9, 1 ]
[]
[]
[ "python", "urlparse" ]
stackoverflow_0003798269_python_urlparse.txt
Q: object oriented programming basics: inheritance & shadowing (Python) Level: Beginner I'm doing my first steps in Object Oriented programming. The code is aimed at showing how methods are passed up the chain. So when i call UG.say(person, 'but i like') the method say is instructed to call class MITPerson. Given th...
object oriented programming basics: inheritance & shadowing (Python)
Level: Beginner I'm doing my first steps in Object Oriented programming. The code is aimed at showing how methods are passed up the chain. So when i call UG.say(person, 'but i like') the method say is instructed to call class MITPerson. Given that MITPerson does not contain a say method it will pass it up to class Per...
[ "You are calling class instead of instance.\n>>> ug = UG('Dylan', 'Bob')\n>>> UG.say(person, 'but i like')\n\n\nUG.say(person, 'bla')\n\nCall instance instead\n>>> ug = UG('Dylan', 'Bob')\n>>> ug.say(person, 'but i like')\n\n", "The answers are quite fine, but there's a side note I think is important to make. Ta...
[ 4, 3, 2, 2 ]
[]
[]
[ "inheritance", "oop", "python", "shadowing" ]
stackoverflow_0003798194_inheritance_oop_python_shadowing.txt
Q: Write MP3 in Python I have a bunch of frames (generated by a function) that I want to write to a MP3 file using Python. I tried using pymedia but I always get a Segmentation fault. Doe anyone know an extension to write MP3 files using Python? Thanks! A: If you're on Gnome, soundconverter might help; but I don't ...
Write MP3 in Python
I have a bunch of frames (generated by a function) that I want to write to a MP3 file using Python. I tried using pymedia but I always get a Segmentation fault. Doe anyone know an extension to write MP3 files using Python? Thanks!
[ "If you're on Gnome, soundconverter might help; but I don't know of a stand-alone equivalent.\n" ]
[ 2 ]
[]
[]
[ "file", "mp3", "python" ]
stackoverflow_0003798386_file_mp3_python.txt
Q: Why urllib2.urlopen can not open pages like "http://localhost/new-post#comment-29"? I'm curious, how come I get 404 error running this line: urllib2.urlopen("http://localhost/new-post#comment-29") While everything works fine surfing http://localhost/new-post#comment-29 in any browser... urlopen method does not p...
Why urllib2.urlopen can not open pages like "http://localhost/new-post#comment-29"?
I'm curious, how come I get 404 error running this line: urllib2.urlopen("http://localhost/new-post#comment-29") While everything works fine surfing http://localhost/new-post#comment-29 in any browser... urlopen method does not parse urls with "#" in it? Anybody knows?
[ "In the HTTP protocol, the fragment (from # onwards) is not sent to the server across the network: it's locally retained by the browser and used, once the server's response is fully received, to somehow \"visually locate\" the exact spot in the page to be shown as \"current\" (for example, if the returned page is i...
[ 7 ]
[]
[]
[ "fragment_identifier", "python", "urllib2", "urlopen" ]
stackoverflow_0003798422_fragment_identifier_python_urllib2_urlopen.txt
Q: Using Both jQuery And FormEncode To Validate Forms Without Repetition I'm working on a Pylons-based web app. Because I am sane, I am using jQuery (and plugins) instead of writing raw JavaScript. I am also using FormEncode to validate forms for my app (especially new user registration). FormEncode is great for v...
Using Both jQuery And FormEncode To Validate Forms Without Repetition
I'm working on a Pylons-based web app. Because I am sane, I am using jQuery (and plugins) instead of writing raw JavaScript. I am also using FormEncode to validate forms for my app (especially new user registration). FormEncode is great for validating forms after they're submitted. jQuery, when JavaScript is availa...
[ "My current solution is to have the FormEncode rules in the controller, and to give the controller one method that responds to a complete form being submitted, and another method that responds to AJAX requests, and validate both methods again the same FormEncode rules. That means that I can have jQuery make reques...
[ 2 ]
[]
[]
[ "ajax", "formencode", "jquery", "python", "validation" ]
stackoverflow_0003773714_ajax_formencode_jquery_python_validation.txt
Q: Scraping Flash: accessing background files, perhaps in Mechanize? I'm scraping a website in Flash, writing in Python. I can see in Firebug that the page loads its Flash file and then some background data in an .asmx file. The background data is what I'm interested in - so how can I get hold of the .asmx file? I a...
Scraping Flash: accessing background files, perhaps in Mechanize?
I'm scraping a website in Flash, writing in Python. I can see in Firebug that the page loads its Flash file and then some background data in an .asmx file. The background data is what I'm interested in - so how can I get hold of the .asmx file? I already know what it's called. I can't get at the .asmx file directly, b...
[ "\ncan I grab it using Mechanize?\n\nI don't believe so. The .asmx extension says that the resource you are accessing is a (SOAP-based) .NET Web service, written in a language such as C# or VB.NET. Normally the .asmx code would return a SOAP response, perhaps to be parsed by the Flash application. But it's hard to ...
[ 1 ]
[]
[]
[ "flash", "mechanize", "python" ]
stackoverflow_0003799000_flash_mechanize_python.txt
Q: How can I monitor mouse events with Python Xlib instead of capture them? I need to monitor and filter mouse events with Xlib in Python. So far I have found out that this code receives events, but does not pass them on, so I can't actually do anything with the mouse anymore. from Xlib.display import Display from Xl...
How can I monitor mouse events with Python Xlib instead of capture them?
I need to monitor and filter mouse events with Xlib in Python. So far I have found out that this code receives events, but does not pass them on, so I can't actually do anything with the mouse anymore. from Xlib.display import Display from Xlib import X display = Display(':0') root = display.screen().root root.grab_p...
[ "The link was broken. I think this is the latest one: http://github.com/pepijndevos/PyMouse/blob/master/pymouse/unix.py Line 58\n", "The answer seemed to be to use Xlib with RECORD, the result can be seen here:\nhttp://github.com/pepijndevos/PyMouse/blob/master/unix.py#L38\n" ]
[ 2, 0 ]
[]
[]
[ "event_handling", "python", "xlib" ]
stackoverflow_0002585647_event_handling_python_xlib.txt
Q: How is possible to create a python shell script like top unix command? I'm need to create a Python shell script that refresh output every n seconds like top unix command. what 's the best way to do this? A: One way to do this is to write a script that prints your output (once), and then run your script using th...
How is possible to create a python shell script like top unix command?
I'm need to create a Python shell script that refresh output every n seconds like top unix command. what 's the best way to do this?
[ "One way to do this is to write a script that prints your output (once), and then run your script using the watch command. The watch command will automatically clear the screen and run your script every few seconds (usually 2 by default).\nIf you really want to do this in pure Python, you can use the curses module,...
[ 4 ]
[]
[]
[ "cmd", "python", "shell" ]
stackoverflow_0003799400_cmd_python_shell.txt
Q: Help with XML parsing in Python I have a XML file which contains 100s of documents inside . Each block looks like this: <DOC> <DOCNO> FR940104-2-00001 </DOCNO> <PARENT> FR940104-2-00001 </PARENT> <TEXT> <!-- PJG FTAG 4703 --> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=90 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG I...
Help with XML parsing in Python
I have a XML file which contains 100s of documents inside . Each block looks like this: <DOC> <DOCNO> FR940104-2-00001 </DOCNO> <PARENT> FR940104-2-00001 </PARENT> <TEXT> <!-- PJG FTAG 4703 --> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=90 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=90 g=1 f=4 --> Federal Register...
[ "You could avoid looping through the doc twice by using xml.sax.handler:\nimport xml.sax.handler\nimport collections\n\n\nclass DocBuilder(xml.sax.handler.ContentHandler):\n def __init__(self):\n self.state=''\n self.docno=''\n self.text=collections.defaultdict(list)\n def startElement(se...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003795984_python_xml.txt
Q: "Zero Iteration" - end to end acceptance test in simple contact-form feature I was reading "Growing Object-Oriented Software, Guided by Tests" lately. Authors of this book sugested to always start developing a feature with an end-to-end acceptance test (before starting TDD cycle) to not loose a track of progress a...
"Zero Iteration" - end to end acceptance test in simple contact-form feature
I was reading "Growing Object-Oriented Software, Guided by Tests" lately. Authors of this book sugested to always start developing a feature with an end-to-end acceptance test (before starting TDD cycle) to not loose a track of progress and to make sure that you're still on the same page while unit-testing. Ok, so I've...
[ "You don't have to contain all possibilities in acceptance tests at all - you will still write unit tests. So I would say that a single tests \"user can fill in the form, save it and load it back\" is enough to start with. Then you can add more tests if you think that a particular aspect of your system is important...
[ 1, 0 ]
[]
[]
[ "bdd", "django", "python", "tdd", "unit_testing" ]
stackoverflow_0003798629_bdd_django_python_tdd_unit_testing.txt
Q: Python: How to use os.spawnv with a lot of arguments? Im working in a Python plugin for XBMC (xbmc.org) and I want to execute a program (ffmpeg.exe) from my plugin without the cmd window appears. If I use os.system() to call ffmpeg.exe works fine but the xbmc minimizes because os.system open a cmd window a few sec...
Python: How to use os.spawnv with a lot of arguments?
Im working in a Python plugin for XBMC (xbmc.org) and I want to execute a program (ffmpeg.exe) from my plugin without the cmd window appears. If I use os.system() to call ffmpeg.exe works fine but the xbmc minimizes because os.system open a cmd window a few seconds. So, I try to use os.spawnv() that I think its possibl...
[ "As per http://docs.python.org/library/os.html#os.spawnv, pass the arguments in a list:\nos.spawnv(os.P_DETACH, \"path\\to\\program.exe\", [\"arg1\", \"arg2\", \"arg3\"])\n\n" ]
[ 0 ]
[ "This way:\nos.system(\"\"C:\\\\Program Files (x86)\\\\XBMC\\\\scripts\\\\Base De Datos\\\\ffmpeg.exe\" -y -ss 423 -i \"C:\\Program Files (x86)\\XBMC\\scripts\\Base De Datos\\Movie.avi\" -f mjpeg -vframes 1 -s 720x320 -an \"C:/Program Files (x86)/XBMC/scripts/Base De Datos/thumbnail.jpg\"\")\n\nWorks fine but minim...
[ -1 ]
[ "ffmpeg", "python", "thumbnails" ]
stackoverflow_0003799531_ffmpeg_python_thumbnails.txt
Q: Python - Best way to compare two strings, record stats comparing serial position of particular item? I'm dealing with two files, both of which have lines that look like the following: This is || an example || line . In one of the files, the above line would appear, whereas the corresponding line in the other file...
Python - Best way to compare two strings, record stats comparing serial position of particular item?
I'm dealing with two files, both of which have lines that look like the following: This is || an example || line . In one of the files, the above line would appear, whereas the corresponding line in the other file would be identical BUT might have the '||' items in a different position: This || is an || example || lin...
[ "Is this what you are looking for?\nThis code assumes that every line is formatted in the same way as in your examples\nfileOne = open('theCorrectFile', 'r')\nfileTwo = open('theSecondFile', 'r')\n\nfor corrrectLine in fileOne:\n otherLine = fileTwo.readline()\n for i in len(correctLine.split(\"||\")):\n ...
[ 1, 0 ]
[]
[]
[ "compare", "python", "string" ]
stackoverflow_0003799407_compare_python_string.txt
Q: Optimizing find and replace over large files in Python I am a complete beginner to Python or any serious programming language for that matter. I finally got a prototype code to work but I think it will be too slow. My goal is to find and replace some Chinese characters across all files (they are csv) in a director...
Optimizing find and replace over large files in Python
I am a complete beginner to Python or any serious programming language for that matter. I finally got a prototype code to work but I think it will be too slow. My goal is to find and replace some Chinese characters across all files (they are csv) in a directory with integers as per a csv file I have. The files are nice...
[ "In your current code, you're reading the whole file into memory at once. Since they're 500Mb files, that means 500Mb strings. And then you do repeated replacements of them, which means Python has to create a new 500Mb string with the first replacement, then destroy the first string, then create a second 500Mb stri...
[ 18, 3, 1, 0 ]
[]
[]
[ "optimization", "python", "replace" ]
stackoverflow_0003800086_optimization_python_replace.txt
Q: Help interpreting code snippet I am very new to python and beautifulsoup. In the for statement, what is incident? Is it a class, type, variable? The line following the for.. totally lost. Can someone please explain this code to me? for incident in soup('td', width="90%"): where, linebreak, what = incident.con...
Help interpreting code snippet
I am very new to python and beautifulsoup. In the for statement, what is incident? Is it a class, type, variable? The line following the for.. totally lost. Can someone please explain this code to me? for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() ...
[ "The first statement starts a loop which parses an HTML document looking for td elements with width set to 90%. The object representing the td element is bound to the name incident.\nThe second line is a multiple assignment and can be rewritten as follows:\nwhere = incident.contents[0]\nlinebreak = incident.content...
[ 3, 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003799402_beautifulsoup_python.txt
Q: How to generate a random partition from an iterator in Python Given the desired number of partitions, the partitions should be nearly equal in size. This question handles the problem for a list. They do not have the random property, but that is easily added. My problem is, that I have an iterator as input, so shuf...
How to generate a random partition from an iterator in Python
Given the desired number of partitions, the partitions should be nearly equal in size. This question handles the problem for a list. They do not have the random property, but that is easily added. My problem is, that I have an iterator as input, so shuffle does not apply. The reason for that is that I want to randomly ...
[ "You're just dealing to various partitions, right?\ndef dealer( iterator, size ):\n for item in iterator\n yield random.randrange( size ), item\n\nWon't that get you started by assigning each item to a partition?\nThen you can do something like this to make lists. Maybe not a good thing, but it shows how...
[ 1, 1, 0 ]
[]
[]
[ "iterator", "partitioning", "python", "random" ]
stackoverflow_0003760752_iterator_partitioning_python_random.txt
Q: Pythonic way to modify python path relative to current directory I have a project that is structured like this (cut down a lot to give the gist)... State_Editor/ bin/ state_editor/ __init__.py main.py features/ __init__.py # .py files io/ ...
Pythonic way to modify python path relative to current directory
I have a project that is structured like this (cut down a lot to give the gist)... State_Editor/ bin/ state_editor/ __init__.py main.py features/ __init__.py # .py files io/ __init__.py # .py files # etc. You get the idea. ...
[ "In the question as stated, you need 2 leading dots (the module containing the import was state_editor.features.foobar). So:\nfrom ..io.fileop import SubInPath \n\nFull docs:\nhttp://docs.python.org/reference/simple_stmts.html#the-import-statement\n", "In recent-enough Python versions, \"relative imports\" as re...
[ 3, 1 ]
[]
[]
[ "filepath", "filesystems", "python" ]
stackoverflow_0003800411_filepath_filesystems_python.txt
Q: Is this a Dictionary in an older Python version? I'm new to Python and am reading a book that came out in 2009 and so uses Python 2.5 syntax. It does the following: _fields_ = [ ("cb", DWORD), ("lpReserved", LPTSTR), ... ] To me it looks like a list of tuples, but at the same time it feels like a Map/...
Is this a Dictionary in an older Python version?
I'm new to Python and am reading a book that came out in 2009 and so uses Python 2.5 syntax. It does the following: _fields_ = [ ("cb", DWORD), ("lpReserved", LPTSTR), ... ] To me it looks like a list of tuples, but at the same time it feels like a Map/Dictionary. Was this the older syntax?
[ "It's perfectly good, current syntax, and expresses a list of pairs (two-item tuples). If you need a dict (and have no problem with duplicate keys;-), dict(_fields_) will make you one (much like somedict.items() makes you a list of pairs from a dict -- list(somedict.items()) if you're in Python 3 but insist on get...
[ 6, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003800617_python.txt
Q: How do you implement 'EXIT_CODES' in python? Initially i thought to do something like: #EXIT CODES class ExitCode(object): (USERHOME_INVALID, \ USERHOME_CANNOT_WRITE, \ USERHOME_CANNOT_READ, \ BASHRC_INVALID) = range(-1, -5, -1) But than I've realized that I'll have to know exactly the total numbe...
How do you implement 'EXIT_CODES' in python?
Initially i thought to do something like: #EXIT CODES class ExitCode(object): (USERHOME_INVALID, \ USERHOME_CANNOT_WRITE, \ USERHOME_CANNOT_READ, \ BASHRC_INVALID) = range(-1, -5, -1) But than I've realized that I'll have to know exactly the total number of EXIT_CODES, so that I can pass it to the rang...
[ "Sounds like what you want is the Python equivalent of an enumeration in C# or other similar languages. How can I represent an 'Enum' in Python? provides several solutions, though they still require the number of items you have. \nEDIT: How can I represent an 'Enum' in Python? looks way better.\nOr you could try so...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "exit_code", "python" ]
stackoverflow_0003731532_exit_code_python.txt
Q: problem with QSqlTalbeModel . table is not showing i have a QsqlTableModel that is assigned to a table view . my problem is that it doesn't populate the table inside the table view . it's still empty and it says (Unable to find table shots) - when printing lastError.text() - the function retrieveShotResults..(ch...
problem with QSqlTalbeModel . table is not showing
i have a QsqlTableModel that is assigned to a table view . my problem is that it doesn't populate the table inside the table view . it's still empty and it says (Unable to find table shots) - when printing lastError.text() - the function retrieveShotResults..(check code below) is to test if there is a table called s...
[ "i found it ^_^ . the (connect) function should be called in the mainloop \n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python", "qtsql" ]
stackoverflow_0003800522_pyqt4_python_qtsql.txt
Q: Python function help Please help! cannot figure this out for the life of me Given the function f(x,n)= n**x(n-1) 5c. Using this function, calculate the rate of change of (((2^3 + 3^2)^4 -2^4)^2 + (3^4 – (6^2 + 3)^4)^3)^3 This is what I came up with in IDLE: def function(x, n): return (n*(x**(n-1))) assertEq...
Python function help
Please help! cannot figure this out for the life of me Given the function f(x,n)= n**x(n-1) 5c. Using this function, calculate the rate of change of (((2^3 + 3^2)^4 -2^4)^2 + (3^4 – (6^2 + 3)^4)^3)^3 This is what I came up with in IDLE: def function(x, n): return (n*(x**(n-1))) assertEqual ( function (((( ...
[ "(function(a, b), c) is a 2-tuple consisting of the result of function(a,b) and c.\nIf you want to represent (a^b)^c, you'd need something like function(function(a,b), c) (assuming function() computes its first parameter raised to the second.)\n", "There are a few occurances of this, but here is the first one.\nf...
[ 3, 2, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003799786_function_python.txt
Q: MongoDB for realtime ajax stuff? Howdie stackoverflow people! So I've been doing some digging regarding these NoSQL databases, MongoDB, CouchDB etc. Though I am still not sure about real time-ish stuff therefore I thought i'd ask around to see if someone have any practical experience. Let's think about web stuff, ...
MongoDB for realtime ajax stuff?
Howdie stackoverflow people! So I've been doing some digging regarding these NoSQL databases, MongoDB, CouchDB etc. Though I am still not sure about real time-ish stuff therefore I thought i'd ask around to see if someone have any practical experience. Let's think about web stuff, let's say we've got a very dynamic sup...
[ "\nLet's say we have 5000 users at the\n same time, every 5, 10 or 20 seconds\n ajax requests that updates various\n interfaces.\n\nOK, so to get this right, you're talking about 250 to 1000 writes per second? Yeah, MongoDB can handle that.\nThe real key on performance is going to be whether or not these are que...
[ 2, 0 ]
[]
[]
[ "ajax", "mongodb", "php", "python", "real_time" ]
stackoverflow_0003798728_ajax_mongodb_php_python_real_time.txt
Q: Overriding a parent class's methods Something that I see people doing all the time is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') super(ExcitingMan, self).say_hi() # Calling the parent version once done with ...
Overriding a parent class's methods
Something that I see people doing all the time is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') super(ExcitingMan, self).say_hi() # Calling the parent version once done with custom stuff. Something that I never see...
[ "I'd argue that explicitly returning the return value of the super class method is more prudent (except in the rare case where the child wants to suppress it). Especially when you don't know what exactly super is doing. Agreed, in Python you can usually look up the super class method and find out what it does, but ...
[ 8, 5, 3 ]
[]
[]
[ "class", "methods", "overriding", "python", "subclass" ]
stackoverflow_0003801484_class_methods_overriding_python_subclass.txt
Q: python regex speed regarding regex (specifically python re), if we ignore the way the expression is written, is the length of the text the only factor for the time required to process the document? Or are there other factors (like how the text is structured) that play important roles too? A: One important consid...
python regex speed
regarding regex (specifically python re), if we ignore the way the expression is written, is the length of the text the only factor for the time required to process the document? Or are there other factors (like how the text is structured) that play important roles too?
[ "One important consideration can also be whether the text actually matches the regular expression. Take (as a contrived example) the regex (x+x+)+y from this regex tutorial.\nWhen applied to xxxxxxxxxxy it matches, taking the regex engine 7 steps. When applied to xxxxxxxxxx, it fails (of course), but it takes the e...
[ 6, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003801576_python_regex.txt
Q: permissive equality test on string I'm a python newbie with a problem too hard to tackle. I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path? e.g. a string like /some/path_to/directory_1/and_to/directory_2 with a real path: /some...
permissive equality test on string
I'm a python newbie with a problem too hard to tackle. I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path? e.g. a string like /some/path_to/directory_1/and_to/directory_2 with a real path: /some/path_to/directory 1/and_to/directory 2 ...
[ "Use glob but replacing every underscore with a range [ _]:\nimport glob\nglob.glob('/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]'))\n\nNote that this will fail if your path contains the character [. You can fix this by first replacing [ with [[].\n" ]
[ 5 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003802450_path_python.txt
Q: Fetching multiple IMAP messages at once The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. I want to speed things up by fetching them all at once. A: RFC 3501 says fetch takes a sequence set, but I didn't see a definition for th...
Fetching multiple IMAP messages at once
The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. I want to speed things up by fetching them all at once.
[ "RFC 3501 says fetch takes a sequence set, but I didn't see a definition for that and the example uses a range form (2:4 = messages 2, 3, and 4). I figured out that a comma separated list of ids works. In python with imaplib, I've got something like:\n status, email_ids = con.search(None, query)\n if status !...
[ 16, 3 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0003581657_imap_imaplib_python.txt
Q: What is correct python syntax for this kind of list comprehension? task: {x*y such that x belongs to S & y is iteration count } where S is some other set something like this: j=0 [i*j for j++ and i in S] [s1*1, s2*2, s3*3...] A: for your edited question, you want [i * j for j, i in enumerate(S)] python doesn't...
What is correct python syntax for this kind of list comprehension?
task: {x*y such that x belongs to S & y is iteration count } where S is some other set something like this: j=0 [i*j for j++ and i in S] [s1*1, s2*2, s3*3...]
[ "\nfor your edited question, you want\n[i * j for j, i in enumerate(S)]\n\n\npython doesn't have ++ because it keeps a clear distinction between statements and expressions. use\n[(i + 40) * i for i in xrange(60)]\n\nanother way to do this is\n[i * j for i, j in enumerate(xrange(60), start=40)]\n\nand yet another wa...
[ 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003802653_list_comprehension_python.txt
Q: Qt: No border on buttons making them non-clickable? I'm trying to set a style to a button so that it has no border, but it seems the lack of border then makes the button non-clickable. Is there a better way of getting no border? button = QtGui.QPushButton(todo, self) button.move(0, i * 32) button.setFixedSize(200,...
Qt: No border on buttons making them non-clickable?
I'm trying to set a style to a button so that it has no border, but it seems the lack of border then makes the button non-clickable. Is there a better way of getting no border? button = QtGui.QPushButton(todo, self) button.move(0, i * 32) button.setFixedSize(200,32) button.setCheckable(True) button.setStyleSheet("QPush...
[ "EDIT: WHOOPS, just noticed this is a Question regarding Qt/Python (and not Qt/C++), well maybe my answer helps anyways..\nJust tried it, and it works for me...\nHere is the code i used:\n#include <QtGui/QApplication>\n#include <QtGui/QPushButton>\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, arg...
[ 1 ]
[]
[]
[ "pyside", "python", "qt" ]
stackoverflow_0003800757_pyside_python_qt.txt
Q: How can I pairwise sum two equal-length tuples How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer. A: tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7)))) If you prefer to avoid map and lambda then you can do: tuple(...
How can I pairwise sum two equal-length tuples
How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer.
[ "tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))\n\nIf you prefer to avoid map and lambda then you can do:\ntuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))\n\nEDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip. Therefore you can rewrite the ...
[ 14, 6, 4, 3 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0003802760_python_tuples.txt
Q: Whats the correct way of writing this list comprehension? I'm getting an error: name 'i' is not defined k = [ [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ] for j in range(0,len(furs[i])) ] but k = [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) for j in range...
Whats the correct way of writing this list comprehension?
I'm getting an error: name 'i' is not defined k = [ [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ] for j in range(0,len(furs[i])) ] but k = [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) for j in range(0,len(furs[i])) ] works surprisingly! EDIT: What is the corre...
[ "for j in range(0,len(furs[i])) in your first example: i is not in scope here, due to the preceding ].\n", "Look carefully at the second for loop: for j in range(0,len(furs[i])). You are referring to i here even though it is created and used in the preceding first list comprehension ([ rids[i][j][0]['a'] * rids[...
[ 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003803241_list_comprehension_python.txt
Q: sqlalchemy polymorhic_identity not working I'm trying to use polymorphic_on on a python class with several inheritances: engine = create_engine( 'mysql://xxx:yyy@localhost:3306/zzz?charset=utf8&use_unicode=0', pool_recycle=3600, echo=True) Base = declarative_base() class AbstractPersistent(object): v...
sqlalchemy polymorhic_identity not working
I'm trying to use polymorphic_on on a python class with several inheritances: engine = create_engine( 'mysql://xxx:yyy@localhost:3306/zzz?charset=utf8&use_unicode=0', pool_recycle=3600, echo=True) Base = declarative_base() class AbstractPersistent(object): version = Column('VERSION', Integer) last_mod...
[ "Thanks to Michael on the google group sqlalchemy, this is the answer:\n\nAbstractContainer is not mapped, its a mixin, so its __mapper_args__ are not\n used until a subclass of Base is invoked, which starts up a declarative\n mapping. Your only mapped class then is CourseSet, which has its own\n __mapper_args_...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003799841_python_sqlalchemy.txt
Q: Create variables from dictionary? Is something like the following possible in Python? >>> vars = {'a': 5} >>> makevars(vars) >>> print a 5 So, makevars converts the dictionary into variables. (What is this called in general?) A: It's possible, sometimes, but it's generally a very bad idea. In spite of their nam...
Create variables from dictionary?
Is something like the following possible in Python? >>> vars = {'a': 5} >>> makevars(vars) >>> print a 5 So, makevars converts the dictionary into variables. (What is this called in general?)
[ "It's possible, sometimes, but it's generally a very bad idea. In spite of their name, variables themselves should not be variable. They're part of your code, part of its logic. Trying to 'replace' local variables this way makes code inefficient (since Python has to drop some of its optimizations), buggy (since it ...
[ 10, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0003803419_python_variables.txt
Q: zc.buildout, Installing requirements into the parts directory? I am attempting to write a zc.buildout package that installs some of it's requirements into the parts directory. Any idea how this can be done? The reason for this is because the zc.buildout application itself is being distributed out, but parts of my ...
zc.buildout, Installing requirements into the parts directory?
I am attempting to write a zc.buildout package that installs some of it's requirements into the parts directory. Any idea how this can be done? The reason for this is because the zc.buildout application itself is being distributed out, but parts of my package cannot go with it. So instead i would like to install them i...
[ "You can use omelette recipe in order to unzip all eggs and put in to one directory in parts directory. Example buildout.cfg\n[buildout]\nparts = my_omelette\neggs = \n BeautifulSoup\n django-registration\n other_package_from_pypi\n\nunzip = true\n\n[my_omelette]\nrecipe = collective.recipe.omelette\neggs ...
[ 2 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0003720231_buildout_python.txt
Q: Using mod_rewrite to hide the .py extension of a Python script accessed on a web browser I want to hide the .py extension of a Python script loaded in a web browser and still have the script run. For example: typing url.dev/basics/pythonscript in the address bar fires pythonscript.py and shows the results in the b...
Using mod_rewrite to hide the .py extension of a Python script accessed on a web browser
I want to hide the .py extension of a Python script loaded in a web browser and still have the script run. For example: typing url.dev/basics/pythonscript in the address bar fires pythonscript.py and shows the results in the browser window. The URL url.dev/basics/pythonscript fetches the static file /pythonscript.py T...
[ "If you are running on a linux box, dont use mod-rewrite - rename the script. \nyou can call the script - pythonscript not pythonscript.py \nyou add to the first line of the script \n pointing to your python interpreter \nand set the file to be executable \nwith \nchmod +x pythonscript \n\nwhen the file is executed...
[ 4, 1 ]
[]
[]
[ "apache", "mod_rewrite", "python" ]
stackoverflow_0003418687_apache_mod_rewrite_python.txt
Q: Using regex in python i have the following problem. I want to escape all special characters in a python string. str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\1', str) 'eFEx\\1x\\1k\\1\\1\\1' str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\1', str) 'eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\\1', str) I can't see...
Using regex in python
i have the following problem. I want to escape all special characters in a python string. str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\1', str) 'eFEx\\1x\\1k\\1\\1\\1' str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\1', str) 'eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\\1', str) I can't seem to win here. '\1' indicat...
[ "Use r'\\\\\\1'. That's a backslash (escaped, so denoted \\\\) followed by \\1.\nTo verify that this works, try:\nstr = 'eFEx-x?k=;-'\nprint re.sub(\"([^a-zA-Z0-9])\",r'\\\\\\1', str)\n\nThis prints:\neFEx\\-x\\?k\\=\\;\\-\n\nwhich I think is what you want. Don't be confused when the interpreter outputs 'eFEx\\\\-x...
[ 7, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003804149_python_regex.txt
Q: wx.TreeCtrl drag and drop, copy and move I'm trying to implement drag and drop on a wx.TreeCtrl and I need to handle both "copy" and "move" operations (if the user keeps CTRL pressed). First of all, I searched the wiki for an example and I'm confused as to which method to use.. Should I use DropSource/DropTarget o...
wx.TreeCtrl drag and drop, copy and move
I'm trying to implement drag and drop on a wx.TreeCtrl and I need to handle both "copy" and "move" operations (if the user keeps CTRL pressed). First of all, I searched the wiki for an example and I'm confused as to which method to use.. Should I use DropSource/DropTarget or just handle EVT_TREE_BEGIN_DRAG and EVT_TREE...
[ "Reading the relevant paragraph from Cross-Platform GUI Programming with wxWidgets gave me the necessary insight to solve the issue :)\nIn the end I went for the first solution (DropSource/DropTarget), so:\ntree.SetDropTarget(MyDropTarget())\ntree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.on_drag)\ntree.GetMainWindow().Bin...
[ 3 ]
[]
[]
[ "drag_and_drop", "python", "wxpython" ]
stackoverflow_0003803386_drag_and_drop_python_wxpython.txt
Q: network programming in python how do i run a python program that is received by a client from server without writing it into a new python file? A: code = "for a in range(10):\n\tprint 'lol'\n" eval(compile(code, 'downloaded_code_fake_filename', 'exec')) but Beware of Security Issues ! The source code should be ...
network programming in python
how do i run a python program that is received by a client from server without writing it into a new python file?
[ "code = \"for a in range(10):\\n\\tprint 'lol'\\n\"\neval(compile(code, 'downloaded_code_fake_filename', 'exec'))\n\nbut Beware of Security Issues ! The source code should be cryptographically signed and not transmitted in plaintext.\n", "I'd recommend using execnet. It's well supported and from what I've read m...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003798067_python.txt
Q: uploading records of list of files in parallel using python to DB I have a list of files each file have mass of records separting by \n , i need to proccess those records in parallel and upload them to some sql server could someone provide an idea what is the best way to do this with python A: The best way migh...
uploading records of list of files in parallel using python to DB
I have a list of files each file have mass of records separting by \n , i need to proccess those records in parallel and upload them to some sql server could someone provide an idea what is the best way to do this with python
[ "The best way might not be to upload in parallell but use SQL Servers bulk importing mechanisims\ne.g.\nBULK INSERT\nbcp\nEDIT:\nIf you need to process them then a way I have often used is\n1) bulk load the data into a staging table\n2) Process the data on the database\n3) Insert into main tables \nStages 2 and 3 ...
[ 1, 0 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0003802800_asynchronous_multithreading_python.txt
Q: Does File exist in Python? Possible Duplicate: Pythonic way to check if a file exists? How can Check if file exist with python 2.6? If file exists run exec redo.py. If file does not exists exec file start.py The file is a 0kb, but name Xxx100926.csv Ans seems to be from os path import exists from __future__ ...
Does File exist in Python?
Possible Duplicate: Pythonic way to check if a file exists? How can Check if file exist with python 2.6? If file exists run exec redo.py. If file does not exists exec file start.py The file is a 0kb, but name Xxx100926.csv Ans seems to be from os path import exists from __future__ import with_statement if e...
[ "you can put main function in redo.py and start.py and then\nfrom os path import exists\n\nif exists('Xxx100926.csv'):\n from redo import main\nelse:\n from start import main\n\n#and run main function\nmain()\n\n" ]
[ 3 ]
[]
[]
[ "exists", "file_io", "path", "python" ]
stackoverflow_0003805132_exists_file_io_path_python.txt
Q: Inserting additional items into an inherited list in Django/Python I'm using some subclasses in my Django app, and I'm continuing that logic through to my admin implementation. Currently, I have this admin defintion: class StellarObjectAdmin(admin.ModelAdmin): list_display = ('title','created_at','created_by','u...
Inserting additional items into an inherited list in Django/Python
I'm using some subclasses in my Django app, and I'm continuing that logic through to my admin implementation. Currently, I have this admin defintion: class StellarObjectAdmin(admin.ModelAdmin): list_display = ('title','created_at','created_by','updated_at','updated_by) Now, I have a Planet class, that is a subclass ...
[ "You'll need to use:\nStellarObjectAdmin.list_display.insert(1, 'size')\n\nAlso, you'll need to change list_display from a tuple (which is immutable) to a list. Eg: list_display = [ ... ].\nFinally, you'll probably be surprised by what happens: by inserting the item, you're going to be changing the list on StellarO...
[ 2, 1 ]
[]
[]
[ "django", "django_admin", "list", "python" ]
stackoverflow_0003804666_django_django_admin_list_python.txt
Q: run out of system resource (execute many programs in a shell script) I'm running a shell script on the university's server. In this shell script, I will execute java, c, c++, python and perl programs. Because every program will be executed many many times(I'm a teaching assistant and will test the students' progra...
run out of system resource (execute many programs in a shell script)
I'm running a shell script on the university's server. In this shell script, I will execute java, c, c++, python and perl programs. Because every program will be executed many many times(I'm a teaching assistant and will test the students' programs with many different inputs). The server always gives me an error: "runn...
[ "You seem to be running maxconnect4, then waitng for it to finish before starting the next run, so I don't think your shell script itself is the isuue. The big question is what maxconnect4 is doing. It could be very hungry for resources, or it itself could start child processes and return to your script.\nI would t...
[ 1, 1 ]
[]
[]
[ "c", "c++", "java", "python", "shell" ]
stackoverflow_0003801552_c_c++_java_python_shell.txt
Q: C# vs Python: XML Handling/Processing Productivity I am planning on writing a medium size web application that will be XML heavy. I will need to do heavy xml processing. When a user requests a webpage the program will fetch the XML from the database then it will process the XML then render the results to the brows...
C# vs Python: XML Handling/Processing Productivity
I am planning on writing a medium size web application that will be XML heavy. I will need to do heavy xml processing. When a user requests a webpage the program will fetch the XML from the database then it will process the XML then render the results to the browser. The XML is not big but i will need to make changes t...
[ "I am not familiar with C# but I dare say that it can competently mangle XML. So can Python, especially if you use something like lxml. Given this, and not knowing more about your specific background, I'd say it boils down to choice of programming language. If you like Python, Django is probably the most popular we...
[ 4, 4 ]
[]
[]
[ "asp.net_mvc_2", "c#", "django", "python" ]
stackoverflow_0003805563_asp.net_mvc_2_c#_django_python.txt
Q: Matplotlib draw boxes I have a set of data, where each value has a (x, y) coordinate. Different values can have the same coordinate. And I want to draw them in a rectangular collection of boxes. For example, if I have the data: A -> (0, 0) B -> (0, 1) C -> (1, 2) D -> (0, 1) I want to get the following drawing: ...
Matplotlib draw boxes
I have a set of data, where each value has a (x, y) coordinate. Different values can have the same coordinate. And I want to draw them in a rectangular collection of boxes. For example, if I have the data: A -> (0, 0) B -> (0, 1) C -> (1, 2) D -> (0, 1) I want to get the following drawing: 0 1 2 ++++++++++++...
[ "Just thought, maybe what you actually wanted to know was just this:\ndef drawbox(list,x,y):\n # write some graphics code to draw box index x,y containing items 'list'\n\n[[drawbox(u,x,y) for u in X.keys() if X[u]==(y,x)] for x in range(0,3) for y in range(0,3)]\n\n", "Perhaps it would be better to use the Repor...
[ 2, 1, 1 ]
[]
[]
[ "drawing", "matplotlib", "python" ]
stackoverflow_0003805000_drawing_matplotlib_python.txt
Q: Convert ascii encoding to int and back again in python (quickly) I have a file format (fastq format) that encodes a string of integers as a string where each integer is represented by an ascii code with an offset. Unfortunately, there are two encodings in common use, one with an offset of 33 and the other with an...
Convert ascii encoding to int and back again in python (quickly)
I have a file format (fastq format) that encodes a string of integers as a string where each integer is represented by an ascii code with an offset. Unfortunately, there are two encodings in common use, one with an offset of 33 and the other with an offset of 64. I typically have several 100 million strings of length...
[ "If you look at the code for urllib.quote, there is something that is similar to what you're doing. It looks like:\n_map = {}\ndef phred64ToStdqual2(qualin):\n if not _map:\n for i in range(31, 127):\n _map[chr(i)] = chr(i - 31)\n return ''.join(map(_map.__getitem__, qualin))\n\nNote that th...
[ 4 ]
[]
[]
[ "algorithm", "cython", "performance", "python" ]
stackoverflow_0003805763_algorithm_cython_performance_python.txt
Q: My facebook authentication is not working? I changed my domain from abc.com to xyz.com. After that my facebook authentication is not working. It is throwing a key error KeyError: 'access_token'I am using python as my language. A: You probably need to update the domain in the facebook settings/api key which allow...
My facebook authentication is not working?
I changed my domain from abc.com to xyz.com. After that my facebook authentication is not working. It is throwing a key error KeyError: 'access_token'I am using python as my language.
[ "You probably need to update the domain in the facebook settings/api key which allow you access.\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003806082_facebook_python.txt
Q: Django web interface components I am using python and django and like it a lot. But than i use it, I catch myself thinking what i do a lot of work to render result data and write specific actions for it. For example than i pass result set of objects to template i must render all data and write all possible actions...
Django web interface components
I am using python and django and like it a lot. But than i use it, I catch myself thinking what i do a lot of work to render result data and write specific actions for it. For example than i pass result set of objects to template i must render all data and write all possible actions such as sorting by columns,filtering...
[ "\nmust render all data and write all\n possible actions such as sorting by\n columns,filtering,deletion,edit etc\n\nLike django.contrib.admin? But I guess it's way to complicated and bloated for your needs.\n\nsometimes helps generic view but it's\n has poor functions\n\nAnd that's the way, I think, you should ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003805970_django_python.txt
Q: How do I create a Django model field that evaluates based on other fields? I'll try to describe my problem with a simple example. Say I have items of type Item and every item relates to a certain type of Category. Now I can take any two items and combine into an itemcombo of type ItemCombo. This itemcombo relates ...
How do I create a Django model field that evaluates based on other fields?
I'll try to describe my problem with a simple example. Say I have items of type Item and every item relates to a certain type of Category. Now I can take any two items and combine into an itemcombo of type ItemCombo. This itemcombo relates to a certain category called ComboCategory. The ComboCategory is based on which ...
[ "Your model classes are full Python classes, so you can add attributes, methods, and properties to them:\nclass ItemCombo(models.Model):\n item1 = models.ForeignKey(Item)\n item2 = models.ForeignKey(Item)\n\n @property\n def combocategory(self):\n return .. # some mumbo-jumbo of i...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003804502_django_django_models_python.txt
Q: Python regular expressions what is the regular expressions that will identify the class of valid NRIC numbers (inclusive of the ending alphabets) A: Assuming you mean the Singaporean National Registration Identity Card, try: ^[SFTG]\d{7}[A-Z]$ This follows the structure documented by Wikipedia. Note that the l...
Python regular expressions
what is the regular expressions that will identify the class of valid NRIC numbers (inclusive of the ending alphabets)
[ "Assuming you mean the Singaporean National Registration Identity Card, try:\n^[SFTG]\\d{7}[A-Z]$\n\nThis follows the structure documented by Wikipedia.\nNote that the last letter is a checksum, and that if you want to check the checksum you’ll have to do so separately.\n", "Regex patterns for many common uses ca...
[ 5, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003806155_python_regex.txt
Q: New to google app engine ! what to do next? I want to develop some web apps using Google app engine. I had deployed a guest book application which was their in "gooleappengine" folder by changing its ID.and also was successful.This is simple one.But not getting how to develop complex web apps. Can anyone please su...
New to google app engine ! what to do next?
I want to develop some web apps using Google app engine. I had deployed a guest book application which was their in "gooleappengine" folder by changing its ID.and also was successful.This is simple one.But not getting how to develop complex web apps. Can anyone please suggest me any good Tutarial or example codes Or an...
[ "Here are some good resources :\nArticles :\n\nOfficial documentation :\nhttp://code.google.com/appengine/docs/python/overview.html\nNick Johnson's blog :\nhttp://blog.notdot.net\nGoogle App Engine articles :\nhttp://code.google.com/appengine/articles/\n\nCode examples :\n\nGoogle App Engine Cookbook :\nhttp://appe...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003805802_google_app_engine_python.txt
Q: How to get field with ForeignKey('self') without the possibility to link to same entry? I came in touch with a little problem while building a model with a foreign key to itself. Here an example: class Example (model.Model): parent = models.ForeignKey('self', null=True, blank=True) # and some other fields ...
How to get field with ForeignKey('self') without the possibility to link to same entry?
I came in touch with a little problem while building a model with a foreign key to itself. Here an example: class Example (model.Model): parent = models.ForeignKey('self', null=True, blank=True) # and some other fields After creating a new entry in the admin panel and going into this example for editing some c...
[ "one way to do this would be to override the model's clean method\nclass Example(model.Model):\n #...\n def clean(self):\n if self.parent.id == self.id:\n raise ValidationError(\"no self referential models\")\n\nthis will be called as the second step of object validation and will prevent the...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003806346_django_django_models_python.txt
Q: How to change my wx.toolbar event? I have a wx.toolbar with some buttons. One of the buttons makes pan left! I want to click on the button and while I keep it pressed, the pan left is made. For now I only saw that the wx.EVT_TOOL only works when mouse left is up. Is there a way to do what I intend ? A: In the to...
How to change my wx.toolbar event?
I have a wx.toolbar with some buttons. One of the buttons makes pan left! I want to click on the button and while I keep it pressed, the pan left is made. For now I only saw that the wx.EVT_TOOL only works when mouse left is up. Is there a way to do what I intend ?
[ "In the toolbar button's event, you should be able to get the state of the mouse via wx.GetMouseState.\nAlternatively, you can make your own toolbar with a panel and some wx.Buttons (or other button widgets).\n" ]
[ 1 ]
[]
[]
[ "events", "mouseevent", "python", "wxpython" ]
stackoverflow_0003793526_events_mouseevent_python_wxpython.txt
Q: PyObject_CallFunction Access violation writing location 0x0000000c I am trying to wrap a c communication library in python and am having some trouble when I attempt to handle large amounts of data. The following code will work for smaller messages but when the message is larger than 400MB I get the following error...
PyObject_CallFunction Access violation writing location 0x0000000c
I am trying to wrap a c communication library in python and am having some trouble when I attempt to handle large amounts of data. The following code will work for smaller messages but when the message is larger than 400MB I get the following error from the PyObject_CallFunction call: Unhandled exception at 0x1e00d65f ...
[ "After debugging the code further it is actually a problem with the the python code that uses the string. The string is a google protocol buffer and when the data is written from a file and the bytes are parsed I can catch a python exception thrown by the library.\n" ]
[ 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003805025_c_python.txt
Q: Function to validate an E-mail (IDN aware) Is there any python function that validates E-mail addresses, aware of IDN domains ? For instance, user@example.com should be as correct as user@zääz.de or user@納豆.ac.jp Thanks. A: Django supports IDN email validation as of version 1.2. See the code for validation here...
Function to validate an E-mail (IDN aware)
Is there any python function that validates E-mail addresses, aware of IDN domains ? For instance, user@example.com should be as correct as user@zääz.de or user@納豆.ac.jp Thanks.
[ "Django supports IDN email validation as of version 1.2. \nSee the code for validation here: http://code.djangoproject.com/svn/django/trunk/django/core/validators.py\nReference: http://docs.djangoproject.com/en/1.2/ref/forms/fields/#emailfield\nExample:\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003806393_python.txt
Q: Altering data in GQL I need to change values for an entry, but the following code doesn't work. logList = db.GqlQuery("SELECT * FROM Log ORDER BY date DESC LIMIT 1") logList[0].content = "some text" db.put(logList) The value for the newest element doesn't change when I run this. I checked the output with Print, ...
Altering data in GQL
I need to change values for an entry, but the following code doesn't work. logList = db.GqlQuery("SELECT * FROM Log ORDER BY date DESC LIMIT 1") logList[0].content = "some text" db.put(logList) The value for the newest element doesn't change when I run this. I checked the output with Print, it gives correct value (to...
[ "logList = db.GqlQuery(\"SELECT * FROM Log ORDER BY date DESC LIMIT 1\")\nresult = logList.get()\nresult.content = \"some text\"\nresult.put()\n\nTry this. You are confusing the GqlQuery object for the results of actually eexecuting the query.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003806023_google_app_engine_gql_python.txt
Q: Subsetting data in Python I want to use the equivalent of the subset command in R for some Python code I am writing. Here is my data: col1 col2 col3 col4 col5 100002 2006 1.1 0.01 6352 100002 2006 1.2 0.84 304518 100002 2006 2 1.52 148219 100002 2007 1.1 0.01 6292 10002 ...
Subsetting data in Python
I want to use the equivalent of the subset command in R for some Python code I am writing. Here is my data: col1 col2 col3 col4 col5 100002 2006 1.1 0.01 6352 100002 2006 1.2 0.84 304518 100002 2006 2 1.52 148219 100002 2007 1.1 0.01 6292 10002 2006 1.1 0.01 5968 10002 ...
[ "While the iterator-based answers are perfectly fine, if you're working with numpy arrays (as you mention that you are) there are better and faster ways of selecting things:\nimport numpy as np\ndata = np.array([\n [100002, 2006, 1.1, 0.01, 6352],\n [100002, 2006, 1.2, 0.84, 304518],\n [100002,...
[ 21, 5, 2 ]
[]
[]
[ "arrays", "numpy", "python", "r", "subset" ]
stackoverflow_0003806878_arrays_numpy_python_r_subset.txt
Q: how to have command as input for a shell launched inside a python subprocess I want to create a GUI python script to launch several processes. All of these processes originally were called by setting up a shell with a perl script (start_workspace.perl), and type the executable file name under the shell. inside, s...
how to have command as input for a shell launched inside a python subprocess
I want to create a GUI python script to launch several processes. All of these processes originally were called by setting up a shell with a perl script (start_workspace.perl), and type the executable file name under the shell. inside, start_workspace.perl, it first set some ENV variables, and then call exec(/bin/bash...
[ "You are very close. In the subprocess documentation, see:\n\nstdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indica...
[ 2, 1 ]
[]
[]
[ "command", "input", "python", "subprocess" ]
stackoverflow_0003806784_command_input_python_subprocess.txt
Q: AI and Design of an El-fish like simulator environment? first post here on stack overflow, hoping to get some advice on how to construct a simulation program akin to the 1993 maxis simulator known as El-Fish wiki here , Also, game info here . Are there known "Simulation system" algorithm groups that can function a...
AI and Design of an El-fish like simulator environment?
first post here on stack overflow, hoping to get some advice on how to construct a simulation program akin to the 1993 maxis simulator known as El-Fish wiki here , Also, game info here . Are there known "Simulation system" algorithm groups that can function and create real life interaction etc... e.g. the visualization...
[ "In terms of simulation systems, I recommend you search for \"agent-based modeling\" software. There are a lot of free toolkits available. The two I like the most are NetLogo and Repast.\nAlso, it looks like you are implementing a \"genetic algorithm\". There are many good books and pages on that topic.\nPython is ...
[ 2, 1, 1 ]
[]
[]
[ "artificial_intelligence", "python", "simulation" ]
stackoverflow_0003745093_artificial_intelligence_python_simulation.txt
Q: Printing results in reverse order from raw_input in python When using raw_input in a loop, until a certain character is typed (say 'a'), how can I print all the inputs before that, in reverse order, without storing the inputs in a data structure? Using a string is simple: def foo(): x = raw_input("Enter chara...
Printing results in reverse order from raw_input in python
When using raw_input in a loop, until a certain character is typed (say 'a'), how can I print all the inputs before that, in reverse order, without storing the inputs in a data structure? Using a string is simple: def foo(): x = raw_input("Enter character: ") string = "" while not (str(x) == "a"): ...
[ "This is not a practical approach, but since you asked for it:\ndef getchar():\n char = raw_input(\"Enter character: \")\n if char != 'a':\n getchar()\n print char\n\ngetchar()\n\nOf course this only means that I'm using \"hidden\" data structures, the local namespace and the call stack.\n", "...
[ 5, 2 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0003807336_python_raw_input.txt
Q: python, subprocess: reading output from subprocess I have following script: #!/usr/bin/python while True: x = raw_input() print x[::-1] I am calling it from ipython: In [5]: p = Popen('./script.py', stdin=PIPE) In [6]: p.stdin.write('abc\n') cba and it works fine. However, when I do this: In [7]: p = P...
python, subprocess: reading output from subprocess
I have following script: #!/usr/bin/python while True: x = raw_input() print x[::-1] I am calling it from ipython: In [5]: p = Popen('./script.py', stdin=PIPE) In [6]: p.stdin.write('abc\n') cba and it works fine. However, when I do this: In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [8]: p....
[ "I believe there are two problems at work here:\n1) Your parent script calls p.stdout.read(), which will read all data until end-of-file. However, your child script runs in an infinite loop so end-of-file will never happen. Probably you want p.stdout.readline()?\n2) In interactive mode, most programs do buffer on...
[ 15, 3, 3, 1, 1 ]
[ "Use communicate() instead of .stdout.read().\nExample:\nfrom subprocess import Popen, PIPE\np = Popen('./script.py', stdin=PIPE, stdout=PIPE, stderr=PIPE)\ninput = 'abc\\n'\nstdout, stderr = p.communicate(input)\n\nThis recommendation comes from the Popen objects section in the subprocess documentation:\n\nWarning...
[ -3 ]
[ "python", "stdout", "subprocess" ]
stackoverflow_0003804727_python_stdout_subprocess.txt
Q: How to construct GQL to not contain a value from a set? Is it possible to select from a google app engine db where the key of a db.Model object is not in a given list? If so, what would be the syntax? Ex of a model class: class Spam(db.Model): field1 = db.BooleanProperty(default=false) field2 = db.Integer...
How to construct GQL to not contain a value from a set?
Is it possible to select from a google app engine db where the key of a db.Model object is not in a given list? If so, what would be the syntax? Ex of a model class: class Spam(db.Model): field1 = db.BooleanProperty(default=false) field2 = db.IntegerProperty() Example of a query which I'd like to work but can...
[ "No Though app engine supports an \"IN\" query, it does not support a \"NOT IN\" query.\nHowever, if your list of entities you don't want is small, then you might as well just retrieve every entity and filter out the ones you don't need yourself.\nAlternatively, if the list of entities you want to exclude is a lar...
[ 6 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python" ]
stackoverflow_0003807591_google_app_engine_gql_gqlquery_python.txt
Q: Django TemplateSyntaxError I am getting a TemplateSyntaxError, that is only happening on my dev server, but works fine on the django testing server locally. Here's the error Caught SyntaxError while rendering: invalid syntax (urls.py, line 1) and the html: <li><a href="{% url plan.views.profile %}">Plan Details</...
Django TemplateSyntaxError
I am getting a TemplateSyntaxError, that is only happening on my dev server, but works fine on the django testing server locally. Here's the error Caught SyntaxError while rendering: invalid syntax (urls.py, line 1) and the html: <li><a href="{% url plan.views.profile %}">Plan Details</a></li> and here is the profile...
[ "In your urls.py use named urls via url function ie.\nurlpatterns = patterns('your_app.views',\n url(r'^somehiing/$', 'your_view_function', name='my_view'),\n)\n\nThen in your template use {% url my_view %}.\nIf it will not help, paste here your urls.py - maybe it's just some tiny syntax error.\n", "Here's one...
[ 3, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003807401_django_django_templates_python.txt
Q: Set timeout on getaddrinfo() in Python Is it possible to set a timeout on a getaddrinfo() call in CPython 2.7? socket.setdefaulttimeout() does not work. I don't really want a solution that wraps a function using threads or signals. A solution that only uses the standard library is best, but using a third-party p...
Set timeout on getaddrinfo() in Python
Is it possible to set a timeout on a getaddrinfo() call in CPython 2.7? socket.setdefaulttimeout() does not work. I don't really want a solution that wraps a function using threads or signals. A solution that only uses the standard library is best, but using a third-party package would be acceptable. For example, I w...
[ "My understanding is that getaddrinfo is wrapper over OS provided library:\nOn unix:\nint getaddrinfo(const char *nodename, const char *servname,\n const struct addrinfo *hints, struct addrinfo **res);\n\nOn Windows:\nint WSAAPI getaddrinfo(\n __in_opt PCSTR pNodeName,\n __in_opt PCSTR pServiceNa...
[ 4 ]
[]
[]
[ "python", "sockets", "timeout" ]
stackoverflow_0003807822_python_sockets_timeout.txt
Q: Google Apps Engine / Django, calling action upon user login? I'm new to Google Apps Engine (working on an existing project for someone else) and it seems a bit different than Django as far as the login as the login is handled by Google, I'm trying to make it so the app creates a custom cookie for a user upon their...
Google Apps Engine / Django, calling action upon user login?
I'm new to Google Apps Engine (working on an existing project for someone else) and it seems a bit different than Django as far as the login as the login is handled by Google, I'm trying to make it so the app creates a custom cookie for a user upon their logging in but can't seem to find the handler for the login actio...
[ "I solved that problem using the Django middleware system and a session. I think the use of a session is the best way to guarantee that the action only happens on login (whereas an url can be reloaded manually).\nDjango sessions does not work out of the box, so I implemented my own sessions. However, there exists g...
[ 0 ]
[]
[]
[ "authentication", "django", "google_app_engine", "python", "session" ]
stackoverflow_0003773956_authentication_django_google_app_engine_python_session.txt
Q: Pass success_url to the activate Docs say : ``success_url`` The name of a URL pattern to redirect to on successful acivation. This is optional; if not specified, this will be obtained by calling the backend's ``post_activation_redirect()`` method. How can I do it ? A: You can do it in your ur...
Pass success_url to the activate
Docs say : ``success_url`` The name of a URL pattern to redirect to on successful acivation. This is optional; if not specified, this will be obtained by calling the backend's ``post_activation_redirect()`` method. How can I do it ?
[ "You can do it in your urls.py, e.g.:\nurl(r'^account/activate/(?P<activation_key>\\w+)/$', 'registration.views.activate', {'success_url': 'registration_activation_complete'}, name='registration_activate'),\nurl(r'^account/activate/success/$', direct_to_template, {'template': 'registration/activation_complete.html'...
[ 7 ]
[]
[]
[ "django", "django_registration", "python" ]
stackoverflow_0003808241_django_django_registration_python.txt
Q: twisted: unhelpful "AlreadyCalled" error My twisted python program keeps spewing this message ever so often: Unhandled error in Deferred: Traceback (most recent call last): File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 757, in gotResult _inlineCallbacks(r, g, deferred) File "c:\pyth...
twisted: unhelpful "AlreadyCalled" error
My twisted python program keeps spewing this message ever so often: Unhandled error in Deferred: Traceback (most recent call last): File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 757, in gotResult _inlineCallbacks(r, g, deferred) File "c:\python25\lib\site-packages\twisted\internet\defer....
[ "If you don't have any other hints about what's going wrong (like your unit tests pointing out the specific cases which cause this, or if pyfunc's answer doesn't make it obvious why this would be happening) then enable Deferred debugging to get information about where the first (and only allowed) result of the Defe...
[ 7, 2 ]
[]
[]
[ "debugging", "python", "twisted" ]
stackoverflow_0003807666_debugging_python_twisted.txt
Q: Django Google app engine reference issues I am working on an application on Django and google application engine. In my application I have several models with several ReferenceProperty fields. The issue is that if any of the ReferenceProperty field gets deleted it produces a ReferenceProperty related errors in al...
Django Google app engine reference issues
I am working on an application on Django and google application engine. In my application I have several models with several ReferenceProperty fields. The issue is that if any of the ReferenceProperty field gets deleted it produces a ReferenceProperty related errors in all the other models where it has been used. What...
[ "You could also just set a flag, say deleted, on the entity you're deleting, and then leave it in the datastore. This has the advantage of avoiding all referential integrity problems in the first place, but it comes at the cost of two main disadvantages:\n\nAll your existing queries need to be changed to deal with ...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003759003_django_django_models_google_app_engine_google_cloud_datastore_python.txt
Q: Mapping Languages to Paradigms I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today. His advice is that it's not so important wh...
Mapping Languages to Paradigms
I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today. His advice is that it's not so important which specific languages a programmer ...
[ "I think you're approaching it wrong. As esr himself says, it's not the language that matters, it's the paradigm. So when you say that \n\n\nPerl is a functional language\nIt's great for quick text substitutions in multiple files from the command line\n\n\nyou are missing one of the main points of a functional lang...
[ 11 ]
[ "If you can, go to a school that will give you experience with a variety of languages.\n\nPython: multi-paradigm, focused on OO and polymorphism-based generic programming.\nC/C++: Are two separate languages. Having grouped them together reflects ESR's level of, er, practicality.\n\nC: classic imperative language.\n...
[ -2, -2 ]
[ "c++", "java", "lisp", "perl", "python" ]
stackoverflow_0003793030_c++_java_lisp_perl_python.txt