content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python/scrapy question: How to avoid endless loops I am using the web-scraping framework, scrapy, to data mine some sites. I am trying to use the CrawlSpider and the pages have a 'back' and 'next' button. The URLs are in the format www.qwerty.com/### where ### is a number that increments every time the next butto...
python/scrapy question: How to avoid endless loops
I am using the web-scraping framework, scrapy, to data mine some sites. I am trying to use the CrawlSpider and the pages have a 'back' and 'next' button. The URLs are in the format www.qwerty.com/### where ### is a number that increments every time the next button is pressed. How do I format the rules so that an endle...
[ "Endless loop shouldn't happen. Scrapy will filter out duplicate urls. \n", "what makes you think the program will go into infinite loop, how have you tested it?\nscrapy wont download a url if it has already done it before. Did you try to go through all the pages, what happens when you click next on the last page...
[ 8, 1, 1 ]
[]
[]
[ "loops", "python", "scrapy", "web_crawler" ]
stackoverflow_0006684129_loops_python_scrapy_web_crawler.txt
Q: board-drawing code to move an oval I am working on a python checkers game for college. I have the board drawn, using tk, but I can't seem to implement a movement function for the pieces. If anyone see any errors in my code, or can offer help, I would appreciate. Here is the complete source. Thanks in advance. I kn...
board-drawing code to move an oval
I am working on a python checkers game for college. I have the board drawn, using tk, but I can't seem to implement a movement function for the pieces. If anyone see any errors in my code, or can offer help, I would appreciate. Here is the complete source. Thanks in advance. I know that this draws the checker pieces. I...
[ "You can move an item on a canvas using the coords and/or move methods to change the coordinates from what they are to what you want them to be.\nHere's a simple example showing how to create and move an item on a canvas:\nimport tkinter as tk # python 3\n# import Tkinter as tk # python 2\n\nclass Example(tk....
[ 34, 2 ]
[]
[]
[ "python", "python_2.7", "tk_toolkit", "tkinter" ]
stackoverflow_0006740855_python_python_2.7_tk_toolkit_tkinter.txt
Q: wrapping a list of structs with boost.python I have a C++ function that returns a list of structs. Inside the struct, there are more lists of structs. struct CameraInfo { CamName name; std::list<CamImageFormat> lImgFormats; std::list<CamControls> lCamControls; }; std::list<Ca...
wrapping a list of structs with boost.python
I have a C++ function that returns a list of structs. Inside the struct, there are more lists of structs. struct CameraInfo { CamName name; std::list<CamImageFormat> lImgFormats; std::list<CamControls> lCamControls; }; std::list<CameraInfo> getCameraInfo() { std::list<CameraIn...
[ "Does it have to be std::list ? If you use std::vector instead you can use boost::python::vector_indexing_suite to wrap the list. See this post for details.\nIf you must use std::list you'll need to create a helper class that wraps the std::list functionality with python's list methods. That can be quite involve...
[ 13, 0 ]
[]
[]
[ "boost_python", "c++", "list", "python", "word_wrap" ]
stackoverflow_0006776888_boost_python_c++_list_python_word_wrap.txt
Q: virtual-burrito .bashrc entry I installed virtual-burrito the python virtualenv creator. On rebooting I cannot restart virtual-burrito somehow my .bashrc entry for virtual-burrito is missing. Does anyone know the format for the .bashrc entry for this? I tried copying my pythonbrew entry but it is not the same also...
virtual-burrito .bashrc entry
I installed virtual-burrito the python virtualenv creator. On rebooting I cannot restart virtual-burrito somehow my .bashrc entry for virtual-burrito is missing. Does anyone know the format for the .bashrc entry for this? I tried copying my pythonbrew entry but it is not the same also tried source ~/.venvburrito/b...
[ "source $HOME/.venvburrito/startup.sh\n\n" ]
[ 0 ]
[]
[]
[ "bash", "python", "virtualenv", "wrapper" ]
stackoverflow_0006775321_bash_python_virtualenv_wrapper.txt
Q: Changing the type of a field in a collection in a mongodb database The type of a field in a collection in my mongodb database is unicode string. This field currently does not have any data associated with it in any of the documents in the collection. I dont want the type to be string because,i want to add subfield...
Changing the type of a field in a collection in a mongodb database
The type of a field in a collection in my mongodb database is unicode string. This field currently does not have any data associated with it in any of the documents in the collection. I dont want the type to be string because,i want to add subfields to it from my python code using pymongo. The collection already has ma...
[ "Sure, simply create a script that iterates over your current collection, reads the existing value and overwrite it with the new value (an embedded document in your case). You change the typ of the field by simply setting a new value for that field. E.g. setting a string field to an integer field :\ndb.test.update(...
[ 1, 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0006789562_mongodb_pymongo_python.txt
Q: Install BeautifulSoup for another Python version on Mac OS X I have three versions of Python on my Mac: 2.6.1 (built-in), 2.5.4 (Google App Engine development), and 2.7.2 (general Python programming). I installed BeautifulSoup with python setup.py install. However, only 2.7.2 is able to work with it. How do I inst...
Install BeautifulSoup for another Python version on Mac OS X
I have three versions of Python on my Mac: 2.6.1 (built-in), 2.5.4 (Google App Engine development), and 2.7.2 (general Python programming). I installed BeautifulSoup with python setup.py install. However, only 2.7.2 is able to work with it. How do I install it for 2.5.4 as well?
[ "/path/to/other/python setup.py install\n\nIt can be helpful to make aliases for your various system Pythons (e.g. python25, and so on) in your .bashrc.\nIn regards to changing what python points to from the default system Python, I know that this will work if you alias to a newer version, but it may cause issues w...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "installation", "python" ]
stackoverflow_0006789757_beautifulsoup_installation_python.txt
Q: Python: Change Tuple Order in List Of Tuples I have a list of tuples like so: ListOfTuples = [(var1,var2,var3,var4,var5), (var6,var7,var8,var9,var10), (var11,var12,var13,var14,var15), (var16,var17,var18,var19,var20)] I want to swap two tuples, i.e. have the list like: ListOfTuples = [(var1,var2,var3...
Python: Change Tuple Order in List Of Tuples
I have a list of tuples like so: ListOfTuples = [(var1,var2,var3,var4,var5), (var6,var7,var8,var9,var10), (var11,var12,var13,var14,var15), (var16,var17,var18,var19,var20)] I want to swap two tuples, i.e. have the list like: ListOfTuples = [(var1,var2,var3,var4,var5), (var6,var7,var8,var9,var10), ...
[ "Your code working fine for me. I have also tried code below and it works for me:\ndata = [(1,2,3), (3,4,5), (5,6,7), (7,8,9)]\ndata[2:] = reversed(data[2:])\n>>> [(1, 2, 3), (3, 4, 5), (7, 8, 9), (5, 6, 7)]\n\nI have tried this in the following way to use condition:\ndata = [(1,2,3), (3,4,5), (5,6,7), (7,8,9)]\nfo...
[ 2 ]
[ "hope this would help:\ntemp = ListOfTuples[2]\nListOfTuples[2] = ListOfTuples[3]\nListOfTuples[3] = temp\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0006789917_python.txt
Q: Subprocess is not invoking my command(or is doing it wrong) Overview: I have an application that sometimes must make something with celery- and if it is simple task such as count something- everything is ok. I' ve got one task which must convert existing file to another file using MS Windows program. So- I install...
Subprocess is not invoking my command(or is doing it wrong)
Overview: I have an application that sometimes must make something with celery- and if it is simple task such as count something- everything is ok. I' ve got one task which must convert existing file to another file using MS Windows program. So- I installed WINE, then installed application and added folowing task to my...
[ "Use \np = subprocess.Popen( commands, shell=True, cwd='/home/test', env=os.environ, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n\nfor your Popen command, then \nprint p.communicate()\np.wait()\nprint p.communicate()\n\nTo see what it prints to stdout and stderr and figure out what you're doing wrong.\nEd...
[ 3 ]
[]
[]
[ "celery", "django", "python", "wine", "xvfb" ]
stackoverflow_0006790006_celery_django_python_wine_xvfb.txt
Q: Crontab: Setting Timezone I have a django-based website installed on a shared web server. I am planning to have few cron jobs to automate creation of reports, sending emails etc. The problem is that the Timezone of the shared server is "America/New_York" (since it's a shared server I don't have the permission to c...
Crontab: Setting Timezone
I have a django-based website installed on a shared web server. I am planning to have few cron jobs to automate creation of reports, sending emails etc. The problem is that the Timezone of the shared server is "America/New_York" (since it's a shared server I don't have the permission to change it) while I have to run t...
[ "One solution might be to have the cron run at 20 minutes past every hour, then have the script check whether it is the right Asia time and only continue if it is.\n", "Put this line in your crontab:\nTZ=Asia/Kolkata\n\n" ]
[ 1, 0 ]
[]
[]
[ "cron", "crontab", "python", "timezone" ]
stackoverflow_0006785164_cron_crontab_python_timezone.txt
Q: Windows System Menu in Python I am trying to create a new item in the Windows System Menu for my app and have an action performed when it is click. I have worked out the frist part using the below code. import win32con import win32gui hwnd = win32gui.GetForegroundWindow () hmenu = win32gui.GetSystemMenu (hwnd, F...
Windows System Menu in Python
I am trying to create a new item in the Windows System Menu for my app and have an action performed when it is click. I have worked out the frist part using the below code. import win32con import win32gui hwnd = win32gui.GetForegroundWindow () hmenu = win32gui.GetSystemMenu (hwnd, False) win32gui.AppendMenu(hmenu, wi...
[ "You have to hook into the windows procedure of the menu and handle the messages being sent. See e.g. http://wiki.wxpython.org/HookingTheWndProc\n" ]
[ 2 ]
[]
[]
[ "python", "win32com" ]
stackoverflow_0006789741_python_win32com.txt
Q: Django: add model fields to list_display and display related values per entry I have the following model definitions, see below. models.py: class Userstatus(models.Model): label = models.CharField(...) description = models.CharField(...) class Foo(models.Model): title = models.CharField(...) visib...
Django: add model fields to list_display and display related values per entry
I have the following model definitions, see below. models.py: class Userstatus(models.Model): label = models.CharField(...) description = models.CharField(...) class Foo(models.Model): title = models.CharField(...) visibility = models.ManyToManyField(Userstatus) admin.py: class FooAdmin(ModelAdmin): ...
[ "Django documentation says ...\n\nManyToManyField fields aren't supported, because that would entail\n executing a separate SQL statement for each row in the table. If you\n want to do this nonetheless, give your model a custom method, and add\n that method's name to list_display. (See below for more on custom\n...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006789742_django_django_admin_python.txt
Q: Python/Pygame Making An Object Follow Another Object I Have Been Trying for days on how to do this. Basically You Control A Player, And zombies follow you. Problem Is, I Cant Seem To Get The Zombies To Follow! I Tried If Statements For Example if playerx > zombiex: zombiex=zombiex - 2 screen.bl...
Python/Pygame Making An Object Follow Another Object
I Have Been Trying for days on how to do this. Basically You Control A Player, And zombies follow you. Problem Is, I Cant Seem To Get The Zombies To Follow! I Tried If Statements For Example if playerx > zombiex: zombiex=zombiex - 2 screen.blit(zombie,(zombiex,zombiey)) aaaaaand That Didnt Work.......
[ "Maybe this is what you searched for.\ndef length(x, y):\n return (x ** 2 + y ** 2) ** .5\n\ndef norm(x, y):\n _len = length(x, y)\n return x / _len, y / _len\n\nclass ZombieController(object):\n\n def __init__(self, zombie_view_range):\n self._zombs = []\n self.append = self._zombs.app...
[ 1, 0 ]
[]
[]
[ "programming_languages", "pygame", "python" ]
stackoverflow_0006790284_programming_languages_pygame_python.txt
Q: Look for img and id tag, store URL in variable if both are true I have been playing around with some Python now and start to get a hang of it. I have already came up with a project, but I can't work out some things. The purpose is to look inside a defined tag, such as the img tag or the a tag. If that's true, it a...
Look for img and id tag, store URL in variable if both are true
I have been playing around with some Python now and start to get a hang of it. I have already came up with a project, but I can't work out some things. The purpose is to look inside a defined tag, such as the img tag or the a tag. If that's true, it also needs to look for a id tag, always the same one. If the img take ...
[ "People generally use BeautifulSoup, http://www.crummy.com/software/BeautifulSoup/, to do this sort of thing.\nAfter installing:\nfrom BeautifulSoup import BeautifulSoup\n# if the file is on your computer use this\n#file = open('/path/to/the/file')\n# and if the file is on the internet use this\n#import urllib\n#fi...
[ 2 ]
[]
[]
[ "html", "python", "urllib2" ]
stackoverflow_0006790770_html_python_urllib2.txt
Q: How to change behavior of dict() for an instance So I'm writing a class that extends a dictionary which right now uses a method "dictify" to transform itself into a dict. What I would like to do instead though is change it so that calling dict() on the object results in the same behavior, but I don't know which me...
How to change behavior of dict() for an instance
So I'm writing a class that extends a dictionary which right now uses a method "dictify" to transform itself into a dict. What I would like to do instead though is change it so that calling dict() on the object results in the same behavior, but I don't know which method to override. Is this not possible, or I am I miss...
[ "Nothing wrong with your approach, but this is similar to the Autovivification feature of Perl, which has been implemented in Python in this question. Props to @nosklo for this.\nclass RecursiveDict(dict):\n \"\"\"Implementation of perl's autovivification feature.\"\"\"\n def __getitem__(self, item):\n ...
[ 29, 2, 2, 2, 1, 0 ]
[]
[]
[ "autovivification", "dictionary", "overriding", "python" ]
stackoverflow_0006780952_autovivification_dictionary_overriding_python.txt
Q: using *args in struct.pack I just read about the *args and **kwargs notation in python and decided to use it with my functions that use struct.pack as such: def pack_floats(*args): return struct.pack('%df' %len(args), args) But of course, it doesn't work because args is a tuple. If I wanted to pack three num...
using *args in struct.pack
I just read about the *args and **kwargs notation in python and decided to use it with my functions that use struct.pack as such: def pack_floats(*args): return struct.pack('%df' %len(args), args) But of course, it doesn't work because args is a tuple. If I wanted to pack three numbers, I would call pack as such ...
[ ">>> import struct\n>>> def pack_floats(*args):\n... return struct.pack('%df' %len(args), *args)\n... \n>>> pack_floats(0.1,1.2,2.3)\n'\\xcd\\xcc\\xcc=\\x9a\\x99\\x99?33\\x13@'\n\n", "def pack_floats(*args):\n return struct.pack('%df' % len(args), *args)\n\nYou were almost right: you packed the arguments i...
[ 6, 1, 1 ]
[]
[]
[ "function", "python", "variadic_functions" ]
stackoverflow_0006791050_function_python_variadic_functions.txt
Q: What is the benefit to define a function in a function in python? I encountered this piece of python code (pasted below) on effbot and I was wondering: Why defining a function within a function? import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param tex...
What is the benefit to define a function in a function in python?
I encountered this piece of python code (pasted below) on effbot and I was wondering: Why defining a function within a function? import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode...
[ "\nWhy defining a function within a function?\n\nTo keep it isolated. It's only used in this one place. Why define it more globally when it's used locally?\n", "It's just another way of breaking down a large function into smaller pieces without polluting the global namespace with another function name. Quite o...
[ 72, 8, 7 ]
[]
[]
[ "function", "python", "syntax" ]
stackoverflow_0006791198_function_python_syntax.txt
Q: library management system in django I just started developing library management system using django. I'm new to Django, so where do you suggest me to start? I used the tutorial on django's website but I think it's not enough for me to do something like this. I will probably use this ER diagram of database of the...
library management system in django
I just started developing library management system using django. I'm new to Django, so where do you suggest me to start? I used the tutorial on django's website but I think it's not enough for me to do something like this. I will probably use this ER diagram of database of the system, but probably I should transfer i...
[ "I firmly recommend starting with this tutorial:\nhttps://docs.djangoproject.com/en/dev/intro/tutorial01/\nWhat you gonna do then is just use more models than they have in tutorial. The idea is - you describe you domain with classes called \"models\". Each of them describes an entity from your domain. You also desc...
[ 1 ]
[]
[]
[ "database", "django_models", "python" ]
stackoverflow_0006791383_database_django_models_python.txt
Q: Making bigger matrices out of smaller matrices in Python I have a problem making a bigger matrix out of smaller matrixs. Lets suppose i have the matrices: 1 2 3 A= 4 5 6 7 8 9 and 1 0 0 B= 0 1 0 0 0 1 The result i want to get is 1 2 3 1 0 0 C = 4 5 6 0 1 0 7 8 9 0 0 1 If I...
Making bigger matrices out of smaller matrices in Python
I have a problem making a bigger matrix out of smaller matrixs. Lets suppose i have the matrices: 1 2 3 A= 4 5 6 7 8 9 and 1 0 0 B= 0 1 0 0 0 1 The result i want to get is 1 2 3 1 0 0 C = 4 5 6 0 1 0 7 8 9 0 0 1 If I'm to do this in MATLab it would be as simple as doing C = [A ...
[ "try using np.hstack:\nC = np.hstack((A,B))\n\nor np.concanenate:\nC = np.concatenate((A,B),axis=1)\n\n" ]
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006791528_numpy_python.txt
Q: wxPython get event ID I have some code, which binds a menu item to a method: def getEventID(self, event): print id # how do I get id? EVT_MENU(self, 123, self.getEventID) So basicly, I want my app to print "123" when the menu item with that ID is pressed. How would I do that? A: You should just be able to...
wxPython get event ID
I have some code, which binds a menu item to a method: def getEventID(self, event): print id # how do I get id? EVT_MENU(self, 123, self.getEventID) So basicly, I want my app to print "123" when the menu item with that ID is pressed. How would I do that?
[ "You should just be able to use event.GetId() I believe. You can also use event.GetEventObject() to get the widget that fired the event.\n" ]
[ 4 ]
[]
[]
[ "events", "python", "wxpython" ]
stackoverflow_0006791676_events_python_wxpython.txt
Q: How can a python project containing native bindings be distributed via PyPi My python project contains some C/C++ bindings with some python code and I want to distribute it through PyPi. If I create a source archive with python setup.py sdist and upload it to PyPi, my understanding is it will contain only the sour...
How can a python project containing native bindings be distributed via PyPi
My python project contains some C/C++ bindings with some python code and I want to distribute it through PyPi. If I create a source archive with python setup.py sdist and upload it to PyPi, my understanding is it will contain only the source files. How will the native bindings be compiled to match the platform (win/osx...
[ "By default it will use the default compiler available on the system. If you want to change that, take a look at these docs about saveopts.\n" ]
[ 0 ]
[]
[]
[ "packaging", "pypi", "python", "setuptools" ]
stackoverflow_0006791236_packaging_pypi_python_setuptools.txt
Q: How to get the last value in a list/string using Python I am a beginner in writing Python scripts and I need help on the following: Threads::num,47141,47146,47151,47156,47161,47166,47171,47176 How can I get and display the last value '47176' The following is the part of the code I have written: elif sys.argv[1] ==...
How to get the last value in a list/string using Python
I am a beginner in writing Python scripts and I need help on the following: Threads::num,47141,47146,47151,47156,47161,47166,47171,47176 How can I get and display the last value '47176' The following is the part of the code I have written: elif sys.argv[1] == "-c": b = sys.argv[2] with open(b) as f: for...
[ "I think your post got re-formatted, because the Python interpreter definitely won't execute it, but take a look at this:\nprint line.strip(',').split(',')[-1] \nprint line\n\nThe phrase line.strip(',').split(',')[-1] ends up as '47116', but then you do a print line which just outputs the whole of the contents of l...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006791788_python.txt
Q: python. how to get attribute value with libxml2 I was using MINIDOM but it does not provide xpath methods. I am now trying to use libxml2 but I am having trouble retrieving attribute values. An extract of my xml looks as follow: <Class name="myclass1" version="0"> <Owner user-login="smagnoni"/> </Class> and I...
python. how to get attribute value with libxml2
I was using MINIDOM but it does not provide xpath methods. I am now trying to use libxml2 but I am having trouble retrieving attribute values. An extract of my xml looks as follow: <Class name="myclass1" version="0"> <Owner user-login="smagnoni"/> </Class> and I wrote the following code: import libxml2 doc = libxm...
[ ".prop('user-login') should work:\nimport libxml2\nimport io\ncontent='''\\\n<Class name=\"myclass1\" version=\"0\">\n <Owner user-login=\"smagnoni\"/>\n</Class>\n'''\ndoc = libxml2.parseMemory(content,len(content))\nclassName='myclass1'\nclassVersion='0'\nris = doc.xpathEval('//Class[@name=\"'+className+'\" and...
[ 5, 4, 2 ]
[]
[]
[ "get", "python", "xml" ]
stackoverflow_0006791503_get_python_xml.txt
Q: How to extend this search-and-replace python script to accept variables from command line? Currently, I have a script which does the following. If I have text file with the lines: <<Name>> is at <<Location>>. <<Name>> is feeling <<Emotion>>. The script will take in the this input file as a command line argument a...
How to extend this search-and-replace python script to accept variables from command line?
Currently, I have a script which does the following. If I have text file with the lines: <<Name>> is at <<Location>>. <<Name>> is feeling <<Emotion>>. The script will take in the this input file as a command line argument and prompt the user for the variables: Name? Bob Location? work Emotion? frustrated Note that na...
[ "OK, if you want to dynamically generate the options:\nparser = argparse.ArgumentParser()\nparser.add_argument('infile', type=argparse.FileType('r'))\nparser.add_argument('outfile', type=argparse.FileType('w'))\n\nrequired, extra = parser.parse_known_args()\ninfile, outfile = required.infile, required.outfile\n\nar...
[ 3 ]
[]
[]
[ "python", "replace", "scripting" ]
stackoverflow_0006791712_python_replace_scripting.txt
Q: SqlAlchemy Migrate Declarative I've modified the tutorial on the SqlAlchemy-Migrate tutorial to declarative syntax for my Pylons Pyramid project. I can successfully upgrade and downgrade, but I'm concerned about the Base.metadata.drop_all(migrate_engine) command below. Here is my migration file: from sqlalchemy im...
SqlAlchemy Migrate Declarative
I've modified the tutorial on the SqlAlchemy-Migrate tutorial to declarative syntax for my Pylons Pyramid project. I can successfully upgrade and downgrade, but I'm concerned about the Base.metadata.drop_all(migrate_engine) command below. Here is my migration file: from sqlalchemy import Column from sqlalchemy.types im...
[ "The proper solution on upgrade is to get the table and create it individually, like such:\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind migrate_engine\n # to your metadata\n User.__table__.create(migrate_engine)\n\nand, for downgrading:\ndef downgrade(mig...
[ 7 ]
[]
[]
[ "orm", "pylons", "pyramid", "python", "sqlalchemy" ]
stackoverflow_0006786227_orm_pylons_pyramid_python_sqlalchemy.txt
Q: This code works running from Aptana but fails in python HTMLParser So that's the point, in Aptana 3 wiyh pyDev i get no exceptions, everything seems to be fine. But when i try to run directly in python, the bucle stops in some point, i guess it can be a match with some special character like ó or something like th...
This code works running from Aptana but fails in python HTMLParser
So that's the point, in Aptana 3 wiyh pyDev i get no exceptions, everything seems to be fine. But when i try to run directly in python, the bucle stops in some point, i guess it can be a match with some special character like ó or something like that. class Spider(HTMLParser): def __init__(self, url): HTMLP...
[ "Try this:\nimport sys\nsys.setdefaultencoding('latin-1')\n\nSome related reading: Python Unicode HOWTO.\n", "Unfortunately, Max's solution didn't work.\n\nAttributeError: 'module' object has no attribute 'setdefaultencoding'\n\nI finally got it to work by adding:\nz=urlopen(url).read().decode('utf-8')\nself.feed...
[ 1, 0 ]
[]
[]
[ "aptana", "python" ]
stackoverflow_0006763671_aptana_python.txt
Q: How to mask numpy structured array on multiple columns? I have a numpy structured array with a dtype such as: A = numpy.empty(10, dtype=([('segment', '<i8'), ('material', '<i8'), ('rxN', '<i8')])) I know I can create a mask such as: A[A['segment'] == 42] = ... Is there a way to create a mask on multiple columns?...
How to mask numpy structured array on multiple columns?
I have a numpy structured array with a dtype such as: A = numpy.empty(10, dtype=([('segment', '<i8'), ('material', '<i8'), ('rxN', '<i8')])) I know I can create a mask such as: A[A['segment'] == 42] = ... Is there a way to create a mask on multiple columns? For example (I know this doesn't work, but I wish it did): A...
[ "You can use the & operator instead of and:\nA[(A['segment'] == 42) & (A['material'] == 5)]\n\nNote that extra parantheses are required.\n" ]
[ 12 ]
[]
[]
[ "mask", "masked_array", "numpy", "python" ]
stackoverflow_0006792395_mask_masked_array_numpy_python.txt
Q: character classification of strings in python def isLower(ch): return ch in string.lowercase def isLower(ch): return 'a' <= ch <= 'z' def isLower(ch): return string.find(string.lowercase, ch) != -1 Which version of isLower you think will be fastest? What are the other reasons besides speed to prefer...
character classification of strings in python
def isLower(ch): return ch in string.lowercase def isLower(ch): return 'a' <= ch <= 'z' def isLower(ch): return string.find(string.lowercase, ch) != -1 Which version of isLower you think will be fastest? What are the other reasons besides speed to prefer one or the other?
[ "str (and unicode) already has a islower method, which also works for multi-character strings. The unicode version also handles unicode characters correctly, unlike your attempts which assume ASCII (a capital sin for quite a few applications, and for all others, there is zero reason to impose this restriction as a ...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0006792606_python.txt
Q: multiprocessing | catching an exiting interpreter I'm working on an evolutionary computing problem, which I'm implementing with the excellent ECSPY module. The fitness value I'm using is derived from a pretty complex dynamics simulation. Thing is that I do not like the approach of making my simulation bomb-proof;...
multiprocessing | catching an exiting interpreter
I'm working on an evolutionary computing problem, which I'm implementing with the excellent ECSPY module. The fitness value I'm using is derived from a pretty complex dynamics simulation. Thing is that I do not like the approach of making my simulation bomb-proof; its pretty useless since the evolutionary process coul...
[ "Use subprocess to \"wrap\" a Python interpreter inside a Python script.\n\nStart a Python interpreter that runs your thing.\nStart a clock.\nWait until the clock runs out or the child process crashes. \n\nThe easy, lazy way to do this is to poll the subprocess periodically to see if it's dead yet. Yes, it's \"bu...
[ 3 ]
[]
[]
[ "evolutionary_algorithm", "multiprocessing", "python", "segmentation_fault" ]
stackoverflow_0006791596_evolutionary_algorithm_multiprocessing_python_segmentation_fault.txt
Q: How to create an Elixir class that has a ManyToMany relationship with itself I'm having trouble thinking this through, but basically I want to create an Elixir class called Assets which can have many Assets. So, it could look something like this (but this doesn't work, obviously): class Asset(Entity): has_fie...
How to create an Elixir class that has a ManyToMany relationship with itself
I'm having trouble thinking this through, but basically I want to create an Elixir class called Assets which can have many Assets. So, it could look something like this (but this doesn't work, obviously): class Asset(Entity): has_field('Name', Unicode) has_many('Assets', of_kind='Asset', inverse='Assets') So,...
[ "I'm not savvy in Elixir but this is how you can do it using SQLAlchemy declarative. Hopefully the Elixir definition will be similar enough that this help you.\nfrom sqlalchemy.ext.declarative import declarative_base\nBase = declarative_base()\n\nclass Employee(Base):\n __tablename__ = 'employee'\n id = Column(I...
[ 2, 1 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0006782810_python_python_elixir_sqlalchemy.txt
Q: How to limit import that may throw I have a class that will normally run under Windows and uses the win32com module. I also have a mock version of this class, both for testing and for demo purposes, which imports from the original, and should be able to run anywhere. So, it's like this, in two files: import win3...
How to limit import that may throw
I have a class that will normally run under Windows and uses the win32com module. I also have a mock version of this class, both for testing and for demo purposes, which imports from the original, and should be able to run anywhere. So, it's like this, in two files: import win32com.client class basic(): def local...
[ "\nnest the import and the def's inside a try block,\n\nThis is the standard approach that most people use.\nDo this outside any class definitions. At the very top level with your ordinary imports. Once only.\nUse the two functions within any class definition which occurs after this in the module.\ntry:\n impo...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006791920_python.txt
Q: Regex Simple Multiline Question pattern = '^([R][uU][nN])(.*)\((.*)\).' Essentially what I am trying to do with this is find procedure calls in the data I have in the form: RUN proc-name-can-be-anything (input parameters, input, output). can also be: RUN proc-name-long ( in...
Regex Simple Multiline Question
pattern = '^([R][uU][nN])(.*)\((.*)\).' Essentially what I am trying to do with this is find procedure calls in the data I have in the form: RUN proc-name-can-be-anything (input parameters, input, output). can also be: RUN proc-name-long ( input parameter, ot...
[ "http://docs.python.org/library/re.html#re.S\nhttp://docs.python.org/library/re.html#re.DOTALL\n\nMake the '.' special character match any character at all, including a newline\n\nAnd you can include this in your regex by prepending the pattern string with '(?s)'\nAlso, don't forget that you might want to use the r...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006792549_python_regex.txt
Q: What is the best way of describing day of week? I planning my inaugural data load into GAE and really want to get my ducks in a row. The language I am using is Python. My question is about the storing of storing read only temporal data in app engine. I have a spreadsheet with ~50k rows times 30 columns. It is hi...
What is the best way of describing day of week?
I planning my inaugural data load into GAE and really want to get my ducks in a row. The language I am using is Python. My question is about the storing of storing read only temporal data in app engine. I have a spreadsheet with ~50k rows times 30 columns. It is historic data and the table will be read-only. I envisa...
[ "If you plan to query based on day-of-week - that is, you need to select several Fridays, but not the neighbouring days - you should absolutely break this out into a separate property, as it'll make it possible to do efficient queries for it.\nTo do the query 'Fridays in July', as you suggest, you've got several op...
[ 3, 1, 1, 1 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0006763623_datetime_google_app_engine_python.txt
Q: Detecting mulitple cycles in a cyclic directed graph I have a directed cyclic graph with more than one cycle in it and I need a way to detect (and list) each cycle present in the digraph. The graph can be seen here: http://img412.imageshack.us/img412/3327/schematic.gif This is a dummy graph put together for the sa...
Detecting mulitple cycles in a cyclic directed graph
I have a directed cyclic graph with more than one cycle in it and I need a way to detect (and list) each cycle present in the digraph. The graph can be seen here: http://img412.imageshack.us/img412/3327/schematic.gif This is a dummy graph put together for the sake of debugging my python script. It contains the cycles: ...
[ "You didn't really specify how you represent the Directed graph, but you can have a look at Neopythonic:Detecting Cycles in directed graph.\n", "AFAIK, python-graph only finds one cycle, not all posible cycles. See:\nhttp://groups.google.com/group/python-graph/browse_thread/thread/9170926f1bdd097b\nThis other art...
[ 2, 1, 0 ]
[]
[]
[ "cycle", "directed_graph", "graph_theory", "python" ]
stackoverflow_0003349508_cycle_directed_graph_graph_theory_python.txt
Q: Auto Increment on Composite Primary Key - Sqlite3 + Python I have a code like this c.execute('CREATE TABLE IF NOT EXISTS base (ID INTEGER NOT NULL, col2 TEXT NOT NULL, col3 INTEGER, PRIMARY KEY(ID, col2))') This code gives me an sqlite3.IntegrityError exception even though I am very sure that I am writing the rec...
Auto Increment on Composite Primary Key - Sqlite3 + Python
I have a code like this c.execute('CREATE TABLE IF NOT EXISTS base (ID INTEGER NOT NULL, col2 TEXT NOT NULL, col3 INTEGER, PRIMARY KEY(ID, col2))') This code gives me an sqlite3.IntegrityError exception even though I am very sure that I am writing the record for the first time. So, I tried c.execute('CREATE TABLE IF N...
[ "In sqlite, you only get autoincrement behavior when only one integer column is the primary key. composite keys prevent autoincrement from taking effect.\nYou can get a similar result by defining id as the only primary key, but then adding an additional unique constraint on id, col3. \nIf that's still not quite w...
[ 13 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006793205_python_sqlite.txt
Q: How do you change a list of integers and strings into a list of integers and floats in python? I have a long list with a bunch of lists: [0, ['0.2000', '0.2000', '3.0000', '0.5000']] How do I make the '...' floats and keep the integers (0) integers? I've tried numpy, but it doesn't work for me numpy.array(lis...
How do you change a list of integers and strings into a list of integers and floats in python?
I have a long list with a bunch of lists: [0, ['0.2000', '0.2000', '3.0000', '0.5000']] How do I make the '...' floats and keep the integers (0) integers? I've tried numpy, but it doesn't work for me numpy.array(list, numpy.float) I don't really mind if the integers are also floats.
[ "I'd do something like this:\nnewlist = [[element[0], [float(e) for e in element[1]] for element in oldlist]\n\nelement[0] is the integer that's left as-is, element[1] is the list of strings that are converted to floats in the inner list comprehension.\n", "I need to see more data to know for sure if this fits, b...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0006792692_list_python_string.txt
Q: escaping single quotes in python mysqldb It seems like a typical issue in programming, but i didn't find nothing usefull in google. This is the code: file=open('list.txt','r') for line in file: cursor.execute("CREATE TABLE IF NOT EXISTS \ %s(id INT(2) NOT NULL PRIMARY KEY AUTO_INCREMENT, \ ...
escaping single quotes in python mysqldb
It seems like a typical issue in programming, but i didn't find nothing usefull in google. This is the code: file=open('list.txt','r') for line in file: cursor.execute("CREATE TABLE IF NOT EXISTS \ %s(id INT(2) NOT NULL PRIMARY KEY AUTO_INCREMENT, \ entry TEXT NOT NULL)" % line) file.cl...
[ "afaik (see MySQL 5.0 Reference here) you aren't allowed to have single quotes in a table name:\n\nPermitted characters in unquoted identifiers:\nASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)\nExtended: U+0080 .. U+FFFF\n\n\n", "I'm not sure why you're doing that and I think I shoul...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0006792952_mysql_mysql_python_python.txt
Q: Appending a list to itself in Python I want to attach a list to itself and I thought this would work: x = [1,2] y = x.extend(x) print y I wanted to get back [1,2,1,2] but all I get back is the builtin None. What am I doing wrong? I'm using Python v2.6 A: x.extend(x) does not return a new copy, it modifies the l...
Appending a list to itself in Python
I want to attach a list to itself and I thought this would work: x = [1,2] y = x.extend(x) print y I wanted to get back [1,2,1,2] but all I get back is the builtin None. What am I doing wrong? I'm using Python v2.6
[ "x.extend(x) does not return a new copy, it modifies the list itself.\nJust print x instead.\nYou can also go with x + x\n", "x.extend(x) modifies x in-place.\nIf you want a new, different list, use y = x + x.\n", "or just:\nx = [1,2]\ny = x * 2\nprint y\n\n", "x.extend(x) will extend x inplace.\n>>> print x\...
[ 11, 2, 1, 0, 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0006793545_append_list_python.txt
Q: Gunicorn Internal Server Errors I have a Gunicorn server running a Django application which has a tendency to crash quite frequently. Unfortunately when it crashes all the Gunicorn workers go down simultaneously and silently bypass Django's and django-sentry's logging. All the workers return "Internal Server Error...
Gunicorn Internal Server Errors
I have a Gunicorn server running a Django application which has a tendency to crash quite frequently. Unfortunately when it crashes all the Gunicorn workers go down simultaneously and silently bypass Django's and django-sentry's logging. All the workers return "Internal Server Error" but the arbiter does not crash so s...
[ "I highly recommend using zc.buildout. Here is an example using plugin Superlance for supervisord with buildout:\n[supervisor]\nrecipe = collective.recipe.supervisor\nplugins =\n superlance\n...\nprograms =\n 10 zeo ${zeo:location}/bin/runzeo ${zeo:location}\n 20 instance1 ${instance1:location}/bin/runzop...
[ 1 ]
[]
[]
[ "deployment", "django", "gunicorn", "python" ]
stackoverflow_0006790156_deployment_django_gunicorn_python.txt
Q: Protein structure visualization I've been asked to work on Protein structure visualization, something like RasMol where a user will be opening a pdb file to get the protein structure. How I can generate protein structure from the pdb file? I would like to code in Python and to visualize the structure should I be u...
Protein structure visualization
I've been asked to work on Protein structure visualization, something like RasMol where a user will be opening a pdb file to get the protein structure. How I can generate protein structure from the pdb file? I would like to code in Python and to visualize the structure should I be using OpenGL or VTK? are there any oth...
[ "You should try pymol that has a python interface.\nHere you have a beginners tutorial of how to script pymol to interact with the views\nAs a student you can get pymol with no charge from the pymols site. In addition, Gohlke provides installers for 32 and 64-bit windows and python 2.6-2.7.\n", "I think Pymol is ...
[ 6, 3, 1 ]
[]
[]
[ "bioinformatics", "opengl", "protein_database", "python", "vtk" ]
stackoverflow_0006793029_bioinformatics_opengl_protein_database_python_vtk.txt
Q: Is "import"-ing data pythonic? I have a python script that, in it's "initialize" runmode, accesses multiple files on my system and assembles what it thinks is the correct data. This data needs to be reviewed by a user before setting the script to run in "final" mode, when the data is actually used. Right now I'm w...
Is "import"-ing data pythonic?
I have a python script that, in it's "initialize" runmode, accesses multiple files on my system and assembles what it thinks is the correct data. This data needs to be reviewed by a user before setting the script to run in "final" mode, when the data is actually used. Right now I'm writing out the data to be reviewed i...
[ "This is a fine thing to do with a module. The thing you want to avoid is executing code that does too much, or has side-effects, at import time, and this doesn't do that.\n", "I think you should put your data in text files (JSON, CSV, whatever is appropriate) and then just have your script read it in. In genera...
[ 6, 3, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006794241_import_python.txt
Q: Python, doing conditional imports the right way Right now I have a class called A. I have some code like this.. from my.package.location.A import A ... foo = A.doSomething(bar) This is great. But now I have a new version of A called A, but in a different package, but I only want to use this other A in a certain...
Python, doing conditional imports the right way
Right now I have a class called A. I have some code like this.. from my.package.location.A import A ... foo = A.doSomething(bar) This is great. But now I have a new version of A called A, but in a different package, but I only want to use this other A in a certain scenario. So I can do something like this: if(OldVe...
[ "Put your lines into a_finder.py:\nif OldVersion:\n from my.package.location.A import A\nelse:\n from new.package.location.A import A\n\nThen in your product code:\nfrom a_finder import A\n\nand you will get the proper A.\n", "You could do something like this:\nAlwaysRightA.py\nimport sys\nif(OldVersion):\n...
[ 18, 2, 1 ]
[ "from my.package.location.A import A as old\nfrom new.package.location.A import A as new \n\nsomthing like that?\nold.someFunc()\nnew.someFunc()\n\ni did't get the point of the question.\n" ]
[ -1 ]
[ "conditional", "factory_pattern", "import", "python" ]
stackoverflow_0006793748_conditional_factory_pattern_import_python.txt
Q: JSON vs. Pickle security I recently came across the security problems of the Python pickle and cPickle modules. Obviously, there are no real security measures implemented in pickle unless you overwrite the find_class method as a basic modification to get a bit more security. But I often heard that JSON is more sec...
JSON vs. Pickle security
I recently came across the security problems of the Python pickle and cPickle modules. Obviously, there are no real security measures implemented in pickle unless you overwrite the find_class method as a basic modification to get a bit more security. But I often heard that JSON is more secure. Can anyone elaborate a bi...
[ "json is more secure because it's fundamentally more limited. The only python types that a json document can encode are unicode, int, float, NoneType, bool, list and dict. these are marshaled/unmarshalled in a basically trivial fashion that isn't vulnerable to code injection attacks.\n", "Pickle's problem is th...
[ 17, 9 ]
[]
[]
[ "json", "pickle", "python" ]
stackoverflow_0006794454_json_pickle_python.txt
Q: Converting untagged corpora to tagged (NLTK) I have a plaintext corpora, that I want to tag and save, so I can use it further. What's the best way to do this? I already have my tagger made, but I can't figure out a way to change the corpora that isn't messy A: Take a look at other tagged corpora, like brown, fo...
Converting untagged corpora to tagged (NLTK)
I have a plaintext corpora, that I want to tag and save, so I can use it further. What's the best way to do this? I already have my tagger made, but I can't figure out a way to change the corpora that isn't messy
[ "Take a look at other tagged corpora, like brown, for output examples. This will give you an idea of what a tagged corpus should look like. Next, load your corpus (with the PlaintextCorpusReader) and iterate over the sentences, tagging each sentence. Then write each tagged sentence to a file by making a string from...
[ 1, 0 ]
[]
[]
[ "nltk", "python", "stop_words" ]
stackoverflow_0006784748_nltk_python_stop_words.txt
Q: Python: how to dynamically set function closure environment I want to declare a function dynamically and I want to wrap any access to global variables OR alternatively define which variables are free and wrap any access to free variables. I'm playing around with code like this: class D: def __init__(self): ...
Python: how to dynamically set function closure environment
I want to declare a function dynamically and I want to wrap any access to global variables OR alternatively define which variables are free and wrap any access to free variables. I'm playing around with code like this: class D: def __init__(self): self.d = {} def __getitem__(self, k): print...
[ "What you're looking for is object proxying.\nHere is a recipe for an object proxy which supports pre- and post- call hooks: \nhttp://code.activestate.com/recipes/366254-generic-proxy-object-with-beforeafter-method-hooks/\nCreate a subclass that doesn't actually load the object until the first time the _pre hook is...
[ 2, 1 ]
[]
[]
[ "compilation", "dynamic_execution", "eval", "global_variables", "python" ]
stackoverflow_0006792526_compilation_dynamic_execution_eval_global_variables_python.txt
Q: How to convert decimal string in python to a number? Possible Duplicate: Python - Parse String to Float or Int How can I convert '1.03' (string) to a number in Python, preferably a decimal ? A: Just use float() >>> float('1.03') 1.03 If you need an actual Decimal type, use the decimal module: >>> from decima...
How to convert decimal string in python to a number?
Possible Duplicate: Python - Parse String to Float or Int How can I convert '1.03' (string) to a number in Python, preferably a decimal ?
[ "Just use float()\n>>> float('1.03')\n1.03\n\nIf you need an actual Decimal type, use the decimal module:\n>>> from decimal import *\n>>> Decimal('1.03')\nDecimal('1.03')\n\nIn general, using floats will be easier for you, but you pay for that with the inexact precision that comes with floats.\n", "float, int, an...
[ 28, 6 ]
[]
[]
[ "python" ]
stackoverflow_0006794779_python.txt
Q: Twisted > How to read a TCP message longer than TCP frame-length e.g. 1380 bytes from a window TCP client I am writing a twisted server to read TCP messages up to 64KB. What I discovered was that mt datareciever was called by the linereciever class every 1380 bytes, which turned out to be the Windows client's TCP ...
Twisted > How to read a TCP message longer than TCP frame-length e.g. 1380 bytes from a window TCP client
I am writing a twisted server to read TCP messages up to 64KB. What I discovered was that mt datareciever was called by the linereciever class every 1380 bytes, which turned out to be the Windows client's TCP frame size. Is there a way to get around this without having to loop through these 1380 byte blocks? from twist...
[ "You asked this question on the python_forum, I answered you there. You want to be using LineReciever, and you want to set MAX_LENGTH to a higher number.\n", "TCP sends streams of data, not messages. The intermediary network may break your streams up into arbitrarily small chunks for transport. If you have cont...
[ 1, 1 ]
[]
[]
[ "networking", "python", "tcp", "twisted" ]
stackoverflow_0006787547_networking_python_tcp_twisted.txt
Q: Variable assignment and modification (in python) When I ran this script (Python v2.6): a = [1,2] b = a a.append(3) print a >>>> [1,2,3] print b >>>> [1,2,3] I expected print b to output [1,2]. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How? ...
Variable assignment and modification (in python)
When I ran this script (Python v2.6): a = [1,2] b = a a.append(3) print a >>>> [1,2,3] print b >>>> [1,2,3] I expected print b to output [1,2]. Why did b get changed when all I did was change a? Is b permanently tied to a? If so, can I make them independent? How?
[ "Memory management in Python involves a private heap memory location containing all Python objects and data structures.\nPython's runtime only deals in references to objects (which all live in the heap): what goes on Python's stack are always references to values that live elsewhere.\n>>> a = [1, 2]\n\n\n>>> b = a\...
[ 64, 13, 4, 4, 3, 3 ]
[]
[]
[ "list", "python", "variables" ]
stackoverflow_0006793872_list_python_variables.txt
Q: Python function "remembering" earlier argument (**kwargs) I have some objects that have a dictionary of attributes, obj.attrs. The constructor for these objects accepts a dict and/or **kwargs, for convenience. It looks a little like this: class Thing: def __init__(self, attrs={}, **kwargs): for arg in ...
Python function "remembering" earlier argument (**kwargs)
I have some objects that have a dictionary of attributes, obj.attrs. The constructor for these objects accepts a dict and/or **kwargs, for convenience. It looks a little like this: class Thing: def __init__(self, attrs={}, **kwargs): for arg in kwargs: attrs[arg] = kwargs[arg] self.attrs...
[ "The problem with using default arguments is that only one instance of them actually exists. When you say attrs={} in your init method definition, that single default {} instance is the default for every call to that method (it doesn't make a new default empty dict every time, it uses the same one).\nThe problem i...
[ 13, 2, 2, 1, 1 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0006794285_keyword_argument_python.txt
Q: Large TXT file Parsing Problem in python Been trying to figure this one out all day. I have a large text file (546 MB) that I am trying to parse in python looking to pull out the text between the open tag and the close tag and I keep getting memory problems. With the help of good folks on this board this is what...
Large TXT file Parsing Problem in python
Been trying to figure this one out all day. I have a large text file (546 MB) that I am trying to parse in python looking to pull out the text between the open tag and the close tag and I keep getting memory problems. With the help of good folks on this board this is what I have so far. answer = '' output_file = open...
[ "\nYour logic is wrong because .find() returns -1 if the string is not found, and -1 is a true-ish value, so your code will think every line has <A> in it.\nYou don't need to make a new substring to find the '</W>', because .find() also has an optional start argument.\nNeither of these explain why you are running o...
[ 4, 2, 1 ]
[]
[]
[ "full_text_search", "python", "text" ]
stackoverflow_0006795027_full_text_search_python_text.txt
Q: Number Guesser Program Malfunction Possible Duplicate: Learning Python: If condition executing all the time This Python code is for guessing a number from 1 to 100. There is nothing wrong with the 'guesser()' function, which I know because my program also has a "manual mode" that works perfectly. For some reason...
Number Guesser Program Malfunction
Possible Duplicate: Learning Python: If condition executing all the time This Python code is for guessing a number from 1 to 100. There is nothing wrong with the 'guesser()' function, which I know because my program also has a "manual mode" that works perfectly. For some reason, it always assigns the 'guesss' value ...
[ "You should use int(raw_input()) instead of raw_input in order to retain the guess as an integer. raw_input() alone returns a string, and so comparisons will not hold. \nSee these previously answered question, and this exact question as yours.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0006795255_python.txt
Q: Python, check type of object after circular import Here are two files, foo.py and bar.py bar.py has... from foo import * ...at the top. bar.py uses types defined n foo. When importing bar.py from foo I am having trouble determining the types of objects. Looking at the example below why do the calls to isinstance...
Python, check type of object after circular import
Here are two files, foo.py and bar.py bar.py has... from foo import * ...at the top. bar.py uses types defined n foo. When importing bar.py from foo I am having trouble determining the types of objects. Looking at the example below why do the calls to isinstance return False? How can I check if these types are the sa...
[ "With:\nif __name__ == '__main__':\n import sys\n main('bar.py')\n sys.exit(0)\n\nI got :\nSpam object 'hi'\nSpam object 'there'\nEggs object (1, 2, 3)\n\nMove the main code and the main function to adifferent file and import foo and will work\n#-- main.py --\n\nimport foo\n\ndef main(fname):\n if not f...
[ 1, 1 ]
[]
[]
[ "circular_dependency", "import", "python" ]
stackoverflow_0006794960_circular_dependency_import_python.txt
Q: Python Tkinter: Draw arrows within Label I want to draw arrows (that change size dynamically) within a Label or any other widget. I have these arranged as a grid. How can I do this? Would I need a Canvas? (not used yet ... currently just a grid of labels). I am using Python & Tkinter Gui library. A: It will not ...
Python Tkinter: Draw arrows within Label
I want to draw arrows (that change size dynamically) within a Label or any other widget. I have these arranged as a grid. How can I do this? Would I need a Canvas? (not used yet ... currently just a grid of labels). I am using Python & Tkinter Gui library.
[ "It will not be compatible on older systems, but you could use unicode: \"▲\", \"▼\", \"◀\" and \"▶\".\nTo change the size, you can just change the font size or do something like:\n-▶\n--▶\n---▶\n\n", "The easiest and probably only way to draw arrows in a label widget would be to use some font that provides label...
[ 2, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004830180_python_tkinter.txt
Q: Change printed text color in Idle? Is there a way to specify the color a text is printed within Idle for Python 3.2? I'm looking for something like: print("foo", "#fafafa") print("bar", "#4f4f4f") A: http://docs.python.org/library/idle.html#syntax-colors To change the color scheme, edit the [Colors] section in ...
Change printed text color in Idle?
Is there a way to specify the color a text is printed within Idle for Python 3.2? I'm looking for something like: print("foo", "#fafafa") print("bar", "#4f4f4f")
[ "http://docs.python.org/library/idle.html#syntax-colors\n\nTo change the color scheme, edit the [Colors] section in config.txt.\n\nEdit: As you've edited your question, here is an edited answer. See\nhttp://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/process-management.html\nfor how to use terminal escape ...
[ 2 ]
[]
[]
[ "python", "python_3.x", "python_idle" ]
stackoverflow_0006795330_python_python_3.x_python_idle.txt
Q: What would be the most pythonic way to make an attribute that can be used in a lambda? More specifically, I want to be able to support lambda: <some_or_other_setter>, but I want to keep the code clear and to a concise. I have to validate the value, so I need a setter of some kind. I need to use lambda because I ne...
What would be the most pythonic way to make an attribute that can be used in a lambda?
More specifically, I want to be able to support lambda: <some_or_other_setter>, but I want to keep the code clear and to a concise. I have to validate the value, so I need a setter of some kind. I need to use lambda because I need to pass callbacks to Tkinter events. I also need to be able to modify the value of the at...
[ "Use a closure to return a function to be used as a callback, and define each condition as a function (using lambda or def, your preference) instead of each setter as a function.\nclass Eggs(object):\n\n def __init__(self):\n self.spam = 'Monster'\n def spam_condition(string = None):\n r...
[ 2, 1, 0, 0 ]
[]
[]
[ "oop", "python", "tkinter" ]
stackoverflow_0006793958_oop_python_tkinter.txt
Q: Need help with a Python scraper I am trying to use urllib with python to make a scraper, I can download the images, but they are a thumbnail, 250x250 or less.(I am trying of 4chan, Because I like some of the picture threads) How can I get the full image? here is my code import urllib2, urllib from BeautifulSou...
Need help with a Python scraper
I am trying to use urllib with python to make a scraper, I can download the images, but they are a thumbnail, 250x250 or less.(I am trying of 4chan, Because I like some of the picture threads) How can I get the full image? here is my code import urllib2, urllib from BeautifulSoup import BeautifulSoup import re impo...
[ "Because you can click to see a larger link, the URL in the <a href=\"url\"> that is around the image tag points to the full image. \nSo just read the value of the href property, and download that instead of the src property of the image.\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "image", "python", "thumbnails", "urllib" ]
stackoverflow_0006795345_beautifulsoup_image_python_thumbnails_urllib.txt
Q: TypeError: expected a character buffer object I have the following code: import os import csv listing = os.listdir('/directory/my/files/are/in') os.chdir('/directory/my/files/are/in') for file in listing[1:]: r = csv.reader(open(file, 'rU')) for row in r: stuff = [str.split('\t', 1) for row in ...
TypeError: expected a character buffer object
I have the following code: import os import csv listing = os.listdir('/directory/my/files/are/in') os.chdir('/directory/my/files/are/in') for file in listing[1:]: r = csv.reader(open(file, 'rU')) for row in r: stuff = [str.split('\t', 1) for row in r] print stuff which returns TypeError: e...
[ "str.split('\\t', 1) is the equivalent of '\\t'.split(1), which tries to split the string '\\t' by the non-string 1, which fails. And it's not entirely clear what you expect this to do: you're iterating over r, and then in the body of that loop you are iterating over r again (in the list comprehension.) Did you ins...
[ 2, 1 ]
[]
[]
[ "csv", "error_handling", "python" ]
stackoverflow_0006795422_csv_error_handling_python.txt
Q: Creating a dict from list of key, value tuples while maintaining duplicate keys So I've got a comprehension to the effect of: dict((x.key, x.value) for x in y) The problem, of course, is that if there's multiple x.keys with the same value, they get collapsed with the last x.value with that particular x.key as the...
Creating a dict from list of key, value tuples while maintaining duplicate keys
So I've got a comprehension to the effect of: dict((x.key, x.value) for x in y) The problem, of course, is that if there's multiple x.keys with the same value, they get collapsed with the last x.value with that particular x.key as the only surviving member. I want to actually make the values of the resulting dict a li...
[ "You can add the elements one by one to a dictionary that contains empty lists by default:\nimport collections\n\nresult_dict = collections.defaultdict(list)\nfor x in y:\n result_dict[x.key].append(x.value)\n\nYou can also do something very similar without having to use the collections module:\nresult_dict = {}...
[ 28, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006795361_python.txt
Q: Why does my socket.makefile object block even after a close? If I use socket.makefile and then close the file object as well as the underlying socket, then subsequent calls to read will throw an exception, just as I'd want it to. For example, the following code works as I'd expect: import socket from time import ...
Why does my socket.makefile object block even after a close?
If I use socket.makefile and then close the file object as well as the underlying socket, then subsequent calls to read will throw an exception, just as I'd want it to. For example, the following code works as I'd expect: import socket from time import sleep from threading import Thread ADDR = ("localhost", 4321) de...
[ "In situations like this, I've had success using eventlet and nowadays, gevent is doing the same types of things:\n'monkey patching' the socket library to use non blocking I/O. Here's an example of what you could try:\n>>> from gevent import monkey; monkey.patch_socket()\n>>> import socket\n\nand see how that'd aff...
[ 4, 1 ]
[]
[]
[ "multithreading", "python", "sockets" ]
stackoverflow_0006795500_multithreading_python_sockets.txt
Q: Unit testing framework: Run tests in new processes I programmed a GUI application who use the Unit testing framework. The application shows all found unit tests in a tree-view. If you click on a unit-test name, the program will run this test and show the result. It works! But now I want that every test case runnin...
Unit testing framework: Run tests in new processes
I programmed a GUI application who use the Unit testing framework. The application shows all found unit tests in a tree-view. If you click on a unit-test name, the program will run this test and show the result. It works! But now I want that every test case running in a new process. I created a "Working Thread" (with t...
[ "Obviously, you're trying to \"pickle\" something that is not pickable (seems to be a wx object). Try to use as parameter only \"simple\" objects (ie without graphical object inside), and it should be working better.\nYou could also take a look to the python nose unitest library which allows you to run tests in mul...
[ 1, 0 ]
[ "Spawn a child process using fork. This will require some work from you, but will work.\nAs a note: the multiprocessnig module is implemented using fork.\n\nUpdate: After looking closely at your code it seems that the item viariable is not pickleable (is that a word?). I don't think you need it, as you could replac...
[ -1 ]
[ "multiprocessing", "python", "unit_testing" ]
stackoverflow_0006791350_multiprocessing_python_unit_testing.txt
Q: Check if given lines of code are complete and proper Python code Sorry for my English. This problem is complicated, and my English isn't thats good to describe everything clearly. Ok, I have this example code. This is only a small code, in real environment i operate on much larger code than that. 01: multi_line_st...
Check if given lines of code are complete and proper Python code
Sorry for my English. This problem is complicated, and my English isn't thats good to describe everything clearly. Ok, I have this example code. This is only a small code, in real environment i operate on much larger code than that. 01: multi_line_string = """Abc 02: Dfg 03: Hjk""" 04: # Comment 05: do_somethingA() 06:...
[ "I would suggest looking at pylint.\n", "\nGet the abstract syntax tree. http://docs.python.org/library/ast.html\nWalk the tree inserting \"previous statement\"/\"next statement\" links from each node to the previous statement node. And from the previous statement to the current statement.\nHow this will work w...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006795712_python.txt
Q: For Loop problem in Python I am very new to programming. I want to be able to run this program for both entries in my list but do not understand programming enough to get it right. Members of this site have helped me get this far, and the program works great for one set of tags. I want it to run so I can search mu...
For Loop problem in Python
I am very new to programming. I want to be able to run this program for both entries in my list but do not understand programming enough to get it right. Members of this site have helped me get this far, and the program works great for one set of tags. I want it to run so I can search multiple authors in one pass. The ...
[ "I think this is because you are not resetting start_position; variables in Python are scoped to their enclosing function or class or module, but not to their enclosing loop. So try adding this line:\nfor x in authorList:\n start_position = 0 # Add this\n while True:\n\n", "This will be a problem\n st...
[ 5, 2, 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0006796103_loops_python.txt
Q: How can you define a persistent variable in Django I have a Django project, and what I would like to do is be able to create a reference to a variable defined in urls.py that is kept for the duration of the process. I've tried an approach using global vars - but for whatever reason, the value of the variable in ur...
How can you define a persistent variable in Django
I have a Django project, and what I would like to do is be able to create a reference to a variable defined in urls.py that is kept for the duration of the process. I've tried an approach using global vars - but for whatever reason, the value of the variable in urls.py is the initial value - even if I change it somewhe...
[ "I agree with S.Lott's comment, your question is a little vague. I think you're trying to reference some variable defined in urls? You know you can import urls.py into any other python script as long as it's on your PYTHONPATH. Assuming you're talking about a Django view when you say a \"process\", you could im...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006795708_django_python.txt
Q: ImportError: No module named gasp is there any file i need to download in order to perform? im new to python gasp . im wondering do i need extra add-on module for python so it could work? like a module file or something. my code that i was just trying to see whether it works: from gasp import* begin_graphics(8...
ImportError: No module named gasp is there any file i need to download in order to perform?
im new to python gasp . im wondering do i need extra add-on module for python so it could work? like a module file or something. my code that i was just trying to see whether it works: from gasp import* begin_graphics(800,600,"My Game",color.YELLOW) end_graphics() and it gave me this error: Traceback (most recent...
[ "Please see http://dev.laptop.org/pub/gasp/downloads/ for what to get for your platform.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006796422_python.txt
Q: Parsing XML with minidom I'm struggling with minidom. I need to locate an entry in the dom, update the text it holds, and then save the file. So far, the only way I've successfully been able to do locate the particular element is through a very explicit, direct, hard-coded method: doc.childNodes[0].childNodes[3]....
Parsing XML with minidom
I'm struggling with minidom. I need to locate an entry in the dom, update the text it holds, and then save the file. So far, the only way I've successfully been able to do locate the particular element is through a very explicit, direct, hard-coded method: doc.childNodes[0].childNodes[3].childNodes[5].childNodes[11].c...
[ "minidom is not very powerful, most folks are using some variation of ElementTree these days. Python2.5 and later has it built in.\n>>> from xml.etree import ElementTree as etree\n>>> corpus = \"\"\"<typeBoxes>\n... <typeBox type=\"counter\">\n... <text fontSize=\"140\">123456</text>\n... <text...
[ 4, 0 ]
[]
[]
[ "minidom", "python", "xml", "xml_parsing" ]
stackoverflow_0006796227_minidom_python_xml_xml_parsing.txt
Q: Use of return in long if-elseif-else statements (Python) I am using Python for my example, but my question is referring to programmming languages in general. def some_function(eggs): if eggs == 1: do_something_1() elif eggs == 2: do_something_2() elif eggs == 3: do_something_3()...
Use of return in long if-elseif-else statements (Python)
I am using Python for my example, but my question is referring to programmming languages in general. def some_function(eggs): if eggs == 1: do_something_1() elif eggs == 2: do_something_2() elif eggs == 3: do_something_3() else: do_error() return do_something_...
[ "The main issue I see with your code is that the error case is hidden more than half way down the function body. It makes the code difficult to read. Since what you are doing is validating the arguments to the function, you should do that first.\nMy preference in the case of an invalid argument is to raise an appro...
[ 12, 8, 3, 2, 1 ]
[]
[]
[ "coding_style", "if_statement", "python", "refactoring" ]
stackoverflow_0006796523_coding_style_if_statement_python_refactoring.txt
Q: Python thread is not breaking from parrent thread Question: why is my DAL not running off on its own thread? I've got this program I've been working on that I implemented a simple file manager back end on. This is far from my first experience working with threads, but for some reason I just can't get this one wor...
Python thread is not breaking from parrent thread
Question: why is my DAL not running off on its own thread? I've got this program I've been working on that I implemented a simple file manager back end on. This is far from my first experience working with threads, but for some reason I just can't get this one working. I instantiate my DAL here: self.DAL = DAL(pat...
[ "You should call start, to run the run method in a separate thread. Otherwise run is called as any other method.\nFrom docs:\nOnce a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.\n" ]
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006796743_multithreading_python.txt
Q: pyparsing, Each, results name I'm trying to use pyparsing to build a little not-quite-sql parser (I don't have from clauses, I don't have any joins, etc). I've been basing my work today on the simpleSQL.py example script included with pyparsing. I'm trying to add the "GROUP BY" and "ORDER BY" clauses to the parser...
pyparsing, Each, results name
I'm trying to use pyparsing to build a little not-quite-sql parser (I don't have from clauses, I don't have any joins, etc). I've been basing my work today on the simpleSQL.py example script included with pyparsing. I'm trying to add the "GROUP BY" and "ORDER BY" clauses to the parser, but trying to match them no matte...
[ "Give this a shot:\nStmt << ( selectToken +\n columnNameList('columns') + \n Optional( CaselessKeyword('where') + whereExpression('where'), \"\" ) +\n Each( [ Optional( CaselessKeyword('group by') + columnNameList('group'), \"\" ).setDebug(),\n ...
[ 1 ]
[]
[]
[ "pyparsing", "python", "sql" ]
stackoverflow_0006795252_pyparsing_python_sql.txt
Q: getting two classes to interact I am having trouble getting two classes to interact. Here is the code for the first class where i am importing file youtest.py: from youtest import MyTest class RunIt(object): def __init__(self): self.__class__ = MyTest r = RunIt() r.iffit() I am trying to run class MyT...
getting two classes to interact
I am having trouble getting two classes to interact. Here is the code for the first class where i am importing file youtest.py: from youtest import MyTest class RunIt(object): def __init__(self): self.__class__ = MyTest r = RunIt() r.iffit() I am trying to run class MyTest through this class (code below): ...
[ "The lines starting from print \"What is your name?\" are not indented properly. In python the whitespace is significant.\n", "In Python, this isn't how to subclass.\nfrom youtest import MyTest \n\nclass RunIt(MyTest): pass\n\nr = RunIt()\nr.iffit()\n\nAlthough in this example r = MyTest() would work fine.\nYou...
[ 2, 0 ]
[]
[]
[ "call", "class", "interaction", "python", "return" ]
stackoverflow_0006796840_call_class_interaction_python_return.txt
Q: Python- Get Stock Information for a company for a range of dates Trying to get more than just the stock information at the current time period, and I can't figure out if Google Finance allows for retrieving information for more than just one date. For example, if I wanted to find out the Google Stock value over t...
Python- Get Stock Information for a company for a range of dates
Trying to get more than just the stock information at the current time period, and I can't figure out if Google Finance allows for retrieving information for more than just one date. For example, if I wanted to find out the Google Stock value over the last 30 days and return that data as a list... how would I go about...
[ "Here is a recipe to get a historical values from Google Finance:\nhttp://code.activestate.com/recipes/576495-get-a-stock-historical-value-from-google-finance/\nIt looks like it returns the data in .csv format.\nEdit: Here is your script modified to get the .csv. It works for me.\nimport urllib2\nimport csv\n\nclas...
[ 2, 1 ]
[]
[]
[ "finance", "javascript", "json", "python" ]
stackoverflow_0006796988_finance_javascript_json_python.txt
Q: Searching TXT files in Python I am a new programmer and we are working on a Graduate English project where we are trying to parse a gigantic dictionary text file (500 MB). The file is set up with html-like tags. I have 179 author tags eg. "[A>]Shakes.[/A]" for Shakespeare and what I need to do is find each occurre...
Searching TXT files in Python
I am a new programmer and we are working on a Graduate English project where we are trying to parse a gigantic dictionary text file (500 MB). The file is set up with html-like tags. I have 179 author tags eg. "[A>]Shakes.[/A]" for Shakespeare and what I need to do is find each occurrence of every tag and then write tha...
[ "After opening the file, iterate through the lines like this:\ninput_file = open('huge_file.txt', 'r')\nfor input_line in input_file:\n # process the line however you need - consider learning some basic regular expressions\n\nThis will allow you to easily process the file by reading it in line by line as needed r...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "search" ]
stackoverflow_0006790915_python_search.txt
Q: TCP server is closing connections I have this code class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): _data = self.request.recv(1024) Utils.log("Received from %s: %s" % (self.client_address, _data)) calling it with kamcon_server = ThreadedTCPServer((HOST, 301...
TCP server is closing connections
I have this code class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): _data = self.request.recv(1024) Utils.log("Received from %s: %s" % (self.client_address, _data)) calling it with kamcon_server = ThreadedTCPServer((HOST, 3011), ThreadedTCPRequestHandler) server_...
[ "Your handle() method is only calling recv() once per connection. If you want to handle multiple messages from the client, you need to loop. You should think about your protocol as well, so that you can handle request/response messages larger than 1024 bytes (e.g. parse _data and figure out if you have a complete...
[ 13, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005793252_python.txt
Q: Why doesnt Pythons += (plus equals) operator modify variables from inner functions? I would like to know details about why this doesn't work as expected: def outer(): mylist = [] def inner(): mylist += [1] inner() outer() Especially because mylist.__iadd__([1]) works fine. A: The problem i...
Why doesnt Pythons += (plus equals) operator modify variables from inner functions?
I would like to know details about why this doesn't work as expected: def outer(): mylist = [] def inner(): mylist += [1] inner() outer() Especially because mylist.__iadd__([1]) works fine.
[ "The problem is that when you assign to a variable name inside a function, Python assumes you're trying to create a new local variable that will mask a similarly-named variable in outer scope. Since += has to get the value of mylist before it can modify it, it complains, because the local version of mylist isn't ye...
[ 9, 6, 1, 1 ]
[]
[]
[ "list", "python", "scope" ]
stackoverflow_0006797164_list_python_scope.txt
Q: Checking for matches in a txt file before writing in Python I am working with a very large text file (500MB+) and the code I have is outputting perfectly but I am getting a lot of duplicates. What I am looking to do is check the output file to see if the output exists before it writes to the file. I am sure it is ...
Checking for matches in a txt file before writing in Python
I am working with a very large text file (500MB+) and the code I have is outputting perfectly but I am getting a lot of duplicates. What I am looking to do is check the output file to see if the output exists before it writes to the file. I am sure it is just one line in an if statement, but I do not know python well a...
[ "I suggest that you simply keep track of which author data you have already seen, and only write it if you haven't seen it before. You can use a dict to keep track.\nauthorList = ['Shakes.','Scott']\nalready_seen = {} # dict to keep track of what has been seen\n\nwith open('/Users/Adam/Desktop/Poetrylist.txt','w')...
[ 1, 0, 0, 0 ]
[]
[]
[ "if_statement", "io", "python", "text_files" ]
stackoverflow_0006797075_if_statement_io_python_text_files.txt
Q: Tuning of a Web handler regex routes configuration In a web handler routes configuration I have the following Regex: ('/post/(\w+)/.*', foo.app.WebHandlerFooClass) this regex matches these kind of urls: /post/HUIHUIGgS823SHUIH/this-is-the-slug /post/HUIHUIGgS823SHUIH/ passing the correct HUIHUIGgS823SHUIH Id pa...
Tuning of a Web handler regex routes configuration
In a web handler routes configuration I have the following Regex: ('/post/(\w+)/.*', foo.app.WebHandlerFooClass) this regex matches these kind of urls: /post/HUIHUIGgS823SHUIH/this-is-the-slug /post/HUIHUIGgS823SHUIH/ passing the correct HUIHUIGgS823SHUIH Id parameter to the web handler matched by the (\w+) group. H...
[ "'/post/(\\w+_-)(?:/([\\w-]+))?/?'\n\nThis matches the following.\n\n/post/HUIHUIGgS823SHUIH/this-is-the-slug\n/post/HUIHUIGgS823SHUIH/this-is-the-slug/\n/post/HUIHUIGgS823SHUIH/\n/post/HUIHUIGgS823SHUIH\n\nI think this is a better implementation because it captures only the pieces you want, e.g. the slug doesn't c...
[ 3, 1, 1, 1 ]
[]
[]
[ "google_app_engine", "python", "regex", "routing", "web_applications" ]
stackoverflow_0006788182_google_app_engine_python_regex_routing_web_applications.txt
Q: Getting the Parameter name of a Value in a URL request I have a Python App Engine web app class that I am accessing with the following POST url: http://localhost:8087/moderate?5649364211118945661=on How can I get the Parameter name - not the value of the 5649364211118945661parameter, but a list of all the paramete...
Getting the Parameter name of a Value in a URL request
I have a Python App Engine web app class that I am accessing with the following POST url: http://localhost:8087/moderate?5649364211118945661=on How can I get the Parameter name - not the value of the 5649364211118945661parameter, but a list of all the parameter names that contain the on value. For example, in the follo...
[ "Use urlparse, http://docs.python.org/library/urlparse.html.\nimport urlparse\nurl = urlparse.urlparse('http://localhost:8087/moderate?5649364211118945661=on&23984729386481734=on&456287432349725=on&6753847523429875=off')\nquery = urlparse.parse_qs(url.query)\nprint [key for key, value in query.iteritems() if value ...
[ 9 ]
[]
[]
[ "google_app_engine", "python", "url", "urlparse" ]
stackoverflow_0006797354_google_app_engine_python_url_urlparse.txt
Q: Defining Constants in Django I want to have some constants in a Django Projects. For example, let's say a constant called MIN_TIME_TEST. I would like to be able to access this constant in two places: from within my Python code, and from within any Templates. What's the best way to go about doing this? EDIT: To cla...
Defining Constants in Django
I want to have some constants in a Django Projects. For example, let's say a constant called MIN_TIME_TEST. I would like to be able to access this constant in two places: from within my Python code, and from within any Templates. What's the best way to go about doing this? EDIT: To clarify, I know about Template Contex...
[ "Both Luper and Vladimir are correct imho but you'll need both in order to complete your requirements.\n\nAlthough, the constants don't need to be in the settings.py, you could put them anywhere and import them from that place into your view/model/module code. I sometimes put them into the __init__.py if I don't c...
[ 19, 6, 3, 2, 2, 0, 0 ]
[]
[]
[ "constants", "django", "python" ]
stackoverflow_0004042407_constants_django_python.txt
Q: add an extra link to preview your object in a Django admin form In my django application we are enabling our client to customize their web page. In order to do that I created a model to generate the template and it is actually working fine. My problem is that I would like to add a preview link into the admin form....
add an extra link to preview your object in a Django admin form
In my django application we are enabling our client to customize their web page. In order to do that I created a model to generate the template and it is actually working fine. My problem is that I would like to add a preview link into the admin form. This way I could do "Save and continue editing" to save the template...
[ "You could just override the template for the change_form, or you could add a link to the object tools, which is a common place to put a \"preview\" link. In fact, Django admin puts the \"View on site\" preview link for models that have get_absolute_url defined in the same place.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006795204_django_django_admin_python.txt
Q: Basic python, def function and recall for a text-menu I've just started playing around with python and was looking for advice. The problem is with the MENU(), for some reason on the 7th line I get a syntax error $ MENU() Not sure what I'm doing wrong. def MENU(): print("Menu:") print(" 0. Menu") ...
Basic python, def function and recall for a text-menu
I've just started playing around with python and was looking for advice. The problem is with the MENU(), for some reason on the 7th line I get a syntax error $ MENU() Not sure what I'm doing wrong. def MENU(): print("Menu:") print(" 0. Menu") print(" 1. Random Number Generator") access = in...
[ "You missed the closing brackets in line 5:\naccess = int(input(\"Make a selection from the above list: \"))\n ^\n\n", "I have just had browse through your code, and while you probably have it figured out now I thought a few suggestions might help you get...
[ 4, 3 ]
[]
[]
[ "function", "menu", "python" ]
stackoverflow_0006797599_function_menu_python.txt
Q: Use selected explorer file or folder path as a variable in a python script for a contextual menu I'm writing a python script that takes a file one at a time or recursively through folders and moves them to a new location. The script takes one parameter (the current path of the file). I want to be able to use the...
Use selected explorer file or folder path as a variable in a python script for a contextual menu
I'm writing a python script that takes a file one at a time or recursively through folders and moves them to a new location. The script takes one parameter (the current path of the file). I want to be able to use the selected item in an explorer window as the variable. I am making a contextual menu through the regedi...
[ "If you put a shortcut to this script (written for Python 3) in the user's \"SendTo\" folder (%USERPROFILE%\\SendTo), it will pop up a directory dialog when selected from the right-click SendTo menu. The dialog works for network locations as well. When the script runs, the full path to the selected file/folder is i...
[ 3 ]
[]
[]
[ "contextmenu", "explorer", "python", "selecteditem", "windows" ]
stackoverflow_0006796778_contextmenu_explorer_python_selecteditem_windows.txt
Q: Displaying a single form field in django templates? I only want to create forms.ChoiceField(choices=CHOICES) field to create a simple select html item. Because this is all I want, I don't really want to create a new form class etc. So is there a way to render only one form field in django templates without crea...
Displaying a single form field in django templates?
I only want to create forms.ChoiceField(choices=CHOICES) field to create a simple select html item. Because this is all I want, I don't really want to create a new form class etc. So is there a way to render only one form field in django templates without creating/passing in a form? for example: def index(request, t...
[ "If you don't need an entire Django form class, I would recommend just passing the list of choices to the template and iterating over it to create the <option /> tags for the <select>. That's a lot easier than trying to render a form widget at the template level, imo.\n", "only one choices field? why not just wri...
[ 1, 0 ]
[]
[]
[ "django", "forms", "html", "python", "templates" ]
stackoverflow_0006797994_django_forms_html_python_templates.txt
Q: MySQLdb Best Practices I'm currently developing a Python script that does a few things with some data pulled from a MySQL database. To access this data, I'm using the module MySQLdb. This module follows the guidelines laid out in PEP 249, the Python DB API, and involves creating a connection object, and a subseque...
MySQLdb Best Practices
I'm currently developing a Python script that does a few things with some data pulled from a MySQL database. To access this data, I'm using the module MySQLdb. This module follows the guidelines laid out in PEP 249, the Python DB API, and involves creating a connection object, and a subsequent cursor object, which is u...
[ "the way I think about it, it's best to only keep a connection object open while you need it. It can be cumbersome at times to keep instantiating new connections, but generally speaking that is the better practice.\n", "a multithreaded application that uses database connections should probably use some sort of co...
[ 1, 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python", "resource_management" ]
stackoverflow_0006791573_mysql_mysql_python_python_resource_management.txt
Q: Upload file to NodeJS server every 30 minutes I'm trying to figure out the best way to upload a file to a NodeJS(any server I guess, but just being specific) every 30 mins. I was thinking about using perl or python to acheive this, or even NodeJS or a CGI script? Would it be best to just create a multi-part form? ...
Upload file to NodeJS server every 30 minutes
I'm trying to figure out the best way to upload a file to a NodeJS(any server I guess, but just being specific) every 30 mins. I was thinking about using perl or python to acheive this, or even NodeJS or a CGI script? Would it be best to just create a multi-part form? Trying to figure out the best practice. Thanks.
[ "If this isn't part of other program logic, a simple curl --upload-file <file> <url> would do the job. If not, like Dan Grossman commented, any language capable of opening a socket and write HTTP headers and body would work (all assuming your node.js server is speaking http).\n", "I might recommend crontab for a ...
[ 2, 1 ]
[]
[]
[ "file_upload", "node.js", "perl", "python" ]
stackoverflow_0006798305_file_upload_node.js_perl_python.txt
Q: Python Type Error when setting up pagination in Django Hi I am following the official documentation and setting up pagination for my website, my index template looks like this; {% for post in list_of_posts %} <div class="body"><a class="title" href="/post/{{post.id}}"><h2>{{ post.title }}</h2></a> <P>{{ post.body|...
Python Type Error when setting up pagination in Django
Hi I am following the official documentation and setting up pagination for my website, my index template looks like this; {% for post in list_of_posts %} <div class="body"><a class="title" href="/post/{{post.id}}"><h2>{{ post.title }}</h2></a> <P>{{ post.body|truncatewords:50|wordwrap:110 }}</P> <h3>{{ post.date|da...
[ "Add TypeError in your first catch:\nexcept (PageNotAnInteger, TypeError):\n # ...\n\nBut you also could avoid this error if you will get page number like this:\npage = request.GET.get(\"page\", 1)\n\n", "The body of your view function isn't indented. Is that just how it came out on this page?\nAlso, it shoul...
[ 4, 0, 0 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0006789004_django_pagination_python.txt
Q: How to serve any file type with Python's BaseHTTPRequestHandler Consider the following example: import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.ends...
How to serve any file type with Python's BaseHTTPRequestHandler
Consider the following example: import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #se...
[ "Pass binary as a parameter to open(). This:\nf = open(curdir + sep + self.path, 'rb')\n\nInstead of this:\nf = open(curdir + sep + self.path)\n\nUNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the \"b\" will just be ignored so you're safe.\n", "Your line wo...
[ 10, 4, 3 ]
[]
[]
[ "httpserver", "python" ]
stackoverflow_0001094185_httpserver_python.txt
Q: xlwt writing excel file python problem So I have to two separate lists of data, wordlist and digitlist. And both sets have related sets of data so wordlist[1] is related to digitlist[1]. The data sets are shown below: seglist = ['aaa111', 'bbb222', 'ccc333'] wordlist = ['aaa', 'bbb', 'ccc'] digitlist = ['111', '22...
xlwt writing excel file python problem
So I have to two separate lists of data, wordlist and digitlist. And both sets have related sets of data so wordlist[1] is related to digitlist[1]. The data sets are shown below: seglist = ['aaa111', 'bbb222', 'ccc333'] wordlist = ['aaa', 'bbb', 'ccc'] digitlist = ['111', '222', '333'] I'm tryin to create a a new shee...
[ "The issue is that in your second loop you are continually hitting the same cells over and over again.\nThat is to say assuming your data looks something like this data:\nwordlist = [['cat','feline','kitty'], ['dog','canine','puppy']]\ndigitlist = [[3,7,9000],[17,8,4000]]\n\nWhen you hit wordlist, you write:\nSheet...
[ 1, 1 ]
[]
[]
[ "python", "xlwt" ]
stackoverflow_0006797070_python_xlwt.txt
Q: New to Python: getting NameError in variable NameError: name 'Brandon' is not defined I have a simple username/password program in Python 2.7.2 and keep getting this dumb error message. Here's my code: Username = input ("Please enter your username: ") if Username == brandon: password = input ("Correct! Please...
New to Python: getting NameError in variable
NameError: name 'Brandon' is not defined I have a simple username/password program in Python 2.7.2 and keep getting this dumb error message. Here's my code: Username = input ("Please enter your username: ") if Username == brandon: password = input ("Correct! Please enter password: ") if password == 42: ...
[ "You should use raw_input instead of input, because input expect that you're entering python code. More accurately though, your trouble is in Username == brandon. brandon would be a variable. 'brandon' would be a string for use in comparison.\n", "Use raw_input instead of input.\ninput is essentially running e...
[ 7, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006796513_python.txt
Q: Dynamically populating widgets, how to then access them? So, I've got a small project here that searches a path for files (*.db) and then makes a checkbox and a text control for those widgets. This part works just fine when I run the app: # Get a count of *.db from the filesystem numDB = scrubDB(os.getcwd...
Dynamically populating widgets, how to then access them?
So, I've got a small project here that searches a path for files (*.db) and then makes a checkbox and a text control for those widgets. This part works just fine when I run the app: # Get a count of *.db from the filesystem numDB = scrubDB(os.getcwd()) # Checkbox (enable, disable for launch) # textCtr...
[ "You will need to bind the events dynamically - \nlist_checkbox = []\nlist_textctrl = []\n\nfor db in numDB:\n check = wx.CheckBox(self, -1, db)\n sizer.Add(check, pos=(xIndex,0), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10)\n label = wx.StaticText(panel, label=\"\")\n sizer.Add(label, pos=(xIndex,...
[ 0, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0006757746_python_wxpython_wxwidgets.txt
Q: Please help, this loop isn't working as expected and I don't know how to use booleans in Python Am trying to write a piece of python code that calculate and print 1000 prime number from 2 however i only got 1999 as the last element in my result. I know there a lot of questions like this asked before but I wanna kn...
Please help, this loop isn't working as expected and I don't know how to use booleans in Python
Am trying to write a piece of python code that calculate and print 1000 prime number from 2 however i only got 1999 as the last element in my result. I know there a lot of questions like this asked before but I wanna know why is my code is not working. btw: how do i declare a boolean value in python? cant find a clue e...
[ "Your loop should read while len(mylist) < 1000:, and remove all references to count. Either that, or you should only increment count every time you add a prime to the list.\nAlso, you don't 'declare' values in Python. You simply assign a value of the desired type to a variable, and poof, you have a variable of tha...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006798605_python.txt
Q: Python, C/++,java... any api's for comparing audio signals? Does anyone know of a library for either python, c(++), or java , or even an external app, that I can use to check for a specific audio distortion in an mp3? My problem is this: I have a very robust Django app that automatically does podcasting for a ra...
Python, C/++,java... any api's for comparing audio signals?
Does anyone know of a library for either python, c(++), or java , or even an external app, that I can use to check for a specific audio distortion in an mp3? My problem is this: I have a very robust Django app that automatically does podcasting for a radio station for all the different shows, but about once a week th...
[ "I think all you will need to do is do an fft on the mp3 and you should see a really low frequency spike which corresponds to the big drops. I'm no dsp guru though so not sure that this will work, but its easy to try.\nYou can use the numpy library for python for this. http://numpy.scipy.org/\njust read in the mp3 ...
[ 4, 0 ]
[]
[]
[ "audio", "c", "c++", "java", "python" ]
stackoverflow_0005438188_audio_c_c++_java_python.txt
Q: Python includes files on Lion? Where have been includes files of python in lion ? Usually it was located at "/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6" but there is only one files in there : "pyconfig.h" Is it the same on your system ? Thanks. A: On OS X 10.7, the include files f...
Python includes files on Lion?
Where have been includes files of python in lion ? Usually it was located at "/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6" but there is only one files in there : "pyconfig.h" Is it the same on your system ? Thanks.
[ "On OS X 10.7, the include files for the Apple-supplied Pythons are linked into the locations within /System/Library/Frameworks when you install Xcode 4. You will find also find them in the /Developer/SDKs included with Xcode, for example:\n/Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks/Python.framework/...
[ 3, 1 ]
[]
[]
[ "macos", "osx_lion", "python" ]
stackoverflow_0006788090_macos_osx_lion_python.txt
Q: Using docutils.core.publish_string instead of publish_cmdline, `settings_overrides` argument carrying HTML-Specific Options takes no effect! Below is my code from docutils.core import publish_string from docutils.writers.html4css1 import Writer as HisWriter args = { 'stylesheet' : '/home/wonder/lab/css/note.c...
Using docutils.core.publish_string instead of publish_cmdline, `settings_overrides` argument carrying HTML-Specific Options takes no effect!
Below is my code from docutils.core import publish_string from docutils.writers.html4css1 import Writer as HisWriter args = { 'stylesheet' : '/home/wonder/lab/css/note.css', 'stylesheet-path' : None, } src = 'ccav' print publish_string(src, writer=HisWriter(), settings_overrides=args) I got the following err...
[ "from docutils.core import publish_string\nfrom docutils.writers.html4css1 import Writer as HisWriter\n\nsrc = 'ccav'\nargs = {\n 'stylesheet_path' : '/path/to/your/stylesheet'\n\n}\nprint publish_string(src, writer=HisWriter(), settings=None, settings_overrides=args)\n\nYou need to do settings = None and use st...
[ 3 ]
[]
[]
[ "docutils", "html", "python", "restructuredtext" ]
stackoverflow_0006798167_docutils_html_python_restructuredtext.txt
Q: need design suggestions for an efficient webcrawler that is going to parse 8M pages - Python I'm going to develop a little crawler that's going to fetch a lot of pages from the same website, all of the requests are a change in the ID number of the url. I need to save all of data I'll parse into a csv (nothing fanc...
need design suggestions for an efficient webcrawler that is going to parse 8M pages - Python
I'm going to develop a little crawler that's going to fetch a lot of pages from the same website, all of the requests are a change in the ID number of the url. I need to save all of data I'll parse into a csv (nothing fancy), at most, I will crawl about 6M-8M pages, most of them doesn't contain the data I want, I know ...
[ "I used httplib2 for this kind of thing because there are supposed to be memory leaks in the Python standard library routines. Also, httplib2 can be configured to keep a cache which might be useful if you have to restart and redo some pages.\nI only ran through 1.7 million pages plus about 200000 from another serve...
[ 3 ]
[]
[]
[ "html_parsing", "python", "web_crawler" ]
stackoverflow_0006751306_html_parsing_python_web_crawler.txt
Q: How to send key events to webkit.WebView() control? I created mini browser for touch panels. I used Python, GTK and WebKit. I want to create touch keyboard built-in that browser. How to send key events to webkit.WebView() control? My code: #!/usr/bin/python import webkit, gtk window = gtk.Window() browser = webkit...
How to send key events to webkit.WebView() control?
I created mini browser for touch panels. I used Python, GTK and WebKit. I want to create touch keyboard built-in that browser. How to send key events to webkit.WebView() control? My code: #!/usr/bin/python import webkit, gtk window = gtk.Window() browser = webkit.WebView() window.add(browser) window.show() browser.show...
[ "You can do it like this:\nevent = gtk.gdk.Event(gtk.gdk.KEY_PRESS)\nevent.keyval = gtk.keysyms.Return\nevent.time = 0\nbrowser.emit('key-press-event', event)\n\nfor example, to send an Enter key press.\n", "You will have to use javascript in the code, there is a good example of communicating with webkit on this ...
[ 2, 0 ]
[]
[]
[ "gtk", "keyboard", "python" ]
stackoverflow_0006796191_gtk_keyboard_python.txt
Q: Isolating pieces of code that segfault I have a function call that sometimes produces a segfault. Right now I isolate this code by putting it in a separate Python file and doing Popen('python snippet.py') inside of my main script. Is there a more elegant way of doing this on a Unix system? Update 7/24 I found the ...
Isolating pieces of code that segfault
I have a function call that sometimes produces a segfault. Right now I isolate this code by putting it in a separate Python file and doing Popen('python snippet.py') inside of my main script. Is there a more elegant way of doing this on a Unix system? Update 7/24 I found the following to be convenient if not os.fork():...
[]
[]
[ "Why not find it and fix it?\nstrace python yourapp.py yourargs and options >trace.out 2>&1\n\nThen, after it segfaults try tail -50 trace.out and you will see how it leads up to the segfault. Typically it is a pointer that is garbled and points to memory addresses that are not part of the process. It is quite poss...
[ -1 ]
[ "fonts", "python", "ubuntu" ]
stackoverflow_0006738159_fonts_python_ubuntu.txt
Q: How to stop Apache from freezing up when multiple requests are sent to django views that output Matplotlib images? I have a django site that servers matplotlib images generated from numbers stored in a mysql database. One of the views will display up to 5 images. The src value for the images do not link to static ...
How to stop Apache from freezing up when multiple requests are sent to django views that output Matplotlib images?
I have a django site that servers matplotlib images generated from numbers stored in a mysql database. One of the views will display up to 5 images. The src value for the images do not link to static files but instead to django views that will generate png images. The images can take up to 5 seconds to load. The same d...
[ "You could use a two stage process to generate these pages:\n\nOn the initial request, push the image generation tasks into a queuing system such as celery. Use a separate process to execute these tasks, and tune it to run as many as your system will cope with in parallel.\nOn the client side, use ajax to poll the ...
[ 0, 0 ]
[]
[]
[ "ajax", "apache", "django", "mysql", "python" ]
stackoverflow_0006798120_ajax_apache_django_mysql_python.txt
Q: How to create this nested python dictionary? This is the what-I-want ( warning: Python noob here, this might be an incorrect way of representing, but I hope you get what I want ) forms = { { 'id' : '1', 'form' : form_something, }, { 'id' : '4', 'fo...
How to create this nested python dictionary?
This is the what-I-want ( warning: Python noob here, this might be an incorrect way of representing, but I hope you get what I want ) forms = { { 'id' : '1', 'form' : form_something, }, { 'id' : '4', 'form' : form_something2, } } ...
[ "This will create a list of dictionaries:\nlinks = Links.objects.all()\nforms = []\nfor link in links:\n form = LinkForm(instance = link)\n forms.append({'id': link.id, 'form': form})\n\nIf you want to create a dictionary of dictionaries, you have to have keys:\nlinks = Links.objects.all()\nforms = {}\nfor li...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006799318_django_python.txt
Q: How to make the last gtk.TreeViewColumn resizeable? One can use gtk.TreeViewColumn.set_resizable(True) to make column manually resizeable... except the last column -- it always occupies the available space. While it's sensible in most cases, I use TreeView-in-a-ScrolledView, and I'd like to be able to shrink/expa...
How to make the last gtk.TreeViewColumn resizeable?
One can use gtk.TreeViewColumn.set_resizable(True) to make column manually resizeable... except the last column -- it always occupies the available space. While it's sensible in most cases, I use TreeView-in-a-ScrolledView, and I'd like to be able to shrink/expand the last column too. Currently I use the following klu...
[ "It would be easier to help if you would post a self-contained working example that we could play with! :)\nHowever - if I understand your question correctly (which I'm not 100% sure, to be honest) - it might be that you are thinking to the problem in the wrong terms: what you call \"resizing the last column\" is a...
[ 2 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0006799303_gtktreeview_pygtk_python.txt
Q: Are there any open-source references for the web2py remote-procedure-calls? Are there any open-source references for the web2py remote procedure calls (i.e. @service.run) to get information from and post it to a table in the database? A: @service.run is not very useful it is more for testing before you move on t...
Are there any open-source references for the web2py remote-procedure-calls?
Are there any open-source references for the web2py remote procedure calls (i.e. @service.run) to get information from and post it to a table in the database?
[ "@service.run is not very useful it is more for testing before you move on to xmlrpc or soap or jsonrpc than anything else. You should use a restful interface for what you asked. For example:\ndb.define_table('mytable,Field('name'))\n\n@request.restful()\ndef callme():\n def GET(id):\n return db.mytable(i...
[ 2 ]
[]
[]
[ "python", "rpc", "web2py" ]
stackoverflow_0006737999_python_rpc_web2py.txt
Q: SQLite database file size didn't shrink after dropping huge table I created a table in my database file which turned out to be way too huge (increased my database file's size from 2 GB to around 50GB). I just dropped it but the file size didn't go down. Any way to get the db file back to normal? I'm using sqlite3 ...
SQLite database file size didn't shrink after dropping huge table
I created a table in my database file which turned out to be way too huge (increased my database file's size from 2 GB to around 50GB). I just dropped it but the file size didn't go down. Any way to get the db file back to normal? I'm using sqlite3 from Python.
[ "Try vacuum.\n", "You can activate auto_vacuum so you don't need to bother with running vacuum moving forward.\n" ]
[ 9, 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006795444_python_sqlite.txt
Q: Spectral Clustering, Image Segmentation and Eigenvectors Based on the book Computer Vision a Modern Approach page 425, I attempted to use eigenvectors for image segmentation. http://dl.dropbox.com/u/1570604/tmp/comp-vis-modern-segment.pdf The author mentions that image pixel affinites can be captured in matrix A....
Spectral Clustering, Image Segmentation and Eigenvectors
Based on the book Computer Vision a Modern Approach page 425, I attempted to use eigenvectors for image segmentation. http://dl.dropbox.com/u/1570604/tmp/comp-vis-modern-segment.pdf The author mentions that image pixel affinites can be captured in matrix A. Then we can maximize w^T A w product where w's are weights. A...
[ "I've just tried the algorithm in Mathematica, it works fine on your image, so there must be a subtle bug in your code.\nThis part:\nV,D = np.linalg.eig(A)\nV = np.real(V)\nres = n_max(V,1) # take largest \nidx = res[0][1][0] \na = np.real(D[idx]) # look at corresp eigv\n\nlooks strange: all linear algebra packages...
[ 2 ]
[]
[]
[ "image_processing", "image_segmentation", "linear_algebra", "python" ]
stackoverflow_0006799105_image_processing_image_segmentation_linear_algebra_python.txt