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: Query client's timezone with Google AppEngine XMPP library Context I have a jabber bot implemented in Python on Google AppEngine and their xmpp library. The bot forwards posts from a social network and I'd like post timestamps are in client's timezone. Question Is it possible (and how) to query client for their lo...
Query client's timezone with Google AppEngine XMPP library
Context I have a jabber bot implemented in Python on Google AppEngine and their xmpp library. The bot forwards posts from a social network and I'd like post timestamps are in client's timezone. Question Is it possible (and how) to query client for their local timezone so my bot can do respective adjustments? Again, the...
[ "Currently it is not possible, although XMPP has the ability to query for time zone Google App Engine doesn't allow to send raw stanzas.\nThere is an issue about it in acknowledged mode but don't bet on seeing it anytime soon.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "xmpp" ]
stackoverflow_0007727885_google_app_engine_python_xmpp.txt
Q: csv rows into separate txt files? Task 1: Read each row from one csv file into one seprate txt file. Task 2: Reverse: in one folder, read text from each txt file and put into a row in a single csv. So, read all txt files into one csv file. How would you do this? Would Java or Python be good to get this task done i...
csv rows into separate txt files?
Task 1: Read each row from one csv file into one seprate txt file. Task 2: Reverse: in one folder, read text from each txt file and put into a row in a single csv. So, read all txt files into one csv file. How would you do this? Would Java or Python be good to get this task done in very quickly? Update: For Java, there...
[ "From what you write there is little need on using something specific for CSV files. In particular for Task 1, this is a pure data I/O operation on text files. In Python for instance:\nfor i,l in enumerate(open(the_file)):\n f = open('new_file_%i.csv' % i, 'w')\n f.write(l)\n f.close()\n\nFor Task 2, if you c...
[ 3, 1, 0 ]
[]
[]
[ "csv", "java", "python", "text_files" ]
stackoverflow_0007728029_csv_java_python_text_files.txt
Q: How to define range of months for any year on Django model? I have a Django model called Event that has a date field for the date of the event: class Event(models.Model): event_date = models.DateField() I'd like to be able to set a method on the model to tell whether the event is a "spring semester" event or ...
How to define range of months for any year on Django model?
I have a Django model called Event that has a date field for the date of the event: class Event(models.Model): event_date = models.DateField() I'd like to be able to set a method on the model to tell whether the event is a "spring semester" event or a "fall semester" event. The spring semester would be defined as ...
[ "One approach is:\nclass SpringSemesterEventManager(models.Manager):\n def get_query_set(self):\n return super(SpringSemesterEventManager, self).get_query_set() \\\n .filter(is_spring_semester=True)\n\nclass FallSemesterEventManager(models.Manager):\n def get_query_set(self):\n return...
[ 2, 1, 1 ]
[]
[]
[ "date", "django", "methods", "python" ]
stackoverflow_0007727801_date_django_methods_python.txt
Q: self.exit and self.quit do not exit PyQt application I'm trying to write a PyQt application that renders HTML, waits, and finishes. I've got the rendering mostly down (but stripped out here for simplicity's sake). The code here runs and hangs, it seems as if the self.exit call (or self.quit) is not being honored. ...
self.exit and self.quit do not exit PyQt application
I'm trying to write a PyQt application that renders HTML, waits, and finishes. I've got the rendering mostly down (but stripped out here for simplicity's sake). The code here runs and hangs, it seems as if the self.exit call (or self.quit) is not being honored. Having no prior experience with Qt, I feel as if I'm missi...
[ "I don't really understand what you are trying to do but, that said, you are calling exit (or quit) in the constructor of your QApplication. exit (or quit) tells the QApplication to leave its event loop, but in the constructor, the eventloop is not yet started (it is once exec_ is called).\n" ]
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0007728220_pyqt_pyqt4_python.txt
Q: Pygraph - path between two nodes with specific weight I want to find a path in a graph that has connects two nodes and does not use the same node twice. The sum of the weights of the edges must be within a certain range. I need to implement this in pygraph. I'm not sure if there is already an algorithm that I can...
Pygraph - path between two nodes with specific weight
I want to find a path in a graph that has connects two nodes and does not use the same node twice. The sum of the weights of the edges must be within a certain range. I need to implement this in pygraph. I'm not sure if there is already an algorithm that I can use for this purpose or not. What's the best way to achiev...
[ "EDIT: I misunderstood the question initially. I've corrected my answer. This functionality isn't built into the pygraphlib library, but you can easily implement it. Consider something like this, which basically gets the shortest path, decides if it's in a predefined range, then removes the edge with the smalle...
[ 2 ]
[]
[]
[ "graph", "pygraph", "python" ]
stackoverflow_0007728481_graph_pygraph_python.txt
Q: Python instances/Django Say I want to print all my installed apps their version info on server startup.. I have this setup: Project /app-one __init__.py otherstuff /app-two __init__.py otherstuff /__init__.py /admin.py /urls.py /settings.py main init file im...
Python instances/Django
Say I want to print all my installed apps their version info on server startup.. I have this setup: Project /app-one __init__.py otherstuff /app-two __init__.py otherstuff /__init__.py /admin.py /urls.py /settings.py main init file import settings if settings.DE...
[ "app in your loop is not a module but a string. To load module by name you have to use django.utils.importlib.import_module function:\nfrom django.conf import settings\nfrom django.utils.importlib import import_module\n\nfor app in settings.INSTALLED_APPS:\n app_module = import_module(app)\n print getattr(app...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007728414_django_python.txt
Q: (boost.python) Error exposing overloaded operator+(). "TypeError: No to_python (by-value) converter found" I'm a newbie in boost.python and i'm getting this error that I would like to get some help with. As a part of a larger project I'm writing a wrapper for a vector class that I have. As you will notice from the...
(boost.python) Error exposing overloaded operator+(). "TypeError: No to_python (by-value) converter found"
I'm a newbie in boost.python and i'm getting this error that I would like to get some help with. As a part of a larger project I'm writing a wrapper for a vector class that I have. As you will notice from the code bellow, this class can be 2D or 3D, but not a big difference for the current problem I'm having. I'm tryin...
[ "It seems the matrix/vector library is using expression templates. In this case, and as you have remarked, operator+ is not returning a vector but a private type that represents the operation. The returned value is left trapped on the C++ side of things and can't be passed to Python as the private type is not regis...
[ 3 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0007728382_boost_boost_python_c++_python.txt
Q: ERROR - python.sdk.PySkeletonRefresher reported by pycharm.sh I have seen the following errors while I start to set the environment of pycharm. Should I address those issues or it is ok to leave it. Thank you user@ubuntu:~/Downloads/pycharm-1.5.4/bin$ ./pycharm.sh [ 426143] ERROR - python.sdk.PySkeletonRefresher...
ERROR - python.sdk.PySkeletonRefresher reported by pycharm.sh
I have seen the following errors while I start to set the environment of pycharm. Should I address those issues or it is ok to leave it. Thank you user@ubuntu:~/Downloads/pycharm-1.5.4/bin$ ./pycharm.sh [ 426143] ERROR - python.sdk.PySkeletonRefresher - Exit code 137 java.lang.Throwable at com.intellij.openapi....
[ "Please file a bug report in the PyCharm issue tracker.\n" ]
[ 1 ]
[]
[]
[ "pycharm", "python", "ubuntu_11.04" ]
stackoverflow_0007728485_pycharm_python_ubuntu_11.04.txt
Q: Strange exception with python's cgitb and inspect.py I have a function that decodes an exception and pushes the info to a file. Following is what I do basically: exc_info = sys.exc_info txt = cgitb.text(exc_info) Using this, I got the following exception trace: Traceback (most recent call last): File "<stdin>...
Strange exception with python's cgitb and inspect.py
I have a function that decodes an exception and pushes the info to a file. Following is what I do basically: exc_info = sys.exc_info txt = cgitb.text(exc_info) Using this, I got the following exception trace: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages...
[ "You passed a wrong type to text function\nbelow is the correct way.\ncgitb.text((sys.last_type, sys.last_value, sys.last_traceback))\n", "Im not sure specifically why this exception is happening, but have you read the docs for cgitb module? It seems that since python 2.2 it has supported writing exceptions to a ...
[ 1, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0007623329_python_python_2.7.txt
Q: move a file to the current directory using shutil module I know this may sound really stupid, but how can I move a file in a directory a user browsed to ( I named mine filedir) to the current directory I am in? for example: I have a file called "pages.html" in "C:\webs". How can I move that file to the current wo...
move a file to the current directory using shutil module
I know this may sound really stupid, but how can I move a file in a directory a user browsed to ( I named mine filedir) to the current directory I am in? for example: I have a file called "pages.html" in "C:\webs". How can I move that file to the current working directory "."? This is my code: shutil.move(filedir, "*....
[ "The second argument of shutil.move specifies a directory, not a glob mask:\nimport os.path\nshutil.move(os.path.join(filedir, \"pages.html\"), os.getcwd())\n\nshould work.\n", "It would be very helpful if you posted the error message and the complete traceback. However, to get the current working directory you c...
[ 4, 2 ]
[]
[]
[ "cmd", "python", "shutil" ]
stackoverflow_0007729210_cmd_python_shutil.txt
Q: writing Python shell output to file Very simple question. I am using the IDLE Python shell to run my Python scripts. I use the following type of structure import sys sys.argv = ['','fileinp'] execfile('mypythonscript.py') Is there a simple way of outputting the results to a file? Something like execfile('mypython...
writing Python shell output to file
Very simple question. I am using the IDLE Python shell to run my Python scripts. I use the following type of structure import sys sys.argv = ['','fileinp'] execfile('mypythonscript.py') Is there a simple way of outputting the results to a file? Something like execfile('mypythonscript.py') > 'output.dat' Thanks
[ "$ python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\n\n>>> import sys\n>>> sys.displayhook(stdout)\n<open file '<stdout>', mode 'w' at 0x7f8d3197a150>\n>>> x=open('myFile','w')\n>>> sys.displayhook(x)\n<open file 'myFile', mode 'w' at 0x7fb729060c00>\n>>> sys.stdout=x\n>>> print 'cha...
[ 5, 4 ]
[]
[]
[ "python", "python_idle", "shell" ]
stackoverflow_0007728991_python_python_idle_shell.txt
Q: How to capture the build number from the Buildbot Is there a variable that I can access in master.cfg? The docs aren't clear at all. Thanks. A: There are ways of getting this information, but it depends on where you are trying to access it. If you are inside a doStepIf procedure (as a parameter to addStep), this...
How to capture the build number from the Buildbot
Is there a variable that I can access in master.cfg? The docs aren't clear at all. Thanks.
[ "There are ways of getting this information, but it depends on where you are trying to access it.\nIf you are inside a doStepIf procedure (as a parameter to addStep), this should work:\ndef insideDoStepIf(step):\n step.build.getStatus().number\n\nIf you are trying to prioritize your builders by their next build ...
[ 6 ]
[]
[]
[ "buildbot", "python" ]
stackoverflow_0007714605_buildbot_python.txt
Q: Method to reverse a string Hi I'm trying to reverse a string with the following code. Does anyone see the bug here? def reverse(string): length = len(string) last = length -1 middle = length/2 newstring = [] for i in range(middle): newstring[i] = string[last -i] newstrin...
Method to reverse a string
Hi I'm trying to reverse a string with the following code. Does anyone see the bug here? def reverse(string): length = len(string) last = length -1 middle = length/2 newstring = [] for i in range(middle): newstring[i] = string[last -i] newstring[last -i] = string[i] retur...
[ "There are multiple bugs:\n\nYou can't index into an empty list: newstring[i] and newstring[last -i].\nYou always add characters in pairs, so the result (if other bugs are fixed) always has an even length, even if the input string had an odd length.\n\nThere may be more.\nLastly, I think you're making it too hard f...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007729347_python_string.txt
Q: Python HDF5 H5Py issues opening multiple files I am usint the 64-bit version of Enthought Python to process data across multiple HDF5 files. I'm using h5py version 1.3.1 (HDF5 1.8.4) on 64-bit Windows. I have an object that provides a convenient interface to my specific data heirarchy, but testing the h5py.File...
Python HDF5 H5Py issues opening multiple files
I am usint the 64-bit version of Enthought Python to process data across multiple HDF5 files. I'm using h5py version 1.3.1 (HDF5 1.8.4) on 64-bit Windows. I have an object that provides a convenient interface to my specific data heirarchy, but testing the h5py.File(fname, 'r') independently yields the same results. ...
[ "I've concluded that this is a strange manifestation of Perplexing assignment behavior with h5py object as instance variable . I re-wrote my code so that each file is handled within a function call and the variable is not reused. Using this approach, I don't see the same strange behavior and it seems to work much...
[ 4 ]
[]
[]
[ "h5py", "hdf5", "python" ]
stackoverflow_0007675838_h5py_hdf5_python.txt
Q: Exit signal not being caught in PyQt Writing a script to render arbitrary HTML as an image, and using PyQt. I'm confused as to why my QApplication.exit call isn't making QApplication.exec_ return. Any ideas on this? class ScreenshotterApplication(QApplication): def __init__(self, args, html): QApplica...
Exit signal not being caught in PyQt
Writing a script to render arbitrary HTML as an image, and using PyQt. I'm confused as to why my QApplication.exit call isn't making QApplication.exec_ return. Any ideas on this? class ScreenshotterApplication(QApplication): def __init__(self, args, html): QApplication.__init__(self, args) self.ht...
[ "QApplication.exit tells the application to leave the main event loop, i.e. to return from exec_() as soon as possible.\nYour problem is that the small piece of static HTML is so easy to retrieve and render, QtWebKit does it right when setHtml is called. No delays or background processing, everything's done before ...
[ 4 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0007730015_pyqt_python_qt.txt
Q: Macports duplicate packages I have already Python 2.7 on my Mac Os 10.7 and i tried to install py27-mysql package that contains MySQLdb interface for Python. I had run sudo ports install py27-mysql and macports began to install all dependencies for that package python2.7, mysql5, etc that I already has. Now the q...
Macports duplicate packages
I have already Python 2.7 on my Mac Os 10.7 and i tried to install py27-mysql package that contains MySQLdb interface for Python. I had run sudo ports install py27-mysql and macports began to install all dependencies for that package python2.7, mysql5, etc that I already has. Now the questions: Why that happens? Wher...
[ "Macports installs the packages in /opt/local/ and /opt/local/bin.\nYou can always find your default OS package installation in /bin and /usr/bin.\nOS default python installation: /usr/bin/python\nOf course, you can choose the macports by having /opt/local/bin first in your path. Macport installation works very wel...
[ 1 ]
[]
[]
[ "homebrew", "macos", "macports", "python" ]
stackoverflow_0007730207_homebrew_macos_macports_python.txt
Q: Fast RGB Thresholding in Python (possibly some smart OpenCV code?) I need to do some fast thresholding of a large amount of images, with a specific range for each of the RGB channels, i.e. remove (make black) all R values not in [100;110], all G values not in [80;85] and all B values not in [120;140] Using the pyt...
Fast RGB Thresholding in Python (possibly some smart OpenCV code?)
I need to do some fast thresholding of a large amount of images, with a specific range for each of the RGB channels, i.e. remove (make black) all R values not in [100;110], all G values not in [80;85] and all B values not in [120;140] Using the python bindings to OpenCV gives me a fast thresholding, but it thresholds a...
[ "I think the inRange opencv method is what you are interested in. It will let you set multiple thresholds simultaneously.\nSo, with your example you would use\n# Remember -> OpenCV stores things in BGR order\nlowerBound = cv.Scalar(120, 80, 100);\nupperBound = cv.Scalar(140, 85, 110);\n\n# this gives you the mask f...
[ 6, 6, 2, 0 ]
[]
[]
[ "opencv", "python", "rgb", "threshold" ]
stackoverflow_0007722519_opencv_python_rgb_threshold.txt
Q: Django static files not loading with default setup So I installed Bitnami Django stack, and enabled the admin module, and followed the tutorial for creating an admin menu for "Polls". However, when I go to /admin/ everything is white plaintext. All the css and images are 404 error. All I did was: enable in settin...
Django static files not loading with default setup
So I installed Bitnami Django stack, and enabled the admin module, and followed the tutorial for creating an admin menu for "Polls". However, when I go to /admin/ everything is white plaintext. All the css and images are 404 error. All I did was: enable in settings.py installed_apps: 'django.contrib.admin', In urls.p...
[ "I almost missed the answer to this until I re-read your question and finally caught the bit in the last line: \"and I type: localhost/Alpha/admin to go to admin\". That means all your URL settings are wrong.\nCurrently, you have:\nMEDIA_URL = '/media/'\nSTATIC_URL = '/static/'\nADMIN_MEDIA_PREFIX = STATIC_URL + 'a...
[ 4, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007666016_django_django_templates_python.txt
Q: Getting the value of a ModelForm's field Would any of you be able to tell me how I can get the data/value of a model-form's fields? I know how to get the initial data but if I've understood correctly, a form's fields also have a data/value value associated with it. Thanks A: You use cleaned_data https://docs.dja...
Getting the value of a ModelForm's field
Would any of you be able to tell me how I can get the data/value of a model-form's fields? I know how to get the initial data but if I've understood correctly, a form's fields also have a data/value value associated with it. Thanks
[ "You use cleaned_data https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form\nHere's an example:\n>> models.py\nclass Book(models.Model):\n author = models.CharField(max_length=140)\n\n>> forms.py\nclass BookForm(forms.ModelForm):\n\n class Meta:\n model = Book\n\n>> views....
[ 5 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007730370_django_django_forms_python.txt
Q: change process state with python I want to search for a process and show it,emacs for example,I use `p = subprocess.Popen('ps -A | grep emacs',shell=True,stdout=subprocess.PIPE)` to get the process, then how can I wake it up and show it? in other words,the question shoud be : how python change the state of proce...
change process state with python
I want to search for a process and show it,emacs for example,I use `p = subprocess.Popen('ps -A | grep emacs',shell=True,stdout=subprocess.PIPE)` to get the process, then how can I wake it up and show it? in other words,the question shoud be : how python change the state of process?
[ "In short, python has a pty module and look for the solution there.\nThis question is not that simple as it may look like.\nIt is simple to change the running state of a process by delivering corresponding signals but it is not simple to manipulate foreground/background properties.\nWhen we talk about manipulating ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007723006_python.txt
Q: Splitting a range of numbers up recursively with Python I would like to write a recursive function in Python. I have written one but it doesn't work correctly. I have a range of numbers from 1 to 1000 and I want cut it into two parts 1 to 500 and 501 to 1000. Then I want to do this recursively until there are onl...
Splitting a range of numbers up recursively with Python
I would like to write a recursive function in Python. I have written one but it doesn't work correctly. I have a range of numbers from 1 to 1000 and I want cut it into two parts 1 to 500 and 501 to 1000. Then I want to do this recursively until there are only 20 numbers in each part. Here is my attempt: mw = range(1,1...
[ "Try something like this, where seq is a list with the range of numbers:\ndef cutter(seq):\n n = len(seq)\n if n <= 20:\n # here the recursion stops, do your stuff with the sequence\n return\n a = cutter(seq[:n/2])\n b = cutter(seq[n/2:])\n # combine the answer from both subsequences\n ...
[ 4 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0007730471_python_recursion.txt
Q: Moving sprites with key events in pygame I just got a sprite moving around the window using "w,a,s,d", and i want to make this sprite "shoot" by pressing the space bar. The problem i've got is that the sprite appears but doesn't move until i release the space bar, and i want the sprite shot to go forward until the...
Moving sprites with key events in pygame
I just got a sprite moving around the window using "w,a,s,d", and i want to make this sprite "shoot" by pressing the space bar. The problem i've got is that the sprite appears but doesn't move until i release the space bar, and i want the sprite shot to go forward until the end of the window, just by pressing the space...
[ "You are setting xpos to the player most right position on every loop when the K_SPACE is pressed. You shouldn't do that. Try removing that line.\nif key[K_SPACE]:\n ypos = player.rect.top\n shot_on_screen = True\n\nAlso, I don't know if you are checking if the shot is on the screen somewhere else on the code...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007707450_pygame_python.txt
Q: Retrieving pages from what.cd I'm working on a screen scraper using BeautifulSoup for what.cd using Python. I came across this script while working and decided to look at it, since it seems to be similar to what I'm working on. However, every time I run the script I get a message that my credentials are wrong, e...
Retrieving pages from what.cd
I'm working on a screen scraper using BeautifulSoup for what.cd using Python. I came across this script while working and decided to look at it, since it seems to be similar to what I'm working on. However, every time I run the script I get a message that my credentials are wrong, even though they are not. As far as ...
[ "After a few more hours of searching, I found the solution to my problem. I'm still not sure why this code works as apposed to the version above, but it does. Here is the code I'm using now:\nimport urllib\nimport urllib2\nimport cookielib\n\ncj = cookielib.LWPCookieJar()\nopener = urllib2.build_opener(urllib2.HT...
[ 1 ]
[]
[]
[ "cookies", "python", "screen_scraping" ]
stackoverflow_0007716994_cookies_python_screen_scraping.txt
Q: Implementing __neg__ in a generic way for all subclasses in Python I apologize in advance for the rather long question. I'm implementing callable objects and would like them to behave somewhat like (mathematical) functions. I have a base class whose __call__ method raises NotImplementedError so users must subclass...
Implementing __neg__ in a generic way for all subclasses in Python
I apologize in advance for the rather long question. I'm implementing callable objects and would like them to behave somewhat like (mathematical) functions. I have a base class whose __call__ method raises NotImplementedError so users must subclass to define __call__. My question is: how can I define the special method...
[ "Your approach has several downsides. One example is that you copy all members of the original instance to the new instance -- this won't work if your class overrides any special methods other than __call__, since special methods are only looked up in the dictionary of the object's type when called implicitly. Mo...
[ 4, 3, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0007719018_metaprogramming_python.txt
Q: pygtk console output for debugging I have this problem. I'm creating an editor and I need console output(sys.stderr and sys.stdout) outputted to a textview. The problem is that when I start the console, it waits for it to quit, but I want it to catch anything and output it to the textview, so I thought that you mi...
pygtk console output for debugging
I have this problem. I'm creating an editor and I need console output(sys.stderr and sys.stdout) outputted to a textview. The problem is that when I start the console, it waits for it to quit, but I want it to catch anything and output it to the textview, so I thought that you might need different threads, but does it ...
[ "Since you want to catch sys.stdout and sys.stderr and these are global to the interpreter according to the documentation, you should be able to catch them regardless of the thread where the output was done.\nOn the other hand, your code wasn't very far from working. It was missing a call to the event loop, which i...
[ 2 ]
[]
[]
[ "gtk", "linux", "pygtk", "python", "windows" ]
stackoverflow_0007726985_gtk_linux_pygtk_python_windows.txt
Q: The memory usage reported by guppy differ from ps command I am profiling my twisted server. It uses much more memory than I expected. Its memory usage grows over time. ps -o pid,rss,vsz,sz,size,command PID RSS VSZ SZ SZ COMMAND 7697 70856 102176 25544 88320 twistd -y broadcast.tac As you can see it...
The memory usage reported by guppy differ from ps command
I am profiling my twisted server. It uses much more memory than I expected. Its memory usage grows over time. ps -o pid,rss,vsz,sz,size,command PID RSS VSZ SZ SZ COMMAND 7697 70856 102176 25544 88320 twistd -y broadcast.tac As you can see it costs 102176 KBs, namely, 99.78125 MBs. And I use guppy from a...
[ "possibly due to swapping/memory reservation, based on ps's definition:\nRSS: resident set size, the non-swapped physical memory\n that a task has used (in kiloBytes).\n\nVSZ: virtual memory usage of entire process.\n vm_lib + vm_exe + vm_data + vm_stack\n\nit can be a bit confusing, 4 different size metric...
[ 6, 3, 0 ]
[]
[]
[ "guppy", "memory_management", "python", "twisted" ]
stackoverflow_0002066279_guppy_memory_management_python_twisted.txt
Q: Parsing/Extracting Data from API XML feed with Python and Beautiful Soup Python/xml newb here playing around with Python and BeautifulSoup trying to learn how to parse XML, specifically messing with the Oodle.com API to list out car classifieds. I've had success with simple XML and BS, but when working with this, ...
Parsing/Extracting Data from API XML feed with Python and Beautiful Soup
Python/xml newb here playing around with Python and BeautifulSoup trying to learn how to parse XML, specifically messing with the Oodle.com API to list out car classifieds. I've had success with simple XML and BS, but when working with this, I can't seem to get the data I want no matter what I try. I tried reading the ...
[ "You could do something like this:\nfor element in soup('element'):\n id = element.id.text\n mileage = element.attributes.mileage.text\n price = element.attributes.price.text\n year = element.attributes.year.text\n vin = element.attributes.vin.text\n\n" ]
[ 0 ]
[]
[]
[ "api", "beautifulsoup", "python", "xml", "xml_parsing" ]
stackoverflow_0007730530_api_beautifulsoup_python_xml_xml_parsing.txt
Q: add module to pythonpath - nothing works I don't have root access so I installed psycopg2 module to /opt (I have permission for that directory): $python setup.py install --prefix=/opt I've tried several methods: #.bashrc PATH=$PATH:$HOME/bin:/opt/lib/python2.4/site-packages/psycopg2/ export PATH or...
add module to pythonpath - nothing works
I don't have root access so I installed psycopg2 module to /opt (I have permission for that directory): $python setup.py install --prefix=/opt I've tried several methods: #.bashrc PATH=$PATH:$HOME/bin:/opt/lib/python2.4/site-packages/psycopg2/ export PATH or #.bash_profile PATH=$PATH:$HOME/bin:/opt...
[ "Try $PYTHONPATH instead of $PATH in your bash configuration file.\nFor more info look at the official documentation on this topic.\n" ]
[ 20 ]
[]
[]
[ "linux", "module", "python" ]
stackoverflow_0007731947_linux_module_python.txt
Q: Installing pycurl on OS X 10.7 Lion I'm trying to install PyCurl in my local environment which has python 2.7 and gcc-4.2 on OS X 10.7 Lion. I've tried doing this based on this answer Error installing PyCurl: sudo env ARCHFLAGS="-arch x86_64" pip install pycurl Which fails because I have gcc-4.2 installed via Xco...
Installing pycurl on OS X 10.7 Lion
I'm trying to install PyCurl in my local environment which has python 2.7 and gcc-4.2 on OS X 10.7 Lion. I've tried doing this based on this answer Error installing PyCurl: sudo env ARCHFLAGS="-arch x86_64" pip install pycurl Which fails because I have gcc-4.2 installed via Xcode: error: command 'gcc-4.0' failed with ...
[ "Chances are you have a 32-bit-only Python 2.7 installed on your system (possibly downloaded from python.org) which was built with gcc-4.0 and includes a PPC universal variant. Building C extension modules with these Pythons is very problematic with Xcode 4 installed (the default for 10.7 and optional for 10.6) be...
[ 1 ]
[]
[]
[ "gcc", "pycurl", "python" ]
stackoverflow_0007732059_gcc_pycurl_python.txt
Q: Pythonic way to emulate itertools.product in python 2.4 I have a python 3 script that uses itertools.product, but I need to be able to run it on a machine that only has python 2.4 installed. Since itertools.product is new in python 2.6, I no longer have access to this function. How can I emulate itertools.product ...
Pythonic way to emulate itertools.product in python 2.4
I have a python 3 script that uses itertools.product, but I need to be able to run it on a machine that only has python 2.4 installed. Since itertools.product is new in python 2.6, I no longer have access to this function. How can I emulate itertools.product in Python 2.4 in a pythonic way?
[ "Equivalent code from http://docs.python.org/library/itertools.html#itertools.product\ndef product(*args, **kwds):\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111\n pools = map(tuple, args) * kwds.get('repeat', 1)\n result = [[]]\...
[ 6, 5 ]
[]
[]
[ "python", "python_2.4", "python_itertools" ]
stackoverflow_0007732141_python_python_2.4_python_itertools.txt
Q: Numpy C-Api example gives a SegFault I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension. So, I started this tutorial: http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html Tried to do the first example there, a C module that calcula...
Numpy C-Api example gives a SegFault
I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension. So, I started this tutorial: http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html Tried to do the first example there, a C module that calculates the trace of a 2d numpy array, was ver...
[ "Your init function for the module needs to call \nimport_array();\n\nafter \n(void) Py_InitModule(\"trace\", TraceMethods);\n\nIt mentions this in the tutorial near the top, but it is easy to miss. Without this, it segfaults on PyArray_ContiguousFromObject.\n" ]
[ 17 ]
[]
[]
[ "c", "numpy", "python", "python_c_api" ]
stackoverflow_0007730717_c_numpy_python_python_c_api.txt
Q: File Upload With Hosting Account Killing Scripts After 60 Seconds I have set all of my PHP settings in the php.ini file to allow for file sizes over 30mb and max times over 5 minutes. The problem I am having is that the hosting account I have to use is killing all scripts within 60 seconds Script restrictions A...
File Upload With Hosting Account Killing Scripts After 60 Seconds
I have set all of my PHP settings in the php.ini file to allow for file sizes over 30mb and max times over 5 minutes. The problem I am having is that the hosting account I have to use is killing all scripts within 60 seconds Script restrictions All scripts have the following memory and run time limitations: Memory: ...
[ "You could create some kind of flash uploader which uploads a chunk at a time of the file, each request will then be short but you will instead make several of them. When the last chunk is uploaded you call a script which merges all the chunks to one file.\nA simple googling gave me this: http://www.plupload.com/\n...
[ 4 ]
[]
[]
[ "large_file_upload", "php", "python" ]
stackoverflow_0007732256_large_file_upload_php_python.txt
Q: How to get a variable from the shell in python? I'm writing a script that needs to take advantage of a Java daemon via the local dbus of the linux machines it will run on. This daemon in particular will return an array of tuples which I want so that I can parse through/use the information in later in my code. I wa...
How to get a variable from the shell in python?
I'm writing a script that needs to take advantage of a Java daemon via the local dbus of the linux machines it will run on. This daemon in particular will return an array of tuples which I want so that I can parse through/use the information in later in my code. I want this code to take this value from multiple machine...
[ "You can't avoid serialization if there is no shared memory. There are only bytes on the wire.\nYou could use a library that hides it from you e.g., with execnet module:\n#!/usr/bin/env python\nimport execnet\n\ngw = execnet.makegateway(\"ssh=user@host\")\nchannel = gw.remote_exec(\"\"\"\nimport dbus, sys\n\nbus = ...
[ 1, 0, 0 ]
[]
[]
[ "python", "shell", "variables" ]
stackoverflow_0007730991_python_shell_variables.txt
Q: Auto-Terminating Long-Running Requests in Django I've got a setup with Apache + mod_wsgi running django code, and I'd like to add a layer of protection in case a non-terminating view slips in. Something that kills-off a requests exceeding, say, 30 seconds would be ideal. For testing I've just put a time.sleep(60)...
Auto-Terminating Long-Running Requests in Django
I've got a setup with Apache + mod_wsgi running django code, and I'd like to add a layer of protection in case a non-terminating view slips in. Something that kills-off a requests exceeding, say, 30 seconds would be ideal. For testing I've just put a time.sleep(60) in a view. I've tried the TimeOut 30 setting in Apach...
[ "It is actually really difficult to terminate a single Python request thread in a multithread application. The best you can do is make a decision to shutdown the whole process and restart it. Because such an action will disrupt concurrent requests, you would as a result really need to restrict yourself to a single ...
[ 6 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0007730257_apache_django_mod_wsgi_python.txt
Q: NULL tstate Error when using matplotlib together with Tkinter I draw some matplotlib.pyplot figures onto a Tkinter GUI. When I destroy the window the "Fatal Python Error" is raised. I seem to not be the only one with the problem but I cannot read a solution to it out of the discussions. As it does not cause a rea...
NULL tstate Error when using matplotlib together with Tkinter
I draw some matplotlib.pyplot figures onto a Tkinter GUI. When I destroy the window the "Fatal Python Error" is raised. I seem to not be the only one with the problem but I cannot read a solution to it out of the discussions. As it does not cause a real problem, but is just fairly inconvenient and has been bugging me ...
[ "What's your platform, python version, matplotlib version ?\n-- those details matter\nTry the example shown here: http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg21791.html\ndoes it work properly?\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0007727397_matplotlib_python_tkinter.txt
Q: Can i use nltk to build an answer engine using wikipedia's content I have built an answer engine using wikipedia's content with php. It just returns the most relevant wikipedia article for a particular query which in most of the cases turn out to be useles.The users tend to ask in a question format like "`what is ...
Can i use nltk to build an answer engine using wikipedia's content
I have built an answer engine using wikipedia's content with php. It just returns the most relevant wikipedia article for a particular query which in most of the cases turn out to be useles.The users tend to ask in a question format like "`what is the height of wayne rooney" and i want to give the exact height of roone...
[ "in general: yes it is possible, BUT it is a very difficult task to build such a program.\nwhat you are searching trying to build is called a 'semantic search engine' (see wikipedia) and there is a lot of research going on, how we can build a 'semantic web' and how to extract information of webpages, so that questi...
[ 3 ]
[]
[]
[ "nlp", "nltk", "python", "search" ]
stackoverflow_0007731981_nlp_nltk_python_search.txt
Q: Why can't iterate through this list in a Django template I have a variable from my view that is the output of a Model.objects.all() call on that Model. I'm passing it to my template in my view, and I'm trying to iterate over it in the template. I can access the first element of it simply by this line of code. 'cod...
Why can't iterate through this list in a Django template
I have a variable from my view that is the output of a Model.objects.all() call on that Model. I'm passing it to my template in my view, and I'm trying to iterate over it in the template. I can access the first element of it simply by this line of code. 'code' is the name of a field in my django model. This line does p...
[ "I found that changing the name of single_var to something without an underscore seemed to fix it. This doesn't make a lot of sense to me because the Django template language documentation states the following:\nVariable names consist of any combination of alphanumeric characters and the underscore (\"_\").\n\nDoes...
[ 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0007718720_django_python_templates.txt
Q: Python parsing tree-like data I have a glyph information from a font that looks like this: (CHARACTER C T (CHARWD R 0.6944475) (CHARHT R 0.686111) (COMMENT (KRN C y R -0.027779) (KRN C e R -0.083334) (KRN C o R -0.083334) (KRN C r R -0.083334) (KRN C a R -0.083334) (KRN...
Python parsing tree-like data
I have a glyph information from a font that looks like this: (CHARACTER C T (CHARWD R 0.6944475) (CHARHT R 0.686111) (COMMENT (KRN C y R -0.027779) (KRN C e R -0.083334) (KRN C o R -0.083334) (KRN C r R -0.083334) (KRN C a R -0.083334) (KRN C A R -0.083334) (KRN C u R ...
[ "You could use pyparsing. Your example looks very much like an s-expression, and they have an s-expression parser in their examples section: http://pyparsing.wikispaces.com/file/view/sexpParser.py\n", "This will convert your data into a python data structure. Not sure if it's what you're looking for?\ns = \"\"\"...
[ 6, 2 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0007732754_parsing_python.txt
Q: Django IntegerField returning long I am wondering why, when I get a field from db which is defined as models.IntegerField in models.py I am getting long instead of int e.g. I have a model EventSchedule class EventSchedule(models.Model): monthly_day = models.IntegerField(default=1) ... in db it is mysql> d...
Django IntegerField returning long
I am wondering why, when I get a field from db which is defined as models.IntegerField in models.py I am getting long instead of int e.g. I have a model EventSchedule class EventSchedule(models.Model): monthly_day = models.IntegerField(default=1) ... in db it is mysql> describe t_event_schedule; +-------------...
[ "this is probably a side effect of the underlying dbapi handler, which returns long for most everything:\n>>> import MySQLdb\n>>> db=MySQLdb.connect(db=\"test\")\n>>> c = db.cursor()\n>>> c.execute(\"Select 1\")\n1L\n\nThe difference for most uses is cosmetic. There are subtle differences from one driver to anothe...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007733002_django_python.txt
Q: editable Text window with wx in Python I need to create a window for showing text in multiple line(like notepad.below is my application).I create a wx.TextCtrl using wxPython Problem is it can't print in multiple lines even if you put \n at end of your strings.What should I use? I couldn't find wxPython documentat...
editable Text window with wx in Python
I need to create a window for showing text in multiple line(like notepad.below is my application).I create a wx.TextCtrl using wxPython Problem is it can't print in multiple lines even if you put \n at end of your strings.What should I use? I couldn't find wxPython documentation.
[ "Use the wx.TE_MULTILINE style for your textctrl, e.g.\ntext = wx.TextCtrl(self, style=wx.TE_MULTILINE)\n\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007733068_python_wxpython.txt
Q: Expanding tuple into number repeated X times in a list (python) This seems simple, but I can't figure it out. I have ten categories and scores assigned to each of them. In an intermediate step, I am storing results as ["score", repeats] pairs, as in: [20,3] [40,7] [50,2] ... What I want to do in the end is expand...
Expanding tuple into number repeated X times in a list (python)
This seems simple, but I can't figure it out. I have ten categories and scores assigned to each of them. In an intermediate step, I am storing results as ["score", repeats] pairs, as in: [20,3] [40,7] [50,2] ... What I want to do in the end is expand these pairs into repeats of numbers, then merge and average to get o...
[ "You can do this:\n>>> a = [20,3]\n>>> [a[0]] * a[1]\n[20, 20, 20]\n\nHowever, this step isn't really necessary. To get the weighted average, you can multiply the values by the weights, sum them, and then divide by the sum of the weights, such as:\nfloat(20*3 + 40*7 + 50*2) / (3 + 7 + 2)\n\nThe conversion to float ...
[ 8, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007733033_python.txt
Q: Searching through IMAP folder for multiple criterion (python) Is it possible to use more than on criteria in one search request through imaplib? i.e emails sent after a date by a specific sender? A: import datetime date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%b-%Y") result, data = mail....
Searching through IMAP folder for multiple criterion (python)
Is it possible to use more than on criteria in one search request through imaplib? i.e emails sent after a date by a specific sender?
[ "import datetime\ndate = (datetime.date.today() - datetime.timedelta(1)).strftime(\"%d-%b-%Y\")\nresult, data = mail.uid('search', None, '(SENTSINCE {date})'.format(date=date))\n\n" ]
[ 0 ]
[]
[]
[ "imap", "python" ]
stackoverflow_0007727279_imap_python.txt
Q: Python equivalent of vector::reserve() I am looking for the Python equivalent of the C++ vector::reserve(). I don't know how big the list is going to be ahead of time, but I know it's going to be fairly large, and I want to avoid as many resizings as possible as the list is being grown inside a deep inner loop. T...
Python equivalent of vector::reserve()
I am looking for the Python equivalent of the C++ vector::reserve(). I don't know how big the list is going to be ahead of time, but I know it's going to be fairly large, and I want to avoid as many resizings as possible as the list is being grown inside a deep inner loop. The only solution I've come up with so far is...
[ "For the heck of it, I did some performance testing:\ndef foo(n):\n x = []\n for y in xrange(n): x.append(y)\n\ndef bar(n):\n x = [None] * n\n for y in xrange(n): x[y] = y\n\ndef baz(n):\n # This is obviously silly; we could just do range(n)\n # but this way makes for a fairer test\n x = [y for y in xrange(n...
[ 8, 7, 3 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0007730754_c++_python.txt
Q: Python 2.7 Virtualenv Path issues on OSX 10.5 Problem Discription The issues I'm having when I try to load a Django website that's using mod_wsgi, python 2.7 and virtualenv, is that I get a 500 error when I go to the site in my browser. When I look at the error that's created in my apache log I get the following.....
Python 2.7 Virtualenv Path issues on OSX 10.5
Problem Discription The issues I'm having when I try to load a Django website that's using mod_wsgi, python 2.7 and virtualenv, is that I get a 500 error when I go to the site in my browser. When I look at the error that's created in my apache log I get the following... [Tue Oct 11 09:32:30 2011] [error] [client 206.13...
[ "As I pointed out in my reply to my own question and as others have replied it's not possible to use different version of python with mod_wsgi. My solution was to install and setup gunicorn for my specific site that needed a different version of python.\nFirst I installed gunicorn...\n$ /usr/local/virtualenvs/my.ex...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "osx_leopard", "python", "virtualenv" ]
stackoverflow_0007730715_django_osx_leopard_python_virtualenv.txt
Q: python string to symbolic name I want to check imported names. Code: import fst # empty file fst.py for s in dir(fst): print(s) # got string with symbolic names Output: __builtins__ __cached__ __doc__ __file__ __name__ __package__ Now I want to check values of each defined name: Code: print(__builtins__) p...
python string to symbolic name
I want to check imported names. Code: import fst # empty file fst.py for s in dir(fst): print(s) # got string with symbolic names Output: __builtins__ __cached__ __doc__ __file__ __name__ __package__ Now I want to check values of each defined name: Code: print(__builtins__) print(__cached__) print(__doc__) prin...
[ "Use getattr:\nfor s in dir(fst):\n print (getattr(fst, s))\n\n", "Use the getattr function:\nprint(s, getattr(fst, s))\n\n", "There's no such thing as a \"symbolic name\". What module contains is available as its attributes, so getattr(module, name) is what you're looking for.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007733377_python.txt
Q: Optimizing gravitation calculation for particles in a zero gravity 2d space I've have created a small visualisation of particles in python. I'm caclulation the movement of particels in a 2D space with zero gravity. As each particle attracts all other particles based on the particle mass and distance. I made a vis...
Optimizing gravitation calculation for particles in a zero gravity 2d space
I've have created a small visualisation of particles in python. I'm caclulation the movement of particels in a 2D space with zero gravity. As each particle attracts all other particles based on the particle mass and distance. I made a visualsation in pygame and everything works as plan (with the caluclation), however ...
[ "You can first try to work with complex numbers: the relevant gravitation and dynamics formulas are very simple in this formalism, and can also be quite fast (because NumPy can do the calculation internally, instead of you handling separately x and y coordinates). For instance, the force between two particules at ...
[ 5, 4, 4, 2, 1 ]
[]
[]
[ "numpy", "optimization", "physics", "python" ]
stackoverflow_0007115439_numpy_optimization_physics_python.txt
Q: python local modules I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such: myproject/ mymodules/ __init__.py myfunctions.py myreports/ mycode.py Assuming there is a function called add in myfunct...
python local modules
I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such: myproject/ mymodules/ __init__.py myfunctions.py myreports/ mycode.py Assuming there is a function called add in myfunctions.py, I can call it fro...
[ "Don't mess around with execfile or sys.path.append unless there is some very good reason for it. Rather, just arrange your code into proper python packages and do your importing as you would any other library.\nIf your mymodules is in fact a part of one large project, then set your package up like so:\nmyproject/\...
[ 15 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0007732685_python_python_module.txt
Q: setItemSelected in QListWidget on PyQt4 I have this barebones code, I am trying to make it so some items (all even for this example) are preselected inside the QListWidget. Where am I going wrong? from PyQt4 import QtGui, QtCore, Qt import sys class Main(QtGui.QWidget): def __init__(self, parent=None): ...
setItemSelected in QListWidget on PyQt4
I have this barebones code, I am trying to make it so some items (all even for this example) are preselected inside the QListWidget. Where am I going wrong? from PyQt4 import QtGui, QtCore, Qt import sys class Main(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self,parent) ...
[ "Each QtGui.QListWidgetItem(...) call creates a new item. What you are doing in that code is first creating an item, adding it to the list... And then, if it's in an odd position, creating a whole new item and selecting it without ever adding it to the list.\nYou need to make sure that you're only dealing with one ...
[ 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0007733465_pyqt4_python.txt
Q: Python 2.6 font/colour change + error window I just have two hopefully quick questions. I'm using Python 2.6 How should I go about changing the font and colour of a string with the tkfont class? I seem to find tonnes of documentation about the different functions the tkfont class has, e.g. I think I should be usi...
Python 2.6 font/colour change + error window
I just have two hopefully quick questions. I'm using Python 2.6 How should I go about changing the font and colour of a string with the tkfont class? I seem to find tonnes of documentation about the different functions the tkfont class has, e.g. I think I should be using the tkfont.config(), and what to specify as the...
[ "Tkinter comes with many stantard dialogs. A good point of reference for these is the Standard Dialogs page on effbot.\nI'll answer your question about colors when you clarify it a little. \n" ]
[ 0 ]
[]
[]
[ "colors", "fonts", "python", "tkinter", "window" ]
stackoverflow_0007733209_colors_fonts_python_tkinter_window.txt
Q: Where is the Cherrypy config file located on Ubuntu? I have a tool written to be added to the configuration file but I cannot find the file anywhere. Where is the configuration file? A: There is no configuration file. All forms of configuration is done through code. A simple site-config example using cheerypy.co...
Where is the Cherrypy config file located on Ubuntu?
I have a tool written to be added to the configuration file but I cannot find the file anywhere. Where is the configuration file?
[ "There is no configuration file. All forms of configuration is done through code.\nA simple site-config example using cheerypy.config:\n#cheerypy.config is flat dictionary that you can modify using\ncherrypy.config.update({'server.socket_host': '10.10.10.10',\n 'server.socket_port': 80,\n ...
[ 2 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0007733875_cherrypy_python.txt
Q: Is it possible to create attributes out of the class scope? Is it possible to add attributes to a object outside of its scope? I.e: The following code doesnt works, how do I do what I intended to do with that code? b = object() b.foo = "bar" A: In general, it is possible. However, it is not possible for most typ...
Is it possible to create attributes out of the class scope?
Is it possible to add attributes to a object outside of its scope? I.e: The following code doesnt works, how do I do what I intended to do with that code? b = object() b.foo = "bar"
[ "In general, it is possible. However, it is not possible for most types that are implemented in C, instead of in Python. Unfortunately, this applies to the most often-used of the standard Python interpreter's built-in types.\nIf you define a class of your own in Python, you'll see that it works fine.\nclass MyObjec...
[ 5, 5 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0007733980_oop_python.txt
Q: How to import a library GMP into Sage/Python project I have already installed the GMP library, Now i want to import this library to sage project i tried to put : import libgmpxx.so.4 libgmpxx.so.4.path.append('usr/local/lib/') but it does'nt work unfortunately, how can i do that. regards A: Sage'...
How to import a library GMP into Sage/Python project
I have already installed the GMP library, Now i want to import this library to sage project i tried to put : import libgmpxx.so.4 libgmpxx.so.4.path.append('usr/local/lib/') but it does'nt work unfortunately, how can i do that. regards
[ "Sage's Integer class uses GMP (or MPIR) automatically. If you are trying to use GMP independently of Sage, look at gmpy.\nDisclaimer: I'm the maintainer of gmpy.\n" ]
[ 2 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0007733733_python_sage.txt
Q: recursive nodes I'm trying to understand within my lesson how to read the below function called printBackward. How is it that when I type printBackward(node1) and my output is 3,2,1 which is what it's suppose to do. I just don't understand why that is. See below how I interpret it and please school me on where I s...
recursive nodes
I'm trying to understand within my lesson how to read the below function called printBackward. How is it that when I type printBackward(node1) and my output is 3,2,1 which is what it's suppose to do. I just don't understand why that is. See below how I interpret it and please school me on where I saw it wrong... class...
[ "You are correct about everything that is happening leading up to when printBackward(node3) is called. What is going on is every time you get to the recursive printBackward() call, you go deeper into the call stack. The final print doesn't actually get called until the recursion stops calling printBackward(), and t...
[ 2, 2 ]
[]
[]
[ "nodes", "python", "recursion" ]
stackoverflow_0007734087_nodes_python_recursion.txt
Q: how to use "where in" clause I have these models: class AgencyPosition(models.Model): Agency=models.ForeignKey(Agency) Users=models.ManyToManyField(User) PositionTypeCode=models.ForeignKey(PositionType) PhoneNumber=models.CharField(max_length=50) Email=models.CharField(max_length=50) StatusTypeCo...
how to use "where in" clause
I have these models: class AgencyPosition(models.Model): Agency=models.ForeignKey(Agency) Users=models.ManyToManyField(User) PositionTypeCode=models.ForeignKey(PositionType) PhoneNumber=models.CharField(max_length=50) Email=models.CharField(max_length=50) StatusTypeCode=models.ForeignKey(StatusType) ...
[ "News.objects.filter(created_by__in = AgencyPositionList.Users)[:5]. It's all documented.\n", "Try this:\nNews.objects.filter(created_by__agency_position__id=your_agency_id)[:5]\n\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007731859_django_python.txt
Q: Regular expression quantifier I have a regular expression pattern as follows: .*\b(?P<core>[A-Z][0-9]?\b.*)(?P<extra>\b[0-9]+[xX][0-9]+.*)?\.png To match some strings as follows:- UI SCREEN 5-1 F2 ROUND TAB REFLECTION 224x18px.png In Python, I get the following result {u'core': u'F2 ROUND TAB REFLECTION 224x18...
Regular expression quantifier
I have a regular expression pattern as follows: .*\b(?P<core>[A-Z][0-9]?\b.*)(?P<extra>\b[0-9]+[xX][0-9]+.*)?\.png To match some strings as follows:- UI SCREEN 5-1 F2 ROUND TAB REFLECTION 224x18px.png In Python, I get the following result {u'core': u'F2 ROUND TAB REFLECTION 224x18px', u'extra': None} instead of {...
[ "The expression (?P[A-Z][0-9]?\\b.*) probably doesn't do what you think it does ... it will match:\n\na character\nthen a number, or not\nthen a word boundary\nthen absolutely everything after that\n\nWhich swallows everything up to your terminating .png (which should be a \\.png)\n", "Add a ? after your first g...
[ 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007734213_python_regex.txt
Q: Python: find sequential change in one member of list pairs, report other There must be a simpler, more pythonic way of doing this. Given this list of pairs: pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] How do I most easily find the first item in adjacent pairs where the second item changes (here, from 1 to 2)....
Python: find sequential change in one member of list pairs, report other
There must be a simpler, more pythonic way of doing this. Given this list of pairs: pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] How do I most easily find the first item in adjacent pairs where the second item changes (here, from 1 to 2). Thus I'm looking for ['c','d']. Assume there will only be one change in pair[...
[ "import itertools as it\n\npp = [('a',1),('b',1),('c',1),('d',2),('e',2)]\n\n# with normal zip and slicing\nfor a,b in zip(pp,pp[1:]):\n if a[1] != b[1]:\n x=(a[0],b[0])\n print x\n break\n# with generators and izip\niterfirst = (b for a,b in pp)\nitersecond = (b for a,b in pp[1:])\niterfirs...
[ 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0003601934_list_list_comprehension_python.txt
Q: Google app engine or query (python) Can anyone share your approach for doing a 'or' query in app-engine? Let say I have class A_db_model(db.Model): valueA = db.ListProperty(basestring) in valueA I have aaa aaa, bbb bbb ccc I would like to return result of if the valueA match 'aaa' or 'bbb' and return not duplic...
Google app engine or query (python)
Can anyone share your approach for doing a 'or' query in app-engine? Let say I have class A_db_model(db.Model): valueA = db.ListProperty(basestring) in valueA I have aaa aaa, bbb bbb ccc I would like to return result of if the valueA match 'aaa' or 'bbb' and return not duplicated result.
[ "Try this?\nA_db_model.all().filter('valueA IN', ['aaa', 'bbb'])\n\nor the equivalent GQL:\nGqlQuery('SELECT * FROM A_db_model WHERE valueA IN :1', ['aaa', 'bbb'])\n\n", "The two main problems with @Amber's approach is that it is slow as it basically runs a query for each value behind the scenes and it maxes out ...
[ 6, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003714972_google_app_engine_python.txt
Q: optparse and strings Trying to learn how to use outparse. So here is the situation, I think I got my setup correct its just how to set my options is kinda... confusing me. Basically I just want to check my filename to see if there are specific strings. For example: python script.py -f filename.txt -a hello sim...
optparse and strings
Trying to learn how to use outparse. So here is the situation, I think I got my setup correct its just how to set my options is kinda... confusing me. Basically I just want to check my filename to see if there are specific strings. For example: python script.py -f filename.txt -a hello simple I want it to return s...
[ "You should use OptionParser.add_option()... add_option_group() isn't doing what you think it does... this is a complete example in the spirit of what you're after... note that --all relies on comma-separating the values... this makes it easier, instead of using space separation (which would require quoting the opt...
[ 2 ]
[]
[]
[ "optparse", "parsing", "python" ]
stackoverflow_0007734462_optparse_parsing_python.txt
Q: I'm unable to compile Phoenix on OSX (10.6.7) Using python that's installed by default on OSX, I'm trying to run phoenix https://en.bitcoin.it/wiki/Phoenix_miner and I'm getting: python phoenix.py import itertools, md5 Traceback (most recent call last): File "phoenix.py", line 29, in <module> import mine...
I'm unable to compile Phoenix on OSX (10.6.7)
Using python that's installed by default on OSX, I'm trying to run phoenix https://en.bitcoin.it/wiki/Phoenix_miner and I'm getting: python phoenix.py import itertools, md5 Traceback (most recent call last): File "phoenix.py", line 29, in <module> import minerutil File "/Users/george/Downloads/phoenix-1.4/m...
[ "You probably have to upgrade your version of Twisted. 11.0 should work; it did for me. Try\nsudo easy_install --upgrade twisted\n\n[This assumes that easy_install is going to pick up the system python. If it's in a weird state, try sudo python_version path_to_easy_install --upgrade twisted.]\n", "I installed...
[ 1, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0006380134_macos_python.txt
Q: Django ORM: Why would Django use SELECT (1) on its own? When using Django (with SQLite3) I noticed the following query in connection.queries : "sql": "SELECT (1) AS \"a\" FROM \"blog_comment\" WHERE \"blog_comment\".\"id\" = 5 LIMIT 1" I understand what the query does (just returns the first column from each mat...
Django ORM: Why would Django use SELECT (1) on its own?
When using Django (with SQLite3) I noticed the following query in connection.queries : "sql": "SELECT (1) AS \"a\" FROM \"blog_comment\" WHERE \"blog_comment\".\"id\" = 5 LIMIT 1" I understand what the query does (just returns the first column from each matching row), but why do this? Is it just an inexpensive way of...
[ "It is just checking for existence of rows. \nIt doesn't have any meaning otherwise because \"1\" is a constant value\n" ]
[ 7 ]
[]
[]
[ "django", "python", "sql", "sqlite" ]
stackoverflow_0007734489_django_python_sql_sqlite.txt
Q: Practical examples of NLTK use I'm playing around with the Natural Language Toolkit (NLTK). Its documentation (Book and HOWTO) are quite bulky and the examples are sometimes slightly advanced. Are there any good but basic examples of uses/applications of NLTK? I'm thinking of things like the NTLK articles on the ...
Practical examples of NLTK use
I'm playing around with the Natural Language Toolkit (NLTK). Its documentation (Book and HOWTO) are quite bulky and the examples are sometimes slightly advanced. Are there any good but basic examples of uses/applications of NLTK? I'm thinking of things like the NTLK articles on the Stream Hacker blog.
[ "Here's my own practical example for the benefit of anyone else looking this question up (excuse the sample text, it was the first thing I found on Wikipedia):\nimport nltk\nimport pprint\n\ntokenizer = None\ntagger = None\n\ndef init_nltk():\n global tokenizer\n global tagger\n tokenizer = nltk.tokenize.R...
[ 28, 18, 14 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0000526469_nlp_nltk_python.txt
Q: syntax error due to several top-level functions in Python? I searched and found a very similar question here Syntax Error when trying to define multiple functions in python? but the question wasn't really answered I am getting a syntax error at the second "def" . My indentation may be messed up here because I ca...
syntax error due to several top-level functions in Python?
I searched and found a very similar question here Syntax Error when trying to define multiple functions in python? but the question wasn't really answered I am getting a syntax error at the second "def" . My indentation may be messed up here because I cannot figure out the formatting in this place....BUT it is correc...
[ "I was able to run your code with no problems once I fixed the indentation error:\ndef encryptString(string, key):\n newString = \"\"\n for i in range(len(string)):\n newString += encryptChar(string[i], key)\n return newString # << HERE\n\nDemo: http://codepad.org/eaaiHUJZ\nI would also rewrite your...
[ 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "function", "python", "syntax" ]
stackoverflow_0007735045_function_python_syntax.txt
Q: Marking query in particular case I have the relationship follow as: class Question(models.Model): qid = models.PositiveIntegerField(primary_key=True) content = models.CharField(max_length=128) class Answer(models.Model): answerid = models.PositiveIntegerField(primary_key=True) content = models.CharField(m...
Marking query in particular case
I have the relationship follow as: class Question(models.Model): qid = models.PositiveIntegerField(primary_key=True) content = models.CharField(max_length=128) class Answer(models.Model): answerid = models.PositiveIntegerField(primary_key=True) content = models.CharField(max_length=128) question = models.For...
[ "If you are trying to find all the questions that have answers:\nQuestion.objects.filter(answer__isnull=False).distinct()\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007734939_django_django_models_python.txt
Q: Convert Hex Chars into a String of Bits (Python or Ruby) I have a microcontroller that returns a status response like this from an HTTP API: <response><BS>026219AAF80F440206025019AAF816A944274480</BS></response> The last two characters, in this case 80, represent a hexadecimal value that I need to convert to a it...
Convert Hex Chars into a String of Bits (Python or Ruby)
I have a microcontroller that returns a status response like this from an HTTP API: <response><BS>026219AAF80F440206025019AAF816A944274480</BS></response> The last two characters, in this case 80, represent a hexadecimal value that I need to convert to a its binary bits 10000000. Each bit is a flag that corresponds to...
[ "In Ruby:\nyourbits = \"026219AAF80F440206025019AAF816A944274480\"[-2,2].to_i(16).to_s(2)\n=> \"10000000\"\nputs yourbits\n10000000\n=> nil\n\nExplaining each step -- first, slice the string to get the last 2 characters:\n\"026219AAF80F440206025019AAF816A944274480\"[-2,2]\n=> '80'\n\nConvert it to Integer:\n\"80\"....
[ 5, 3, 2, 1 ]
[]
[]
[ "hex", "python", "ruby" ]
stackoverflow_0007735005_hex_python_ruby.txt
Q: I need a function that given similar inputs returns similar indexes So I was looking at the hash functions, and figured out that given 2 similar strings, even if the differ by a single bit, the result would be a completely different hash key. I actually need to create some sort of unique id, which has this feature...
I need a function that given similar inputs returns similar indexes
So I was looking at the hash functions, and figured out that given 2 similar strings, even if the differ by a single bit, the result would be a completely different hash key. I actually need to create some sort of unique id, which has this feature of being quite similar for similar input (will be millions of alpha nume...
[ "What you're asking for is not possible, assuming by 'similar hash' you mean that the values should be of similar magnitude - eg, 12345 is similar to 12346 but not to 92345. The reason for this is that similarity of that sort is one dimensional (a number line), but the ways in which strings can be similar to each o...
[ 1, 0, 0 ]
[]
[]
[ "hash", "indexing", "python" ]
stackoverflow_0007733713_hash_indexing_python.txt
Q: sql alchemy python query query.first() _and I am modifying some code I did not write. The problem with this code is that tracking numbers have started to recycle with the carrier. So for a given tracking number there may be two sometimes 3 rows in the database. This code apparently finds the first record in the...
sql alchemy python query query.first() _and
I am modifying some code I did not write. The problem with this code is that tracking numbers have started to recycle with the carrier. So for a given tracking number there may be two sometimes 3 rows in the database. This code apparently finds the first record in the query which in our case is the 'oldest created d...
[ "Your first option cannot be done accurately unless you have a column, like an identity, that helps you understand the order in which rows were put into the table. (EDIT: From your attached comments it seems you have a created_at field ...)\nSo a query would be\nquery = (session.query(database.Manifest)\n ...
[ 4 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0007735313_python_sql_sqlalchemy.txt
Q: Cropping image - Image.crop function not working I have following line of code for image cropping im = Image.open('path/to/image.jpg') outfile = "path/to/dest_img.jpg" im.copy() im.crop((0, 0, 500, 500)) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") But it doesn't seems cropping image. I have big...
Cropping image - Image.crop function not working
I have following line of code for image cropping im = Image.open('path/to/image.jpg') outfile = "path/to/dest_img.jpg" im.copy() im.crop((0, 0, 500, 500)) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") But it doesn't seems cropping image. I have bigger image size e.g. 2048 x 1536 px. [edited] Here's so...
[ "You have forgotten to assign the return values in some statements.\nim = Image.open('path/to/image.jpg')\n\noutfile = \"path/to/dest_img.jpg\"\n\nim = im.crop((0, 0, 500, 500))\nim = im.thumbnail(size, Image.ANTIALIAS)\nim.save(outfile, \"JPEG\")\n\n", "You certainly want to do this:\nfrom PIL import Image\nim =...
[ 5, 2 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0007735554_django_python_python_imaging_library.txt
Q: Why my strange results rendering the user object? For some reason, my variable {{current_user.name}} doesn't display anything and the variable {{username}} displays instead of Niklas R it displays `(u'Niklas R',) on the page that I render with django. Here is the method from the basehandler that I hope you can tel...
Why my strange results rendering the user object?
For some reason, my variable {{current_user.name}} doesn't display anything and the variable {{username}} displays instead of Niklas R it displays `(u'Niklas R',) on the page that I render with django. Here is the method from the basehandler that I hope you can tell me what's wrong with: def render(self, name, **data):...
[ "This happens to me all the time, you have an extra , and the variable becomes a tuple.\nchange the lines to: \ndata[u'current_user']=self.current_user\ndata[u'username']=self.current_user.name\n\n" ]
[ 2 ]
[]
[]
[ "bug_tracking", "facebook_graph_api", "google_app_engine", "python" ]
stackoverflow_0007735502_bug_tracking_facebook_graph_api_google_app_engine_python.txt
Q: Searching IMAP inbox for messages from a specific sender and use of wild cards? Is it possible to use wildcards in searching for a specific sender on IMAP folder? typ, data = M.SEARCH(None, 'from','"security@website*"') A: IMAP RFC 3501 6.4.4: In all search keys that use strings, a message matches the key if th...
Searching IMAP inbox for messages from a specific sender and use of wild cards?
Is it possible to use wildcards in searching for a specific sender on IMAP folder? typ, data = M.SEARCH(None, 'from','"security@website*"')
[ "IMAP RFC 3501 6.4.4:\n\nIn all search keys that use strings, a message matches the key if\nthe string is a substring of the field. The matching is\ncase-insensitive.\n\nSo you need to search without * and you should almost similar result.\n(you get security@website ...)\n" ]
[ 5 ]
[]
[]
[ "imap", "python" ]
stackoverflow_0007719664_imap_python.txt
Q: How to set a timeout in libvirt (using Python) I would like to set a short connection timeout (only some seconds) when using libvirt in my Python program instead of the long default one. I found the C function: virEventAddTimeoutFunc() in the C libvirt API here: http://libvirt.org/html/libvirt-libvirt.html#virEven...
How to set a timeout in libvirt (using Python)
I would like to set a short connection timeout (only some seconds) when using libvirt in my Python program instead of the long default one. I found the C function: virEventAddTimeoutFunc() in the C libvirt API here: http://libvirt.org/html/libvirt-libvirt.html#virEventAddTimeoutFunc and eventInvokeTimeoutCallback(time...
[ "We finally found a simple way to proceed using Python alarm & signal handler: http://docs.python.org/library/signal.html#example\nEdit:\nHere is the idea:\nimport string, time, sys, signal\n\nclass Host:\n\n# (...)\n\ndef timeout_handler(self, sig_code, frame):\n if 14 == sig_code: sig_code = 'SIGALRM'\n pri...
[ 1, 0, 0 ]
[]
[]
[ "libvirt", "python", "timeout", "virtualization" ]
stackoverflow_0005597245_libvirt_python_timeout_virtualization.txt
Q: Adding interactivity in Python? I have developed a PyQt4 application for analysing delimited log files containing numeric data. Is there any way to easily add something like a 'console' to the application so that users can access objects and data created from the application and perform (type) arbitrary commands (...
Adding interactivity in Python?
I have developed a PyQt4 application for analysing delimited log files containing numeric data. Is there any way to easily add something like a 'console' to the application so that users can access objects and data created from the application and perform (type) arbitrary commands (using SciPy and NumPy?).
[ "import code\n\ncode.InteractiveInterpreter(local=locals())\n\nSpawn the interpreter with the appropriate local variables. You probably don't want to spawn an interactive console (which you can also do) because you won't be able to do any other kinds of processing in your GUI application (though maybe you can get a...
[ 2, 2, 0 ]
[]
[]
[ "console", "numpy", "pyqt4", "python", "scipy" ]
stackoverflow_0007734153_console_numpy_pyqt4_python_scipy.txt
Q: why list in object is not showing correctly in python Possible Duplicate: Assign a value to class variable is assiging it for all instances of that object I need a help. I am used to java development and new I am starting python. And I write a simple class which contain a list of string. and In the main function...
why list in object is not showing correctly in python
Possible Duplicate: Assign a value to class variable is assiging it for all instances of that object I need a help. I am used to java development and new I am starting python. And I write a simple class which contain a list of string. and In the main function I create a list of this object and I would like to print ...
[ "In your code, all instances of FastData share the same lines object. Fix it like so:\nclass FastData:\n\n # note that I've removed `name' and `lines' from here\n\n def __init__ (self, name):\n self.name = name\n self.lines = []\n\nThe reason your code worked the way it did was that line...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007736295_python.txt
Q: Python PIL: Create indexed color image with transparent background I wonder how I could create a image with a transparent background and only 2 indexed colours (red and blue) to minimise the file size? More specifically I have two black and white images that I want to convert, one to transparent and blue and the o...
Python PIL: Create indexed color image with transparent background
I wonder how I could create a image with a transparent background and only 2 indexed colours (red and blue) to minimise the file size? More specifically I have two black and white images that I want to convert, one to transparent and blue and the other to transparent and red. Then I want to merge those 2 images. I coul...
[ "So I managed to do it, using \"palette\" image type, but the resulting file is not as small as I expected...\nHere's my code in case its useful for someone else, or if someone can improve on it. \nfrom PIL import Image\n\nim = Image.open(\"image1.png\")\nimP = im.convert('RGB').convert('P', palette=Image.ADAPTIVE,...
[ 7, 2 ]
[]
[]
[ "indexed_image", "python", "python_imaging_library", "transparency" ]
stackoverflow_0007733364_indexed_image_python_python_imaging_library_transparency.txt
Q: identifying the format of files In linux, we have a utility called “file”, which helps us to determine the identification of a file. Is there any python module that can do the same job? I don't prefer to use subprocess.Popen(['file', 'blah.blah']), because it is platform dependent. For instance, windows do not hav...
identifying the format of files
In linux, we have a utility called “file”, which helps us to determine the identification of a file. Is there any python module that can do the same job? I don't prefer to use subprocess.Popen(['file', 'blah.blah']), because it is platform dependent. For instance, windows do not have “file” (although it can be download...
[ "magic\nDon't forget the DLL.\n", "Ignacio mentioned the Magic library, but you could also do it with the standard library if you're confident that the filename is enough to know the file type from (by extension):\n>>> import mimetypes\n>>> mimetypes.guess_type('__init__.py')\n('text/x-python', None)\n\nSee the ...
[ 7, 2, 0 ]
[]
[]
[ "file", "identification", "imghdr", "python" ]
stackoverflow_0007736480_file_identification_imghdr_python.txt
Q: How do I create a function that will create a global (and assign it a value) with a name that contains the name of the argument given to it? I'm using Python and am trying to create a function that will look at the name of the object that is given as an argument and (among other things) create some globals that co...
How do I create a function that will create a global (and assign it a value) with a name that contains the name of the argument given to it?
I'm using Python and am trying to create a function that will look at the name of the object that is given as an argument and (among other things) create some globals that contain this name, for example: object1=someclass(args,kwds) #the object is an instance of a class that is given a certain name (e.g.object1) def so...
[ "It sounds like a terrible idea...\ndef func(prefix):\n g = globals()\n g[prefix + '_tomato'] = 123\n g[prefix + '_broccoli'] = 456\n\nWhatever you are doing, it can probably be done with dictionaries, arrays, and other objects in a way that isn't fragile like the above method.\n", "I'm not so sure about...
[ 3, 0 ]
[]
[]
[ "global", "python" ]
stackoverflow_0007737029_global_python.txt
Q: Print PDF from django form I am in the early process of building a PDF builder for one of my fillable PDFs. At this point I am trying to just display the PDF when I click on my 'Print Form' button but at the moment I don't get any errors and it just opens a blank tab (firefox). Here is my print_rdba from my lib/to...
Print PDF from django form
I am in the early process of building a PDF builder for one of my fillable PDFs. At this point I am trying to just display the PDF when I click on my 'Print Form' button but at the moment I don't get any errors and it just opens a blank tab (firefox). Here is my print_rdba from my lib/tools.py: def print_rdba(client=No...
[ "The response your function is returning will not display a pdf, but will be treated as a file attachment (i.e saved to disk). This is because of this line:\nresponse['Content-Disposition'] = 'attachment; filename=RDBA.xfdf'\n\nwhich tells the browser that a file RDBA.xfdf is to be saved.\nCheck whether the print_r...
[ 3 ]
[]
[]
[ "django", "django_views", "pdf", "python" ]
stackoverflow_0007728484_django_django_views_pdf_python.txt
Q: str.join with my types Is there opportunity to join my types using: str.join() I have my class: class Slice(object): def __init__(self, start, end): self.__start = start self.__end = end def __str__(self): return '{0}:{1}'.format(self.__start, self.__end) def __repr__(self): ...
str.join with my types
Is there opportunity to join my types using: str.join() I have my class: class Slice(object): def __init__(self, start, end): self.__start = start self.__end = end def __str__(self): return '{0}:{1}'.format(self.__start, self.__end) def __repr__(self): return "'{}'".format...
[ "Nothing.\n','.join(str(x) for x in (Slice(1, 2), Slice(3, 4)))\n\n", "I always just do this:\n','.join(map(str, (Slice(1, 2), Slice(3, 4)))\n\nBut you could also create a utility function:\ndef strseq(*args):\n for arg in args:\n yield str(arg)\n','.join(strseq(Slice(1, 2), Slice(3, 4)))\n\nI think thi...
[ 7, 0, 0 ]
[]
[]
[ "inheritance", "overriding", "python", "string" ]
stackoverflow_0007737287_inheritance_overriding_python_string.txt
Q: Python C Extension with Numpy I'm trying to create a C Extension for Python with Numpy and have some problems reading the data from Numpy in my C code. If I create a simple array like this in Python I'm able to read the values in the C code: Python: from numpy import * myarray = zeros([5, 20], dtype=uint32) C: va...
Python C Extension with Numpy
I'm trying to create a C Extension for Python with Numpy and have some problems reading the data from Numpy in my C code. If I create a simple array like this in Python I'm able to read the values in the C code: Python: from numpy import * myarray = zeros([5, 20], dtype=uint32) C: value = (unsigned long*)PyArray_GETPT...
[ "Numpy structured data types are by default equivalent to C packed structs. They can, however, also be more complicated.\nTo access the fields, check e.g. myarray.dtype.fields['f3'], which in your case is (dtype('uint64'), 32). You should be able to access the corresponding data via (npy_uint64*)(((char*)value) + 3...
[ 0 ]
[]
[]
[ "c", "numpy", "python" ]
stackoverflow_0007728117_c_numpy_python.txt
Q: append item in for loop mysql db table XXX id | a | --------- 1 | 111| 2 | 222| 3 | 333| I got query result from mysql database. info = XXX.objects.filter(a = 111) for item in info: item.update({b:111}) It makes error "XXX has no attribute 'update' I want to append more key:value set into item. How can I...
append item in for loop
mysql db table XXX id | a | --------- 1 | 111| 2 | 222| 3 | 333| I got query result from mysql database. info = XXX.objects.filter(a = 111) for item in info: item.update({b:111}) It makes error "XXX has no attribute 'update' I want to append more key:value set into item. How can I go it?
[ "if your table has field b\nXXX.objects.filter(a = 111).update(b=111)\n\nor\ninfo = XXX.objects.filter(a = 111)\nfor item in info:\n item.b = 111\n item.save()\n\n", "item is not a mapping. If you want to set attributes on an object then just do so.\nitem.b = 111\n\nNote that Django will not retain the chan...
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007735588_django_python.txt
Q: Python/sqlite: get PK of newly inserted row I am inserting a row using raw SQL and need to get the Primary key of the newly inserted row. I cannot assume that any of the non-PK inserted data are unique nor can I assume that the row is the last inserted row. If it's not possible using raw SQL, how about with "regul...
Python/sqlite: get PK of newly inserted row
I am inserting a row using raw SQL and need to get the Primary key of the newly inserted row. I cannot assume that any of the non-PK inserted data are unique nor can I assume that the row is the last inserted row. If it's not possible using raw SQL, how about with "regular" inserts? I am thinking that I will have to cr...
[ "\n... nor can I assume that the row is the last inserted row.\n\nGlobally, you cannot assume it. But related to your connection, you can - so you can use SELECT LAST_INSERT_ID() or just cursor.connection.insert_id(). Maybe even cursor.lastrowid, but I'm not sure if it that would work as well.\n" ]
[ 4 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0007737899_python_sql.txt
Q: Clean and type-safe state machine implementation in a statically typed language? I implemented a simple state machine in Python: import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True:...
Clean and type-safe state machine implementation in a statically typed language?
I implemented a simple state machine in Python: import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True: state = state() time.sleep(1) I wanted to port it to C, because it ...
[ "In Haskell, the idiom for this is just to go ahead and execute the next state:\ntype StateMachine = IO ()\na, b, c :: StateMachine\na = print \"a()\" >> b\nb = print \"b()\" >> c\nc = print \"c()\" >> a\n\nYou need not worry that this will overflow a stack or anything like that. If you insist on having states, the...
[ 22, 15, 11, 11, 6, 4, 3, 3, 2, 1 ]
[ "The Python code you posted will be transformed into a recursive function, but it will not be tail call optimized because Python has no tail call optimization, so it will stack overflow at some point. So the Python code is actually broken, and would take more work to get it as good as the Haskell or C versions.\nHe...
[ -6 ]
[ "c", "haskell", "language_agnostic", "python", "typing" ]
stackoverflow_0007699912_c_haskell_language_agnostic_python_typing.txt
Q: Custom signal from widget to widget try to send signal from one gtk.EventBox child to another. on init HeadMode (line 75) got error: TypeError : unknown signal name: message-send why? #!/usr/bin/env python # -*- coding: utf8 -*- import pygtk pygtk.require('2.0') import gtk import gobject def Destroy(widget): ...
Custom signal from widget to widget
try to send signal from one gtk.EventBox child to another. on init HeadMode (line 75) got error: TypeError : unknown signal name: message-send why? #!/usr/bin/env python # -*- coding: utf8 -*- import pygtk pygtk.require('2.0') import gtk import gobject def Destroy(widget): gtk.main_quit() class CustomEventB...
[ "You have to define message-send signal for the object you are emiting or connecting obj.emit('message-send', ...) or obj.connect('message-send', ...) no matter where are you doing these things.\nYou have not defined signal message-send for HeadMode class. So, this line is wrong:\n self.connect('message-send...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python", "signals" ]
stackoverflow_0007706192_gtk_pygtk_python_signals.txt
Q: How to remove all the white space from string in Python I get a string from XML likebelow: This is the Sample text I need to get all this but only with single spaces Actually I am using the following reg-ex which is converting matching pattern to white spac...
How to remove all the white space from string in Python
I get a string from XML likebelow: This is the Sample text I need to get all this but only with single spaces Actually I am using the following reg-ex which is converting matching pattern to white space but I need them to be stripped not replaced by white space....
[ "Simple solution without regex:\ns = 'This is the Sample text I need to get all this but only with single spaces'\n' '.join(s.split())\n#'This is the Sample text I need to get all this but only with single spaces'\n\nFor completeness I'll add ekhumoro's commen...
[ 9 ]
[]
[]
[ "python", "string", "whitespace" ]
stackoverflow_0007738348_python_string_whitespace.txt
Q: wsgi in multijob mode everyone. I have a simple wsgi server and a simple wsgi application. **The application** def app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello here'] **The server** from wsgiref import simple_server server = simple_server.WSGIS...
wsgi in multijob mode
everyone. I have a simple wsgi server and a simple wsgi application. **The application** def app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello here'] **The server** from wsgiref import simple_server server = simple_server.WSGIServer( ('', 8080),...
[ "You may use ThreadingMixIn or ForkingMixIn from SocketServer module like this:\nfrom wsgiref import simple_server\nfrom SocketServer import ThreadingMixIn\n\nclass ThreadingWSGIServer (ThreadingMixIn, simple_server.WSGIServer): pass\n\nserver = ThreadingWSGIServer(...)\nserver.set_app(app)\nserver.serve_forever()\...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "wsgi" ]
stackoverflow_0007738623_multiprocessing_python_wsgi.txt
Q: Controlling how QtWebKit resizes images <img width='500' height='500' src='image.png'> image.png is larger than 500x500 so when I display it webkit automatically resizes it. The problem is the quality is very poor. My guess is it uses a nearest-neighbor algorithm or something similar and so the result leaves much...
Controlling how QtWebKit resizes images
<img width='500' height='500' src='image.png'> image.png is larger than 500x500 so when I display it webkit automatically resizes it. The problem is the quality is very poor. My guess is it uses a nearest-neighbor algorithm or something similar and so the result leaves much to be desired. Is it possible to make it use...
[ "from PyQt4.QtGui import QPainter\n\nyourQWebView.setRenderHints(QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing)\n\nhttp://doc.qt.nokia.com/4.7-snapshot/qwebview.html#renderHints-prop\n" ]
[ 1 ]
[]
[]
[ "pyqt4", "python", "webkit" ]
stackoverflow_0007739094_pyqt4_python_webkit.txt
Q: How To Correctly Install Python On Windows 7 64 Bit? I am having lots of trouble getting python 2.7.2 to install on my system correctly. I have tried to download the activestate version http://www.activestate.com/activepython/downloads and it seems to be installed correctly but when I try to run python from my ter...
How To Correctly Install Python On Windows 7 64 Bit?
I am having lots of trouble getting python 2.7.2 to install on my system correctly. I have tried to download the activestate version http://www.activestate.com/activepython/downloads and it seems to be installed correctly but when I try to run python from my terminal I keep getting this message. 'python' not recognized...
[ "You need to make sure that the Python installation directory is in your PATH environment variable. I thought that the ActiveState installer did that for you, but in any case, that seems to be the problem here.\nYou can set the PATH enviroment variable in: View Advanced System Settings -> Enviroment Variables. Just...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007739204_python.txt
Q: Sqlalchemy many to many mapping with extra fields I created a many to many relationship with sqlalchemy like this: subject_books = Table('subject_books', Base.metadata, Column('subject_id', Integer, ForeignKey('subjects.id')), Column('book_id', Integer, ForeignKey('books.id')), Column('group', Integer)...
Sqlalchemy many to many mapping with extra fields
I created a many to many relationship with sqlalchemy like this: subject_books = Table('subject_books', Base.metadata, Column('subject_id', Integer, ForeignKey('subjects.id')), Column('book_id', Integer, ForeignKey('books.id')), Column('group', Integer) ) class Subject(Base): __tablename__ = 'subjects'...
[ "Razi\nI think you are constructing wrong relation ship.\nYour relation ship must be\nbook M2M subject\nsubject M2M group\nSo you have to create one more model for group and that must be assign as m2m in Subject\nYour models will be like.\nsubject_books = Table('subject_books', Base.metadata,\n Column('subject_i...
[ 6 ]
[]
[]
[ "orm", "pyramid", "python", "sqlalchemy" ]
stackoverflow_0007737987_orm_pyramid_python_sqlalchemy.txt
Q: How do I stop Py_Initialise crashing the application? From VBA and VB6 I'm calling a dll the creates a Python interpreter. If I set the PATH environment variable to point to "C:\python27" and PYTHONPATH to "c:\python27\lib" all is fine. If I don't set the PATH then calling Py_Initialise() crashes XL or my VB6 app...
How do I stop Py_Initialise crashing the application?
From VBA and VB6 I'm calling a dll the creates a Python interpreter. If I set the PATH environment variable to point to "C:\python27" and PYTHONPATH to "c:\python27\lib" all is fine. If I don't set the PATH then calling Py_Initialise() crashes XL or my VB6 app, even if I call Py_SetProgramName with "c:\python27\python...
[ "The best answer I've found so far is that it is a bug in Python - http://bugs.python.org/issue6498. The intepreter seems to call exit() on certain errors rather than passing a code back to the caller. Not very friendly if you're embedding python in an app. But there you go.\n", "try to change the working directo...
[ 3, 1, 0 ]
[]
[]
[ "c++", "excel", "python", "vb6", "vba" ]
stackoverflow_0007565033_c++_excel_python_vb6_vba.txt
Q: Uniformly distributed data in d dimensions How can I generate a uniformly distributed [-1,1]^d data in Python? E.g. d is a dimension like 10. I know how to generate uniformly distributed data like np.random.randn(N) but dimension thing is confused me a lot. A: Assuming independence of the individual coordinates...
Uniformly distributed data in d dimensions
How can I generate a uniformly distributed [-1,1]^d data in Python? E.g. d is a dimension like 10. I know how to generate uniformly distributed data like np.random.randn(N) but dimension thing is confused me a lot.
[ "Assuming independence of the individual coordinates, then the following will generate a random point in [-1, 1)^d\nnp.random.random(d) * 2 - 1\n\nThe following will generate n observations, where each row is an observation\nnp.random.random((n, d)) * 2 - 1\n\n", "As has been pointed out, randn produces normally ...
[ 8, 7, 2, 2 ]
[]
[]
[ "machine_learning", "numpy", "python", "scipy" ]
stackoverflow_0007733969_machine_learning_numpy_python_scipy.txt
Q: Python assignment operator associativity Consider the following Python3 program: a = [0, 0] i = 0 a[i] = i = 1 print(a, i) a = [0, 0] i = 0 i = a[i] = 1 print(a, i) I expected the output to be: [0, 1] 1 [1, 0] 1 But instead I got: [1, 0] 1 [0, 1] 1 My question is: is there anything in the Pyt...
Python assignment operator associativity
Consider the following Python3 program: a = [0, 0] i = 0 a[i] = i = 1 print(a, i) a = [0, 0] i = 0 i = a[i] = 1 print(a, i) I expected the output to be: [0, 1] 1 [1, 0] 1 But instead I got: [1, 0] 1 [0, 1] 1 My question is: is there anything in the Python language specification about associativity...
[ "Short answer: the code is well defined; the order is left-to-right.\nLong answer:\nFirst of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a statement, not an operator. This means that you can't use assignment as part of another expression: for example i = (j = 0) is ...
[ 13, 8 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0007738122_operators_python.txt
Q: Using python to control a phone with bluetooth I would like to know if there are any API's for python to programmatically control a phone, like starting and ending calls, but also to record conversations. I would also like to use the Headphones and Mic of the computer to talk over the phone. Any info would be grea...
Using python to control a phone with bluetooth
I would like to know if there are any API's for python to programmatically control a phone, like starting and ending calls, but also to record conversations. I would also like to use the Headphones and Mic of the computer to talk over the phone. Any info would be great, I tried googling for something, but nothing usefu...
[ "Be careful when using PyBluez! The results will actually depend on the BT-USB dongle you are using. Depending on the hardware(the BT chip in there), PyBluez will use one or another BT stack - for example there was one from WIDCOMM. Results will vary, as PyBluez is actually wrapping around those stacks - all of whi...
[ 2, 1 ]
[]
[]
[ "bluetooth", "python" ]
stackoverflow_0007706497_bluetooth_python.txt
Q: Logical or of Django many to many queries returns duplicate results I have models with many to many relationships like this: class Contact(models.Model): name = models.TextField() address = models.TextField() class Mail(models.Model): to = models.ManyToManyField(Contact, related_name='received_mails')...
Logical or of Django many to many queries returns duplicate results
I have models with many to many relationships like this: class Contact(models.Model): name = models.TextField() address = models.TextField() class Mail(models.Model): to = models.ManyToManyField(Contact, related_name='received_mails') cc = models.ManyToManyField(Contact, related_name='cced_mails') I w...
[ "As SQL returns all matching records, Django dutifully maps them to objects. What you're looking for is the .distinct() queryset method that makes SQL collapse all duplicate rows into one.\n" ]
[ 19 ]
[]
[]
[ "django", "many_to_many", "python", "sql" ]
stackoverflow_0007740356_django_many_to_many_python_sql.txt
Q: How to use sqlalchemy-migrate with declarative db model I try add to some table new column, how its described in documentation for sqlalchemy-migrate< like: col = Column('col1', String, default='foobar') col.create(table, populate_default=True) But I get error, i think its because i use declarative models, how i ...
How to use sqlalchemy-migrate with declarative db model
I try add to some table new column, how its described in documentation for sqlalchemy-migrate< like: col = Column('col1', String, default='foobar') col.create(table, populate_default=True) But I get error, i think its because i use declarative models, how i can use migrations?
[ "def upgrade(migrate_engine):\n Base.metadata.bind = migrate_engine\n col = Column('col1', String, default='foobar')\n col.create(table, populate_default=True)`\n\nworked for me.\n" ]
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006707371_python_sqlalchemy.txt
Q: Installing the igraph package for python I have downloaded the igraph 0.5.4 tar ball for macosx Leopard 10.5.8. When I unpack it and then run: sudo python setup.py install I get the following long error message: Include path: /usr/include /usr/local/include Library path: running install running bdist_egg run...
Installing the igraph package for python
I have downloaded the igraph 0.5.4 tar ball for macosx Leopard 10.5.8. When I unpack it and then run: sudo python setup.py install I get the following long error message: Include path: /usr/include /usr/local/include Library path: running install running bdist_egg running egg_info writing python_igraph.egg-info/P...
[ "What you have downloaded is only the Python interface to the igraph library. The library itself is written in C, and you will have to install the C core of igraph first before trying to compile the Python interface.\nBasically, you have three choices here:\n\nTry to make use of the pre-compiled Mac OS X installer ...
[ 9, 2 ]
[]
[]
[ "igraph", "python" ]
stackoverflow_0003856820_igraph_python.txt
Q: Generate thumbnail for video on external site I have a lot of external links from users, and I need to scrap somehow the video content and generate thumbnail for it to display on my site. I know this is a simple task with django-oembed, but the list of providers is limited. I need to support sites without oembed ...
Generate thumbnail for video on external site
I have a lot of external links from users, and I need to scrap somehow the video content and generate thumbnail for it to display on my site. I know this is a simple task with django-oembed, but the list of providers is limited. I need to support sites without oembed too. So the main task is to determine if page conta...
[ "You can use Pymedia to extract a frame from the video and PIL to create the thumbnail like suggested here\n" ]
[ 0 ]
[]
[]
[ "django", "python", "video_streaming" ]
stackoverflow_0007740997_django_python_video_streaming.txt
Q: What alternatives are there to numpy on Google App Engine? What alternatives can you recommend to numpy to use on the Google App Engine? Specifically I'm interested in matrix manipulations on large matrices. A: The Python 2.7 runtime includes NumPy 1.6.1. A: Update: As remarked by Matthew Simoneau and by @pet...
What alternatives are there to numpy on Google App Engine?
What alternatives can you recommend to numpy to use on the Google App Engine? Specifically I'm interested in matrix manipulations on large matrices.
[ "The Python 2.7 runtime includes NumPy 1.6.1.\n", "Update: As remarked by Matthew Simoneau and by @petr, the Python 2.7 runtime on GAE now includes Numpy among it's libraries.\nWhen this question was originally asked and answered, the old answer was the following.\nOld answer: GAE only supports native python code...
[ 12, 2 ]
[]
[]
[ "google_app_engine", "numpy", "python" ]
stackoverflow_0005490723_google_app_engine_numpy_python.txt
Q: Python, overiding itself I've a following problem. I have a model class in MVC and it has a special purpose. In certain cases it should be able to override itself. Is this kind of behavior possible? Class Text(Document): a = StringField() b = StringField() def save(self): if 1==Text.object(a...
Python, overiding itself
I've a following problem. I have a model class in MVC and it has a special purpose. In certain cases it should be able to override itself. Is this kind of behavior possible? Class Text(Document): a = StringField() b = StringField() def save(self): if 1==Text.object(a=self.a).count(): # if s...
[ "There's no trivial way for an object to become another object in python. Assigning to self won't do this; self is a local variable in the method definition, And assigning to it won't change the existing instance in any way; only make it inaccessible for the rest of the method.\nThere are a few ways to approach th...
[ 1, 0 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0007730509_class_oop_python.txt
Q: Is it possible to trick pip install --find-links into using a downloaded sdist for --editable requirements? Using the following command: pip install -r requirements.txt -d sdists/ You can easily create an archive of requirements for distributing with your project. This works great if your requirements look like ...
Is it possible to trick pip install --find-links into using a downloaded sdist for --editable requirements?
Using the following command: pip install -r requirements.txt -d sdists/ You can easily create an archive of requirements for distributing with your project. This works great if your requirements look like this: Django==1.3.1 django-tagging==0.3.1 django-robots==0.6.1 You can then install those requirements without t...
[ "While it doesn't appear that this is strictly possible using PIP, there is a workaround that accomplishes the same thing. The workaround is to automatically generate a second requirements file from the original requirements file and sdists directory (to be used only for that directory).\nA simple implementation m...
[ 4 ]
[]
[]
[ "dependencies", "django", "pip", "pypi", "python" ]
stackoverflow_0007727866_dependencies_django_pip_pypi_python.txt
Q: Channel disconnect notification in channel api in google app engine Im using my GAE application on my phone. I face a problem in getting the disconnect notification to /_ah/channel/disconnected in channels api even if i manually close the socket by socket.close() function. the post occurs after a delay of say one ...
Channel disconnect notification in channel api in google app engine
Im using my GAE application on my phone. I face a problem in getting the disconnect notification to /_ah/channel/disconnected in channels api even if i manually close the socket by socket.close() function. the post occurs after a delay of say one minute. Does anyone know the way to speed things up? In my case socket.c...
[ "The amount of time it takes the Channel API front-end servers to \"realize\" that a channel is disconnected is contingent on browser implementation.\nOn well-behaved browsers, we catch the beforeunload event and post a message to our front-end that says, \"this client is going away.\" On other browsers, we may not...
[ 4 ]
[]
[]
[ "channel_api", "google_app_engine", "javascript", "python" ]
stackoverflow_0007736105_channel_api_google_app_engine_javascript_python.txt
Q: approximate search in a database I have a large database with a list of institutions (universities, hospitals, etc). The names of institutions come from different sources and can be spelled differently for the same institution. They can be misspelled, for example, or words can be shortened ("uni", or "univ", or "u...
approximate search in a database
I have a large database with a list of institutions (universities, hospitals, etc). The names of institutions come from different sources and can be spelled differently for the same institution. They can be misspelled, for example, or words can be shortened ("uni", or "univ", or "university") Given a name that I need t...
[ "This is the problem of record linkage. Many databases provide basic methods for this such as character-level n-gram matching, where a term like \"university\" is expanded into\n[\"uni\", \"niv\", \"ive\", \"ver\", \"ers\", ...]\nfor n = 3. The database would index all such n-grams and allow a search with some kind...
[ 5, 1, 0 ]
[]
[]
[ "database", "django", "fuzzy_search", "postgresql", "python" ]
stackoverflow_0007741082_database_django_fuzzy_search_postgresql_python.txt