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: Code organization in Python: Where is a good place to put obscure methods? I have a class called Path for which there are defined about 10 methods, in a dedicated module Path.py. Recently I had a need to write 5 more methods for Path, however these new methods are quite obscure and technical and 90% of the time th...
Code organization in Python: Where is a good place to put obscure methods?
I have a class called Path for which there are defined about 10 methods, in a dedicated module Path.py. Recently I had a need to write 5 more methods for Path, however these new methods are quite obscure and technical and 90% of the time they are irrelevant. Where would be a good place to put them so their context is c...
[ "If the method is relevant to the Path - no matter how obscure - I think it should reside within the class itself.\nIf you have multiple places where you have path-related functionality, it leads to problems. For example, if you want to check if some functionality already exists, how will a new programmer know to c...
[ 4, 2, 0, 0, 0, 0 ]
[]
[]
[ "code_organization", "python" ]
stackoverflow_0001383590_code_organization_python.txt
Q: Tornado Web and Threads I am new to Tornado and Python Threads. What I would like to achieve is the following: I have a Tornado web server which takes requests from users. I want to store some of the data locally and write it periodically to a data base as bulk-inserts. import tornado.ioloop import tornado.web imp...
Tornado Web and Threads
I am new to Tornado and Python Threads. What I would like to achieve is the following: I have a Tornado web server which takes requests from users. I want to store some of the data locally and write it periodically to a data base as bulk-inserts. import tornado.ioloop import tornado.web import threading # Keep userDat...
[ "Tornado is not intended to be used with multithreading. It's based on epoll to switch context between different parts of code.\nIn general I would recommend sending the data to separate worker process via message queue (like pika+RabbitMQ, it integrates very well with Tornado). Worker process(es) can accumulate me...
[ 7 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0007846323_python_tornado.txt
Q: Appending a process to a list (but doing nothing with it) alters program behaviour In the following program, when I append the process to a list (a seemingly pointless thing to do), it runs as expected. But if I remove the append, the processes destructor is called many times before it is even run. There are only ...
Appending a process to a list (but doing nothing with it) alters program behaviour
In the following program, when I append the process to a list (a seemingly pointless thing to do), it runs as expected. But if I remove the append, the processes destructor is called many times before it is even run. There are only n constructions but (n)(n+1)/2 (where n is the number of processes) destructions. This l...
[ "Adding the object to a list will prevent it from being deleted in child processes because after forking it will call \"os._exit()\" instead of clearing the whole stack\nThe relevant code is in multiprocessing/forking.py (constructor of Popen, which is called on \"p.start()\")\n self.pid = os.fork()\n if self.pid =...
[ 1 ]
[]
[]
[ "multiprocessing", "python", "python_3.x", "subprocess" ]
stackoverflow_0008023127_multiprocessing_python_python_3.x_subprocess.txt
Q: web presenting framework for SQLObject/SQLAlchemy projects I'm looking for the most graceful way of taking a non-web project based on either SQLObject or SQLAlchemy and overlay it with a decent web-framework. I've looked at Turbogears, and even though it looks like something I could use, the models seems to have t...
web presenting framework for SQLObject/SQLAlchemy projects
I'm looking for the most graceful way of taking a non-web project based on either SQLObject or SQLAlchemy and overlay it with a decent web-framework. I've looked at Turbogears, and even though it looks like something I could use, the models seems to have to be defined inside the Turbogears framework. I want the core fu...
[ "For this kind of thing you might have a look at Pyramid. It is very flexible in that it doesn't enforce any particular group of components (template, database engine, etc.). You could use it with either SqlObject or SqlAlchemy - it's up to you to configure it to your needs. Fortunately it is also very well documen...
[ 3, 1, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlobject", "turbogears2" ]
stackoverflow_0007458205_python_sqlalchemy_sqlobject_turbogears2.txt
Q: Tornado Cookies I am using Apache and PHP as my front-end server and Tornado as my back-end to handle my requests. When allowing a user to login I want to create cookies for the username and password. If I do it as follows: self.set_cookie('emailaddress', email_address, domain='mydomain.com', expires=None, path...
Tornado Cookies
I am using Apache and PHP as my front-end server and Tornado as my back-end to handle my requests. When allowing a user to login I want to create cookies for the username and password. If I do it as follows: self.set_cookie('emailaddress', email_address, domain='mydomain.com', expires=None, path='/', expires_days=ex...
[ "Yes, it seems like the problem is related to subdomains if you are using them to route between Tornado and PHP, without details on this it's hard to tell how to fix it.\nBut in general maybe it will be a good idea to just map Tornado to some relative url on a main domain and do not mess with subdomains?\nP.S.: sto...
[ 2 ]
[]
[]
[ "apache", "cookies", "php", "python", "tornado" ]
stackoverflow_0007974357_apache_cookies_php_python_tornado.txt
Q: rearding regex (python) I have long strings. Like this {{ name = name prodcuer =producer writer = writer language = {{english}} country = USA }} Here is text I Need This paragraph.; I don't want text between {{ }}. I tried with regex but not found any luck. Can anyone help me please? A: He...
rearding regex (python)
I have long strings. Like this {{ name = name prodcuer =producer writer = writer language = {{english}} country = USA }} Here is text I Need This paragraph.; I don't want text between {{ }}. I tried with regex but not found any luck. Can anyone help me please?
[ "Here: http://rubular.com/r/CCW7sAUMrs is an example regex that matches whole text within {{ }}. \nYou can easily clean up Your string with it using re.sub.\nNote, that it will not work when You have text like {{test}} paragraph {{test}}, because it will match whole string.\nAs larsmans said, it gets harder if You ...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008028729_python_regex.txt
Q: How to undo a Python setuptools --prefix path blunder When I installed Python's setuptools I absent mindedly tacked on a --prefix path I had been using on another machine: sh setuptools-0.6c11-py2.7.egg --prefix=/opt/python2.7.2 Now after this blunder when I try to install pip I get the following error: [root@kk...
How to undo a Python setuptools --prefix path blunder
When I installed Python's setuptools I absent mindedly tacked on a --prefix path I had been using on another machine: sh setuptools-0.6c11-py2.7.egg --prefix=/opt/python2.7.2 Now after this blunder when I try to install pip I get the following error: [root@kkdev src]# easy_install pip Searching for pip Best match: pi...
[ "I managed to get back to square one by using brute force and eradicating any and all evidence of setuptools, easy_install and pip from my site-packages folder.\nAfter that I re-ran sh setuptools-0.6c11-py2.7.egg without the --prefix switch and things are as they should be now.\n", "easy_install --help mentions t...
[ 1, 0 ]
[]
[]
[ "pip", "python", "setuptools" ]
stackoverflow_0008022240_pip_python_setuptools.txt
Q: Socket.io handler using Gevent / Tornado & Flask can anyone show me and example of how to handle a generic socket.io connection (depends on the client browser, could be websockets, or xhr-longpolling, etc..) using gevent and flask, or maybe flask with tornado as an async server thank you A: TornadIO works well e...
Socket.io handler using Gevent / Tornado & Flask
can anyone show me and example of how to handle a generic socket.io connection (depends on the client browser, could be websockets, or xhr-longpolling, etc..) using gevent and flask, or maybe flask with tornado as an async server thank you
[ "TornadIO works well enough with stable version of socket.io (0.6), it integrates into any Tornado-powered application as a common request handler, wrapped around class with socket events callbacks. Works pretty stable.\nBut I'd recommend not to use the provided SocketServer class and just configure correctly the c...
[ 3 ]
[]
[]
[ "flask", "gevent", "python", "socket.io", "tornado" ]
stackoverflow_0007533386_flask_gevent_python_socket.io_tornado.txt
Q: Open Passive FTP (Socket) connection using Python I am trying to connect to an FTP server in Passive mode from Python (through Socket) i am doing it this way: mftp = socket (AF_INET, SOCK_STREAM) mftp.connect((serverHost, 21)) print mftp.recv(1024) print mftp.close() but this command (.connect) i believe opens an...
Open Passive FTP (Socket) connection using Python
I am trying to connect to an FTP server in Passive mode from Python (through Socket) i am doing it this way: mftp = socket (AF_INET, SOCK_STREAM) mftp.connect((serverHost, 21)) print mftp.recv(1024) print mftp.close() but this command (.connect) i believe opens an active connection to the server. How can i open a pass...
[ "Not answering your question... but did you know Python has an FTP module as part of its standard library? It might be suitable for your needs, and could save you a lot of time.\n" ]
[ 0 ]
[]
[]
[ "ftp", "python", "sockets" ]
stackoverflow_0008028970_ftp_python_sockets.txt
Q: Asyncmongo not return _id Use PyMongo: import pymongo conn=pymongo.Connection(host='127.0.0.1',port=27017) db=conn.cms db.comments.save({'content':'test', 'user':'admin'}) Then return: ObjectId('4ea175b96e955237aa000000') That all right with PyMongo. But I cannot get _id in response when I use AsyncMongo. class ...
Asyncmongo not return _id
Use PyMongo: import pymongo conn=pymongo.Connection(host='127.0.0.1',port=27017) db=conn.cms db.comments.save({'content':'test', 'user':'admin'}) Then return: ObjectId('4ea175b96e955237aa000000') That all right with PyMongo. But I cannot get _id in response when I use AsyncMongo. class PoCommentsHandler(BaseClass): ...
[ "There is nothing wrong, the MongoDB itself does not return id of just inserted document, the pymongo does it for you. There is asynchronous implementation of pymongo API (also on Tornado IOLoop) called APyMongo, which should behave as you expected.\nMore on this topic could be found in this google groups thread: h...
[ 0 ]
[]
[]
[ "mongodb", "python", "tornado" ]
stackoverflow_0007850306_mongodb_python_tornado.txt
Q: Subprocess completes but still doesn't terminate, causing deadlock Ok, since there are currently no answer's I don't feel too bad doing this. While I'm still interested in what is actually happening behind the scenes to cause this problem, my most urgent questions are those specified in update 2. Those being, What...
Subprocess completes but still doesn't terminate, causing deadlock
Ok, since there are currently no answer's I don't feel too bad doing this. While I'm still interested in what is actually happening behind the scenes to cause this problem, my most urgent questions are those specified in update 2. Those being, What are the differences between a JoinableQueue and a Manager().Queue() (an...
[ "From the documentation:\n\nWarning\nAs mentioned above, if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread()), then that process will not terminate until all buffered items have been flushed to the pipe.\nThis means that if you try joining that process you may get a d...
[ 0 ]
[]
[]
[ "deadlock", "debugging", "multiprocessing", "python", "python_3.x" ]
stackoverflow_0008026050_deadlock_debugging_multiprocessing_python_python_3.x.txt
Q: Paths and permissions in Windows I wrote a fast and easy hack to walk thru directories (in stepmania song dir), find conf-files and name the directory the conf-files are in to a certain name found in the conf-file. This works great on my linux box. But not at my wives Windows XP-box running as an admin. I get perm...
Paths and permissions in Windows
I wrote a fast and easy hack to walk thru directories (in stepmania song dir), find conf-files and name the directory the conf-files are in to a certain name found in the conf-file. This works great on my linux box. But not at my wives Windows XP-box running as an admin. I get permission-error. What's wrong? Here's the...
[ "Windows can't rename a path that has an open file. It should work if you move the os.rename call out of the with block so that the file is closed. However, you're repeating this for multiple files in the same path, and the directory name in path will no longer exist after you've renamed it. Also, os.walk can't tra...
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0008027386_python_windows.txt
Q: asynchronous call with Tornado and pyodbc I want to implement a web service based on tornado which can provide the database query service for users. I used the pyodbc module to connect to database and do the query. In practice, I found that printing the query result would take a long time. That is to say, if I use...
asynchronous call with Tornado and pyodbc
I want to implement a web service based on tornado which can provide the database query service for users. I used the pyodbc module to connect to database and do the query. In practice, I found that printing the query result would take a long time. That is to say, if I used the following code to print the query result ...
[ "In order to allow the single-threaded Tornado server to be asynchronous in a request like this you have to give control back to the I/O loop. Try this:\nclass LongRequestHandler(tornado.web.RequestHandler):\n def database_callback(self):\n data = self.cur.fetchone()\n if not data:\n se...
[ 0 ]
[]
[]
[ "pyodbc", "python", "tornado" ]
stackoverflow_0005183541_pyodbc_python_tornado.txt
Q: Python Project with Multiple Modules with the same Name I have two different packages with the same name, each with a set of modules and classes with the same names as each other but they are implemented differently. What is the most logical manner to set up my package/module structure? Right now I'm doing somet...
Python Project with Multiple Modules with the same Name
I have two different packages with the same name, each with a set of modules and classes with the same names as each other but they are implemented differently. What is the most logical manner to set up my package/module structure? Right now I'm doing something like: Common utilities.py VersionA Packa...
[ "Define a globally accessible env variable which you will use to select the version (VersionA,VersionB). Then, in Common/__init__.py put:\nimport whenver_you_put_your_env as envloc\n\nif (envloc.env == VersionA)\n import VersionA.Package as Package\nelif (envloc.env == VersionB)\n import VersionB.Package as P...
[ 3 ]
[]
[]
[ "distribution", "module", "package", "python" ]
stackoverflow_0008029174_distribution_module_package_python.txt
Q: scipy -- how to put randomly one array into another? i want to do this: Lets say i have N=100 and myone=scipy.ones(N) which shape is: myone.shape=100, I want the array myzeros=scipy.zeros(c*N) ,c=0.1 to be inserted randomly in the myone array without changing the dimensions of the myone. A: import scipy as sc m...
scipy -- how to put randomly one array into another?
i want to do this: Lets say i have N=100 and myone=scipy.ones(N) which shape is: myone.shape=100, I want the array myzeros=scipy.zeros(c*N) ,c=0.1 to be inserted randomly in the myone array without changing the dimensions of the myone.
[ "import scipy as sc\nmyone = sc.ones(100)\nind = sc.random.permutation(100)[:10]\nmyone[ind] = 0\n\n" ]
[ 2 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0008028381_python_scipy.txt
Q: Error with wxpython sizers I am not sure how I should size this, I have been trying to use sizer but it seems i am doing something wrong all the time. Basically i have this code: self.button = wx.Button(self, label="Create New", pos=(25,250)) and i would like to use a sizer with it. So it will adjust its position...
Error with wxpython sizers
I am not sure how I should size this, I have been trying to use sizer but it seems i am doing something wrong all the time. Basically i have this code: self.button = wx.Button(self, label="Create New", pos=(25,250)) and i would like to use a sizer with it. So it will adjust its position always to the window. The initi...
[ "Here you have a wxglade automatically-generated code showing how to use a wx.BoxSizer.\nIt is simply a Frame with a panel widget. You can change the panel with your button and it will work perfectly. The idea is that you could add other widgets as it is done for the wx.Panel in:\nsizer_2.Add(self.panel_1, 1, wx.EX...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008029113_python_wxpython.txt
Q: How to make admin page of django do this particular thing? I am using the django admin page to put questions into the database. My models.py is this: from django.db import models # Create your models here. class Question(models.Model): question_name = models.CharField(max_length=200) question_type = mode...
How to make admin page of django do this particular thing?
I am using the django admin page to put questions into the database. My models.py is this: from django.db import models # Create your models here. class Question(models.Model): question_name = models.CharField(max_length=200) question_type = models.CharField(max_length=20) def __unicode__(self): ...
[ "Conceptually I think it might be. You can read more about it in the django docs but essentially Django has 3 types of inheritence; abstract, multitable and proxy which are all useful in different situations:\n\nabstract inheritance is useful when your base class will never need to be instantiated itself (i.e. the ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008029317_django_python.txt
Q: Django - Error: No module named x - When trying to reuse apps I am new to django. I have version 1.3.1 installed. I have created two projects: projectone and projecttwo using django-admin.py And in projectone I have an app called blog created using python manage.py startapp In projecttwo setings.py file when put ...
Django - Error: No module named x - When trying to reuse apps
I am new to django. I have version 1.3.1 installed. I have created two projects: projectone and projecttwo using django-admin.py And in projectone I have an app called blog created using python manage.py startapp In projecttwo setings.py file when put the following in installed_apps: INSTALLED_APPS = ( other cod...
[ "Look at what manage.py does:\nhttps://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-py-and-manage-py\nIt dynamically adds your apps to the python path when you use it - i.e. when you are using runserver during development.\nYou have two separate projects so when you run either one you will only have...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008029363_django_python.txt
Q: OpenCV - new Python Bindings and ImageROI? How can I set the ROI on a numpy Array, since the new Python-Bindings (cv2) don't support ImageROI (or maybe I didn't use it right)? I don't want to convert between IPLImage and numpy. Thanks for your help. A: I found a solution by copying parts from the array to a new ...
OpenCV - new Python Bindings and ImageROI?
How can I set the ROI on a numpy Array, since the new Python-Bindings (cv2) don't support ImageROI (or maybe I didn't use it right)? I don't want to convert between IPLImage and numpy. Thanks for your help.
[ "I found a solution by copying parts from the array to a new numpy array. This new numpy-array could be used with every new binding using numpy. :)\na = arr[y:y + size[1], x:x + size[0]] \ntmp = np.array( a, dtype = arr.dtype )\nreturn tmp\n\narr is the numpy-array-image, size is a tuple, x and y are coordinates.\...
[ 2 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0008021270_opencv_python.txt
Q: Isn't there a PRIMARY selection clipboard in windows First of all, its a windows question. Let me introduce you to the linux counterpart. In Linux, when I select a text anywhere in X Windows System, its gets copied to PRIMARY clipboard. Selecting a clipboard & explicitly copying it using Ctrl+C causes it to be co...
Isn't there a PRIMARY selection clipboard in windows
First of all, its a windows question. Let me introduce you to the linux counterpart. In Linux, when I select a text anywhere in X Windows System, its gets copied to PRIMARY clipboard. Selecting a clipboard & explicitly copying it using Ctrl+C causes it to be copied to secondary keyboard. In linux, I made a dictionary...
[ "There is no equivalent in Windows. There is just the single global clipboard which contains a single item, albeit in potentially multiple formats.\n\nI want to retrieve the current selection in the current window.\n\nThat's not trivial in Windows. You can do it using, for example, UI Automation, for apps that supp...
[ 2 ]
[]
[]
[ "linux", "python", "pywin32", "winapi", "windows" ]
stackoverflow_0008029556_linux_python_pywin32_winapi_windows.txt
Q: My regex is not working properly My regex is not working properly. I'm showing you before regex text and after regex text. I'm using this regex re.search(r'(?ms).*?{{(Infobox film.*?)}}', text). You will see my regex not displaying the result after | country = Assam, {{IND . My regex stuck at this point. Wi...
My regex is not working properly
My regex is not working properly. I'm showing you before regex text and after regex text. I'm using this regex re.search(r'(?ms).*?{{(Infobox film.*?)}}', text). You will see my regex not displaying the result after | country = Assam, {{IND . My regex stuck at this point. Will you please help me ? thanks Before ...
[ "Your regex is catching everything between the first {{ and the first }}, which is in the \"country\" entry of the infobox. If you want everything between the first {{ and the last }}, then you want to make the .* inside the braces greedy by removing the ?:\nre.search(r'(?ms).*?{{(Infobox film.*)}}', text)\n\nNote ...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008029633_python_regex.txt
Q: Django - Creating my own CMS - advice on architecture I was planning how I am going to architecture my CMS. And would like some advice: The plan is that I will create a project called CMS. In that I will create an apps folder with various apps such as an admin module, blog module etc... And for each new site I dev...
Django - Creating my own CMS - advice on architecture
I was planning how I am going to architecture my CMS. And would like some advice: The plan is that I will create a project called CMS. In that I will create an apps folder with various apps such as an admin module, blog module etc... And for each new site I develop I will also create that as a new app within the projec...
[ "It is not clear why do you need one application per site? There are 2 possibilities: if the only difference between sites is templates and static files then you do not need separate application for every site. If the difference is more global than that - you should not really combine these sites into one project b...
[ 3 ]
[]
[]
[ "content_management_system", "django", "python" ]
stackoverflow_0008029835_content_management_system_django_python.txt
Q: Regex to differentiate between sentences and chapter text I have a (running) text with many sentences. I have a regular expression that is able to extract the sentences that are terminated by a period, question or exclamation mark. The end of a sentence must be followed by a beginning of the next sentence ( white ...
Regex to differentiate between sentences and chapter text
I have a (running) text with many sentences. I have a regular expression that is able to extract the sentences that are terminated by a period, question or exclamation mark. The end of a sentence must be followed by a beginning of the next sentence ( white spaces/tabs/new lines and a capital letter or number). I read a...
[ "\nSome people, when confronted with a problem, think \"I know, I'll use\n regular expressions.\" Now they have two problems. \n -- Jamie Zawinski\n\nActually, what you should do is use two regular expressions (now you'll have four problems).\nFirst, go through and break up the text into alternating chapter-heade...
[ 3 ]
[]
[]
[ "python", "regex", "text_segmentation" ]
stackoverflow_0008029965_python_regex_text_segmentation.txt
Q: "Child frame inside Father frame inside Grandfather frame" wxPython The idea here is to login (top frame called LoginFrame). Open a child frame (MainFrame) with 2 option (a or b). Each option opens another child frame (with MainFrame as parent). Inside each one is a button to go back to the MainFrame. I used the L...
"Child frame inside Father frame inside Grandfather frame" wxPython
The idea here is to login (top frame called LoginFrame). Open a child frame (MainFrame) with 2 option (a or b). Each option opens another child frame (with MainFrame as parent). Inside each one is a button to go back to the MainFrame. I used the LoginFrame as parent for MainFrame,a and b as a workaround. But I can't ge...
[ "Modify the methods a and b like this:\ndef a(self,event):\n aframe = aFrame(parent=self, id=997) # parent is the MainFrame instance self\n aframe.Centre()\n aframe.Show()\n self.Hide() # Hide the MainFrame instance\n\nThen modify the Frames a and b like this:\nclass bFrame(wx...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008030106_python_wxpython.txt
Q: Can I commit a large file with bazaar, or is there a better approach to versioning a database dump? Bazaar limits the file size that it can commit based on the available virtual memory (according to an open bug). I would like to put a database (as mysqldump text file) under version control. The database is 3 GB an...
Can I commit a large file with bazaar, or is there a better approach to versioning a database dump?
Bazaar limits the file size that it can commit based on the available virtual memory (according to an open bug). I would like to put a database (as mysqldump text file) under version control. The database is 3 GB and I am working on a server with 64GB of memory. I do not understand why this would be a problem. When I a...
[ "Although I love Bazaar, I would not recommend that you use it for this purpose, unless you definitely need to keep every version of your data indefinitely. If in stead you only need a fixed number of past versions (e.g. 10) or only for a fixed period (eg. 2 years), then I'd suggest that you use an incremental back...
[ 2, 1, 0 ]
[ "First, you want to b*ackup things* with bazaar more than using a versionning system. That's different !\nBazaar stores changeset - differences between files - and keep tracker of them and their merge.\nEven if I can understand your point, I think your are not using the right tool.\nAnyway, to answer your question...
[ -2 ]
[ "bazaar", "database", "memory", "python", "version_control" ]
stackoverflow_0008024846_bazaar_database_memory_python_version_control.txt
Q: Unable to seek video in PyQt4 I wrote a simple video player using Phonon in PyQt4. The videos are playing fine. But I am unable to seek the video to given position. This the code I've written: #!/usr/bin/python from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.phonon import Phonon import sys class ...
Unable to seek video in PyQt4
I wrote a simple video player using Phonon in PyQt4. The videos are playing fine. But I am unable to seek the video to given position. This the code I've written: #!/usr/bin/python from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.phonon import Phonon import sys class VideoPlayer(QWidget): def __in...
[ "It is not possible to seek to a position in a media source whilst it is still loading.\nSo connect a handler to the media object's stateChanged signal, and wait until it's state changes to PlayingState before attempting to seek.\nself.player.mediaObject().stateChanged.connect(self.handleStateChanged)\n...\n\ndef h...
[ 1, 0 ]
[]
[]
[ "phonon", "pyqt4", "python" ]
stackoverflow_0008029861_phonon_pyqt4_python.txt
Q: Python: Renaming member in a tar file during extraction Premise I have a directory /foo/bar I have a tar file containing the directory baz Problem Extracting the contents of baz in the archive to /foo/bar Example The archive contains: baz/ file1.txt The source directory contains: foo/ bar/ file2.txt A...
Python: Renaming member in a tar file during extraction
Premise I have a directory /foo/bar I have a tar file containing the directory baz Problem Extracting the contents of baz in the archive to /foo/bar Example The archive contains: baz/ file1.txt The source directory contains: foo/ bar/ file2.txt After extraction I want it to be: foo/ bar/ file1.txt ...
[ "You could use the tarfile library's extract(), extractall() or extractfile() methods. You should be able to access non-top-level objects in the archive this way.\nJust note that the path in extractall() is not the path inside the archive, but rather the path you want to extract it to, so putting baz there will no...
[ 3 ]
[]
[]
[ "python", "tarfile" ]
stackoverflow_0008030284_python_tarfile.txt
Q: Faster way to access the oldest database record in Django? I have a batch job that processes records in order of the oldest record. In django, I have a model defined similar to this: class mymodel(models.Model): name = models.CharField() ... last_processed = models.DateTimeField(blank=True, editable=Fa...
Faster way to access the oldest database record in Django?
I have a batch job that processes records in order of the oldest record. In django, I have a model defined similar to this: class mymodel(models.Model): name = models.CharField() ... last_processed = models.DateTimeField(blank=True, editable=False, null=True) I need to get the oldest record by the DateTime...
[ "Do you have an index on 'last_processed'? If so, the query will be efficient regardless of the size of the table.\n", "if you are often searching based on the last_processed field, it may be worth indexing it\notherwise what you are doing looks fine\n", "I think you must find out if it is inefficient. If it i...
[ 3, 2, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0008029782_database_django_python.txt
Q: Missing files or something in installing ROS. Lion I am trying to install the ROS complete desktop environment.... in mac osx lion. it is basically a problem on my mac... Log for python26 is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_python26/py...
Missing files or something in installing ROS. Lion
I am trying to install the ROS complete desktop environment.... in mac osx lion. it is basically a problem on my mac... Log for python26 is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_lang_python26/python26/main.log To report a bug, see <http://guide.macpo...
[ "Your MacPorts install is failing to upgrade python.\nIt is trying to upgrade python26, but is doing something from python27\nTry \nsudo port selfupdate\nsudo port install python26\n\nand report back\n" ]
[ 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0008029491_installation_python.txt
Q: python reading HID I'd like to do a program that takes input from HIDs attached to a linux system and generates MIDI from those. I'm ok on the MIDI side, but I'm struggling on the HID side of things. While this approach works ok (taken from here): #!/usr/bin/python2 import struct inputDevice = "/dev/input/event0"...
python reading HID
I'd like to do a program that takes input from HIDs attached to a linux system and generates MIDI from those. I'm ok on the MIDI side, but I'm struggling on the HID side of things. While this approach works ok (taken from here): #!/usr/bin/python2 import struct inputDevice = "/dev/input/event0" #keyboard on my system ...
[ "there are a lot of events that don't meet your requirements. you must filter events by type or code:\nwhile event:\n (time1, time2, type, code, value) = struct.unpack(inputEventFormat, event)\n if type==X and code==Y:\n print type,code,value\n event = file.read(inputEventSize)\n\n" ]
[ 1 ]
[]
[]
[ "hid", "linux", "python" ]
stackoverflow_0007012282_hid_linux_python.txt
Q: South migration for dummy fields We have a dummy Python module (fields.py) with custom Django fields which loads real implementations based on the database configured: if settings.DATABASES['default']['ENGINE'].find('postgresql') != -1: from fields_postgresql import * else: from fields_dummy import * The reas...
South migration for dummy fields
We have a dummy Python module (fields.py) with custom Django fields which loads real implementations based on the database configured: if settings.DATABASES['default']['ENGINE'].find('postgresql') != -1: from fields_postgresql import * else: from fields_dummy import * The reason for this is that we are using Postg...
[ "Drop support for SQLite. \nYou are right, if you aren't running your development environment on a mobile phone, maintaining your very own South-based migration script just in a sake of not installing Postgre probably isn't worth the hassle.\nPostgre installation versus maintaining custom migration code is a one-ti...
[ 1 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0007802384_django_django_south_python.txt
Q: Using STDIN in a Linux init script I'm currently working on an embedded system that needs to read keyboard input (Actually - it needs to read a keyboard-emulated barcode scanner). I'm using a SheevaPlug with Debian Squeeze for the hardware part, and I'm using a pretty basic init script that fires a python program ...
Using STDIN in a Linux init script
I'm currently working on an embedded system that needs to read keyboard input (Actually - it needs to read a keyboard-emulated barcode scanner). I'm using a SheevaPlug with Debian Squeeze for the hardware part, and I'm using a pretty basic init script that fires a python program that's in charge of doing the business l...
[ "try this (but be carefull /dev/input/event0 can be changed in place of repluging multiple USB HID-devices):\nimport struct\n\ninputDevice = \"/dev/input/event0\" #keyboard on my system\ninputEventFormat = 'iihhi'\ninputEventSize = 16\n\nfile = open(inputDevice, \"rb\") # standard binary file input\nevent = file.re...
[ 1 ]
[]
[]
[ "init", "linux", "python", "stdin" ]
stackoverflow_0007181181_init_linux_python_stdin.txt
Q: Reading a .txt into a definition I'm trying to read from a simple text file that looks like this: 11 eggs 1.17 milk 3.54 bread 1.50 coffee 3.57 sugar 1.07 flour 1.37 apple .33 cheese 4.43 orange .37 bananas .53 potato .19 What I'm trying to do is ask an input for a file name such as "milk" than to print the price...
Reading a .txt into a definition
I'm trying to read from a simple text file that looks like this: 11 eggs 1.17 milk 3.54 bread 1.50 coffee 3.57 sugar 1.07 flour 1.37 apple .33 cheese 4.43 orange .37 bananas .53 potato .19 What I'm trying to do is ask an input for a file name such as "milk" than to print the price of that. I am trying to use dictionar...
[ "Here you have. You already had a pretty ready code.\nLook at the diferences:\n-You were overwritting groceries\n-you were not reading the value from the dictionary\n-In python < 3x you shoud use raw_input instead of input. If you are in py3k input is OK\n-Also you do not need parenthesis for print in py2.x. You do...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008030721_dictionary_python.txt
Q: Python closures, default argument isn't equal solution as using functools.partial? I'm doing a little game in Python 3.2 with use of PyQt. I needed to insert in menu actions which did almost the same, but with other parameters. I figured out I will do it with use of lambdas, but it turned out that all actions got ...
Python closures, default argument isn't equal solution as using functools.partial?
I'm doing a little game in Python 3.2 with use of PyQt. I needed to insert in menu actions which did almost the same, but with other parameters. I figured out I will do it with use of lambdas, but it turned out that all actions got the same parameter. It turned out to be a closure problem, which i solved according to ...
[ "But if you write:\n[m(False) for m in lambdas]\n\nIt will call to StartGame with arguments 8,False, too.\nQt is probably calling your lambdas with argument False, so the default argument of the lambda is simply not used.\nBut your idea is good. Try with the following:\nlamb = (lambda a, real_co = co : self.StartGa...
[ 4 ]
[]
[]
[ "closures", "lambda", "partial", "pyqt4", "python" ]
stackoverflow_0008030365_closures_lambda_partial_pyqt4_python.txt
Q: Build dictionary from file and os.listdir python I'm using os.listdir and a file to create a dictionary. I'm getting keys and values from them respectively. os.listdir gives me: EVENT3180 EVENT2894 EVENT2996 and from the file I get: 3.1253 -32.8828 138.2464 11.2087 -33.2371 138.3230 15.8663 -33.1403 1...
Build dictionary from file and os.listdir python
I'm using os.listdir and a file to create a dictionary. I'm getting keys and values from them respectively. os.listdir gives me: EVENT3180 EVENT2894 EVENT2996 and from the file I get: 3.1253 -32.8828 138.2464 11.2087 -33.2371 138.3230 15.8663 -33.1403 138.3051 The main problem is that my final dictionary ...
[ "You'll want to loop over the filenames and the lines of the input file simultaneously. Replace your nested loops with\nfor name, line in zip(event_list, coords_file.readlines()):\n adict.setdefault(name, []).append(line.strip())\n\nwhere I took the liberty of compressing your loop body into one line.\nIf the am...
[ 2 ]
[]
[]
[ "dictionary", "file", "for_loop", "python" ]
stackoverflow_0008031221_dictionary_file_for_loop_python.txt
Q: How do you sort multiple columns of a CSV file using python? I am having issues figuring out how to sort a large data set into more useful data. The original file in CSV format is shown below- the data indicates x,y,z positions and finally energy. The x,y,z coordinates spread for quite a ways this is a small snipp...
How do you sort multiple columns of a CSV file using python?
I am having issues figuring out how to sort a large data set into more useful data. The original file in CSV format is shown below- the data indicates x,y,z positions and finally energy. The x,y,z coordinates spread for quite a ways this is a small snippet below- basically it was an energy search over a volume. -2.800...
[ "This does what you ask in your comment to Raymond's answer -- returns just the row with the lowest z for each x, y pair:\nfrom operator import itemgetter\nfrom itertools import groupby\nfrom csv import reader\n\n\ndef min_z(iterable):\n # the data converted from strings to numbers\n floats = [[float(n) for n...
[ 4, 2, 0 ]
[]
[]
[ "csv", "import_from_csv", "python", "sorting" ]
stackoverflow_0008030468_csv_import_from_csv_python_sorting.txt
Q: Writing a telnet server in Python and embedding IPython as shell I am trying to write a simple telned server that will expose a IPython shell to the connected client. Does someone know how to do that ? The question is really about embedding the IPython shell into the Telnet server (I can probably use Twisted for t...
Writing a telnet server in Python and embedding IPython as shell
I am trying to write a simple telned server that will expose a IPython shell to the connected client. Does someone know how to do that ? The question is really about embedding the IPython shell into the Telnet server (I can probably use Twisted for the Telnet server part ) Thx
[ "You could perhaps use a true telnet or SSH server and just set the user's login shell to be IPython. For instance, given a user whose name is 'adam', perhaps you could change the user's /etc/passwd line to something like:\nadam:x:1000:1000:Adam Frist,,,:/home/adam:/usr/bin/ipython\n\nTypically the final segment in...
[ 1, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0007723399_ipython_python.txt
Q: Getting the next item in a loop What I want to do is quite simple: I have a model which I am running a regroup loop on. Now I want to show the first 4 items of the loop next to each other, and then continue on the next line with the next 4 items until the list is done. If there are no more items, the other cells o...
Getting the next item in a loop
What I want to do is quite simple: I have a model which I am running a regroup loop on. Now I want to show the first 4 items of the loop next to each other, and then continue on the next line with the next 4 items until the list is done. If there are no more items, the other cells on the line can stay empty. I have tri...
[ "<table cellspacing=\"0\">\n{% for item in in_country.list|dictsort:\"name\" %}\n\n{% if forloop.counter0|divisibleby:4 %}\n<tr style=\"text-align:center;\">\n{% endif %}\n\n <td width=\"200px\" class='community_table'>\n <img src=\"{{ item.image }}\" style=\"height:40px;\"><br />\n <a href='{{ item.url }}' s...
[ 1, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "loops", "python" ]
stackoverflow_0008022264_django_templates_google_app_engine_loops_python.txt
Q: python thread crash I have a program (time lapse maker) which has two threads that updates a wx.StaticBitmap. When the two threads access the wx.StaticBitmap it crashes with the error python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed. I tried a G...
python thread crash
I have a program (time lapse maker) which has two threads that updates a wx.StaticBitmap. When the two threads access the wx.StaticBitmap it crashes with the error python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed. I tried a Google search for the answ...
[ "The easiest way to avoid crashes and anomalous behavior of all sorts is to ensure that only the main thread handles the GUI. You could try to do it by finding and locking critical code blocks, but in my opinion that's a losing game. Much easier to synchronize the processing thread(s) with the main thread using e...
[ 4, 0 ]
[]
[]
[ "assertion", "exception", "multithreading", "python", "wxwidgets" ]
stackoverflow_0007801211_assertion_exception_multithreading_python_wxwidgets.txt
Q: How to pass arguments to a python cron task on Google App Engine? I have an application written in Python. It collects and parses data from certain sources (RSS, Atom, Twitter, etc.) and if new data is found, it's saved to a MySQL database. I have many sources defined on the application itself, and not all can be ...
How to pass arguments to a python cron task on Google App Engine?
I have an application written in Python. It collects and parses data from certain sources (RSS, Atom, Twitter, etc.) and if new data is found, it's saved to a MySQL database. I have many sources defined on the application itself, and not all can be checked on the same time basis because of restrictions (Twitter and its...
[ "Put the source variable in your url path:\ncron:\n- description: update source ABC\n url: /cron/ABC/\n schedule: every 5 minutes\n login: admin\n- description: update source XYZ\n url: /cron/XYZ/\n schedule: every 12 minutes\n login: admin\n\nwebapp.WSGIApplication([('/cron/([^/]+)/', CronHandler)]) \n\nc...
[ 3, 0 ]
[]
[]
[ "arguments", "cron", "google_app_engine", "python" ]
stackoverflow_0008014909_arguments_cron_google_app_engine_python.txt
Q: Schwartzian sort example in "Text Processing in Python" I was browsing through "Text Processing in Python" and tried its example about Schwartzian sort. I used following structure for sample data which also contains empty lines. I sorted this data by fifth column: 383230 -49 -78 1 100034 '06 text' 9562 'text' 720...
Schwartzian sort example in "Text Processing in Python"
I was browsing through "Text Processing in Python" and tried its example about Schwartzian sort. I used following structure for sample data which also contains empty lines. I sorted this data by fifth column: 383230 -49 -78 1 100034 '06 text' 9562 'text' 720 'text' 867 335067 -152 -18 3 100030 'text' 2400 'text' 2342 ...
[ "Not directly related to the question, but note that in recent versions of python (since 2.3 or 2.4 I think), the transform and untransform can be performed automatically using the key argument to sort() or sorted(). eg:\ndef key_func(line):\n lst = string.split(line)\n if len(lst) >= 4: \n ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000463032_python.txt
Q: Same equation, different answers from Pylab and Octave I am porting code created in octave into pylab. One of the ported equations gives dramatically different results in python than it does in octave. The best way to explain is to show plots generated by octave and pylab from the same equation. Here is a sim...
Same equation, different answers from Pylab and Octave
I am porting code created in octave into pylab. One of the ported equations gives dramatically different results in python than it does in octave. The best way to explain is to show plots generated by octave and pylab from the same equation. Here is a simplified snippet of the original equation in octave. In this...
[ "Try from __future__ import division to eliminate errors arising from floor division.\n" ]
[ 12 ]
[]
[]
[ "equation", "matlab", "matplotlib", "octave", "python" ]
stackoverflow_0008031937_equation_matlab_matplotlib_octave_python.txt
Q: Can't seem to get django url route correct with numbers I am trying to get a url structure like this. http://example.com/blog/1/title-name-goes-here My main urls file has this line, among others. url(r'^blog/', include('blog.urls')), in my blog.urls I have urlpatterns = patterns('', (r'', 'blog.views.index'),...
Can't seem to get django url route correct with numbers
I am trying to get a url structure like this. http://example.com/blog/1/title-name-goes-here My main urls file has this line, among others. url(r'^blog/', include('blog.urls')), in my blog.urls I have urlpatterns = patterns('', (r'', 'blog.views.index'), (r'^(?P<entry_id>\d+)/(?P<slug>[a-zA-Z0-9_.-]+)/$', 'blo...
[ "try:\nurlpatterns = patterns('',\n (r'^(?P<entry_id>\\d+)/(?P<slug>[-\\w]+)/$', 'blog.views.entry'),\n (r'^$', 'blog.views.index'),\n) \n\nNotice the carat and dollar sign in the lower pattern which signifies an empty pattern. You should (generally) put your patterns in order of how many groups then need ...
[ 1 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0008032047_django_django_urls_python_regex.txt
Q: Insert element into a list method I'm trying to insert a new item into a sorted list, entering the item in the corrected (Sorted) position in the list. Everytime i test my code to see if it's working or not though, i'm getting a message that i'm not really familiar with. i know what i have so far isn't correct, bu...
Insert element into a list method
I'm trying to insert a new item into a sorted list, entering the item in the corrected (Sorted) position in the list. Everytime i test my code to see if it's working or not though, i'm getting a message that i'm not really familiar with. i know what i have so far isn't correct, but i'm not able to see what i'm doing wr...
[ "Looks like the problem is just that your SortedList class isn't defining a way to print it. Try adding:\ndef __str__(self):\n return str(self.L)\n\nSee this for a discussion of special methods.\n", "At some point in the code, possibly in the wrapper code that your instructor provides is a piece of code that l...
[ 1, 0 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0008032245_class_list_python.txt
Q: Solve vigenere code without key - python This is the problem I have to figure out: "A message has been encryption using Vigenere encryption method discussed in class, and its cipher text EQNVZ has been intercepted. Break the code. Assume that the key is the same length as the message, and the message and the key c...
Solve vigenere code without key - python
This is the problem I have to figure out: "A message has been encryption using Vigenere encryption method discussed in class, and its cipher text EQNVZ has been intercepted. Break the code. Assume that the key is the same length as the message, and the message and the key consist only of uppercase letters." Is there ar...
[ "It is a trick question. If \"the key is the same length as the message\" then you have a one-time pad that conceals everything except the message length.\n", "Since your cipher text is so short, it's probably easiest to just brute force it:\ndef break_vignere(input, list_of_words):\n for word in list_of_word...
[ 11, 2, 0 ]
[]
[]
[ "encryption", "python", "vigenere" ]
stackoverflow_0008031920_encryption_python_vigenere.txt
Q: Python: Tracing the Execution of a For Loop I am attempting to trace the execution of a piece of code that contains a for loop with two if conditionals. But I need help understanding exactly how for loops are executed in python. Please consider the following example: numAs = 0 numEs = 0 aStr1 = 'abcdefge' ...
Python: Tracing the Execution of a For Loop
I am attempting to trace the execution of a piece of code that contains a for loop with two if conditionals. But I need help understanding exactly how for loops are executed in python. Please consider the following example: numAs = 0 numEs = 0 aStr1 = 'abcdefge' def someFunc(aString): 1. for i in range(len...
[ "Your understanding of what the code does is correct.\nFWIW, it is easy to follow the execution of a script using python -m trace --trace some_script.py or you can see the execution line counts with python -m trace --count some_script.py.\nFor example, the latter call to trace produces:\n 1: def someFunc(aString...
[ 3 ]
[]
[]
[ "conditional_statements", "if_statement", "python", "trace" ]
stackoverflow_0008032484_conditional_statements_if_statement_python_trace.txt
Q: Python: Expanding Complicated Tree DataStructure I am exploring a data structure which get expands to sub-elements and resolves to a final element. But I only want to store top two levels. Example: Lets say I start with New York which breaks into Bronx, Kings, New York, Queens, and Richmond as counties but then f...
Python: Expanding Complicated Tree DataStructure
I am exploring a data structure which get expands to sub-elements and resolves to a final element. But I only want to store top two levels. Example: Lets say I start with New York which breaks into Bronx, Kings, New York, Queens, and Richmond as counties but then finally somehow they resolve to USA. I am not sure if t...
[ "Are you trying to lookup \"Queens\" and learn that it is in the USA? Have you tried encoding your tree in XML, and using lxml.etree to find an element and then use getpath to return the path in XPath format?\nThis would meaning adding a fourth top level to your tree, namely World, and then you would search for Que...
[ 0 ]
[]
[]
[ "algorithm", "data_structures", "expression_trees", "python", "recursion" ]
stackoverflow_0008031509_algorithm_data_structures_expression_trees_python_recursion.txt
Q: sqlite3 python query with multiple variables error I looked all over for the answer to my question and could not find any good answer.... I am using python with the sqlite3 module to query a database. The problem is that I cannot get a sql query to hold multiple variables. For example... I can get this query to wo...
sqlite3 python query with multiple variables error
I looked all over for the answer to my question and could not find any good answer.... I am using python with the sqlite3 module to query a database. The problem is that I cannot get a sql query to hold multiple variables. For example... I can get this query to work perfectly. ("wordsofar" is the variable name) c.execu...
[ "You code looks fine.\nThe problem is in the data. Either wordsofar or noletter is an object that sqlite3 doesn't know how to store.\nOne solution is to pickle the object. Another solution is to supply converter and adapter functions.\nUse register_adapter to register a callable to convert the custom Python type ...
[ 1, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0008032299_python_sqlite.txt
Q: SQLAlchemy 0.7 MapperEvent error I have model class CreatedMixin(object): __abstract__ = True @declared_attr def created_by(cls): return Column(Integer, ForeignKey('user.user_id', onupdate="cascade", ondelete="restrict")) @declared_attr def updated_by(cls): ...
SQLAlchemy 0.7 MapperEvent error
I have model class CreatedMixin(object): __abstract__ = True @declared_attr def created_by(cls): return Column(Integer, ForeignKey('user.user_id', onupdate="cascade", ondelete="restrict")) @declared_attr def updated_by(cls): return Column(Integer, ForeignKey(...
[ "The problem was quite simple, I use an Mixin in my models and inadvertently added to the basic model of property __abstract__ = True\nExample:\n\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\nengine = create_engine('sql...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007990790_python_sqlalchemy.txt
Q: Creating field value "unique" throughout the collection in Django MongoDB models? I am having hard time to understand how to make field value unique while using Django MongoDB.my models.py has a model: class Projects(models.Model): projectName =models.CharField(max_length = 100,unique=True) projectManager ...
Creating field value "unique" throughout the collection in Django MongoDB models?
I am having hard time to understand how to make field value unique while using Django MongoDB.my models.py has a model: class Projects(models.Model): projectName =models.CharField(max_length = 100,unique=True) projectManager = EmbeddedModelField('Users') Here i want whenever a new project instance is added it ...
[ "Answer to my own question is I had to add unique=True for model field before doing syncdb.Thanks to culebron.Its working now\n" ]
[ 0 ]
[]
[]
[ "django", "mongodb", "python" ]
stackoverflow_0008005616_django_mongodb_python.txt
Q: How can I change in real-time filtered words in tweetstream (Python)? I need to save in real-time to a database all tweets from the Twitter Streaming API, filtering them by out a certain list of words, of course. I've achieved it by using tweetstream, defining the list words like this before calling FilterStream()...
How can I change in real-time filtered words in tweetstream (Python)?
I need to save in real-time to a database all tweets from the Twitter Streaming API, filtering them by out a certain list of words, of course. I've achieved it by using tweetstream, defining the list words like this before calling FilterStream(): words = ["word1","two words","anotherWord"] What I'd like to do, is to b...
[ "Perhaps something like this will work:\ndef rebuild_wordlist(s):\n with open('words.txt','r') as f:\n return set(f.read().split('\\n'))\n\ndef match(tweet):\n return any(w in tweet for w in words)\n\nwords, timestamp = rebuild_wordlist(), time.time()\nstream = tweetstream.SampleStream(\"username\", \"...
[ 0, 0 ]
[]
[]
[ "python", "real_time", "twitter" ]
stackoverflow_0008031854_python_real_time_twitter.txt
Q: What is an Object Oriented desktop application framework similar to Rails? I'm building a Rails web app but I would like to start building a desktop version but I don't know what language or framework to use. I've been thinking on developing it with Ruby too or Python or Java. I'm open to new languages as long as...
What is an Object Oriented desktop application framework similar to Rails?
I'm building a Rails web app but I would like to start building a desktop version but I don't know what language or framework to use. I've been thinking on developing it with Ruby too or Python or Java. I'm open to new languages as long as the framework is awesome and enjoyable to work with. What LANGUAGE and FRAMEWOR...
[ "My rule of thumb for personal (which I think this is) projects is to either use the language you're most familiar with OR the one you're most interested in learning. Java, python and ruby are all great languages and MVC frameworks such as RoR exist for all of them.\nThat being said if you're interested in trying ...
[ 2, 1, 0 ]
[]
[]
[ "java", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0008032655_java_python_ruby_ruby_on_rails.txt
Q: Python Can I add a tuple to a generator? I want to add ('', 'Day') to the front. Right now it makes a drop down menu for the numbers 1 through 31 and I want a 'Day' choice at the top. DAY_CHOICES = ( # I was hoping this would work but apparently generators don't work like this. # ('', 'Day'), (str(x), ...
Python Can I add a tuple to a generator?
I want to add ('', 'Day') to the front. Right now it makes a drop down menu for the numbers 1 through 31 and I want a 'Day' choice at the top. DAY_CHOICES = ( # I was hoping this would work but apparently generators don't work like this. # ('', 'Day'), (str(x), x) for x in range(1,32) ) # I'll include this...
[ "You want itertools.chain().\nfor i in itertools.chain(('foo', 'bar'), xrange(1, 4)):\n print i\n\n", "DAY_CHOICES = ( (str(x),x) if x>0 else('','Day') for x in range(0,32) )\n\n", "This seems like a bad use of generators. A generator is not a list, it is a function that generates a sequence of values, so it i...
[ 6, 1, 1 ]
[]
[]
[ "django", "forms", "generator", "python", "tuples" ]
stackoverflow_0008033096_django_forms_generator_python_tuples.txt
Q: Re.sub not working for me I'm trying to get re.sub to replace a pattern specified with a value for example for lines in f: pattern='\${2}'+key[0]+'\${2}' re.search(pattern,lines) this return the line where the pattern was found. For example this is one of the test returns if got this is a $$test$$ The pro...
Re.sub not working for me
I'm trying to get re.sub to replace a pattern specified with a value for example for lines in f: pattern='\${2}'+key[0]+'\${2}' re.search(pattern,lines) this return the line where the pattern was found. For example this is one of the test returns if got this is a $$test$$ The problem i'm having is when i do th...
[ "You are assigning the result of re.sub back to a variable, right? e.g.\nlines = re.sub(pattern, key[1], lines)\n\nIt's a string, so it can't be changed (strings are immutable in Python), therefore a new string is created and returned to you. If you don't assign it back to a name, you will lose it.\n", "If you h...
[ 19, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008033375_python_regex.txt
Q: Cython built extension fails to export data types and functions I have just managed to build my first C extension for Python, using Cython to call into an existing C library. I declared and defined my data types and functions into logical components (following the logical structure of the C library), and I combine...
Cython built extension fails to export data types and functions
I have just managed to build my first C extension for Python, using Cython to call into an existing C library. I declared and defined my data types and functions into logical components (following the logical structure of the C library), and I combined them into one pyx file - after errors occured when I tried to add t...
[ "# declares start of a comment line so your foo.pyx is effectively empty.\ninclude is a blunt instrument. Use *.pxd and cimport instead.\n" ]
[ 3 ]
[]
[]
[ "cython", "python", "python_extensions" ]
stackoverflow_0008032861_cython_python_python_extensions.txt
Q: Moving items in a list a certain number of spaces I'm trying to make a simple card game in Python. I have to be able to move any card in my Hand list either 1 or 3 spaces to the left and if the card that is already in that spot matches either the number or suite then I need to replace it. Here is what I've tried s...
Moving items in a list a certain number of spaces
I'm trying to make a simple card game in Python. I have to be able to move any card in my Hand list either 1 or 3 spaces to the left and if the card that is already in that spot matches either the number or suite then I need to replace it. Here is what I've tried so far: Assume MN is the number of spaces specified to m...
[ "Moving an item in a list in general means popping it from its original location and inserting it to its desired location. Unfortunately, your question provides insufficient information on what your Hand and Card classes look like, but if Hand is a simple list, then the following should do:\nHI = Hand.index(MC)\nif...
[ 3, 0 ]
[]
[]
[ "items", "list", "python" ]
stackoverflow_0008033408_items_list_python.txt
Q: Python socket bind to any IP? I have a small one sided message sender that works while I specify the IP to connect to in code, however, I am having trouble allowing the socket to accept connections from any IP. Here is the line that is the problem. mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) my...
Python socket bind to any IP?
I have a small one sided message sender that works while I specify the IP to connect to in code, however, I am having trouble allowing the socket to accept connections from any IP. Here is the line that is the problem. mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 2727 ) ) The '...
[ "If you want to bind to all available IPv4 addresses, specify 0.0.0.0 as your IP address. If you're behind a router and wish to have your socket internet-accessible, rather than just available on your LAN, you'll need to set up a port forwarding rule so that users outside your LAN can access the service.\nSee the f...
[ 46, 16, 5 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008033552_python_sockets.txt
Q: Remove BOTH items from list, if one value appears multiple times (Python) Python: How to remove all duplicate items from a list Hey guys I have a list of (file,inode,image,hash)-tuples. I need to delete BOTH items if they have the same hash. I don't have that much of programming experience, so maybe a hint for wha...
Remove BOTH items from list, if one value appears multiple times (Python)
Python: How to remove all duplicate items from a list Hey guys I have a list of (file,inode,image,hash)-tuples. I need to delete BOTH items if they have the same hash. I don't have that much of programming experience, so maybe a hint for what i have to look would already be helpful. I've already searched the Internet, ...
[ ">>> from collections import Counter\n>>> L=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,1,2,3]\n>>> [k for k,v in Counter(L).items() if v==1]\n[7, 8, 9]\n\nTo clarify:\nhash_counter = Counter(x[3] for x in self.files_for_json)\nfor (file,inode,image,hash) in self.files_for_json:\n if hash_counter[hash]>1:\n # duplicat...
[ 3 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0008034436_duplicates_list_python.txt
Q: How to insert multiple values with subquery using SQLAlchemy Core? Using SQLAlchemy Core (not ORM), I'm trying to INSERT multiple rows using subqueries in the values. For MySQL, the actual SQL would look something like this: INSERT INTO widgets (name, type) VALUES ('Melon', (SELECT type FROM widgetTypes WHERE type...
How to insert multiple values with subquery using SQLAlchemy Core?
Using SQLAlchemy Core (not ORM), I'm trying to INSERT multiple rows using subqueries in the values. For MySQL, the actual SQL would look something like this: INSERT INTO widgets (name, type) VALUES ('Melon', (SELECT type FROM widgetTypes WHERE type='Squidgy')), ('Durian', (SELECT type FROM widgetTypes WHERE type='Spiky...
[ "Instead of providing subselect statement as parameter value, you have to embed it into INSERT statement:\ntype_select = select([widgetTypes.c.id]).where(\n widgetTypes.c.type==bindparam('type_name'))\n\ninsert = widgets.insert({'type': type_select})\n\nconn.execute(insert, [\n {'name': 'Melon', 'type_na...
[ 8 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008013781_python_sqlalchemy.txt
Q: Datastore 'Response too large error' since migrated to Python27 I just migrated my GAE/python app from M/S to HRD and then activated the new python27 runtime. Now most of my datastore queries are failing with this error: ResponseTooLargeError: The response from API call datastore_v3.RunQuery() was too large. The s...
Datastore 'Response too large error' since migrated to Python27
I just migrated my GAE/python app from M/S to HRD and then activated the new python27 runtime. Now most of my datastore queries are failing with this error: ResponseTooLargeError: The response from API call datastore_v3.RunQuery() was too large. The same code is still running on older GAE app (M/S and python25) with no...
[ "This is a known bug in the Python 2.7 runtime - if the result of a datastore query is >1MB then you will get this response.\nIt will be fixed in 1.6.1.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008024609_google_app_engine_python.txt
Q: Best way to merge and unmerge objects without losing data Say I have two tables (I am using Django, but this question is mostly language agnostic): Organization(models.Model): name = models.CharField(max_length=100) Event(models.Model): organization = models.ForeignKey(Organization) name = models.Char...
Best way to merge and unmerge objects without losing data
Say I have two tables (I am using Django, but this question is mostly language agnostic): Organization(models.Model): name = models.CharField(max_length=100) Event(models.Model): organization = models.ForeignKey(Organization) name = models.CharField(max_length=100) Users are allowed to create both event...
[ "Personally, I would go with a solution which uses something like django-reversion. However, if you want to create something more robust and less dependent on 3rd party logic, add a merged_into field to Organization and merged_from field to Event:\nOrganization(models.Model):\n name = models.CharField(max_lengt...
[ 2, 0, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "schema" ]
stackoverflow_0007987196_database_django_django_models_python_schema.txt
Q: On what side is 'HTTP Error 403: request disallowed by robots.txt' generated? I am trying out Mechanize to make some routine simpler. I have managed to bypass that error by using br.set_handle_robots(False). There are talks about how ethical it's to use it. What I wonder about is where this error is generated, on ...
On what side is 'HTTP Error 403: request disallowed by robots.txt' generated?
I am trying out Mechanize to make some routine simpler. I have managed to bypass that error by using br.set_handle_robots(False). There are talks about how ethical it's to use it. What I wonder about is where this error is generated, on my side, or on server side? I mean does Mechanize throw the exception when it sees ...
[ "The server detects the user-agent. If the user agent match one in robots.txt, the rules are applied by the client.\nBy default, mechanize returns \"Python-urllib/2.7\".\nSee http://en.wikipedia.org/wiki/Robots_exclusion_standard\n", "The server blocks your activity with such response.\nIs it your site? If not, f...
[ 2, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0008034767_mechanize_python.txt
Q: Python raw_input following sys.stdin.read() throws EOFError a similar question has been asked before, but the answers suggested a workaround which is not applicable to my situation. An email message is piped from mutt to a script, and is read from STDIN: message = sys.stdin.read() # message is parsed and URLs are ...
Python raw_input following sys.stdin.read() throws EOFError
a similar question has been asked before, but the answers suggested a workaround which is not applicable to my situation. An email message is piped from mutt to a script, and is read from STDIN: message = sys.stdin.read() # message is parsed and URLs are printed as a list to choose from... selected_index = raw_input('W...
[ "Have you tried this:\nmessage = sys.stdin.read()\nsys.stdin = open('/dev/tty')\nselected_index = raw_input('Which URL to open?')\n\nThis works on Linux; maybe it will work for OSX too.\n", "Try to reset STDIN using sys.stdin.seek(0) \nReference: http://docs.python.org/library/fileinput.html\n" ]
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008034595_python.txt
Q: What is this print syntax? (print rightshift) Looking at the source code of pstats I see this syntax: print >> self.stream, "in %.3f seconds" % self.total_tt print >> self.stream What is this syntax, how is it called and how to use it? I have never seen it before, nor seen it in any of the Python books/tutorials ...
What is this print syntax? (print rightshift)
Looking at the source code of pstats I see this syntax: print >> self.stream, "in %.3f seconds" % self.total_tt print >> self.stream What is this syntax, how is it called and how to use it? I have never seen it before, nor seen it in any of the Python books/tutorials I have read.
[ "If you mean the >>, that's the Python 2.x syntax for writing to a file-like other than sys.stdout with print. It's defined in the Python docs, 6.6. The print statement and has been around since at least Python 2.5 (and I think earlier).\nThis syntax has been replaced with a file kwarg to the print function in Pyth...
[ 6, 2 ]
[]
[]
[ "bit_shift", "printing", "python", "python_2.7", "syntax" ]
stackoverflow_0008035311_bit_shift_printing_python_python_2.7_syntax.txt
Q: Ternary operator return `True` instead the given value I'm using ternary operator for short conditional variable definition. I was wondering when the expression returned True instead given in the expression value. >>> digits = '123456' >>> conv_d = digits != None if int(digits) else None >>> conv_d >>> True >>>...
Ternary operator return `True` instead the given value
I'm using ternary operator for short conditional variable definition. I was wondering when the expression returned True instead given in the expression value. >>> digits = '123456' >>> conv_d = digits != None if int(digits) else None >>> conv_d >>> True >>> int(digits) >>> 123456 Explain to me please, how this happ...
[ "int(digits) == 123456 which is a true-ish value. So conv_d = digits != None. Since digits is not None, conv_d is set to true.\nYou probably wanted this:\nconv_d = int(digits) if digits is not None else None\n\nRemember that a string containing something not a number will raise an exception though! If you prefer 0 ...
[ 7, 5, 0, 0 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0008034257_conditional_python.txt
Q: how to instantiate a scrapy.http.Response from url string? In order to get the data I need from a website using scrapy, I first need to create a response object so I can use the HtmlXpathSelector on it. HtmlXpathSelector does not accept a url string as argument. In the following code sample the "response2" variabl...
how to instantiate a scrapy.http.Response from url string?
In order to get the data I need from a website using scrapy, I first need to create a response object so I can use the HtmlXpathSelector on it. HtmlXpathSelector does not accept a url string as argument. In the following code sample the "response2" variable is empty because I don't know how to do it. from scrapy.select...
[ "You can also create HtmlXPathSelector by giving at just some html:\nhxs = HtmlXPathSelector(text= '<div>blah-blah</div>')\n\n", "Another option is to create a new Response object, for example a HtmlResponse (TextResponse is also a possibility)\nresponse2 = HtmlResponse(url=url, body=body)\n\nFor all supported ke...
[ 3, 3 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0008030744_python_scrapy.txt
Q: Problem with python soap library suds. Wsdl was not understood The code below throw a SAXParseException: "mismatched tag": from suds.client import Client <br> url = 'http://www.didww.com/api/?wsdl' client = Client(url, cache=None) print client Is it problem with suds, or there is some errors in wsdl? A: H...
Problem with python soap library suds. Wsdl was not understood
The code below throw a SAXParseException: "mismatched tag": from suds.client import Client <br> url = 'http://www.didww.com/api/?wsdl' client = Client(url, cache=None) print client Is it problem with suds, or there is some errors in wsdl?
[ "Have you looked at the WSDL file in a browser or XML viewer? That should answer your question as to whether the problem is in the wsdl. The exception suggests there is something up with it.\n", "Seems to work for me, suds 0.3.3 (without cache option - None is not a valid option for cache in my version of suds):\...
[ 1, 1, 0 ]
[]
[]
[ "python", "soap", "suds", "wsdl" ]
stackoverflow_0001686570_python_soap_suds_wsdl.txt
Q: In line Conditional Expression or Function - Pythonic? I have a situation where I would like to conditionally slice a string from the reported position of an '@' symbol; the condition being: slice the string if the '@' is there, else leave it untouched. I thought up two ways, one using a function, the other using...
In line Conditional Expression or Function - Pythonic?
I have a situation where I would like to conditionally slice a string from the reported position of an '@' symbol; the condition being: slice the string if the '@' is there, else leave it untouched. I thought up two ways, one using a function, the other using an inline conditional expression. Which method is the most ...
[ "Not only is a function more readable, it is also reusable.\nThe inline expression may call c.find('@') twice, which is inefficient.\nAs Useless has mentioned in the comments, there are already built in functions to do this; you really don't need to define your own function in this case:\nagent,_,address = c.partit...
[ 5, 3, 0, 0, 0, 0 ]
[]
[]
[ "coding_style", "conditional_expressions", "python", "ternary_operator" ]
stackoverflow_0008034819_coding_style_conditional_expressions_python_ternary_operator.txt
Q: Install Python modules on new Python version I've used easy_install to get one or two modules, then I used pip to install the Twitter module. However the newer version of Python I downloaded can't see these modules, only the built in OSX version can. Also, I am now unable to download NLTK which I need for some exa...
Install Python modules on new Python version
I've used easy_install to get one or two modules, then I used pip to install the Twitter module. However the newer version of Python I downloaded can't see these modules, only the built in OSX version can. Also, I am now unable to download NLTK which I need for some examples I'm working through on a really good book ca...
[ "Install the packages with the binary from your version of python.\nSo for example if your version is in /usr/local/bin then installing would be either:\n\n/usr/local/bin/python setup.py ...\n/usr/local/bin/easy_install ...\n/usr/local/bin/pip install ...\n\n", "It depends on whether the modules you downloaded a...
[ 1, 0 ]
[]
[]
[ "macos", "python", "python_3.x" ]
stackoverflow_0008035412_macos_python_python_3.x.txt
Q: Python 3.2.2 READ from console I am working on Python 3.2.2. The user has the option of entering the value on the console or let the default value be used if he just hits ENTER. e.g. If the user hits ENTER, the value is set to c:\temp as shown in code snippet below: READ=os.read(0,100) if READ == "\n" : READ="c:...
Python 3.2.2 READ from console
I am working on Python 3.2.2. The user has the option of entering the value on the console or let the default value be used if he just hits ENTER. e.g. If the user hits ENTER, the value is set to c:\temp as shown in code snippet below: READ=os.read(0,100) if READ == "\n" : READ="c:\\temp" This code used to work in p...
[ "The function os.read returns class str in python 2.7, but class bytes in python 3.2. So in python 3.2, if READ == \"\\n\": READ=\"C:\\\\temp\" will never be True. You may change like this:\nif str(READ,\"ascii\") == os.linesep: READ = \"C:\\\\temp\"\n\nMaybe, more exactly:\nimport os,sys\nREAD = os.read(0,100)\nif...
[ 7, 1 ]
[]
[]
[ "console", "python", "python_3.x" ]
stackoverflow_0008036182_console_python_python_3.x.txt
Q: UnicodeWarning: special characters in Tkinter I have written a program in Tkinter (Python 2.7), a scrabblehelper in Norwegian which contains some special characters (æøå), which means my wordlist (ordliste) contains words with special characters. When I run my function finnord(c*), it returns 'cd'. I am using an ...
UnicodeWarning: special characters in Tkinter
I have written a program in Tkinter (Python 2.7), a scrabblehelper in Norwegian which contains some special characters (æøå), which means my wordlist (ordliste) contains words with special characters. When I run my function finnord(c*), it returns 'cd'. I am using an entry.get() to get the word to put in my function. ...
[ "I can reproduce the error this way:\n% python\nPython 2.7.2+ (default, Oct 4 2011, 20:03:08) \n[GCC 4.6.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 'k\\xf8**e' in [u'k\\xf8**e']\n__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both argum...
[ 6 ]
[]
[]
[ "character", "encoding", "python", "tkinter" ]
stackoverflow_0008036499_character_encoding_python_tkinter.txt
Q: Problem with subprocess.call In my current working directory I have the dir ROOT/ with some files inside. I know I can exec cp -r ROOT/* /dst and I have no problems. But if I open my Python console and I write this: import subprocess subprocess.call(['cp', '-r', 'ROOT/*', '/dst']) It doesn't work! I have this err...
Problem with subprocess.call
In my current working directory I have the dir ROOT/ with some files inside. I know I can exec cp -r ROOT/* /dst and I have no problems. But if I open my Python console and I write this: import subprocess subprocess.call(['cp', '-r', 'ROOT/*', '/dst']) It doesn't work! I have this error: cp: cannot stat ROOT/*: No suc...
[ "Just came across this while trying to do something similar.\n\nThe * will not be expanded to filenames\n\nExactly. If you look at the man page of cp you can call it with any number of source arguments and you can easily change the order of the arguments with the -t switch.\nimport glob\nimport subprocess\nsubproce...
[ 10, 7, 4, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001392757_python_subprocess.txt
Q: Sort items in UltimateListCtrl I want to create an ultimate list ctrl based table where the user can sort the columns by clicking on the column header. Here's the code I attempted: import wx import wx.lib.mixins.listctrl as listmix from wx.lib.agw import ultimatelistctrl as ULC APPNAME='Sortable Ultimate List Ctr...
Sort items in UltimateListCtrl
I want to create an ultimate list ctrl based table where the user can sort the columns by clicking on the column header. Here's the code I attempted: import wx import wx.lib.mixins.listctrl as listmix from wx.lib.agw import ultimatelistctrl as ULC APPNAME='Sortable Ultimate List Ctrl' APPVERSION='1.0' MAIN_WIDTH=300 M...
[ "It seems to be bug in the UltimateListControl implementation. It does not refresh itself after column is clicked. This works for me:\nDATA = {\n0 : (\"3\", \"3\", \"1\"),\n1 : (\"2\", \"1\", \"2\"),\n2 : (\"1\", \"2\", \"3\")\n}\n\nimport wx\nimport wx.lib.mixins.listctrl as listmix\nfrom wx.lib.agw import ultimat...
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008023417_python_wxpython.txt
Q: Include console app in GTK app I'd like to create an application similar to gvim, so that I'll have gtk application with console application included (in my case, it's vim or any other console text editor) What is the best way to do this? If there is a way, how can I comunicate with this console editor from GUI? I...
Include console app in GTK app
I'd like to create an application similar to gvim, so that I'll have gtk application with console application included (in my case, it's vim or any other console text editor) What is the best way to do this? If there is a way, how can I comunicate with this console editor from GUI? I should be runnable on linux, but I'...
[ "gvim isn't a gtk wrapper for vim. It is a version of vim that uses gtk+ widgets instead of stdin and stdout.\nYou can add smooth gtk+ support to other programs by modifying their source code, but you'll have to implement the gui from scratch.\nAlternatively, you could embed a VTE terminal widget in your gtk progra...
[ 4 ]
[]
[]
[ "glade", "gtk", "gtkbuilder", "python", "vim" ]
stackoverflow_0008036901_glade_gtk_gtkbuilder_python_vim.txt
Q: Django retrieving a tables data based on another table I have the following tables: class Note(model): note_data = models.ForeignKey(NoteData) important = models.BooleanField(default=0) deleted = models.DateTimeField(null=True) deleted_by = models.ForeignKey(User, null=True) class NoteData(model):...
Django retrieving a tables data based on another table
I have the following tables: class Note(model): note_data = models.ForeignKey(NoteData) important = models.BooleanField(default=0) deleted = models.DateTimeField(null=True) deleted_by = models.ForeignKey(User, null=True) class NoteData(model): created = models.DateTimeField(default=datetime.now) ...
[ "Note.objects.all().order_by('note_data__created')\n\nThis is fully documented.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008037103_django_python.txt
Q: Quick and easy way to check if all items in a dictionary are empty strings? I have a dictionary of N items. Their values are strings, but I'm looking for an easy way to detect if they are all empty strings. {'a': u'', 'b': u'', 'c': u''} A: not any(dict.itervalues()) Or: all(not X for X in dict.itervalues()) W...
Quick and easy way to check if all items in a dictionary are empty strings?
I have a dictionary of N items. Their values are strings, but I'm looking for an easy way to detect if they are all empty strings. {'a': u'', 'b': u'', 'c': u''}
[ "not any(dict.itervalues())\n\nOr:\nall(not X for X in dict.itervalues())\n\nWhichever you find clearer.\n", "Try this:\n>>> d={'a':'', 'b':'', 'c':''}\n>>> any(map(bool, d.values()))\nFalse\n>>> d={'a':'', 'b':'', 'c':'oaeu'}\n>>> any(map(bool, d.values()))\nTrue\n\n" ]
[ 12, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008037060_python.txt
Q: How to simulate a "myscript.py > mylog.txt" I try to implement an option which will save the console output additionally into a file. (if the option is activated) I found two ways: 1. to use the logging module 2. to write a class like this: class MyWriter: def __init__(self, stdout, filename): self.s...
How to simulate a "myscript.py > mylog.txt"
I try to implement an option which will save the console output additionally into a file. (if the option is activated) I found two ways: 1. to use the logging module 2. to write a class like this: class MyWriter: def __init__(self, stdout, filename): self.stdout = stdout self.logfile = file(filen...
[ "If I understand you correctly, you want to redirect stdout of other process that you start right?\nThen all you have to do is use \nsubprocess.Popen(...)\n\ncommand. Then you have use your MyWriter class with it.\n", "My suggestion would be to use the logging module, to use a sockethandler and to push to a socke...
[ 1, 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008036832_logging_python.txt
Q: Why is time.sleep pausing early? I'm teaching myself python with the aid of Head First Programming. I thought I might tweak their example more to my liking, but I think I'm missing something about time.sleep. My code is print("Welcome to SuperBeans!") time.sleep(3) answer = input("Do you need a price now? y/n: ") ...
Why is time.sleep pausing early?
I'm teaching myself python with the aid of Head First Programming. I thought I might tweak their example more to my liking, but I think I'm missing something about time.sleep. My code is print("Welcome to SuperBeans!") time.sleep(3) answer = input("Do you need a price now? y/n: ") But rather than pausing for three sec...
[ "As discussed in comments above, Python output is being buffered, so the programs run (and sleeps for the right time etc) but you don't see the output for a while.\nIf you're running Python from a nonstandard console, you need to pass the \"-u\" option to Python to disable the buffering. I.e.:\npython -u foo.py\n\...
[ 3, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0008031410_python_time.txt
Q: One single MySQL database for many web2py applications I have 3 apps under my web2py framework. Can I use one single MySQL database for all of them (by prefixing tables) so users just need only one single registration to access those 3 apps? I fail on my attempts. Or any other solutions? Thanks so much. A: If mu...
One single MySQL database for many web2py applications
I have 3 apps under my web2py framework. Can I use one single MySQL database for all of them (by prefixing tables) so users just need only one single registration to access those 3 apps? I fail on my attempts. Or any other solutions? Thanks so much.
[ "If multiple apps share the same database table, all but one of the apps must define that table with migrate=False to prevent migration attempts. Note, Auth.define_tables() also takes a migrate argument, so to turn off migrations specifically for the Auth tables, you can do:\nauth.define_tables(migrate=False)\n\nYo...
[ 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0008033307_python_web2py.txt
Q: GQLQuery retrieves empty result set I'm running a GQLQuery to lookup if a user entered the correct credentials: class User(db.Model): UserName = db.TextProperty(); Password = db.TextProperty(); Ticket = db.TextProperty(); class Authentication(webapp.RequestHandler): def post(self): str_use...
GQLQuery retrieves empty result set
I'm running a GQLQuery to lookup if a user entered the correct credentials: class User(db.Model): UserName = db.TextProperty(); Password = db.TextProperty(); Ticket = db.TextProperty(); class Authentication(webapp.RequestHandler): def post(self): str_user = self.request.get('user') str_...
[ "This is probably because you use TextProperty on your fields. TextProperty is for multi-line texts and is not indexed. You can't lookup for non-indexed values in query. You should use StringProperty for single-line text values.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0008037130_google_app_engine_google_cloud_datastore_python.txt
Q: Python interpreter exits when loading DLL I want to test wrapping a dll with ctypes. I've written the following test code and compiled it using Code::Blocks and Cygwin to a dll. #define DLL_EXPORT extern "C" __declspec(dllexport) DLL_EXPORT int sum(int a, int b) { return a + b; } Note: This is the whole code...
Python interpreter exits when loading DLL
I want to test wrapping a dll with ctypes. I've written the following test code and compiled it using Code::Blocks and Cygwin to a dll. #define DLL_EXPORT extern "C" __declspec(dllexport) DLL_EXPORT int sum(int a, int b) { return a + b; } Note: This is the whole code. Maybe there is something missing ? Now, I cop...
[ "Check objdump -p TestDll.dll | grep dll to see if you've linked in \"cygwin1.dll\" and nm TestDll.dll | grep Dll to see if you have a DllMain. The following command should build the DLL correctly:\ng++ testdll.c -mno-cygwin -shared -o TestDll.dll\n\nAlso, you need to use CDLL for the cdecl calling convention, not ...
[ 2, 1 ]
[]
[]
[ "c++", "ctypes", "python" ]
stackoverflow_0008037306_c++_ctypes_python.txt
Q: Catch a key press using accelerator tables without preventing typing in text controls I am trying to use an accelerator table to catch a key press globally in the window so that I can fire a method in response. However, the accelerator table seems to destroy the event that would otherwise be created by pressing th...
Catch a key press using accelerator tables without preventing typing in text controls
I am trying to use an accelerator table to catch a key press globally in the window so that I can fire a method in response. However, the accelerator table seems to destroy the event that would otherwise be created by pressing the key, preventing me from typing it into text controls. Is there any way to get around this...
[ "It's hard to say what the issue is without more information, like OS, wx version or a small example that shows the problem. However, here are a couple example articles on the subject that might help you figure out the problem:\nhttp://www.blog.pythonlibrary.org/2008/07/02/wxpython-working-with-menus-toolbars-and-a...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008033103_python_wxpython.txt
Q: Python Iterating through a list of float widths: TypeError: sequence expected, generator found I am trying to iterate through a list of float widths that varies. [10.5, 15.5, 3.7] <- Randomly generated I am using this list of floats to generate spaces between a list of strings I am trying to print. I am doing t...
Python Iterating through a list of float widths: TypeError: sequence expected, generator found
I am trying to iterate through a list of float widths that varies. [10.5, 15.5, 3.7] <- Randomly generated I am using this list of floats to generate spaces between a list of strings I am trying to print. I am doing this via print ''.join('%*s' %i for i in zip(WIDTHS, LIST_OF_STRINGS)) I am getting the error TypeEr...
[ "You should actually get the error message\nTypeError: * wants int\n\nConvert your floating point numbers to ints first:\nwidths = map(int, widths)\n\nExample:\n>>> widths = [10.5, 15.5, 3.7]\n>>> s = [\"a\", \"b\", \"c\"]\n>>> widths = map(int, widths)\n>>> ''.join('%*s' %i for i in zip(widths, s))\n' a ...
[ 3, 1 ]
[]
[]
[ "printing", "python", "string", "width" ]
stackoverflow_0008037888_printing_python_string_width.txt
Q: json decode issue with bing data (python) I am in trouble with the bing's json api. Here is the json data i am receiving from api.bing.net/json.aspx: {"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"news"},"Translation":{"Results":[{"TranslatedTerm":"Noticias"}]}}} I need to parse the TranslatedTerm va...
json decode issue with bing data (python)
I am in trouble with the bing's json api. Here is the json data i am receiving from api.bing.net/json.aspx: {"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"news"},"Translation":{"Results":[{"TranslatedTerm":"Noticias"}]}}} I need to parse the TranslatedTerm value "Noticias" but it seems i have a problem wi...
[ "The translation Results is a list - presumably because there can be many results.\nIf you're sure you're only interested in the first result, you can do this:\nresult['SearchResponse']['Translation']['Results'][0]['TranslatedTerm']\n\n" ]
[ 3 ]
[]
[]
[ "bing", "bing_api", "json", "python" ]
stackoverflow_0008037992_bing_bing_api_json_python.txt
Q: django-reversion how to get user-id I'm using django-reversion for providing history for models I discovered that reversion creates two tables, the table 'reversion_revision' and the 'reversion_version' And in the reversion_revision, are stored the user id who makes last changes. But i cant get that information...
django-reversion how to get user-id
I'm using django-reversion for providing history for models I discovered that reversion creates two tables, the table 'reversion_revision' and the 'reversion_version' And in the reversion_revision, are stored the user id who makes last changes. But i cant get that information. I use the function 'reversion.get_for_o...
[ "revision is a foreign key on Version. And, reversion.get_for_object(Model) simply returns a queryset of Versions. So, for any item in that query set, you can simply access the user as so:\nversion.revision.user\n\nUPDATE: Just to be more explicit:\nversions = reversion.get_for_object(MyModel)\n\nfor version in ver...
[ 6 ]
[]
[]
[ "django", "django_reversion", "python", "reversion" ]
stackoverflow_0008038035_django_django_reversion_python_reversion.txt
Q: Escape ' in Python What's the right code for this case: p = subprocess.Popen(["git", "log" , "-1", "--pretty=format:\'%s %n%n%b\'", hash], stdout=subprocess.PIPE) out, err = p.communicate() print out message += '\n' + out I always get this error: fatal: ambiguous argument '': unknown revision or path not in t...
Escape ' in Python
What's the right code for this case: p = subprocess.Popen(["git", "log" , "-1", "--pretty=format:\'%s %n%n%b\'", hash], stdout=subprocess.PIPE) out, err = p.communicate() print out message += '\n' + out I always get this error: fatal: ambiguous argument '': unknown revision or path not in the working tree. output:...
[ "Since the call isn't parsed by a shell, you don't need the quotes at all:\np = subprocess.Popen(\n [\"git\", \"log\" , \"-1\", \"--pretty=format:%s %n%n%b\", hash],\n stdout=subprocess.PIPE)\n\n", "I'm not sure whether you want to include the backslashes or not so I just put this here\n>>> s = \"--pretty=...
[ 6, 0 ]
[]
[]
[ "git", "python" ]
stackoverflow_0008038348_git_python.txt
Q: wxPython: call a wxApp from another wxApp Is it possible to run a wxApp from another wxApp? I am trying to simply call a program I wrote (called DataDeck) from a method of another wxApp, like it was a plugin. something like: def on_datadeck_btn_click(self, event): import datadeck.main datadeck.main...
wxPython: call a wxApp from another wxApp
Is it possible to run a wxApp from another wxApp? I am trying to simply call a program I wrote (called DataDeck) from a method of another wxApp, like it was a plugin. something like: def on_datadeck_btn_click(self, event): import datadeck.main datadeck.main.run() event.Skip() where datadeck.mai...
[ "There should only be on wx.App. From what I've read online, you can't have two wx.App objects running in one script. You could probably do it using the subprocess module to open a new process though. Take a look at Editra to see some examples for how to do plugins. It is included with wxPython or you can download ...
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008014752_python_wxpython.txt
Q: glob "one or more" in Python I need to get all text files with numeric names: 1.txt, 2.txt, 13.txt Is it possible to do with glob? import glob for file in glob.glob('[0-9].txt'): print(file) Does not return 13.txt. And there seems to be no regex's one or more + operator. What can I do? A: I don't think th...
glob "one or more" in Python
I need to get all text files with numeric names: 1.txt, 2.txt, 13.txt Is it possible to do with glob? import glob for file in glob.glob('[0-9].txt'): print(file) Does not return 13.txt. And there seems to be no regex's one or more + operator. What can I do?
[ "I don't think that glob() is meant to be that customisable. You might want to try os.listdir() instead:\nimport os,re\nfor f in os.listdir(\"/path/to/dir\"):\n if re.match(r\"^\\d+\\.txt$\", f):\n print(f)\n\n", "From TFM:\n\nNo tilde expansion is done, but *, ?, and character ranges expressed\n with...
[ 2, 2 ]
[]
[]
[ "glob", "python" ]
stackoverflow_0008038345_glob_python.txt
Q: issue when implementing a non-blocking publishing mechanism with zeromq I would like to communicate two processes (sender and receiver) using zeromq. Now, if the receiver process is not running, I would like that the sender process continues its execution, even if the message is lost. Trying to implement it using...
issue when implementing a non-blocking publishing mechanism with zeromq
I would like to communicate two processes (sender and receiver) using zeromq. Now, if the receiver process is not running, I would like that the sender process continues its execution, even if the message is lost. Trying to implement it using the PUB-SUB pattern, I have noticed that if the receiver is not running, the...
[ "You can easily change: sender.connect(\"tcp://localhost:5555\") to sender.bind(\"tcp://localhost:5555\") and vise-versa on receiver.\nIt gives you ability to connect receiver wherever you like. Sender would work no matter is there are receivers or not.\n", "After fixing your sample:\nimport zmq\n\ncontext = zmq....
[ 3, 3 ]
[]
[]
[ "nonblocking", "python", "zeromq" ]
stackoverflow_0008038367_nonblocking_python_zeromq.txt
Q: Circular module dependencies in Python/Django with split-up models I understand how to break up models, and I understand why circular module dependencies blow things up, but I've run across a problem where breaking up a model into separate files appears to be causing circular dependencies. Here's an exerpt from t...
Circular module dependencies in Python/Django with split-up models
I understand how to break up models, and I understand why circular module dependencies blow things up, but I've run across a problem where breaking up a model into separate files appears to be causing circular dependencies. Here's an exerpt from the code, and I'll follow it up with the traceback from the failing proce...
[ "Your problem is that Permission imports Product, but both are imported in ecom/models/__init__.py. You should find a way to either have these two models in the same file or separate them into two apps.\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008038303_django_python.txt
Q: matplotlib hist while ignoring a particular no data value I've got a 2D numpy array with 1.0e6 as the no data value. I'd like to generate a histogram of the data and while I've succeeded this can't be the best way to do it. from matplotlib import pyplot import sys eps = sys.float_info.epsilon no_data = 1.0e6 e_...
matplotlib hist while ignoring a particular no data value
I've got a 2D numpy array with 1.0e6 as the no data value. I'd like to generate a histogram of the data and while I've succeeded this can't be the best way to do it. from matplotlib import pyplot import sys eps = sys.float_info.epsilon no_data = 1.0e6 e_data = elevation.reshape(elevation.size) e_data_clean = [ ] fo...
[ "You can use a boolean array to select the required indices:\nselected_values = (e_data > (no_data + eps)) & (e_data < (no_data - eps))\npyplot.hist(e_data[selected_values])\n\n(e_data > (no_data + eps)) will create an array of np.bool with the same shape as e_data, set to True at a given index if and only if the v...
[ 9 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0008039276_matplotlib_numpy_python.txt
Q: Python 3.2.2 print function syntax error on Mac but not on Windows I am currently testing on a Mac a python program developed in Windows on Python 3.2. When the program is run on Windows there is no problem, but when run on a Mac I get a syntax error pointing to the following print function: LOGFILE = open('./tes...
Python 3.2.2 print function syntax error on Mac but not on Windows
I am currently testing on a Mac a python program developed in Windows on Python 3.2. When the program is run on Windows there is no problem, but when run on a Mac I get a syntax error pointing to the following print function: LOGFILE = open('./test.log','w') print('Testing Started\n', file = LOGFILE) ...
[ "The most likely explanation is that you're running your script using Python 2.x. There could be multiple interpreters installed on the system, so I'd suggest making sure that you're using the interpreter that you think you're using.\nTry printing out sys.version from within your script.\n" ]
[ 6 ]
[]
[]
[ "macos", "printing", "python", "syntax_error", "windows" ]
stackoverflow_0008039364_macos_printing_python_syntax_error_windows.txt
Q: Want to store last paragraph to any variable I have long text. And I'm converting this string to dict. Here is code data_dict = {} filter_dict = {} for each in text.split("\n"): temp = each.split('=') if len(temp) == 2: data_dict[temp[0]] = temp[1] data = dict((k.strip(), v.strip()) for k, ...
Want to store last paragraph to any variable
I have long text. And I'm converting this string to dict. Here is code data_dict = {} filter_dict = {} for each in text.split("\n"): temp = each.split('=') if len(temp) == 2: data_dict[temp[0]] = temp[1] data = dict((k.strip(), v.strip()) for k, v in data_dict.iteritems()) Here is output which ...
[ "You are not storing the text at the bottom. The only place where you assign values to the dictionary entries is under the if len(temp) == 2. Since that text paragraph doesn't have an equal sign, this part will simply fall through and nothing will be done. You need an 'else' somewhere there\n", "As has been po...
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "regex" ]
stackoverflow_0008039422_dictionary_python_regex.txt
Q: Public key not recognized I am trying to export a public key from openssl using python. I have the actual key information transferred to the client from the server but the PEM encoding is not transferred so the key on the client is useless. I basically send the public key using send all in python but unfortunate...
Public key not recognized
I am trying to export a public key from openssl using python. I have the actual key information transferred to the client from the server but the PEM encoding is not transferred so the key on the client is useless. I basically send the public key using send all in python but unfortunately this does not send the PEM e...
[ "The mistake was that the public/private key pair needs to be created from the same wrapper. What I mean by this is that not all key pairs are the same. My specific problem was that Openssl and the M2Crypto instances of key pairs were not in the same underlying format. Thus creating keys with Openssl and then tr...
[ 2 ]
[]
[]
[ "file_transfer", "pem", "public_key_encryption", "python" ]
stackoverflow_0007946777_file_transfer_pem_public_key_encryption_python.txt
Q: Ejabberd, Python: Check user, if not create Is it possible to talk to an Ejabberd interface from python through and xmpp client like sleekxmpp to create a user if it does not exist? Can someone advice the best approach? A: Did you check in-band registration already ? The specification is here: http://xmpp.or...
Ejabberd, Python: Check user, if not create
Is it possible to talk to an Ejabberd interface from python through and xmpp client like sleekxmpp to create a user if it does not exist? Can someone advice the best approach?
[ "Did you check in-band registration already ?\nThe specification is here: http://xmpp.org/extensions/xep-0077.html\nIf you configure ejabberd to allow in-band registration, then your client will be able to create an account if it does not exist yet.\n", "If Twisted is an option for you, you can adapt my jarn.xmpp...
[ 1, 0 ]
[]
[]
[ "ejabberd", "python", "xmpp" ]
stackoverflow_0007785285_ejabberd_python_xmpp.txt
Q: Redis: find all objects older than I store several properties of objects in hashsets. Among other things, something like "creation date". There are several hashsets in the db. So, my question is, how can I find all objects older than a week for example? Can you suggest an algorithm what faster than O(n) (naive imp...
Redis: find all objects older than
I store several properties of objects in hashsets. Among other things, something like "creation date". There are several hashsets in the db. So, my question is, how can I find all objects older than a week for example? Can you suggest an algorithm what faster than O(n) (naive implementation)? Thanks, Oles
[ "My initial thought would be to store the data elsewhere, like relational database, or possibly using a zset.\nIf you had continuous data (meaning it was consistently set at N interval time periods), then you could store the hash key as the member and the date (as a int timestamp) as the value. Then you could do a...
[ 2 ]
[]
[]
[ "python", "redis" ]
stackoverflow_0008039566_python_redis.txt
Q: Python simplepyged graphical representation of family trees Does anyone know a way to use the python package simplepyged (for parsing gedcom files) for graphical representation of family trees? XY-Pic? Matlibplot? pictex? I appreciate any help! Thanks! A: Author here. Sorry, simplepyged does not support anything...
Python simplepyged graphical representation of family trees
Does anyone know a way to use the python package simplepyged (for parsing gedcom files) for graphical representation of family trees? XY-Pic? Matlibplot? pictex? I appreciate any help! Thanks!
[ "Author here. Sorry, simplepyged does not support anything like that. But, if you wish, we can code it together :-)\n" ]
[ 2 ]
[]
[]
[ "family_tree", "gedcom", "graph_layout", "python" ]
stackoverflow_0008024302_family_tree_gedcom_graph_layout_python.txt
Q: python, how i do xml = '%??' % datetime.datetime is there any way to pass a datetime directly in this format? mydate = datetime.datetime.now() myxmldate = '<start>%??</start>' % mydate or have i to pass like a string? I need to pass to an xml a datetime structure. thanks A: Try with datetime.isoformat() mydate ...
python, how i do xml = '%??' % datetime.datetime
is there any way to pass a datetime directly in this format? mydate = datetime.datetime.now() myxmldate = '<start>%??</start>' % mydate or have i to pass like a string? I need to pass to an xml a datetime structure. thanks
[ "Try with datetime.isoformat()\nmydate = datetime.datetime.now()\nmyxmldate = '<start>%s</start>' % mydate.isoformat()\n\n", "Try to reed for 2.6:\n>>> mydate.isoformat()\n'2002-03-11'\n>>> mydate.strftime(\"%d/%m/%y\")\n'11/03/02'\n>>> mydate.strftime(\"%A %d. %B %Y\")\n'Monday 11. March 2002'\n\nAnd for version...
[ 2, 1, 0 ]
[]
[]
[ "datetime", "parameters", "python", "xml" ]
stackoverflow_0008040054_datetime_parameters_python_xml.txt
Q: Parsing out paragraphs in one line of html using python Given the flexibility of HTML codes, parsing out paragraphs as seen by a user through browser seems to be a quite non-trivial task. For now, I have a not so robust solution: tree = lxml.etree.fromstring(html, lxml.etree.HTMLParser()) if isinstance(html, bases...
Parsing out paragraphs in one line of html using python
Given the flexibility of HTML codes, parsing out paragraphs as seen by a user through browser seems to be a quite non-trivial task. For now, I have a not so robust solution: tree = lxml.etree.fromstring(html, lxml.etree.HTMLParser()) if isinstance(html, basestring) else html for skiptag in ('//script', '//iframe', '//...
[ "Use the xpath method to loop over all paragraphs:\nfor para in tree.xpath(\"//p\"):\n ...\n\n", "Have a look at html2text.\nIt may not do exactly what you want, but it's only a 500 line script, so it should be pretty easy to adapt it to your particular needs.\n" ]
[ 3, 1 ]
[]
[]
[ "lxml", "parsing", "python" ]
stackoverflow_0008032022_lxml_parsing_python.txt
Q: python- construction of lattice which traps molecules - doesn't work right I have this problem : Create a program which constructs a lattice of one (1) dimension and 100000 sites. In this lattice put at random positions a number of trap molecules, which will have concentration c. Put 1 particle in a random ...
python- construction of lattice which traps molecules - doesn't work right
I have this problem : Create a program which constructs a lattice of one (1) dimension and 100000 sites. In this lattice put at random positions a number of trap molecules, which will have concentration c. Put 1 particle in a random position on the lattice and let it perform a random walk. In this walk you wil...
[ "On a smaller lattice, to see what is happening:\nimport numpy\n\n# Populate the lattice\nlattice = numpy.concatenate([numpy.ones(90), numpy.zeros(10)])\nnumpy.random.shuffle(lattice)\n\n# Intialize problem\nin_trap = False\nsteps = 0\npos = int(numpy.random.randint(0,len(lattice),1))\nhistory = []\n\nwhile in_trap...
[ 2, 0 ]
[]
[]
[ "python", "random_walk", "scipy" ]
stackoverflow_0008038420_python_random_walk_scipy.txt