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: Generating constructor documentation for class defined in C++ When developing a Python plug-in (in C++), how does one go about setting the documentation for __new__? In particular, given a new type defined by a PyTypeObject structure in the C++, how does one document the arguments which can be passed to the const...
Generating constructor documentation for class defined in C++
When developing a Python plug-in (in C++), how does one go about setting the documentation for __new__? In particular, given a new type defined by a PyTypeObject structure in the C++, how does one document the arguments which can be passed to the constructor.
[ "Constructor arguments are usually documented in the type docstring, i.e. via the tp_doc slot, so you can do help(type) (or type? in IPython) instead of help(type.__new__) or help(type.__init__).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007876250_python.txt
Q: SQLAlchemy 0.7 - maximum column length I am using SQLAlchemy maximum column length recipe from my previous question (SQLAlchemy - maximum column length). Since I upgraded to SQLAlchemy 0.7, the LengthValidator cannot be installed using the following expression: inst.impl.extensions.insert(0, LengthValidator(col.ty...
SQLAlchemy 0.7 - maximum column length
I am using SQLAlchemy maximum column length recipe from my previous question (SQLAlchemy - maximum column length). Since I upgraded to SQLAlchemy 0.7, the LengthValidator cannot be installed using the following expression: inst.impl.extensions.insert(0, LengthValidator(col.type.length)) The extension attribute is not ...
[ "Below is Ants' solution rewritten with event system of SQLAlchemy:\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import ColumnProperty\nfrom sqlalchemy import event\n\ndef check_string_length(cls, key, inst):\n prop = inst.prop\n # Only interested in simple columns, not relati...
[ 10, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0007846180_python_sqlalchemy.txt
Q: Attach validation to an existing Python list instance I have an existing list instance, which in live code has references throughout. When a list reference is passed into a certain function, I need to ensure that all items in that list are valid from that point onwards (validate all list items then attach validati...
Attach validation to an existing Python list instance
I have an existing list instance, which in live code has references throughout. When a list reference is passed into a certain function, I need to ensure that all items in that list are valid from that point onwards (validate all list items then attach validation for future changes). Creating a new class that overrides...
[ "No, there is not. Even if you could replace __class__ attribute, you shouldn't attempt to do that, it's confusing and likely to break in subtle ways. If you need to create a validating list, you need to create a new object and use that instead of the old one.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007876114_python.txt
Q: PyQt assigning button commands using multiple classes I am new to Python as well as to PyQt. I am having problems getting some of the button actions to work when I have multiple classes. For example, in my code I have the following: class main(QDialog): def __init__(self, parent=None, *args): QDialog._...
PyQt assigning button commands using multiple classes
I am new to Python as well as to PyQt. I am having problems getting some of the button actions to work when I have multiple classes. For example, in my code I have the following: class main(QDialog): def __init__(self, parent=None, *args): QDialog.__init__(self, parent, *args) self.setupUi(self) ...
[ "The reason why the button doesn't work is because Ui_Customer has been made a subclass of main (why?) and not initialized properly. If the base class is changed to object, the signal handler will work - although it will generate an AttributeError due to a typo in the dict lookup (I think you meant 'text_%d').\nRat...
[ 0 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0007871126_pyqt_python_qt.txt
Q: What is a better way to readlines from Python file? This is my python file:- TestCases-2 Input-5 Output-1,1,2,3,5 Input-7 Ouput-1,1,2,3,5,8,13 What I want is this:- A variable test_no = 2 (No. of testcases) A list testCaseInput = [5,7] A list testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]] I've tried doing it i...
What is a better way to readlines from Python file?
This is my python file:- TestCases-2 Input-5 Output-1,1,2,3,5 Input-7 Ouput-1,1,2,3,5,8,13 What I want is this:- A variable test_no = 2 (No. of testcases) A list testCaseInput = [5,7] A list testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]] I've tried doing it in this way: testInput = testCase.readline(...
[ "I'm not sure if I follow exactly what you're trying to do, but I guess I'd try something like this:\ntestCaseIn = [];\ntestCaseOut = [];\n\nfor line in testInput:\n if (line.startsWith(\"Input\")):\n testCaseIn.append(giveMeAList(line.split(\"-\")[1]));\n elif (line.startsWith(\"Output\")):\n t...
[ 2, 2, 1, 1 ]
[]
[]
[ "multiline", "parsing", "python" ]
stackoverflow_0007874643_multiline_parsing_python.txt
Q: how to EnsureVisible a newly added item on qlistwidget in python? when i added an item in a qlistwiget and reaches the bottom. A scroll bar appears, how can i ensurevisible an item that was newly added from the qlistwidget? Or how can i get the focus to the last index? A: QListWidget inherits from QAbstractItemV...
how to EnsureVisible a newly added item on qlistwidget in python?
when i added an item in a qlistwiget and reaches the bottom. A scroll bar appears, how can i ensurevisible an item that was newly added from the qlistwidget? Or how can i get the focus to the last index?
[ "QListWidget inherits from QAbstractItemView, which has the methods you are looking for:\n\nYou can use QAbstractItemView.scrollTo(ModelIndex index), using the index of your newly added item.\nAlternatively, since your item is always appended to the end of the list, just call QAbstractItemView.scrollToBottom().\n\n...
[ 4, 2 ]
[]
[]
[ "pyqt4", "python", "qlistwidget" ]
stackoverflow_0007876125_pyqt4_python_qlistwidget.txt
Q: How do I poll the subversion history/log remotely from python? I need to find the first committer of a branch without having to do a checkout of all the entire branches. From command line that is very easy to do: svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname I need to do this from...
How do I poll the subversion history/log remotely from python?
I need to find the first committer of a branch without having to do a checkout of all the entire branches. From command line that is very easy to do: svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname I need to do this from a python script, any idea how can I do that? I checked the python s...
[ "You could just use Python's subprocess module:\nfrom subprocess import Popen, PIPE\np = Popen('svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname',\n stdout=PIPE)\nstdout, stderr = p.communicate()\n\nThis way you can run any SVN command you want: just examine stdout (and perhaps...
[ 5, 0 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0007876680_python_svn.txt
Q: Minimum and maximum of the last 1000 values of the changing list I'm creating an iterative algorithm (Monte Carlo method). The algorithm returns a value on every iteration, creating a stream of values. I need to analyze these values and stop the algorithm when say 1000 returned values are withing some epsilon. I d...
Minimum and maximum of the last 1000 values of the changing list
I'm creating an iterative algorithm (Monte Carlo method). The algorithm returns a value on every iteration, creating a stream of values. I need to analyze these values and stop the algorithm when say 1000 returned values are withing some epsilon. I decided to implement it calculation the max and min values of the last ...
[ "If you are free / willing to change your definition of error, you might want to consider using the variance instead of (max-min)/min. \nYou can compute the variance incrementally.\nTrue, using this method, you are not deleting any values from your stream -- the variance will depend on all the values. But so what? ...
[ 7, 6, 4, 3, 1, 1 ]
[]
[]
[ "algorithm", "epsilon", "max", "min", "python" ]
stackoverflow_0007876453_algorithm_epsilon_max_min_python.txt
Q: Multiple imports in python How do people get around this issue: A controller (say controller.py) imports two models (say a_model.py and b_model.py): from app.model import a_model from app.model import b_model Now let's say that a_model wants to use a function in b_model (let's say it wants to get something from b...
Multiple imports in python
How do people get around this issue: A controller (say controller.py) imports two models (say a_model.py and b_model.py): from app.model import a_model from app.model import b_model Now let's say that a_model wants to use a function in b_model (let's say it wants to get something from b_model where an id of the record...
[ "There's no problem with importing a module from two different modules in Python. Maybe your particular design makes it a problem, but it's not something Python imposes.\nAnyhow, you could probably solve the problem by moving common stuff from a_model and b_model to some other module, i.e. model_common, and importi...
[ 6, 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007874191_google_app_engine_python.txt
Q: Mocking a function throughout a project I would like to mock a certain function in a utility module throughout my project, as part of a testing suite. I could of course patch and mock this function for each module using it, but there are a lot of these and it would be non-robust and tedious. Is there a way to patc...
Mocking a function throughout a project
I would like to mock a certain function in a utility module throughout my project, as part of a testing suite. I could of course patch and mock this function for each module using it, but there are a lot of these and it would be non-robust and tedious. Is there a way to patch\mock it throughout the project? If I patch ...
[ "Sure, just import module in your script, patch it, then import the other modules that use it and invoke whatever you need to test in them. Modules are imported only once in a session; additional import statements use the already-imported module. So the other modules that import the patched module will automaticall...
[ 0 ]
[]
[]
[ "mocking", "patch", "python" ]
stackoverflow_0007873400_mocking_patch_python.txt
Q: Crawling multiple starting urls with different depth I'm trying to get Scrapy 0.12 to change it's "maximum depth" setting for different url in the start_urls variable in the spider. If I understand correctly the documentation there's no way because the DEPTH_LIMIT setting is global for the entire framework and the...
Crawling multiple starting urls with different depth
I'm trying to get Scrapy 0.12 to change it's "maximum depth" setting for different url in the start_urls variable in the spider. If I understand correctly the documentation there's no way because the DEPTH_LIMIT setting is global for the entire framework and there's no notion of "requests originated from the initial on...
[ "Sorry, looks like i didn't understand you question correctly from the beginning. Correcting my answer:\nResponses have depth key in meta. You can check it and take appropriate action.\nclass MySpider(BaseSpider):\n\n def make_requests_from_url(self, url):\n return Request(url, dont_filter=True, meta={'st...
[ 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0007866115_python_scrapy.txt
Q: How Do I Fix this Return/Global Error? def subtract(num): string = str(num) a = string[0] b = string[1] c = string[2] large = max(a, b, c) small = min(a,b,c) summation = int(a) + int(b) + int(c) mid = summation - int(large) - int(small) mid2 = str(mid) ascend = large + mid2 ...
How Do I Fix this Return/Global Error?
def subtract(num): string = str(num) a = string[0] b = string[1] c = string[2] large = max(a, b, c) small = min(a,b,c) summation = int(a) + int(b) + int(c) mid = summation - int(large) - int(small) mid2 = str(mid) ascend = large + mid2 + small descend = small + mid2 + large ...
[ "In the call to print at the end of main you refer to a variable named value that has not been defined in main. Hence the error. Perhaps you meant to retain the value returned from the call to subtract:\nvalue = subtract(dummy)\nprint('The value ... is', value)\n\nI must admit to finding your code a little difficu...
[ 4, 0, 0 ]
[]
[]
[ "global", "python" ]
stackoverflow_0007877339_global_python.txt
Q: cx_Oracle - encoding query result to Raw EDIT: The following print shows my intended value. (both sys.stdout.encoding and sys.stdin.encoding are 'UTF-8'). Why is the variable value different than its print value? I need to get the raw value into a variable. >>username = 'Jo\xc3\xa3o' >>username.decode('utf-8').en...
cx_Oracle - encoding query result to Raw
EDIT: The following print shows my intended value. (both sys.stdout.encoding and sys.stdin.encoding are 'UTF-8'). Why is the variable value different than its print value? I need to get the raw value into a variable. >>username = 'Jo\xc3\xa3o' >>username.decode('utf-8').encode('latin-1') 'Jo\xe3o' >>print username.dec...
[ "You already have the proper 'João', methinks. The difference between >>> 'Jo\\xc3\\xa3o' and >>> print 'Jo\\xc3\\xa3o' is that the former calls repr on the object, while the latter calls str (or probably unicode, in your case). It's just how the string is represented.\nSome examples might make this more clear:\n>>...
[ 2 ]
[]
[]
[ "character_encoding", "cx_oracle", "nls_lang", "python" ]
stackoverflow_0007849145_character_encoding_cx_oracle_nls_lang_python.txt
Q: How to do automatic imagemaps for regions/borders in a map I'm searching for an automated way of generating imagemaps for world, country and region maps. Currently I have an imagemap of regions for one country which was generated manually using this tool. By clicking a region you are then presented with a sub-re...
How to do automatic imagemaps for regions/borders in a map
I'm searching for an automated way of generating imagemaps for world, country and region maps. Currently I have an imagemap of regions for one country which was generated manually using this tool. By clicking a region you are then presented with a sub-region map which was also manually generated. Clicking in the sub-...
[ "Not the perfect solution but what I was able to do so far:\n(Using @Lapple solution's, with the modifications below I was able to use the script provided)\nI've use the maps available here.\n1 - Open the map with inkscape,\n2 - File - Inkscape preferences - svg output and remove the option allow relative coordinat...
[ 0 ]
[]
[]
[ "imagemap", "java", "javascript", "maps", "python" ]
stackoverflow_0007674854_imagemap_java_javascript_maps_python.txt
Q: TypeError: ‘DoesNotExist’ object is not callable It's not always this code chunk but this is the most recent. It seems to be random, any thoughts? try: u = User.objects.get(email__iexact=useremail) except User.DoesNotExist: ... Throws this error, randomly. File "/srv/myapp/registration/models.py", line 23...
TypeError: ‘DoesNotExist’ object is not callable
It's not always this code chunk but this is the most recent. It seems to be random, any thoughts? try: u = User.objects.get(email__iexact=useremail) except User.DoesNotExist: ... Throws this error, randomly. File "/srv/myapp/registration/models.py", line 23, in get_or_create_user u = User.objects.get(email__...
[ "As Chris says in the comments above, your snippet is valid. Somewhere else in your code, you may be catching exceptions incorrectly.\nYou may have something like:\ntry:\n do_something()\nexcept User.MultipleObjectsReturned, User.DoesNotExist:\n pass\n\ninstead of:\ntry:\n do_something()\nexcept (User.Mult...
[ 43 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007877340_django_python.txt
Q: Flask-SQLAlchemy. Create several tables with all fields identical I'm using Flask with its SQLAlchemy extension. I need to define several model classes, which will create tables in MySQL database. The tables will only differ by name, all the field names/datatypes in them will be identical. How do I define the clas...
Flask-SQLAlchemy. Create several tables with all fields identical
I'm using Flask with its SQLAlchemy extension. I need to define several model classes, which will create tables in MySQL database. The tables will only differ by name, all the field names/datatypes in them will be identical. How do I define the classes for all those tables? I'm thinking of some inheritance, but I'm not...
[ "Just define all your columns in a mix-in class:\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nclass MyMixin(object):\n id = Column(Integer, primary_key=True)\n data = Column(String)\n\nclass MyModel1(MyMixin, Base):\n __tablename__ = 'models1'\n\nclass MyModel2(...
[ 8 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0007877196_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Django - Fabric & collecstatic - can't open file 'manage.py' I'm begining to use Fabric for a Django production server. Here is my fabfile.py from fabric.api import * env.hosts = ['me@myserver.net'] def srefresh(): with path('~me/myproject'): run('python manage.py collectstatic') sudo('apachectl restart'...
Django - Fabric & collecstatic - can't open file 'manage.py'
I'm begining to use Fabric for a Django production server. Here is my fabfile.py from fabric.api import * env.hosts = ['me@myserver.net'] def srefresh(): with path('~me/myproject'): run('python manage.py collectstatic') sudo('apachectl restart') And here is the output $ fab srefresh [me@myserver.net] Exec...
[ "Actually, it's quite clearly written in the docs. fabric.context_managers.path alters the PATH variable. fabric.context_managers.cd can be used to change the remote directory. So in your case:\ndef srefresh():\n with cd('~me/myproject'):\n run('python manage.py collectstatic')\n\nshould do the trick.\n",...
[ 1, 0 ]
[]
[]
[ "django", "fabric", "production_environment", "python" ]
stackoverflow_0007877816_django_fabric_production_environment_python.txt
Q: 3D Animation of Fractals I'm giving a presentation on Fractal Antennas (take a look at my previous threads) in November and I wanted to incorporate some animation to make my presentation easier to visualize the content I am referring to. Most of these animations would be relatively short, probably a minute long at...
3D Animation of Fractals
I'm giving a presentation on Fractal Antennas (take a look at my previous threads) in November and I wanted to incorporate some animation to make my presentation easier to visualize the content I am referring to. Most of these animations would be relatively short, probably a minute long at the most. There are a few ani...
[ "Personally, I've used VPython to create simple 3D graphics and animations. It's an easy to learn library that's freely available at http://vpython.org/. Since you have the coordinates already, it should be fairly easy to for you to incorporate that into the drawing.\nBlender is a bit more complicated, but also inc...
[ 2, 2 ]
[]
[]
[ "animation", "blender", "python" ]
stackoverflow_0007604730_animation_blender_python.txt
Q: how to check if two strings have intersection in python? For example, a = "abcdefg", b = "krtol", they have no intersection, c = "hflsfjg", then a and c have intersaction. What's the easiest way to check this? just need a True or False result A: def hasIntersection(a, b): return not set(a).isdisjoint(b) ...
how to check if two strings have intersection in python?
For example, a = "abcdefg", b = "krtol", they have no intersection, c = "hflsfjg", then a and c have intersaction. What's the easiest way to check this? just need a True or False result
[ "def hasIntersection(a, b):\n return not set(a).isdisjoint(b)\n\n", "You can use the built in set class:\na = set(\"abcdefg\")\nb = set(\"krtol\")\nc = set(\"hflsfjg\")\n\nif a.intersection(b): # or simply a & b\n pass\n\n" ]
[ 11, 4 ]
[]
[]
[ "python" ]
stackoverflow_0007878064_python.txt
Q: TurboGears 2 quickstart shows error immediately I am new to TurboGears and have just installed TG2 development in a virtual environment. I'm following along in the quickstart guide, and have successfully built a helloworld via paster quickstart I started the server and navigated a web-browser to localhost:8080 W...
TurboGears 2 quickstart shows error immediately
I am new to TurboGears and have just installed TG2 development in a virtual environment. I'm following along in the quickstart guide, and have successfully built a helloworld via paster quickstart I started the server and navigated a web-browser to localhost:8080 Wouldn't you know it, I immediately get an error, and ...
[ "The problem in wrong dependency to WebOb. IIRC 1.2b2 is installed which lack best_matches method on AcceptLanguage class. The easiest way to overcome that trouble is to replace WebOb-1.2b2 with stable WebOb-1.1.1.\nThis solution works fine for me.\nPS: if you use virtual-env - just replace files inside lib/python2...
[ 4 ]
[]
[]
[ "pylons", "python", "turbogears2" ]
stackoverflow_0007829653_pylons_python_turbogears2.txt
Q: Python Dictionary Floats I came across a strange behavior in Python (2.6.1) dictionaries: The code I have is: new_item = {'val': 1.4} print new_item['val'] print new_item And the result is: 1.4 {'val': 1.3999999999999999} Why is this? It happens with some numbers, but not others. For example: 0.1 becomes 0.100...
Python Dictionary Floats
I came across a strange behavior in Python (2.6.1) dictionaries: The code I have is: new_item = {'val': 1.4} print new_item['val'] print new_item And the result is: 1.4 {'val': 1.3999999999999999} Why is this? It happens with some numbers, but not others. For example: 0.1 becomes 0.1000...001 0.4 becomes 0.4000...0...
[ "This is not Python-specific, the issue appears with every language that uses binary floating point (which is pretty much every mainstream language).\nFrom the Floating-Point Guide:\n\nBecause internally, computers use a format (binary floating-point)\n that cannot accurately represent a number like 0.1, 0.2 or 0....
[ 8, 1 ]
[]
[]
[ "dictionary", "floating_point", "python" ]
stackoverflow_0007878341_dictionary_floating_point_python.txt
Q: How do I set the User-Agent for a QNetworkRequest in PyQtWebkit? I'm trying to set the header "User-Agent" in my little webkit-browser, but I did not get. That piece of code: self.web = QtWebKit.QWebView(self) ... self.request = QNetworkRequest() self.request.setUrl(url) self.request.setRawHeader("User-Agent",...
How do I set the User-Agent for a QNetworkRequest in PyQtWebkit?
I'm trying to set the header "User-Agent" in my little webkit-browser, but I did not get. That piece of code: self.web = QtWebKit.QWebView(self) ... self.request = QNetworkRequest() self.request.setUrl(url) self.request.setRawHeader("User-Agent", QtCore.QByteArray ("TestUserAgent")) self.request.setRawHeader("Acce...
[ "QWebView overrides the QNetworkRequest field and sets the User-Agent header appropriate for the version of WebKit you are using. To change this default behavior you must inherit from QWebPage, reimplement QWebPage.userAgentForUrl and set the page for your QWebView instances to an instance of your new QWebPage type...
[ 6, 4 ]
[]
[]
[ "http_headers", "pyqt", "python", "qt", "webkit" ]
stackoverflow_0005317924_http_headers_pyqt_python_qt_webkit.txt
Q: Python- postgresql timestamp and time without time zone I have 2 strings which represent: date- dd/mm/yyyy hh:mm and I need to convert it to timestamp without time zone start_time/end_tiime- hh:mm:ss and I need to convert it time without time zone I need to do this in order to add them to a sql query. which loo...
Python- postgresql timestamp and time without time zone
I have 2 strings which represent: date- dd/mm/yyyy hh:mm and I need to convert it to timestamp without time zone start_time/end_tiime- hh:mm:ss and I need to convert it time without time zone I need to do this in order to add them to a sql query. which looks like this: sql = ''' INSERT INTO myTable (date, start_...
[ "\ndd/mm/yyyy hh:mm to timestamp without time zone:\nimport time\n\ndate_string='24/10/2011 12:43'\nttuple=time.strptime(date_string,'%d/%m/%Y %H:%M')\ntimestamp=time.mktime(ttuple)\n# 1319474580.0\n\nhh:mm:ss to time without time zone:\nCan you clarify what kind of object is a time? \n\n" ]
[ 2 ]
[]
[]
[ "datetime", "postgresql", "python", "timestamp" ]
stackoverflow_0007878727_datetime_postgresql_python_timestamp.txt
Q: read the whole file at once I'm trying to write a function that gets a path and returns this file's content. No error handling needed. I've came up with the following def read_all_1(path): f = open(path) s = f.read() f.close() return s def read_all_2(path): with open(path) as f: return...
read the whole file at once
I'm trying to write a function that gets a path and returns this file's content. No error handling needed. I've came up with the following def read_all_1(path): f = open(path) s = f.read() f.close() return s def read_all_2(path): with open(path) as f: return f.read() My questions: which o...
[ "They are both quite pythonic. To address your second question, in the second function, the file will indeed be closed automatically. That is part of the protocol used with the with statement. Ironically, the file is not guaranteed to be closed in your first example (more on why in a second).\nUltimately, I woul...
[ 9, 3 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007878844_file_python.txt
Q: How to migrate with south when using 'through' for a ManyToMany field? I want to change a ManyToMany field in a django app. I have the following models: class A: ... class B: as = models.ManyToManyField(A) and I want: class A: ... class C: a = models.ForeignKey(A) b = models.ForeignKey("B"...
How to migrate with south when using 'through' for a ManyToMany field?
I want to change a ManyToMany field in a django app. I have the following models: class A: ... class B: as = models.ManyToManyField(A) and I want: class A: ... class C: a = models.ForeignKey(A) b = models.ForeignKey("B") extra_data = models.BooleanField(default=False) class B: as = mo...
[ "I would try to do it the following way:\n\nAdd the C model but do not add any extra data fields to it yet. Just set the 2 FK's to the linked models, so that it's schema is effectively identical to the default m2m table, except table name.\nRun schemamigration --auto for your app.\nTo effectively \"delete\" the exi...
[ 6, 2, 0 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0007878605_django_django_south_python.txt
Q: Can dynamic backends be started dynamically in Google App Engine? I know the question has been asked before but I have not been able to find a definite answer. I would like to use a dynamic backend to process tasks added to the default push queue. I would prefer to use a backend since I need the extra memory (1g v...
Can dynamic backends be started dynamically in Google App Engine?
I know the question has been asked before but I have not been able to find a definite answer. I would like to use a dynamic backend to process tasks added to the default push queue. I would prefer to use a backend since I need the extra memory (1g vs 128m) The questions How do dynamic backends start in Google App Engin...
[ "Resident backends have to be started and stopped manually. Dynamic backends start automatically when they receive an HTTP request, and shut down after a few minutes of idle time.\nTo address a task to a particular backend, specify a target:\ntaskqueue.add(url='/path/to/my/worker/', params={'key': key},\n ...
[ 4 ]
[]
[]
[ "backend", "google_app_engine", "python" ]
stackoverflow_0007877835_backend_google_app_engine_python.txt
Q: greatest common divisor for strings in python I would like to have a python function that given the list mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn'] returns the string 'abc', i.e., the longest piece contained by all the elements in the list. I have a solution which just loops through the slices of mystring[...
greatest common divisor for strings in python
I would like to have a python function that given the list mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn'] returns the string 'abc', i.e., the longest piece contained by all the elements in the list. I have a solution which just loops through the slices of mystring[0], and compares it to the rest, and breaks out of ...
[ "The way you described, you want the biggest substring at the starting point:\n>>> os.path.commonprefix(['abcde', 'abcdf', 'abcef', 'abcnn'])\n'abc'\n\n", "Once you realize that \"Longest Common Substring\" is the problem you're describing, it's easy to find what you want:\neg, from Wikibooks:\ndef LongestCommonS...
[ 6, 3 ]
[]
[]
[ "algorithm", "longest_substring", "python", "string" ]
stackoverflow_0007879194_algorithm_longest_substring_python_string.txt
Q: No Entry Matches Query django Okay so I've really weird problem. I've mapped my url like this : url(r'^contact/$', 'blog.views.contact'), however whenever I go to /contact/, I get a 404, I've cheked my re several time and can't figure out what is the problem here.. Here's contact view if it's relevant : def cont...
No Entry Matches Query django
Okay so I've really weird problem. I've mapped my url like this : url(r'^contact/$', 'blog.views.contact'), however whenever I go to /contact/, I get a 404, I've cheked my re several time and can't figure out what is the problem here.. Here's contact view if it's relevant : def contact(request): """ """ i...
[ "A few possibilities:\n1) The URLs file in question is not getting included at all. Test this by confirming that other URLs in the same file are working.\n2) Another earlier pattern is matching your URL and then throwing a 404 in the view. Test this by moving this pattern to be the first pattern in your root URLs...
[ 4 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0007879192_django_python_regex.txt
Q: Using anchors in python regex to get exact match I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "v4", "v1004" I have import re pattern = "\Av(?=\d+)\W" m = re.match(pattern, "v303") if m is None: print "noMatch" else: print "match" But this doesn't work! Rem...
Using anchors in python regex to get exact match
I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "v4", "v1004" I have import re pattern = "\Av(?=\d+)\W" m = re.match(pattern, "v303") if m is None: print "noMatch" else: print "match" But this doesn't work! Removing the \A and \W will match for v303 but will also ...
[ "Pretty straightforward. First, put anchors on your pattern:\n\"^patternhere$\"\n\nNow, let's put together the pattern:\n\"^v\\d+$\"\n\nThat should do it.\n", "I think you may want \\b (word boundary) rather than \\A (start of string) and \\W (non word character), also you don't need to use lookahead (the (?=...)...
[ 25, 6, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007879600_python_regex.txt
Q: Patching: Replacing a method call with another I use Python's mocking framework for tests - It works great! However, one thing I wasn't able to figure out, is how to patch a function so that I replace the call with another function. Example: # module_A.py def original_func(arg_a,arg_b): # ... # module_B.py im...
Patching: Replacing a method call with another
I use Python's mocking framework for tests - It works great! However, one thing I wasn't able to figure out, is how to patch a function so that I replace the call with another function. Example: # module_A.py def original_func(arg_a,arg_b): # ... # module_B.py import module_A def func_under_test(): # ... ...
[ "in your test import module_A at the top and then in your setup function use:\nmodule_A.original_func = alternative_func\n\n", "You need to save the original function so you can restore once you're done with the test function:\nimport module_a\n\ndef the_test():\n orig_func = module_a.original_func\n module...
[ 4, 1, 0 ]
[]
[]
[ "patch", "python", "unit_testing" ]
stackoverflow_0007879339_patch_python_unit_testing.txt
Q: Is there static block in class in python I am relatively new to python I would like to run a block of code only once for a class. Like the static block in java. for eg: class ABC: execute this once for a class. Is there any such options available in python? In java we write it like this. This is executed onl...
Is there static block in class in python
I am relatively new to python I would like to run a block of code only once for a class. Like the static block in java. for eg: class ABC: execute this once for a class. Is there any such options available in python? In java we write it like this. This is executed only once for a class, at the time the class is l...
[ "To do this just put the code directly under the class definition (parallel to the function definitions for the class.\nAll code directly in the class gets executed upon creation of that type in the class' namespace. Example:\nclass Test:\n i = 3\n y = 3 * i\n def testF(self):\n print Test.y\n\nv =...
[ 24, 12 ]
[]
[]
[ "block", "python", "static" ]
stackoverflow_0007879943_block_python_static.txt
Q: Reading in a .dic file in Python I have a French dictionary file which I got from WinEdt.org (Zip File). I'd like to read this file into memory, but when I do I get the error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 69: ordinal not in range(128) I've also tried using the codecs mod...
Reading in a .dic file in Python
I have a French dictionary file which I got from WinEdt.org (Zip File). I'd like to read this file into memory, but when I do I get the error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 69: ordinal not in range(128) I've also tried using the codecs module with the encoding utf-8, but that ...
[ "latin1 aka ISO-8859-1 is \"a snare and a delusion\". Decoding random binary gibberish with latin1 \"works\", because the latin1 codec maps all 256 bytes to a Unicode codepoint.\nIn this case given the information (1) French (2) \"WinEdt.org\" (hello hello, that's \"Win\" as in \"Windows\"). the file is likely to b...
[ 4 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0007879142_encoding_python.txt
Q: Python dictionary values merging based on specific key I want to merge two CSV files that I have read into python using the following code, a = csv.DictReader(csv1) b = csv.DictReader(csv2) aMap = {} bMap = {} for row in a: aMap[row['id']] = row for row in b: bMap[row['id']] = row Now I should have two...
Python dictionary values merging based on specific key
I want to merge two CSV files that I have read into python using the following code, a = csv.DictReader(csv1) b = csv.DictReader(csv2) aMap = {} bMap = {} for row in a: aMap[row['id']] = row for row in b: bMap[row['id']] = row Now I should have two dictionaries whose keys are the 'id' field from the two CSV...
[ "You could use one collections.defaultdict, and use update to merge rows from csv2.\nimport collections\n\naMap = collections.defaultdict(dict)\n\nfor row in csv.DictReader(csv1):\n aMap[row['id']] = row\n\nfor row in csv.DictReader(csv2):\n aMap[row['id']].update(row)\n\n", "I don't think there is a builti...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007879868_python.txt
Q: Why is Django redirecting my forms to a different location than the form's "action" specifies? I am making use of Django's django.contrib.auth.forms module, specifically the UserCreationForm class. Here is the templated verion of my form, where register_form is the variable passed from views.py holding the empty U...
Why is Django redirecting my forms to a different location than the form's "action" specifies?
I am making use of Django's django.contrib.auth.forms module, specifically the UserCreationForm class. Here is the templated verion of my form, where register_form is the variable passed from views.py holding the empty UserCreationForm: <form id="registration" method="post" action="/register"> {% csrf_token %} ...
[]
[]
[ "Unless you've explicitly set it otherwise, Django's devserver serves your pages on 127.0.0.1:8000. \nFrom your POST URL I can only guess that you have some PHP application configured to be served on http://localhost:8000, probably through Apache.\n" ]
[ -1 ]
[ "django", "forms", "python", "redirect" ]
stackoverflow_0007880051_django_forms_python_redirect.txt
Q: Django doesn't go in view method and returns nothing def search(request): print "Here!" #some work here In django i have a view method like this. When i call the url associated this view i dont get any error. But "print 'Here!'" doenst work and it returns nothing. Also i have a post method like this...
Django doesn't go in view method and returns nothing
def search(request): print "Here!" #some work here In django i have a view method like this. When i call the url associated this view i dont get any error. But "print 'Here!'" doenst work and it returns nothing. Also i have a post method like this.(i request via jquery) How ever my index view method ret...
[ "What are you expecting it to do? The print method outputs the specified text to STDOUT, but in the case of a Django view being served by a webserver, STDOUT is not the response to the client; it's your console if running the dev server or perhaps a log file on your production server.\nThe fact that you're not gett...
[ 2 ]
[]
[]
[ "django", "get", "jquery", "post", "python" ]
stackoverflow_0007879776_django_get_jquery_post_python.txt
Q: Getting many to many fields of many to many association in django model I have two levels of many to many associations in django. A player can belong to one or many teams. And a team can play one or many tournaments. Given a player i want to know in which all tournaments he has played. Following is the simplified...
Getting many to many fields of many to many association in django model
I have two levels of many to many associations in django. A player can belong to one or many teams. And a team can play one or many tournaments. Given a player i want to know in which all tournaments he has played. Following is the simplified model: class Tournament(models.Model): name = models.CharField(max_lengt...
[ " p1_tournaments = Tournament.objects.filter(team__player=p1)\n\nThere's an implicit lookup created for every reverse foreign key or m2m field. It's either the lowercased model class or the related_name argument, if specified.\nSo, essentially, that filter says get the tournaments related to teams that are related ...
[ 3 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0007880435_django_django_models_many_to_many_python.txt
Q: how to execute python from php more efficiently? Ok, I have to ask this. When I use shell_exec, exec or other commands to execute python code from php, my page loads 10x slower. So even in my localhost, empty pages with exec or system functions load in around 0.01 seconds while under normal circumstances this tim...
how to execute python from php more efficiently?
Ok, I have to ask this. When I use shell_exec, exec or other commands to execute python code from php, my page loads 10x slower. So even in my localhost, empty pages with exec or system functions load in around 0.01 seconds while under normal circumstances this time is around 0.001 seconds. I feel more comfortable wit...
[ "If you are forking a process on every page request, this is going to kill performance. Consider having your python process run as a daemon, and communicate using some sort of queuing or IPC.\nForking a process is an expensive operation and should be avoided on a per-request basis.\nSuggestions for inter-process c...
[ 1 ]
[]
[]
[ "exec", "performance", "php", "python" ]
stackoverflow_0007880887_exec_performance_php_python.txt
Q: Why is not the code executed serially in a python for loop I have the following functionality in a python script: invoke the shell to create some files(it is a split command from the shell) for f in a folder open f and write something commands.. I have seen that when the program goes to commands after the ex...
Why is not the code executed serially in a python for loop
I have the following functionality in a python script: invoke the shell to create some files(it is a split command from the shell) for f in a folder open f and write something commands.. I have seen that when the program goes to commands after the execution of the for loop many files have not been altered correct...
[ "If you have not flushed or closed the files, they may not have been written out yet. The file object will be implicitly closed by the garbage collection, but that may not be occurring soon enough for your usecase.\nfor f in files:\n out = open(f)\n out.write(something)\n out.close()\n\ndo_more.stuff()\n\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007880145_python.txt
Q: How can I extract text from an uploaded file to populate a Django model field? I'm writing a Django application which will require a Script object which has access both to a file containing the script and the fulltext of the script. The script file is an xls file, and I have no problems in extracting the data fro...
How can I extract text from an uploaded file to populate a Django model field?
I'm writing a Django application which will require a Script object which has access both to a file containing the script and the fulltext of the script. The script file is an xls file, and I have no problems in extracting the data from it or writing data to it programmatically (xlrd and friends are great!), and I'm s...
[ "It turns out that I was overengineering this problem. The signal I was actually looking for was post_init, and the function that I wrote is literally just\n@receiver(post_save, sender=Script)\ndef retrieve_fulltext(sender, **kwargs):\n script = kwargs['instance']\n s = open(script.script.path)\n text = s....
[ 1 ]
[]
[]
[ "django", "file", "python" ]
stackoverflow_0006208366_django_file_python.txt
Q: Cant get listbox to show for tkinter So, what I am trying to do is open a file when pressing a button and displaying the contents in a listbox. This is what I have so far, but I am not getting the listbox to display, let alone get the info to be in the listbox: #!/usr/bin/perl -w import time from Tkinter import ...
Cant get listbox to show for tkinter
So, what I am trying to do is open a file when pressing a button and displaying the contents in a listbox. This is what I have so far, but I am not getting the listbox to display, let alone get the info to be in the listbox: #!/usr/bin/perl -w import time from Tkinter import * import tkFileDialog def listbox(listbox...
[ "You are forgetting to pack the frame that contains the listbox.\nFWIW, your overloading of the name \"listbox\" makes your code very confusing - you have def listbox(listbox), self.listbox and frame.listbox. And you also have call_listbox and the Listbox class to add to the confusion.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007880339_python_tkinter.txt
Q: Pyramid ACL without traversal I really have little idea how ACL do work. I know it's pretty cool and could save me lots of time and pain. But currently i'm a bit lost. All example for pyramid do use traversal. I exclusively use URL Dispatch. I'm not sure to understand how I can build a ressource tree structure. He...
Pyramid ACL without traversal
I really have little idea how ACL do work. I know it's pretty cool and could save me lots of time and pain. But currently i'm a bit lost. All example for pyramid do use traversal. I exclusively use URL Dispatch. I'm not sure to understand how I can build a ressource tree structure. Here is a sample of code: class Quest...
[ "It looks like you're interested in some object/row-level security features to allow only owners of accounts to view their data. I would refer you to my previous SO answer on this topic, as well as the tutorial I've been working on for auth in URL Dispatch which is built around this answer. Specifically you might w...
[ 6 ]
[]
[]
[ "acl", "pyramid", "python", "routes" ]
stackoverflow_0007880022_acl_pyramid_python_routes.txt
Q: How to get response URL from RPC object in Asynchronous Requests App engine? rpcs = [] for url in urls: rpc = urlfetch.create_rpc(deadline=5.0) urlfetch.make_fetch_call(rpc, url) rpcs.append(rpc) while len(rpcs) > 0: rpc = apiproxy_stub_map.UserRPC.wait_any(rpcs) res = rpc.get_result() if res.status_co...
How to get response URL from RPC object in Asynchronous Requests App engine?
rpcs = [] for url in urls: rpc = urlfetch.create_rpc(deadline=5.0) urlfetch.make_fetch_call(rpc, url) rpcs.append(rpc) while len(rpcs) > 0: rpc = apiproxy_stub_map.UserRPC.wait_any(rpcs) res = rpc.get_result() if res.status_code == 200: ...... do something with result rpcs.remove(rpc) How to determin...
[ "Use a callback:\ndef handle_result(rpc, url):\n ..... [your code goes here]\n\ndef create_callback(rpc, url):\n return lambda: handle_result(rpc, url)\n\nrpcs = []\nfor url in urls:\n rpc = urlfetch.create_rpc(deadline=5.0)\n rpc.callback = create_callback(rpc, url)\n urlfetch.make_fetch_call(rpc, url)\n rpc...
[ 2 ]
[]
[]
[ "asynchronous", "google_app_engine", "python", "urlfetch" ]
stackoverflow_0007881459_asynchronous_google_app_engine_python_urlfetch.txt
Q: Why Does This Program Run on Linux Python Shell But Not on Windows? I ran this program on Linux with Python 2.6.2 and it ran fine returning me with decimal values but when I run it on Python 2.7.2 on Windows it does not work and just gives a blank space for a while and then a memory error but I can't figure out wh...
Why Does This Program Run on Linux Python Shell But Not on Windows?
I ran this program on Linux with Python 2.6.2 and it ran fine returning me with decimal values but when I run it on Python 2.7.2 on Windows it does not work and just gives a blank space for a while and then a memory error but I can't figure out why..I need it to run on Windows its a program to calculate stock equity (R...
[ "You have stuffed up the indentation of your a+=1 line, possibly because of (mis)use of tabs in your source file. As displayed here on SO, a will never be incremented and so the loop will never be exited.\n", "It helps to know where it's blowing up. You should try the Python debug module if the error isn't enough...
[ 1, 0, 0 ]
[]
[]
[ "linux", "python", "python_idle", "shell", "windows" ]
stackoverflow_0007881110_linux_python_python_idle_shell_windows.txt
Q: Pascal's Triangle with iterative algorithm via list comprehension in Python Just for the sake of exercise I'm trying to find a way to express Pascal's Triangle with Python list comprehension, and do that in iterative way. I'm representing Pascal's Triangle in Python as: tri = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1],...
Pascal's Triangle with iterative algorithm via list comprehension in Python
Just for the sake of exercise I'm trying to find a way to express Pascal's Triangle with Python list comprehension, and do that in iterative way. I'm representing Pascal's Triangle in Python as: tri = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], ...] As I'm doing it iteratively, I need to somehow access pre...
[ "You can simply use the definition of the binomial coefficients:\n\nfrom math import factorial\ntri = [[factorial(n) // (factorial(k) * factorial(n - k)) for k in range(n+1)]\n for n in range(height)]\n\n", "As explicitly iterative approaches are wanted, I would use an iterator.\ndef bincoeff(num=None):\n fro...
[ 9, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007880189_python.txt
Q: Which executable does a core file belong to? I have a python program that spawns a number of processes, one of which segfaults and dumps core. Is there a way to find out which executable produced the resulting core file? A: The "file" program can tell you; type "file core".
Which executable does a core file belong to?
I have a python program that spawns a number of processes, one of which segfaults and dumps core. Is there a way to find out which executable produced the resulting core file?
[ "The \"file\" program can tell you; type \"file core\".\n" ]
[ 5 ]
[]
[]
[ "core", "debugging", "python" ]
stackoverflow_0007881926_core_debugging_python.txt
Q: Python List: IndexError: list index out of range When I try to print splited_data[1] I'm getting error message IndexError: list index out of range, On the other hand splited_data[0] is working fine. I want to insert data into MySQL. splited_data[0] are my MySQL columns and splited_data[1] is mysql column values. I...
Python List: IndexError: list index out of range
When I try to print splited_data[1] I'm getting error message IndexError: list index out of range, On the other hand splited_data[0] is working fine. I want to insert data into MySQL. splited_data[0] are my MySQL columns and splited_data[1] is mysql column values. I want if splited_data[1] is empty then insert empty st...
[ "split_data = item.partition('=')\n# If there was an '=', then it is now in split_data[1],\n# and the pieces you want are split_data[0] and split_data[2].\n# Otherwise, split_data[0] is the whole string, and\n# split_data[1] and split_data[2] are empty strings ('').\n\n", "Try removing the whitespace on both side...
[ 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007880786_python_string.txt
Q: Don't split double-quoted words with Python string split()? When using the Python string function split(), does anybody have a nifty trick to treat items surrounded by double-quotes as a non-splitting word? Say I want to split only on white space and I have this: >>> myStr = 'A B\t"C" DE "FE"\t\t"GH I JK L" "" ""\...
Don't split double-quoted words with Python string split()?
When using the Python string function split(), does anybody have a nifty trick to treat items surrounded by double-quotes as a non-splitting word? Say I want to split only on white space and I have this: >>> myStr = 'A B\t"C" DE "FE"\t\t"GH I JK L" "" ""\t"O P Q" R' >>> myStr.split() ['A', 'B', '"C"', 'DE', '"FE"', '...
[ "You won't be able to get this behaviour with str.split(). If you can live with the rather complex parsing it does (like ignoring double quotes preceded by a back slash), shlex.split() might be what you are looking for:\n>>> shlex.split(myStr)\n['A', 'B', 'C', 'DE', 'FE', 'GH I JK L', '', '', 'O P Q', 'R']\n\n",...
[ 35, 4, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0007881794_python_split_string.txt
Q: Grouping totals in SQLAlchemy I can't seem to find any good documentation on this. I have a list of users and order amounts, and I want to display the users with the top 10 order amount totals. I've been having trouble creating a query that sufficiently extracts this data in SQLAlchemy. Is there a better way to ap...
Grouping totals in SQLAlchemy
I can't seem to find any good documentation on this. I have a list of users and order amounts, and I want to display the users with the top 10 order amount totals. I've been having trouble creating a query that sufficiently extracts this data in SQLAlchemy. Is there a better way to approach this? customers, amount = DB...
[ "from sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\nimport random\n\nBase= declarative_base()\n\nclass Customer(Base):\n __tablename__ = 'customer'\n id = Column(Integer, primary_key=True)\n name = Column(Unicode)\n orders = relationship(\"Or...
[ 4 ]
[]
[]
[ "pyramid", "python", "sqlalchemy" ]
stackoverflow_0007882129_pyramid_python_sqlalchemy.txt
Q: Formencode in pyramid and pyramid_simplefrom: set fixed locale I know I can run the following code in python shell: import formencode ne = formencode.validators.NotEmpty() formencode.api.set_stdtranslation(languages=["it"]) try: ne.to_python("") except formencode.api.Invalid, e: print str(e) and get prin...
Formencode in pyramid and pyramid_simplefrom: set fixed locale
I know I can run the following code in python shell: import formencode ne = formencode.validators.NotEmpty() formencode.api.set_stdtranslation(languages=["it"]) try: ne.to_python("") except formencode.api.Invalid, e: print str(e) and get printed Inserire un valore Now how do I get the same result im my pyra...
[ "I've just found a way to do it, but I'm not sure it's the best one... Anyway, I mixed information from the Mako i18n recipe, the simpleform documentation and how Pylons did it (the PylonsFormEncodeState inside pylons.decorators) and I came up with the following...\nI subscribe to a NewRequest event like this:\ncon...
[ 4 ]
[]
[]
[ "formencode", "pyramid", "python" ]
stackoverflow_0007766011_formencode_pyramid_python.txt
Q: Implementing IMAP server I need to write an IMAP wrapper around some messaging system. With all the complexity of IMAP protocol i'd rather use some existing library to do the heavy lifting for me. Are there any IMAP servers / libraries / frameworks available in PHP or Python? Alternatively, is there such IMAP serv...
Implementing IMAP server
I need to write an IMAP wrapper around some messaging system. With all the complexity of IMAP protocol i'd rather use some existing library to do the heavy lifting for me. Are there any IMAP servers / libraries / frameworks available in PHP or Python? Alternatively, is there such IMAP server which would allow to write ...
[ "If you do not mind using Java then, Apache James IMAP provides RFC2040 compliant data access layer for IMAP. It is not fully optimized for performance yet but appears to be tested and in working condition otherwise. They also provide a full IMAP server and because everything is under Apache license, you should be ...
[ 1, 0 ]
[]
[]
[ "imap", "php", "python" ]
stackoverflow_0007882194_imap_php_python.txt
Q: PIL: selftest fails, but package shows status is fine? I have PIL installed with the required libraries (so I think). During installation it shows *** TKINTER support not available --- JPEG support available --- ZLIB (PNG/ZIP) support available --- FREETYPE2 support available --- LITTLECMS support available Howe...
PIL: selftest fails, but package shows status is fine?
I have PIL installed with the required libraries (so I think). During installation it shows *** TKINTER support not available --- JPEG support available --- ZLIB (PNG/ZIP) support available --- FREETYPE2 support available --- LITTLECMS support available However, when I run selftest.py, I get this: *** PIL CORE suppor...
[ "Try building the C extensions in-place in the source directory with setup.py build_ext -i before running selftest.py or Tests\\run.py.\n" ]
[ 5 ]
[]
[]
[ "centos", "freetype", "python", "python_imaging_library" ]
stackoverflow_0007880964_centos_freetype_python_python_imaging_library.txt
Q: Using deferred objects inside Twisted applications I feel like I am not understanding some things in writing Twisted applications (.tac files). Using deferred objects in .py scripts is easy by just calling reactor.run() at the end, but I have not seen reactor.run() used in any twisted application sample code. Can...
Using deferred objects inside Twisted applications
I feel like I am not understanding some things in writing Twisted applications (.tac files). Using deferred objects in .py scripts is easy by just calling reactor.run() at the end, but I have not seen reactor.run() used in any twisted application sample code. Can someone explain: why reactor.run() is not called in tw...
[ "1. Why is reactor.run() not called in example .tac files?\n.tac files are meant to be loaded by the \"twistd\" command-line tool, which runs the reactor for you.\nRunning the reactor is something that's done once, by whatever bit of code is serving as the main-point for your program. Most Twisted code is effectiv...
[ 12 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007880479_python_twisted.txt
Q: Failure to upload image to Plone 2.5 via xmlrpc Based on the answer to Bad interaction between Zope2 XML-RPC and AT Image mutator? I'd expect to be able to do the following with Plone 2.5: proxy = xmlrpclib.ServerProxy('http://admin:admin@localhost:8080/Plone/screenshot.png', verbose=True) wrappedData = xmlrpclib....
Failure to upload image to Plone 2.5 via xmlrpc
Based on the answer to Bad interaction between Zope2 XML-RPC and AT Image mutator? I'd expect to be able to do the following with Plone 2.5: proxy = xmlrpclib.ServerProxy('http://admin:admin@localhost:8080/Plone/screenshot.png', verbose=True) wrappedData = xmlrpclib.Binary(open(filename).read()) proxy.setImage(wrappedD...
[ "With this patch it works like a charm:\n--- Field.py 2011-10-24 20:33:49.000000000 +0200\n+++ Field.py 2011-10-25 00:24:49.360826000 +0200\n@@ -2,6 +2,7 @@\n\n import sys\n\n+import xmlrpclib\n from copy import deepcopy\n from cgi import escape\n from cStringIO import StringIO\n@@ -869,6 +870,8 @@\n ...
[ 2 ]
[]
[]
[ "plone", "python", "xml_rpc" ]
stackoverflow_0007880222_plone_python_xml_rpc.txt
Q: What is the deal about https when using lxml? I am using lxml to parse html files given urls. For example: link = 'https://abc.com/def' htmltree = lxml.html.parse(link) My code is working well for most of the cases, the ones with http://. However, I found for every https:// url, lxml simply gets an IOError. Does ...
What is the deal about https when using lxml?
I am using lxml to parse html files given urls. For example: link = 'https://abc.com/def' htmltree = lxml.html.parse(link) My code is working well for most of the cases, the ones with http://. However, I found for every https:// url, lxml simply gets an IOError. Does anyone know the reason? And possibly, how to correc...
[ "I don't know what's happening, but I get the same errors. HTTPS is probably not supported. You can easily work around this with urllib2, though:\nfrom lxml import html\nfrom urllib2 import urlopen\n\nhtml.parse(urlopen('https://duckduckgo.com'))\n\n", "From the lxml documentation:\n\nlxml can parse from a local ...
[ 20, 6 ]
[]
[]
[ "lxml", "parsing", "python" ]
stackoverflow_0007882673_lxml_parsing_python.txt
Q: reshape an irregular list in python I would like to reshape the following list : wide_list = [[1,['a','b','c']],[2,['d','e']],[3,'f']] in a "long format": long_list = [[1,'a'],[1,'b'],[1,'c'],[2,'d'],[2,'e'],[3,'f']] How can this be achieved efficiently in Python? A: Try a nested list comprehension: >>> wide_l...
reshape an irregular list in python
I would like to reshape the following list : wide_list = [[1,['a','b','c']],[2,['d','e']],[3,'f']] in a "long format": long_list = [[1,'a'],[1,'b'],[1,'c'],[2,'d'],[2,'e'],[3,'f']] How can this be achieved efficiently in Python?
[ "Try a nested list comprehension:\n>>> wide_list = [[1,['a','b','c']],[2,['d','e']],[3, ['f']]]\n>>> long_list = [[k, v] for k, sublist in wide_list for v in sublist]\n>>> long_list\n[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'd'], [2, 'e'], [3, 'f']]\n\nNote, the last group had to be changed to match the pattern of the fi...
[ 5, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007882997_list_python.txt
Q: Explaining Python's site-packages. Do I put my libraries in there? I recently came upon a new project with Python as the code-base. I have never done Python before - coming from the C/C++ world of compiled code. I am running into some issues understanding my current codebase. When we write code, we have our libra...
Explaining Python's site-packages. Do I put my libraries in there?
I recently came upon a new project with Python as the code-base. I have never done Python before - coming from the C/C++ world of compiled code. I am running into some issues understanding my current codebase. When we write code, we have our libraries (components that are more general than other code), and our applica...
[ "Python libraries are usually installed via distutils or setuptools. Those utilties install the libraries in python's site-packages folder, which is where python knows to look for libs when an import x statement is encountered.\nDeveloping code directly in the site-packages folder seems a little odd, although there...
[ 7, 2 ]
[ "Its easy importing those libraries using Eclipse.\nInstall Easy_install and import all those libraries from your command prompt.\nNow in Eclipse, just link those libraries, in your preferences and wola! you are ready to GO!\n" ]
[ -3 ]
[ "import", "ironpython", "python" ]
stackoverflow_0007882969_import_ironpython_python.txt
Q: IndentationError while using formset I have these models: class Tour(models.Model): Name=models.CharField(max_length=100) Count=models.SmallIntegerField() PriceUnitCode=models.ForeignKey(PriceUnit) Price=models.CharField(max_length=12) Description=models.TextField() ActionDate=models.DateTimeFie...
IndentationError while using formset
I have these models: class Tour(models.Model): Name=models.CharField(max_length=100) Count=models.SmallIntegerField() PriceUnitCode=models.ForeignKey(PriceUnit) Price=models.CharField(max_length=12) Description=models.TextField() ActionDate=models.DateTimeField(auto_now=True,editable=False) Action...
[ "maybe you put spaces instead of tabs in that line (or the oposite), it happends to me sometimes\n", "Very likely, your indentation differs in line 122, most probably because you have invisible differences in leading whitespace.\nExample: You have many lines in a block, all start with a tab, which is displayed by...
[ 3, 3, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007874728_django_python.txt
Q: Python CSV DictReader ignore columns? If I'm using CSV.dictReader to read in an CSV, how would I go about having it ignore certain columns in the CSV? For example, "id","name","address","number","created" "123456","someName","someAddress","someNumber","2003-5-0294" And I want to just get the id and name using the...
Python CSV DictReader ignore columns?
If I'm using CSV.dictReader to read in an CSV, how would I go about having it ignore certain columns in the CSV? For example, "id","name","address","number","created" "123456","someName","someAddress","someNumber","2003-5-0294" And I want to just get the id and name using the reader, discarding and ignoring the rest. ...
[ "This simple generator will do it.\ndef dict_filter(it, *keys):\n for d in it:\n yield dict((k, d[k]) for k in keys)\n\nUse it like this:\ndreader = [{'id':1, 'name':'Bob', 'other_stuff':'xy'},\n {'id':2, 'name':'Jen', 'other_stuff':'xx'}]\n\nfor d in dict_filter(dreader, 'id', 'name'):\n pri...
[ 6, 5, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007880391_python.txt
Q: Django Admin: let people test a regexp? I'm building a Django app that will let researchers send text messages to study participants and parse the responses. While parsing, say, 'Y/N' and numbers is going to be pretty easy, we'll need to send messages that need more complex responses. Which, I think, means regular...
Django Admin: let people test a regexp?
I'm building a Django app that will let researchers send text messages to study participants and parse the responses. While parsing, say, 'Y/N' and numbers is going to be pretty easy, we'll need to send messages that need more complex responses. Which, I think, means regular expressions. All this is easy enough; the th...
[ "My guess is that it would be easiest to do this as a javascript widget--it'll be easier to wedge into the admin and there's tons of examples to work off of.\nDaring to venture slightly off of the question though, I'll say I'd be pretty nervous trying to write regexes to parse human-generated responses of any compl...
[ 1 ]
[]
[]
[ "django", "django_admin", "python", "user_interface" ]
stackoverflow_0007882442_django_django_admin_python_user_interface.txt
Q: python - parsing website table with blank entries I'm am writing a bit of python code that gets data from a website. The table is well formed and everything is working fine most of the time. However, when the parser encounters a blank field, it totally ignores it. I need it to count the blank space but I can't fig...
python - parsing website table with blank entries
I'm am writing a bit of python code that gets data from a website. The table is well formed and everything is working fine most of the time. However, when the parser encounters a blank field, it totally ignores it. I need it to count the blank space but I can't figure out how to do this. The problem lies with some arra...
[ "One possible solution would be adding cell_data=\"\" when finding <td>s, updating it with cell_data += data on handle_data and appending cell_data to the data array on </td>s.\n", "OK, I know its frowned upon for answering your own question, but in case anyone comes across this problem in the future, I'll just p...
[ 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0007883041_parsing_python.txt
Q: Alternative to eval in Python Python eval is quite slow. I need to evaluate simple boolean expression with logical operators (like "True or False"). I am doing this for thousands of line of data and eval is a huge bottleneck in terms of performance. It's really slow.. Any alternative approaches? I tried creating a...
Alternative to eval in Python
Python eval is quite slow. I need to evaluate simple boolean expression with logical operators (like "True or False"). I am doing this for thousands of line of data and eval is a huge bottleneck in terms of performance. It's really slow.. Any alternative approaches? I tried creating a dict of possible expression combin...
[ "import operator\nops = { 'or': operator.or_, 'and': operator.and_ }\nprint ops[op](True, False)\n\n", "It's not clear to me how @CatPlusPlus's solution will evaluate any boolean expression. Here is an example from the pyparsing wiki examples page of a Boolean expression parser/evaluator. Here are the test case...
[ 14, 1 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0007882987_eval_python.txt
Q: python: how do I get around variable variables As python is my first OO language, I cannot understand. I need to run a dialog, and put the return into a variable passed from another function. How do I get around variable variables in this case, in dGetPath? def dGetPath(self, widget, data=None): print "%s need...
python: how do I get around variable variables
As python is my first OO language, I cannot understand. I need to run a dialog, and put the return into a variable passed from another function. How do I get around variable variables in this case, in dGetPath? def dGetPath(self, widget, data=None): print "%s needs to be filled with output from a dialog here" % (da...
[ "If I read your question correctly, you're confused about event handling and callback functions -- you need to do something (dupChk()) on the value returned from a dialog box (not yet defined...) when the user clicks on Apath.\nWhat I think you're missing here is some place to store the file or directory chosen by ...
[ 2 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0007883462_pygtk_python.txt
Q: Does opening multiple file handlers slow down write times? In python is the process of opening a file handler slow compared to the actual write time? One large file, one file handler import marshal bigDataStructure = [[1000000.0 for j in range(1000000)] for i in range(1000000)] f = open('bigFile' , 'w') marshal.d...
Does opening multiple file handlers slow down write times?
In python is the process of opening a file handler slow compared to the actual write time? One large file, one file handler import marshal bigDataStructure = [[1000000.0 for j in range(1000000)] for i in range(1000000)] f = open('bigFile' , 'w') marshal.dump(bigDataStructure , f) f.close() multiple smaller files, mul...
[ "I suppose the multiple-filehandler-approach may be slower, because there will be performed a write to the file system for every close() operation. If you're writing small chunks at a time, this is slower (because you may be writing less bytes than a sector size) than letting the lower levels (OS, file system, bloc...
[ 2, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007883521_file_python.txt
Q: Does not come out from MainLoop() We were using Python2.3 and wxPython V2.4.2.4 in our project. And it was working fine. Now we are upgrading it to Python2.7 and wxPython2.8.12.1. Our project is compiled fine with new version. But in our project at one stage in the code we destroy the current window and then creat...
Does not come out from MainLoop()
We were using Python2.3 and wxPython V2.4.2.4 in our project. And it was working fine. Now we are upgrading it to Python2.7 and wxPython2.8.12.1. Our project is compiled fine with new version. But in our project at one stage in the code we destroy the current window and then create & open new window again. And I have n...
[ "Your trouble (as far as I can tell) is that you have your MainLoop inside of your OnInit function, which is halting your program flow. I can't speak for how it worked like that before, to be honest, because you shouldn't be able to enter the MainLoop for an App until it's OnInit has returned True. The OnInit coul...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007883948_python_wxpython.txt
Q: multiple invocations of OptionParser.parse_args() within the same python execution I have the following example setup: |-- main_script.py `-- module |-- __init__.py `-- submodule.py where the contents of main_script are: import optparse import module parser = optparse.OptionParser() group = optparse.Opti...
multiple invocations of OptionParser.parse_args() within the same python execution
I have the following example setup: |-- main_script.py `-- module |-- __init__.py `-- submodule.py where the contents of main_script are: import optparse import module parser = optparse.OptionParser() group = optparse.OptionGroup("submodules options") group.add_option("","--main_script.bar", dest="bar", actio...
[ "The easiest way is to break your logic into functions. You should not execute logic at the global module scope in the first place, but use a if name == \"__main__\" wrapper construct.\nYou could define a function add_options(parser) to each module that must define options, and call this at the root level before c...
[ 2, 0 ]
[]
[]
[ "optionparser", "python" ]
stackoverflow_0007871918_optionparser_python.txt
Q: How to structure standard Python project (modules, libraries) for future use in Google App Engine? I'm currently developing a Python project which is growing and I may implement it as a webapp in GAE in the future. As the project is growing I'm pruning potentially reusable code into separate packages & modules, ...
How to structure standard Python project (modules, libraries) for future use in Google App Engine?
I'm currently developing a Python project which is growing and I may implement it as a webapp in GAE in the future. As the project is growing I'm pruning potentially reusable code into separate packages & modules, which at present are on my PYTHONPATH. Do you have any advice on how to structure my project, and reusab...
[ "Just put your various libraries in packages off the root directory of your app. The root directory is automatically added to your app's sys.path.\nIf you wish you can put them in a lib directory off the root, you can do so, but you'll have to write a module that adds that directory to the end of sys.path, and impo...
[ 5, 2, 2, 1 ]
[]
[]
[ "google_app_engine", "python", "virtualenv" ]
stackoverflow_0007843181_google_app_engine_python_virtualenv.txt
Q: GAE text search with secondary sorting In lieu of full-text search on GAE I'm using the solution below to return a resultset that's sorted, first by keyword relevance, and secondly by date (though the second sorting could be anything really). It feels a bit bulky and I'm concerned about performance at scale so I'...
GAE text search with secondary sorting
In lieu of full-text search on GAE I'm using the solution below to return a resultset that's sorted, first by keyword relevance, and secondly by date (though the second sorting could be anything really). It feels a bit bulky and I'm concerned about performance at scale so I'm looking for optimization suggestions or a ...
[ "search_terms = ['a','b','c'] #User's search query, split into a list of strings\n\nYou can accumulate the keys in the order of appearance\nand can build-up the key frequencies in all in one pass.\nTake advantage of sort stability to make a sort by decreasing frequency, then by order of appearance:\nkeys_in_order_o...
[ 2, 2 ]
[]
[]
[ "full_text_search", "google_app_engine", "python" ]
stackoverflow_0007840811_full_text_search_google_app_engine_python.txt
Q: Why doesn't this work? ''.join(' '.join(string).split().remove(str[n])) I'm playing with codingbat.com, and I found this really easy problem to solve, so I started trying to play newbie code golf. Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of...
Why doesn't this work? ''.join(' '.join(string).split().remove(str[n]))
I'm playing with codingbat.com, and I found this really easy problem to solve, so I started trying to play newbie code golf. Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be i...
[ "This is because remove returns None. Most (all?) builtin functions in python that mutate a value return None.\nTherefore your outer join is trying to join nothing together.\n", "Not a direct answer to your question, but that seems like a very hard way to do a slice...\ndef missing_char(s, n):\n return s[:n] ...
[ 13, 9, 2 ]
[]
[]
[ "behavior", "join", "python", "string" ]
stackoverflow_0007884134_behavior_join_python_string.txt
Q: google app engine datastore performance bad while data entry has more property Version1 class ActionLog(db.Model): action = db.StringProperty() time_slice = db.IntegerProperty() trace_code = db.StringProperty() # which profile this log belong to # Who facebook_id = db.StringProperty() # t...
google app engine datastore performance bad while data entry has more property
Version1 class ActionLog(db.Model): action = db.StringProperty() time_slice = db.IntegerProperty() trace_code = db.StringProperty() # which profile this log belong to # Who facebook_id = db.StringProperty() # the user's facebook id ip = db.StringProperty() # the user's ip addres...
[ "Set index=False on all properties that you don't need indexed (i.e., properties that you won't use in a query). This cuts down the number of index writes it takes to save an entity.\nSee http://code.google.com/appengine/docs/python/datastore/queries.html#Introduction_to_Indexes for an explanation.\n", "Your firs...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007839723_google_app_engine_google_cloud_datastore_python.txt
Q: How to add dynamics to a static HTML page? What's a quick'n easy way to add edit function to static HTML? I could save HTML with a textproperty and an /admin area to edit the entity with the variable that contains the HTML but is this a good solution or can you recommend a better solution? I'm considering using t...
How to add dynamics to a static HTML page?
What's a quick'n easy way to add edit function to static HTML? I could save HTML with a textproperty and an /admin area to edit the entity with the variable that contains the HTML but is this a good solution or can you recommend a better solution? I'm considering using the tool appengine_admin and 2 model: Content and...
[ "It sounds like you want a CMS. Rather than reinventing the wheel, you should probably use an existing one.\n" ]
[ 1 ]
[ "First identify the bits of the static HTML you want to edit - make them variables. Then use php to generate dynamic content\n" ]
[ -1 ]
[ "google_app_engine", "google_cloud_datastore", "html", "python", "wysiwyg" ]
stackoverflow_0007837304_google_app_engine_google_cloud_datastore_html_python_wysiwyg.txt
Q: Populate a Google App Engine app's datastore with 20.000 strings I'm trying to create and store 20000 random codes in my local datastore, before trying this in appspot... This is the model class PromotionCode (db.Model): code = db.StringProperty(required=True) And this is the class that handles the populate req...
Populate a Google App Engine app's datastore with 20.000 strings
I'm trying to create and store 20000 random codes in my local datastore, before trying this in appspot... This is the model class PromotionCode (db.Model): code = db.StringProperty(required=True) And this is the class that handles the populate request (only a logged admin may use it). It creates random alphanumeric ...
[ "Why not just change your code above to insert 100 at a time, and just run something like:\nfor i in {1..200}\n do\n curl --cookie \"ACSID=your-acsid-cookie\" http://your-app-id.appspot.com/populatepath\n sleep(5)\n done\n\nfrom your command line? The entries are random anyway, you don't need to remember an...
[ 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007836014_google_app_engine_google_cloud_datastore_python.txt
Q: Selecting 10 items based on N number types I am writing a program that has to select 10 items randomly from a database . the criteria is that its type should be based on users choice . So if the user chooses type 1 the program has to choose 10 items of type 1 if the user chooses type 1 and 2 the program has to ch...
Selecting 10 items based on N number types
I am writing a program that has to select 10 items randomly from a database . the criteria is that its type should be based on users choice . So if the user chooses type 1 the program has to choose 10 items of type 1 if the user chooses type 1 and 2 the program has to choose 5 items from type 1 and 5 items from type 2 ...
[ "One way is to scan the DB in a single pass, building up your ten selecions. Here's some pseudo code:\n\nQuery the whole database for records meeting the user's criteria\nBuild-up the first ten encountered in a results list\nIf any additional records arise, decide randomly whether to include it (the n-th item shou...
[ 3, 1, 0 ]
[]
[]
[ "algorithm", "multiple_choice", "python" ]
stackoverflow_0007884577_algorithm_multiple_choice_python.txt
Q: Can a Django model field's default value be defined by a function dependent on a foreign parent model? I'm trying to have the default value of Report's fee be based on a parent model's attributes. I don't want to do this in save(), because the field needs to be presented to the user if they choose to override the ...
Can a Django model field's default value be defined by a function dependent on a foreign parent model?
I'm trying to have the default value of Report's fee be based on a parent model's attributes. I don't want to do this in save(), because the field needs to be presented to the user if they choose to override the value before saving. Here are the three methods I've tried, in addition to passing only function pointers (i...
[ "Your last example could potentially work with some work: \n\nFirst all, you need to __init__ on your class, not models.Model\nYou need to set your attribute after the model has been initialized\nYou need check if the model has been saved, or else your model will revert to the overridable fee every time you load it...
[ 8 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007884376_django_django_models_python.txt
Q: How to read the value of an XML tag having attributes using minidom I have an XML which looks like this. <nb:myelement param='oxygen'>Value</nb:element> I am using the following python code. for sub in dom.getElementsByTagName('nb:myelement'): if(sub.getAttributeNode("param").nodeValue == 'oxygen'): valu...
How to read the value of an XML tag having attributes using minidom
I have an XML which looks like this. <nb:myelement param='oxygen'>Value</nb:element> I am using the following python code. for sub in dom.getElementsByTagName('nb:myelement'): if(sub.getAttributeNode("param").nodeValue == 'oxygen'): value = sub.getElementsByTagName('nb:myelement')[0].toxml() But the last lin...
[ "There are no other nb:myelement elements in your nb:myelement. So last line is really\n[][0].toxml()\n\nIf there is only text in nb:myelement, just use text node of this element\nsub.firstChild.nodeValue\n\n" ]
[ 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0007884558_minidom_python_xml.txt
Q: writing lines group by group in different files I've got a little script which is not working nicely for me, hope you can help and find the problem. I have two starting files: traveltimes: contains the lines I need, it's a column file (every row has just a number). The lines I need are separated by a line which st...
writing lines group by group in different files
I've got a little script which is not working nicely for me, hope you can help and find the problem. I have two starting files: traveltimes: contains the lines I need, it's a column file (every row has just a number). The lines I need are separated by a line which starts with 11 whitespaces header lines: contains three...
[ "Suggestion:\n\nRead the header rows first. Make sure this works before proceeding. None of the rest of the code needs to be indented under this.\nConsider writing a separate function to group the traveltimes file into a list of lists.\nOnce you have a working traveltimes reader and grouper, only then create a ne...
[ 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007884798_file_python.txt
Q: Iterating over data in Django template I am processing a queryset in a view to get a summary of data and need to be able to iterate over the resultant dataset in my template. I did this OK with a key and single value by building a dictionary and then using .items to work over key value pairs using: {% for id,total...
Iterating over data in Django template
I am processing a queryset in a view to get a summary of data and need to be able to iterate over the resultant dataset in my template. I did this OK with a key and single value by building a dictionary and then using .items to work over key value pairs using: {% for id,total in list_summary.items %} <tr class="{% ...
[ "\nI tried building a dictionary using a dictionary as the value but in\n the template I can't get to the values in the dictionary.\n\nWhy not? The values are also key/value pairs..\n{% for list_id, dict in list_summary.items %}\n list_id: {{ list_id }}\n {% for k, v in dict.items %}\n key: {{ k }} <!...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007884628_django_python.txt
Q: How to wait only DOM to load with Selenium (without images) There is a long list of the images on the page. There is an AJAX "Load more images" button in the application (at the bottom of the page) which is activated automatically when user scrolling page down. I want to scroll the page to the very end with Selen...
How to wait only DOM to load with Selenium (without images)
There is a long list of the images on the page. There is an AJAX "Load more images" button in the application (at the bottom of the page) which is activated automatically when user scrolling page down. I want to scroll the page to the very end with Selenium and make sure that there is no button "Load more images" at t...
[ "You can wait for browser/document status to interactive. That is wait for js condition\ndocument.readyState='interactive'\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium", "webdriver" ]
stackoverflow_0007881189_python_selenium_webdriver.txt
Q: Network Shares listing I am in a process to write a lan scan application in python or ironpython . But, it is turning out to be not that easy due to lack of good libraries !! (yes, even i am surprised!! maybe i did'nt search well enough). THIS is one library in c# and seems very easy to use for the purpose. And,...
Network Shares listing
I am in a process to write a lan scan application in python or ironpython . But, it is turning out to be not that easy due to lack of good libraries !! (yes, even i am surprised!! maybe i did'nt search well enough). THIS is one library in c# and seems very easy to use for the purpose. And, as per this SO post it ...
[ "Look into WMI. Here is a ref to Python library that lets you access WMI queries http://timgolden.me.uk/python/wmi/index.html here is a link to how to use WMI to get a list of network shares http://vbscriptblog.com/vbscript/wmi/shares/wmi-vbscript-to-show-the-network-shares-of-a-computer/ the last script is in V...
[ 0 ]
[]
[]
[ "ironpython", "lan", "python", "smb", "windows" ]
stackoverflow_0007884737_ironpython_lan_python_smb_windows.txt
Q: ForeignKey to abstract class (generic relations) I'm building a personal project with Django, to train myself (because I love Django, but I miss skills). I have the basic requirements, I know Python, I carefully read the Django book twice if not thrice. My goal is to create a simple monitoring service, with a Djan...
ForeignKey to abstract class (generic relations)
I'm building a personal project with Django, to train myself (because I love Django, but I miss skills). I have the basic requirements, I know Python, I carefully read the Django book twice if not thrice. My goal is to create a simple monitoring service, with a Django-based web interface allowing me to check status of ...
[ "For a start, use Django's multi-table inheritance, rather than the abstract model you have currently.\nYour code would then become:\nfrom django.db import models\n\nclass Service(models.Model):\n port = models.PositiveIntegerField()\n\nclass SSHService(Service):\n username = models.CharField(max_length=64)\n...
[ 16, 7, 1, 0 ]
[]
[]
[ "django", "model", "model_view_controller", "python" ]
stackoverflow_0007884359_django_model_model_view_controller_python.txt
Q: Keyboard Strokes Python How does one apply a keystroke to console code without using Pygame's event checking system. I would prefer something that internalizes the loop and only requires a main running loop. A: I'm fairly new to Python myself, but when I looked into the tkinter GUI framework I came across a way...
Keyboard Strokes Python
How does one apply a keystroke to console code without using Pygame's event checking system. I would prefer something that internalizes the loop and only requires a main running loop.
[ "I'm fairly new to Python myself, but when I looked into the tkinter GUI framework I came across a way to make keystrokes perform commands.\nHere's the detailed page regarding keyboard strokes, although you probably should read from earlier in the tutorial to get a hang on things:\nhttp://infohost.nmt.edu/tcc/help/...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007884712_python.txt
Q: Another Token error: EOF in multi-line statement The following code gives me this error "Token Error: EOF in multi-line statement". I cannot seem to find the error though! Maybe someone else will see it? import easygui import time namegui = easygui.enterbox(msg='Enter your name:', title='Name query', default='Gian...
Another Token error: EOF in multi-line statement
The following code gives me this error "Token Error: EOF in multi-line statement". I cannot seem to find the error though! Maybe someone else will see it? import easygui import time namegui = easygui.enterbox(msg='Enter your name:', title='Name query', default='Gian') situationgui = easygui.enterbox(msg='Please enter y...
[ "You are missing a closing ) for variable thinking_trapsgui. Check if thats the problem.\nA missing ) usually gives a Syntax Error so I am not really sure, but EOF multi-line Token Error could be pointing to that.\nEDIT\nYou have written\nthinking_trapsgui = easygui.choicebox(\n msg='Please identify your thinkin...
[ 1 ]
[]
[]
[ "easygui", "python", "tkinter", "user_interface" ]
stackoverflow_0007885740_easygui_python_tkinter_user_interface.txt
Q: Converting Markov Chain Python Script to PHP. Not sure of what some of the equivalent functions are in PHP I've seen this Markov Chain gibberish detector written in response to another question on Stackoverflow and I would like to convert it to PHP, I'm not looking for someone to do this for me, but I am confused ...
Converting Markov Chain Python Script to PHP. Not sure of what some of the equivalent functions are in PHP
I've seen this Markov Chain gibberish detector written in response to another question on Stackoverflow and I would like to convert it to PHP, I'm not looking for someone to do this for me, but I am confused over portions of the Python code that I have no knowledge of. I've looked at the python docs but it confuses me ...
[ "1. What is the PHP equivalent of yield?\nThere is no equivalent to yield in PHP. yield is used in generator functions - a special class of function that returns a result but retains its state.\nFor example:\ndef simple_generator(start=0, end=100):\n while start < end:\n start += 1\n yield start\ng...
[ 4, 1 ]
[]
[]
[ "markov_chains", "php", "python" ]
stackoverflow_0007885761_markov_chains_php_python.txt
Q: related to List (want to insert into database) I have two List. first list element Name Age Sex and second list element test 10 female. I want to insert this data into database. In first list having MySQL Column and in second MySQL Column Values.I'm trying to make this query. INSERT INTO (LIST1) VALUES (List2) =>...
related to List (want to insert into database)
I have two List. first list element Name Age Sex and second list element test 10 female. I want to insert this data into database. In first list having MySQL Column and in second MySQL Column Values.I'm trying to make this query. INSERT INTO (LIST1) VALUES (List2) =>INSERT INTO table (name,age,sex) values (test,10,fem...
[ "How about this?\n>>> query = 'INSERT INTO (%s) VALUES (%s)' % (','.join([str(i) for i in list1]),\n ','.join([str(i) for i in list2]))\n>>> print query\nINSERT INTO (name,age,sex) VALUES (test,10,female)\n\nThe str is needed because that way, numbers are allowed to be i...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007886024_python.txt
Q: python issue regarding "LearnPythonTheHardWay" book, ex18 Im having some issues to get exercise 18 'Names, variables, code, functions' to work. And to be very honest, i dont quite understand it either, like I didnt fully understand couple previous ones, but yeah. Here is the code i've writed: def print_two(*args):...
python issue regarding "LearnPythonTheHardWay" book, ex18
Im having some issues to get exercise 18 'Names, variables, code, functions' to work. And to be very honest, i dont quite understand it either, like I didnt fully understand couple previous ones, but yeah. Here is the code i've writed: def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" %(arg1, a...
[ "Looks like you're missing a colon on the print_none() line.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007886398_python.txt
Q: defaultdict(None) I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example: states = defaultdict(None) if new_state_1 != states["State 1"]: dispatch_transition() I would have thought ...
defaultdict(None)
I wish to have a dictionary which contains a set of state transitions. I presumed that I could do this using states = defaultdict(None), but its not working as I expected. For example: states = defaultdict(None) if new_state_1 != states["State 1"]: dispatch_transition() I would have thought that states["State 1"] ...
[ "defaultdict requires a callable as argument that provides the default-value when invoked without arguments. None is not callable. What you want is this:\ndefaultdict(lambda: None)\n\n", "In this use case, don't use defaultdict at all -- a plain dict will do just fine:\nstates = {}\nif new_state_1 != states.get(\...
[ 119, 14, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007886355_python.txt
Q: How can I keep a Python script command window open when opened from a .Net application? Now the obvious answer is to just open the script from a command line, but that isn't an option. I'm writing a simple application to syntax highlight Python and then run the scripts from the same program. A Python IDE if you ...
How can I keep a Python script command window open when opened from a .Net application?
Now the obvious answer is to just open the script from a command line, but that isn't an option. I'm writing a simple application to syntax highlight Python and then run the scripts from the same program. A Python IDE if you will. The scripts I want to run are entirely command line programs. I'm using a System.Diagn...
[ "Don't use a Windows console. Create your own console panel or window which attaches to the stdin, stdout, and stderr of the interpreter executable. Or embed your own interpreter.\n", "I had a similar issue, I solved it by adding raw_input() at the end of the script. \nEven if it's not using the value the script ...
[ 1, 0 ]
[]
[]
[ "c#", "command_line", "python" ]
stackoverflow_0002277571_c#_command_line_python.txt
Q: ForeignKey field with another ForeignKey in FormWizard with MultiValueField I have a model with a ForeignKey to another model that also has a ForeignKey. I am rendering it with a django form wizard (trying to support as old a django version as possible) which is not inlineformset friendly. I want the user to put i...
ForeignKey field with another ForeignKey in FormWizard with MultiValueField
I have a model with a ForeignKey to another model that also has a ForeignKey. I am rendering it with a django form wizard (trying to support as old a django version as possible) which is not inlineformset friendly. I want the user to put in both models and extra information in the form wizard and translate that into th...
[ "I figured this out I think. The answer was to use a MultiWidget subclass but not to subclass a MultiValueField. I just point my topics field to my SubjectTopicInput which inherits MultiWidget and then in addition to decompress I subclass value_from_datadict to return the pk (I know I can make it prettier but this ...
[ 1 ]
[]
[]
[ "django", "django_forms", "django_formwizard", "python" ]
stackoverflow_0007877678_django_django_forms_django_formwizard_python.txt
Q: Selecting a Python Class I have some servers of varying age here that are running varying versions of Python. On these servers I am running a script that requires MySQL interaction. I have written a wrapper class that uses the Python MySQLdb module, but on the older servers this module doesn't exist. To get around...
Selecting a Python Class
I have some servers of varying age here that are running varying versions of Python. On these servers I am running a script that requires MySQL interaction. I have written a wrapper class that uses the Python MySQLdb module, but on the older servers this module doesn't exist. To get around this, I'd like to find if the...
[ "If both modules have the same API, the usual way is to import one of them under some common name:\ntry:\n import MySQLdb as mysql\nexcept ImportError:\n import mymodule as mysql\n\nand then use that name as usual.\n" ]
[ 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007886862_class_python.txt
Q: Change empty_label for Django forms I'm having some problems in changing the empty label for a form. I've read the documentation https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField and some pages here on stackoverflow, but I still don't get it. In my models, I have a tuple of coun...
Change empty_label for Django forms
I'm having some problems in changing the empty label for a form. I've read the documentation https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField and some pages here on stackoverflow, but I still don't get it. In my models, I have a tuple of countiescounty_choices = (('county1', _('coun...
[ "Create a model for the counties and syncdb. This way you can manipulate and access them with a queryset, same way you do with Users. i.e. queryset=Counties.objects.all().\nLook at the ModelChoiceField documentation for more help.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0007886855_django_django_forms_django_models_python.txt
Q: creating new python objects seems to be the same object I have a problem with objects. The following code class Data: def __init__(self,data=[]): self.data = data def add(self,data): self.data.extend(data) class Parent: def testa(self): a = Data() a.add('a') pri...
creating new python objects seems to be the same object
I have a problem with objects. The following code class Data: def __init__(self,data=[]): self.data = data def add(self,data): self.data.extend(data) class Parent: def testa(self): a = Data() a.add('a') print a.data def testb(self): b = Data() b.a...
[ "Using [] as a default argument to a function will only create a list once, and reuse this list on each call. See http://docs.python.org/tutorial/controlflow.html#default-argument-values for an explanation. Thus, both Data objects share the list referenced by their self.data member!\nYou should modify your code lik...
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0007887193_python.txt
Q: pyinstaller seems not to find a data file Edit 3: I replaced __file__ with sys.argv[0], when I need to know the location of my script/executable. This is not exactly the same, but in my case it seems to run fine (at least on executable version...). Now everything is working fine, in one-file mode, with use of acce...
pyinstaller seems not to find a data file
Edit 3: I replaced __file__ with sys.argv[0], when I need to know the location of my script/executable. This is not exactly the same, but in my case it seems to run fine (at least on executable version...). Now everything is working fine, in one-file mode, with use of accepted answer's function to access resource files...
[ "Firstly, it might be wise to do a print config_file / os.path.exists(config_file) before reading it, so you can be sure where the file is and if python can find it. \nAs to actually accessing it, os.path.split(__file__) looks almost correct, but I'm not sure it works properly under pyinstaller - the proper way of ...
[ 10, 0, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0007838606_pyinstaller_python.txt
Q: Python Assign-Print statement? So I'm writing some python scripts to help me do some simple calculations: WireRadius = .455 / 1000 / 2 #m, 25AWG CoilInnerRadius = 10.0 / 1000 / 2 #m CoilOuterRadius = 20.0 / 1000 / 2 #m CoilLength = 20.0 / 1000 #m CoilVolume = 3.14 * (CoilOuterRadius**2 - CoilInnerRadius**2) * Coi...
Python Assign-Print statement?
So I'm writing some python scripts to help me do some simple calculations: WireRadius = .455 / 1000 / 2 #m, 25AWG CoilInnerRadius = 10.0 / 1000 / 2 #m CoilOuterRadius = 20.0 / 1000 / 2 #m CoilLength = 20.0 / 1000 #m CoilVolume = 3.14 * (CoilOuterRadius**2 - CoilInnerRadius**2) * CoilLength #m^3 print "CoilVolume: " + ...
[ "def debug(val):\n logging.debug('DEBUG: %r', val)\n return val\n\n ...\nLengthOfWire = debug(CoilVolume / WireCrossSection / 2)\n\nDon't forget to set up your logger appropriately.\n", "An improved version of Ignacio's function:\nimport logging\n\ndef debug(val, label=None):\n \"\"\"Prints a debug message con...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007884722_python.txt
Q: Scrapy SgmlLinkExtractor question I am trying to make the SgmlLinkExtractor to work. This is the signature: SgmlLinkExtractor(allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths(), tags=('a', 'area'), attrs=('href'), canonicalize=True, unique=True, process_value=None) I am just using allow=() So...
Scrapy SgmlLinkExtractor question
I am trying to make the SgmlLinkExtractor to work. This is the signature: SgmlLinkExtractor(allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths(), tags=('a', 'area'), attrs=('href'), canonicalize=True, unique=True, process_value=None) I am just using allow=() So, I enter rules = (Rule(SgmlLinkExtract...
[ "You are overriding the \"parse\" method it appears. \"parse\", is a private method in CrawlSpider used to follow links.\n", "if you check documentation a \"Warning\" is clearly written \n\"When writing crawl spider rules, avoid using parse as callback, since the Crawl Spider uses the parse method itself to impl...
[ 10, 3, 1, 1 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0001809817_python_scrapy_web_crawler.txt
Q: How to continue after the return command in python? Imagine we have a piece of code which cuts the large data into smaller data and do some process on it. def node_cut(input_file): NODE_LENGTH = 500 count_output = 0 node_list=[] for line in input_file.readlines(): if len(node_list) >= NOD...
How to continue after the return command in python?
Imagine we have a piece of code which cuts the large data into smaller data and do some process on it. def node_cut(input_file): NODE_LENGTH = 500 count_output = 0 node_list=[] for line in input_file.readlines(): if len(node_list) >= NODE_LENGTH : count_output += 1 r...
[ "Use yield:\ndef node_cut(input_file):\n NODE_LENGTH = 500\n count_output = 0\n node_list=[]\n\n for line in input_file.readlines():\n if len(node_list) >= NODE_LENGTH :\n count_output += 1 \n yield( node_list,count_output )\n node_list=[] \n\n node,t=li...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0007887621_python.txt
Q: Python large app: how to use other modules that might be needed or not, depending on the request given? I have a web app in python and there is a main file that is a router. The router reads the path and should: only now import the module needed for the request, or call the method directly. (In this case all modu...
Python large app: how to use other modules that might be needed or not, depending on the request given?
I have a web app in python and there is a main file that is a router. The router reads the path and should: only now import the module needed for the request, or call the method directly. (In this case all modules needed by the app are imported at the beginning of the file) In the first case: router(path, args): ...
[ "From PEP 8, \"Style Guide for Python Code\":\n\nImports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.\n\nUnless you have a good reason to violate this, follow it.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007887785_python.txt
Q: How can I use a Python streaming socket as a proxy? I'm trying to write a python process which listens on a port and when a client connects to it, it starts up a thread which does the following: Connects to a remote service (http://193.108.24.18:8000/magicFM) Passes any data received to the connected client (whi...
How can I use a Python streaming socket as a proxy?
I'm trying to write a python process which listens on a port and when a client connects to it, it starts up a thread which does the following: Connects to a remote service (http://193.108.24.18:8000/magicFM) Passes any data received to the connected client (which happens to be Windows Media Player) The story is tha...
[ "As a start, to connect to a remote site using TCP, use this code\nimport socket, struct\n\ndef connectToHost(host, port=80, timeout=0):\n try:\n sock=socket.socket()\n timeval=struct.pack(\"2I\", timeout, 0)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)\n ...
[ 2, 1, 0 ]
[]
[]
[ "proxy", "python", "sockets", "streaming" ]
stackoverflow_0007875369_proxy_python_sockets_streaming.txt
Q: Are there any more Unobtrusive Server-side Scripts like hQuery for easier templating? I came across this interesting templating tool, what the author calls as hQuery which is an 'Unobtrusive Server-side Scripting'. [More information here - https://github.com/choonkeat/hquery ]. It is built in Ruby for the RoR plat...
Are there any more Unobtrusive Server-side Scripts like hQuery for easier templating?
I came across this interesting templating tool, what the author calls as hQuery which is an 'Unobtrusive Server-side Scripting'. [More information here - https://github.com/choonkeat/hquery ]. It is built in Ruby for the RoR platform. I wanted to know if something similar is available for other platforms (PHP, Python, ...
[ "Not that I know of, but I have been doing something similar in concept, although a lot more simple, in PHP using phpQyery and some custom html-like markup.\nFor instance, here is a simplified non-standard html chunk:\n<bodynode>\n<!--[if lt IE 9]>\n<script src=\"//html5shiv.googlecode.com/svn/trunk/html5.js\"></sc...
[ 1, 0 ]
[]
[]
[ "php", "python", "ruby", "templating_engine" ]
stackoverflow_0007887917_php_python_ruby_templating_engine.txt
Q: combining ctypes and swig I have been using SWIG for a long time - generally I like it. But doing callback functions seems (much) easier using ctypes. How can I combine the two "ways" of interacting with a C dll ? The first step would be to know, how to get a ctypes object to the dll after the dll is already load...
combining ctypes and swig
I have been using SWIG for a long time - generally I like it. But doing callback functions seems (much) easier using ctypes. How can I combine the two "ways" of interacting with a C dll ? The first step would be to know, how to get a ctypes object to the dll after the dll is already loaded via the import of the corres...
[ "The Buffer Protocol may be your best bet ( http://docs.python.org/c-api/buffer.html ). \nFrom C code (eg swig generated code) you can get the pointer to the underlying C data by accessing this interface.\nWatch out there are two versions of the buffer interface, ctypes objects in python 2.x will expose the old pro...
[ 0, 0 ]
[]
[]
[ "ctypes", "python", "swig" ]
stackoverflow_0007886790_ctypes_python_swig.txt
Q: Unable to invoke/call a Python method can't get my class variables working properly, class World: def __init__(self, size): self.size = size self.grid = [] for i in range(0,size): self.grid.append([]) for j in range(0,size): self.grid[i].append(0) def Display(self): ...
Unable to invoke/call a Python method
can't get my class variables working properly, class World: def __init__(self, size): self.size = size self.grid = [] for i in range(0,size): self.grid.append([]) for j in range(0,size): self.grid[i].append(0) def Display(self): for row in self.grid: print row Th...
[ "You are not calling the function, you are merely referencing the function object. Try:\nTheWorld.Display()\n\n", "Well that should be because you have not actually called the Display function. You have to say\nTheWorld.Display()\n\nfor the function to be actually called. \n", "This is not VBA. I have to call t...
[ 8, 3, 1, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007888181_class_python.txt
Q: deploying a WSGI application on mod_python I wrote a WSGI application which I need to deploy to a server, however I've been given a server that already has mod_python installed. I am not allowed to remove mod_python since there are some mod_python applications running on it already. One option I considered was ins...
deploying a WSGI application on mod_python
I wrote a WSGI application which I need to deploy to a server, however I've been given a server that already has mod_python installed. I am not allowed to remove mod_python since there are some mod_python applications running on it already. One option I considered was installing mod_wsgi alongside mod_python, however I...
[ "You can use mod_python and mod_wsgi together so long as same Python version and mod_python not linked against a static Python library.\nRun the 'ldd' command on the mod_python.so file:\nldd mod_python.so\n\nto find out if it links to libpythonX.Y.so. Build mod_wsgi to use same Python version, ensuring it is simila...
[ 3, 2, 1, 0 ]
[]
[]
[ "mod_fastcgi", "mod_python", "mod_wsgi", "python" ]
stackoverflow_0007881474_mod_fastcgi_mod_python_mod_wsgi_python.txt