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:
print_r functionality in iPython
Is there a way to get PHP-like print_r(object) funcionality in iPython?
I know I can use '?' to get info about an object, but how do I view the values of the object?
A:
Is
print my_object.__dict__
perhaps what you are looking for?
Or have a look at the standard python pretty pr... | print_r functionality in iPython | Is there a way to get PHP-like print_r(object) funcionality in iPython?
I know I can use '?' to get info about an object, but how do I view the values of the object?
| [
"Is \nprint my_object.__dict__\n\nperhaps what you are looking for?\nOr have a look at the standard python pretty printer for more advanced, recursive printing.\n",
"dir(object) will give you all its attribute names.\n",
"I'd use the pprint module if you want it to be nicely formatted:\nimport pprint\nobj = {'a... | [
3,
2,
1,
0
] | [] | [] | [
"ipython",
"object",
"php",
"python"
] | stackoverflow_0002317921_ipython_object_php_python.txt |
Q:
How do I use a regular expression to match a name?
I am a newbie in Python. I want to write a regular expression for some name checking.
My input string can contain a-z, A-Z, 0-9, and ' _ ', but it should start with either a-z or A-Z (not 0-9 and ' _ '). I want to write a regular expression for this. I tried, but... | How do I use a regular expression to match a name? | I am a newbie in Python. I want to write a regular expression for some name checking.
My input string can contain a-z, A-Z, 0-9, and ' _ ', but it should start with either a-z or A-Z (not 0-9 and ' _ '). I want to write a regular expression for this. I tried, but nothing was matching perfectly.
Once the input string f... | [
"Here's an answer to your question:\nInterpreting that you want _ (not -), this should do the job:\n>>> tests = [\"a\", \"A\", \"a1\", \"a_1\", \"1a\", \"_a\", \"a\\n\", \"\", \"z_\"]\n>>> for test in tests:\n... print repr(test), bool(re.match(r\"[A-Za-z]\\w*\\Z\", test))\n...\n'a' True\n'A' True\n'a1' True\n'a... | [
7,
4
] | [
"here's a non re way\nimport string\nflag=0\nmystring=\"abcadsf123\"\nif not mystring[0] in string.digits+\"_\":\n for c in mystring:\n if not c in string.letters+string.digits+\"-\":\n flag=1\n if flag: print \"%s not ok\" % mystring\n else: print \"%s ok\" % mystring\nelse: print \"%s sta... | [
-1
] | [
"python",
"regex"
] | stackoverflow_0002317134_python_regex.txt |
Q:
Python Environment Variables in Windows?
I'm developing a script that runs a program with other scripts over and over for testing purposes.
How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch t... | Python Environment Variables in Windows? | I'm developing a script that runs a program with other scripts over and over for testing purposes.
How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.
For som... | [
"You could use atexit to write a small file (flag.txt) when script1.py exits. mainscript.py could regularly be checking for the existence of flag.txt and when it finds it, will kill program.exe and exit.\nEdit:\nI've set persistent environment variables using this, but I only use it for python-based installation s... | [
1,
0,
0
] | [] | [] | [
"environment_variables",
"python",
"testing",
"windows"
] | stackoverflow_0000923586_environment_variables_python_testing_windows.txt |
Q:
is there a limit to command.getstatusoutput() buffer in python
I have created a script to run a test script on a batch of files,have been testing it overnight for two nights, however it just hangs at a certain point.
I was wondering if the the commands.getstatusoutput() is the issue here since the test script is ... | is there a limit to command.getstatusoutput() buffer in python | I have created a script to run a test script on a batch of files,have been testing it overnight for two nights, however it just hangs at a certain point.
I was wondering if the the commands.getstatusoutput() is the issue here since the test script is has a heavy logging mechanism.
Update:
How is using subprocess modu... | [
"The method getstatusoutput() returns a string, which can be very long and therefore take up a lot of space and cause paging to disk and other nasty things. \nSince the commands module is deprecated anyway, better use the subprocess module which provides a file-like access to the process output. If you need the ou... | [
6
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0002318881_linux_python.txt |
Q:
Simple question: In numpy how do you make a multidimensional array of arrays?
Right, perhaps I should be using the normal Python lists for this, but here goes:
I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.
So, ... | Simple question: In numpy how do you make a multidimensional array of arrays? | Right, perhaps I should be using the normal Python lists for this, but here goes:
I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.
So, I want to be able to go something like
column = 0 ... | [
"Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values \nmay complicate your code and force you to use loops instead of built-in numpy functions.\nIt may be worth investing the time to refactor your co... | [
8,
0
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0002318667_arrays_multidimensional_array_numpy_python.txt |
Q:
Dictionaries in Python
I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries).
d1={key1:1, key2:2}
d2={key1:1,... | Dictionaries in Python | I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries).
d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
I want t... | [
"Try this:\nimport collections\nmerged = collections.defaultdict(list)\nfor k in d1:\n merged[k].append( d1[k] )\nfor k in d2:\n merged[k].append( d2[k] )\n\nThis may be what you're looking for.\nOr possibly this.\nimport collections\nmerged = collections.defaultdict(set)\nfor k in d1:\n merged[k].add( d1[k] ... | [
13,
6,
4,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0000631463_dictionary_python.txt |
Q:
django and sqlalchemy
I'm fairly new to Django and have a basic question: I want to use an ORM that I can work with it for Django and other python projects, so the basic question is Django ORM agnostic and if so how can I use SQLAlchemy with it for example?
If it's not, then what do you suggest for the above prob... | django and sqlalchemy | I'm fairly new to Django and have a basic question: I want to use an ORM that I can work with it for Django and other python projects, so the basic question is Django ORM agnostic and if so how can I use SQLAlchemy with it for example?
If it's not, then what do you suggest for the above problem (using ORM objects that... | [
"Option 1: Use the Django ORM for other projects. Using only the DB part of Django\nThis works well. I prefer it.\nOption 2: Use SQLAlchemy with Django. SQLAlchemy and django, is it production ready? and Configuring Django to use SQLAlchemy\nThis works well, also. I don't prefer it because I don't like reconfigu... | [
14
] | [] | [] | [
"django",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0002319231_django_orm_python_sqlalchemy.txt |
Q:
Python+parsing custom config file
I have a quite big custom made config file I need to extract data from once a week. This is an "in house" config file which doesn't comply to any know standard like INI or such.
My quick and dirty approach was to use re to search for the section header I want and then extract the ... | Python+parsing custom config file | I have a quite big custom made config file I need to extract data from once a week. This is an "in house" config file which doesn't comply to any know standard like INI or such.
My quick and dirty approach was to use re to search for the section header I want and then extract the one or 2 lines of information under thi... | [
"A simple parser using pyparsing can give you something close to a deserializer, that would let you access fields by key name (like in a dict), or as attributes. Here is the parser:\nfrom pyparsing import (Suppress,quotedString,removeQuotes,Word,alphas,\n alphanums, printables,delimitedList,Group,Dict,ZeroO... | [
2,
1,
0,
0
] | [] | [] | [
"config",
"file",
"parsing",
"python"
] | stackoverflow_0002317070_config_file_parsing_python.txt |
Q:
PyQt beginremoverows
In the example below:
from PyQt4 import QtCore, QtGui
class Ui_Dialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setObjectName("Dialog")
self.resize(600, 500)
self.model = QtGui.QDirModel()
self.tree =... | PyQt beginremoverows | In the example below:
from PyQt4 import QtCore, QtGui
class Ui_Dialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setObjectName("Dialog")
self.resize(600, 500)
self.model = QtGui.QDirModel()
self.tree = QtGui.QTreeView()
... | [
"\nI know I'm making mistake on this\n line:\nself.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))\n\n\nYes, you're right. Let's look at what you're passing in:\nindex.parent() - the parent of index\nindex.row() - the row number of index, the row you want deleted\nself.model.rowCount(... | [
4,
0,
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0002240582_pyqt_python.txt |
Q:
django, admin template error Caught an exception while rendering: 'NoneType' object has no attribute 'label'
good day guys!
in project, among others, have models:
class Category(models.Model):
name = models.CharField(max_length = 50, blank = False, null = False)
def __unicode__(self):
return "Cat... | django, admin template error Caught an exception while rendering: 'NoneType' object has no attribute 'label' | good day guys!
in project, among others, have models:
class Category(models.Model):
name = models.CharField(max_length = 50, blank = False, null = False)
def __unicode__(self):
return "Category %s" % self.name
class Meta:
db_table = "categories"
managed = False
class Site(models... | [
"For that you need to add undocumented formfield_for_manytomany method to your SiteAdmin class:\nfrom django.contrib.admin import widgets\n\nclass SitebAdmin(admin.ModelAdmin):\n\n list_display = ('id', 'name')\n list_filter = ('name', 'categories')\n\n def formfield_for_manytomany(self, db_field, request, **... | [
1
] | [] | [] | [
"django_admin",
"django_models",
"django_templates",
"python"
] | stackoverflow_0002319649_django_admin_django_models_django_templates_python.txt |
Q:
python & sql server
When I do a select statement for varbinary field in microsoft enterprise manager i get the field on readabel hex format like ab2c2f2d... but when i do the same statment with pymssql i get a gibrish
the select statment is : select x from table --where x the varbinary field
could someone help wi... | python & sql server | When I do a select statement for varbinary field in microsoft enterprise manager i get the field on readabel hex format like ab2c2f2d... but when i do the same statment with pymssql i get a gibrish
the select statment is : select x from table --where x the varbinary field
could someone help with this issue ?
| [
"Microsoft Enterprise Manager is converting the binary value to a hexadecimal string for you. \nOne option is to change your query to SELECT CAST( x AS varchar ) FROM table. This will have SQL Server convert the varbinary to a hexdecimal string for you, http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).asp... | [
2
] | [] | [] | [
"python",
"sql_server"
] | stackoverflow_0002320342_python_sql_server.txt |
Q:
Python: Fastest way to iterate this through a large file
Right, I'm iterating through a large binary file
I need to minimise the time of this loop:
def NB2(self, ID_LEN):
r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)
num_receivers=r1[0][0]
num_channels=r1[0][1]
num_samples=r1[0][5]
blockReturn ... | Python: Fastest way to iterate this through a large file | Right, I'm iterating through a large binary file
I need to minimise the time of this loop:
def NB2(self, ID_LEN):
r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)
num_receivers=r1[0][0]
num_channels=r1[0][1]
num_samples=r1[0][5]
blockReturn = np.zeros((num_samples,num_receivers,num_channels))
for ... | [
"import numpy as np\ndef NB2(self, ID_LEN):\n r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)\n num_receivers=r1[0][0]\n num_channels=r1[0][1]\n num_samples=r1[0][5]\n\n # first, match your array bounds to the way you are walking the file\n blockReturn = np.zeros((num_receivers,num_channels,num_sampl... | [
3,
3,
1,
1,
0
] | [] | [] | [
"binary",
"iteration",
"numpy",
"python"
] | stackoverflow_0002319928_binary_iteration_numpy_python.txt |
Q:
python egg development environment setup
I inherited a python project, which has been packaged as egg. Upon check out through SVN, I am seeing package content as:
__init__.py
scripts/
ptools/
setup.py
...
Here, ptools/ hold the source of various modules. scripts/ is bunch of end-user tools that make use of module... | python egg development environment setup | I inherited a python project, which has been packaged as egg. Upon check out through SVN, I am seeing package content as:
__init__.py
scripts/
ptools/
setup.py
...
Here, ptools/ hold the source of various modules. scripts/ is bunch of end-user tools that make use of modules provided by the "ptools". The package has be... | [
"I think I have found the solution to my problem, and this has been answered in the following post. \"setup.py develop\" seems to be the perfect solution\nPYTHONPATH vs. sys.path\n",
"You can use the PYTHONPATH environment variable to customize the locations Python searches for modules.\n"
] | [
1,
0
] | [] | [] | [
"egg",
"python",
"setuptools"
] | stackoverflow_0002316052_egg_python_setuptools.txt |
Q:
Python and curl question
I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
$xml= Some xml holding data... | Python and curl question | I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
$xml= Some xml holding data of a purchase.
$curl = `/usr/... | [
"Use of the standard library urllib2 module should be enough:\nimport urllib\nimport urllib2\n\nrequest_data = urllib.urlencode({\"DATA\": xml})\nresponse = urllib2.urlopen(\"https://url of the virtual bank POS\", request_data)\n\nresponse_data = response.read()\ndata = response_data.split('\\n')\n\nI assume that x... | [
10,
3
] | [] | [] | [
"curl",
"django",
"python"
] | stackoverflow_0002320107_curl_django_python.txt |
Q:
Yet another Subversion "Commit failed" MERGE of 'blabla': 200 OK
I get the infamous "MERGE of 'whatever': 200 OK" whenever I try to commit using a post-commit hook on Windows (running the repository and Trac locally), and I'm going crazy. I've been looking all over for a day now, without finding any solutions.
So ... | Yet another Subversion "Commit failed" MERGE of 'blabla': 200 OK | I get the infamous "MERGE of 'whatever': 200 OK" whenever I try to commit using a post-commit hook on Windows (running the repository and Trac locally), and I'm going crazy. I've been looking all over for a day now, without finding any solutions.
So here's how it's set up and what I've tried so far:
Settings:
Windows 7... | [
"To get the error message while doing the SVN commit, you should be able to change:\nif __name__ == \"__main__\": \n if len(sys.argv) < 5: \n print \"For usage: %s --help\" % (sys.argv[0]) \n else: \n CommitHook() \n\nto:\nif __name__ == \"__main__\": \n if len(sys.argv) < 5: \n print ... | [
0
] | [] | [] | [
"post_commit",
"python",
"svn",
"tortoisesvn",
"visualsvn_server"
] | stackoverflow_0002320787_post_commit_python_svn_tortoisesvn_visualsvn_server.txt |
Q:
Is it just me...or is "Facebook Mobile Web" only for PHP?
http://wiki.developers.facebook.com/index.php/Mobile
I use Django/Python as my mobile website.
Am I missing something?
A:
The library may be "officially' for PHP, But that doesnt stop you from making your own.
I would suggest looking at the API. You may b... | Is it just me...or is "Facebook Mobile Web" only for PHP? | http://wiki.developers.facebook.com/index.php/Mobile
I use Django/Python as my mobile website.
Am I missing something?
| [
"The library may be \"officially' for PHP, But that doesnt stop you from making your own.\nI would suggest looking at the API. You may be able to port the calls to python using python's httplib.\nAll the PHP library does is make curl POST and GET calls to Facebook's REST server. \nIf you are familiar with PHP or Ja... | [
3,
1
] | [] | [] | [
"django",
"facebook",
"mobile",
"php",
"python"
] | stackoverflow_0002316802_django_facebook_mobile_php_python.txt |
Q:
How to get the original TCP connection hostname in Python Twisted?
With Twisted's TCP mechanisms, when a protocol is created, the only information about the peer is its IP address and port. How can I retrieve the original hostname that I tried to connect with?
reactor.connectTCP('somehost.com', 80, MyFactory)
How... | How to get the original TCP connection hostname in Python Twisted? | With Twisted's TCP mechanisms, when a protocol is created, the only information about the peer is its IP address and port. How can I retrieve the original hostname that I tried to connect with?
reactor.connectTCP('somehost.com', 80, MyFactory)
How can I ever get 'somehost.com' through a callback somehow? In other word... | [
"Jerub's answer makes sense semantically. After digging through Twisted code, there is a more expedient and direct way of doing specifically what I'm trying to achieve.\nIn protocol:\ndef connectionMade(self):\n # This is the original connector that connectTCP returned\n connector = self.transport.connector\n... | [
3,
2
] | [] | [] | [
"python",
"tcp",
"twisted"
] | stackoverflow_0002316365_python_tcp_twisted.txt |
Q:
In Python, what's a good pattern for disabling certain code during unit tests?
In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can yo... | In Python, what's a good pattern for disabling certain code during unit tests? | In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can you please not make your call to solr, instead can you please stick what you would sen... | [
"You can use Mock objects to intercept the method calls that you do not want to execute. \nE.g. You have some class A, where you don't want method no() to be called during a test.\nclass A:\n def do(self):\n print('do')\n def no(self):\n print('no')\n\nA mock object could inherit from A and override no() to... | [
7,
5,
1,
0,
0,
0
] | [] | [] | [
"dependency_injection",
"python",
"testing",
"unit_testing"
] | stackoverflow_0002320210_dependency_injection_python_testing_unit_testing.txt |
Q:
Why am I getting the error "cannot import name Scanner" when I try to use the mwclient module for Python?
I'm using Python 2.5.2 (because mwclient still only works for 2.x). I've copied the mwclient folder into the /usr/lib/python2.5/site-packages/mwclient folder, and when I run a program that imports mwclient I g... | Why am I getting the error "cannot import name Scanner" when I try to use the mwclient module for Python? | I'm using Python 2.5.2 (because mwclient still only works for 2.x). I've copied the mwclient folder into the /usr/lib/python2.5/site-packages/mwclient folder, and when I run a program that imports mwclient I get this:
Traceback (most recent call last):
File "get_wiki.py", line 2, in <module>
import mwclient
F... | [
"Remove the simplejson subdirectory in mwclient if you already have simplejson installed. Or download the latest version from SVN; it has been fixed.\n"
] | [
2
] | [] | [] | [
"import",
"mediawiki",
"module",
"python",
"wikipedia"
] | stackoverflow_0002307805_import_mediawiki_module_python_wikipedia.txt |
Q:
How to create nested lists in python?
I know you can create easily nested lists in python like this:
[[1,2],[3,4]]
But how to create a 3x3x3 matrix of zeroes?
[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
or
[[[0]*3]*3]*3
Doesn't seem right. There is no way to create it just passing a list of dimension... | How to create nested lists in python? | I know you can create easily nested lists in python like this:
[[1,2],[3,4]]
But how to create a 3x3x3 matrix of zeroes?
[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
or
[[[0]*3]*3]*3
Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex:
CreateArray([3,3,3])
| [
"In case a matrix is actually what you are looking for, consider the numpy package.\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros\nThis will give you a 3x3x3 array of zeros:\nnumpy.zeros((3,3,3)) \n\nYou also benefit from the convenience features of a module built for scientific ... | [
9,
1,
1,
0
] | [
"Just nest the multiplication syntax:\n[[[0] * 3] * 3] * 3\n\nIt's therefore simple to express this operation using folds\ndef zeros(dimensions):\n return reduce(lambda x, d: [x] * d, [0] + dimensions)\n\nOr if you want to avoid reference replication, so altering one item won't affect any other you should instea... | [
-3
] | [
"arrays",
"list",
"matrix",
"nested_lists",
"python"
] | stackoverflow_0002173087_arrays_list_matrix_nested_lists_python.txt |
Q:
How to get the status of an Asterisk Server using a Socket - Python
I'm trying to get the status of an Asterisk Server using a python socket but nothing happens.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params ... | How to get the status of an Asterisk Server using a Socket - Python | I'm trying to get the status of an Asterisk Server using a python socket but nothing happens.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = """Action: login
Events: off
Username: admin
Secret: mypass
Action: st... | [
"You have malformed your code there. The Asterisk AMI requires \\r\\n termination between commands.\nYou need to send each command in a separate packet:\nparams = \"\"\"Action: login\nEvents: off\nUsername: admin\nSecret: mypass\"\"\"\n\ns.send(params + '\\r\\n')\ndata = s.recv(1024)\nprint data + '\\n'\n\nparams =... | [
2,
1
] | [] | [] | [
"asterisk",
"python",
"sockets"
] | stackoverflow_0002306115_asterisk_python_sockets.txt |
Q:
How to override NULL value from aggregate query using MySQLdb module in python?
I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but wou... | How to override NULL value from aggregate query using MySQLdb module in python? | I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but would prefer to do it in python.
Any recommendations on a simple way to do this? I figur... | [
"\nI could do this in the MySQL using a sub-query, but would prefer to do it in python.\n\nWhy do you say you need a subquery? You can just use COALESCE:\n\"select COALESCE(max(date_val), 'your_default_value_here') from my_table;\"\n\n",
"Try this:\nmin_date = cur.fetchone()[0]\nmin_date = min_date if min_date is... | [
4,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002321518_mysql_python.txt |
Q:
Render wikitext with Python
I need to render wikitext (pulled from the database of a mediawiki of it's relevant) and display in some other format (ultimately to be rendered as a PDF, but basically any other format will do).
I can definately hack together something that does the job but ultimately I'll be writing i... | Render wikitext with Python | I need to render wikitext (pulled from the database of a mediawiki of it's relevant) and display in some other format (ultimately to be rendered as a PDF, but basically any other format will do).
I can definately hack together something that does the job but ultimately I'll be writing it as I go along, and I can see th... | [
"redirect Python module for wiki markup\n",
"http://www.mediawiki.org/wiki/Extension:Collection\n"
] | [
5,
1
] | [
"pywikipedia i have found to be best\n"
] | [
-1
] | [
"mediawiki",
"python",
"wikitext"
] | stackoverflow_0001836884_mediawiki_python_wikitext.txt |
Q:
Feedparser newbie questions
After a break from Python(and I knew very little then!) I'm coming back to it for a project(hopefully!). I want to do some parsing using Feedparser & need a few hints to start. Before anyone shouts, I have searched Google and read the docs, but I'm a bit too rusty unfortunately!(So pl... | Feedparser newbie questions | After a break from Python(and I knew very little then!) I'm coming back to it for a project(hopefully!). I want to do some parsing using Feedparser & need a few hints to start. Before anyone shouts, I have searched Google and read the docs, but I'm a bit too rusty unfortunately!(So please don't lmgtfy me!)
If I have ... | [
"import feedparser\nurl = \"http://...\"\nfeed = feedparser.parse(url)\nfor post in feed.entries:\n title = post.title\n print(title)\n\nIf you'd like to extract just the third post, then you could use\npost=feed.entries[2]\n\n(since python uses 0-based indexing). Printing post might be helpful; it'll show yo... | [
1
] | [] | [] | [
"feedparser",
"python",
"rss"
] | stackoverflow_0002321523_feedparser_python_rss.txt |
Q:
UTF-8 Encoding error, need help converting text
I've been working on a statistical translation system for haiti (code.google.com/p/ccmts) that uses a C++ backend (http://www.statmt.org/moses/?n=Development.GetStarted) and Python drives the C++ engine/backend.
I've passed a UTF-8 Python string into a C++ std::strin... | UTF-8 Encoding error, need help converting text | I've been working on a statistical translation system for haiti (code.google.com/p/ccmts) that uses a C++ backend (http://www.statmt.org/moses/?n=Development.GetStarted) and Python drives the C++ engine/backend.
I've passed a UTF-8 Python string into a C++ std::string, done some processing, gotten a result back into Py... | [
"It looks like a case of garbage in, garbage out. Here are a few clues on how to see what you've got in your data. repr() and unicodedata.name() are your friends.\n>>> s = ' mwen bezwen \\xc3\\xa3 \\xc2\\xa8 d medikal '\n>>> print repr(s.decode('utf8'))\nu' mwen bezwen \\xe3 \\xa8 d medikal '\n>>> import unicodedat... | [
3,
1,
1
] | [] | [] | [
"c++",
"python",
"swig",
"unicode"
] | stackoverflow_0002320315_c++_python_swig_unicode.txt |
Q:
Certain Python commands aren't caught in Stdout
I've written a simple program that captures and executes command line Python scripts, but there is a problem. The text passed to a Python input function isn't written to my program despite my program capturing stdout.
For example:
The Python script:
import sys
prin... | Certain Python commands aren't caught in Stdout | I've written a simple program that captures and executes command line Python scripts, but there is a problem. The text passed to a Python input function isn't written to my program despite my program capturing stdout.
For example:
The Python script:
import sys
print("Hello, World!")
x = input("Please enter a number: ... | [
"Smells like the Python i/o is line buffered, i.e. waits for a CRLF then sends a whole line at once. You could try turning that off (python -u myscript.py, or set the PYTHONUNBUFFERED environment variable) or work around it with something like this:\nprint(\"Hello, World!\")\nprint(\"Please enter a number: \")\nx =... | [
1,
1
] | [] | [] | [
"c#",
"input",
"python",
"stdout"
] | stackoverflow_0002321868_c#_input_python_stdout.txt |
Q:
Why does this code have the "ball" seem to slide along the edge
My son asked me if I could write a small program to have a ball bounce around the screen then have me explain it.
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
#!/usr/bin/python
#
# W... | Why does this code have the "ball" seem to slide along the edge | My son asked me if I could write a small program to have a ball bounce around the screen then have me explain it.
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
#!/usr/bin/python
#
# We have to tell python what stuff we're
# going to use. We do this by ... | [
"You need to add twice dir_* in the \"change direction\" code. \n",
"You are figuring out a new x and y coordinate before you are testing. So, say the ball is at 20, 1 and is drawn, and assume the dir is North East with slope 1. The next position will be calculated at 21, 0. Here you see the y is out of range ... | [
10,
4,
0,
0
] | [
"Not really too familiar with python, but is\ndir_x = -dir_x\n\nAcceptable? Maybe try\ndir_x *= -1\n\nor\ndir_x = dir_x * -1\n\n?\n"
] | [
-2
] | [
"python"
] | stackoverflow_0002121287_python.txt |
Q:
Should a Python generator raise an exception when there are no more elements to yield?
Should a Python generator raise an exception when there are no more elements to yield?
Which one?
A:
The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to... | Should a Python generator raise an exception when there are no more elements to yield? | Should a Python generator raise an exception when there are no more elements to yield?
Which one?
| [
"The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for ... | [
11,
9
] | [] | [] | [
"python"
] | stackoverflow_0002322342_python.txt |
Q:
How can I interactively explore why a test is failing?
I have a test that is failing with:
======================================================================
FAIL: test_register_should_create_UserProfile (APP.forum.tests.test_views.UserTestCAse)
---------------------------------------------------... | How can I interactively explore why a test is failing? | I have a test that is failing with:
======================================================================
FAIL: test_register_should_create_UserProfile (APP.forum.tests.test_views.UserTestCAse)
----------------------------------------------------------------------
Traceback (most recent call last):... | [
"This doesn't look right.\nuser = User.objects.get('username'=='john') \n\nIf you want to query, you have to write queries in the style shown in the tutorial\nhttp://docs.djangoproject.com/en/1.1/topics/db/queries/#topics-db-queries\nuser = User.objects.get( username = 'john' ) \n\nfor example.\nTo debug, you can ... | [
3,
2
] | [] | [] | [
"django",
"django_testing",
"python"
] | stackoverflow_0002322093_django_django_testing_python.txt |
Q:
Automatically prompt to update default site domain name when running Django’s ./manage.py syncdb?
Regarding Django Sites module and manage.py syncdb
The Auth module can prompt to ask for default superuser for the admin site, during .\manage.py syncdb. I would like to see similar things happen for the default site ... | Automatically prompt to update default site domain name when running Django’s ./manage.py syncdb? | Regarding Django Sites module and manage.py syncdb
The Auth module can prompt to ask for default superuser for the admin site, during .\manage.py syncdb. I would like to see similar things happen for the default site domain name. Currently it is example.com, hardcoded unless I use admin web site to change it. I want to... | [
"I made a small django app that can be plugged in and play. To plug it in:\n\ndownload it into project directory or into where your project can find.\nadd, in your settings.py INSTALLED_APPS, \"site_default\" (the app name) at the end or after \"django.contrib.sites\" that it depends on.\nRun manage.py syncdb \nor ... | [
6,
4
] | [] | [] | [
"django",
"django_sites",
"python"
] | stackoverflow_0002321771_django_django_sites_python.txt |
Q:
assign output of print to a variable in python
i want to know how to assign the output of print to a variable.
so if
mystring = "a=\'12\'"
then
print mystring
a=12
and i want to pass this like **kwargs,
test(mystring)
how can i do this?
for more of an explanation: i have a list of strings i got from a a c... | assign output of print to a variable in python | i want to know how to assign the output of print to a variable.
so if
mystring = "a=\'12\'"
then
print mystring
a=12
and i want to pass this like **kwargs,
test(mystring)
how can i do this?
for more of an explanation: i have a list of strings i got from a a comment line of a data file. it looks like this:
"a='... | [
"Redirect stdout and capture its output in an object?\nimport sys\n\n# a simple class with a write method\nclass WritableObject:\n def __init__(self):\n self.content = []\n def write(self, string):\n self.content.append(string)\n\n# example with redirection of sys.stdout\nfoo = WritableObject() ... | [
6,
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002321939_python.txt |
Q:
Django array or list output?
I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.
For example;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
... | Django array or list output? | I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.
For example;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.tit... | [
"You want a dict, which is Python's associative data structure, whereas you are creating a list. \nBut I'm not sure I understand your problem. Why not just pass your media collection into the template and iterate like this:\n{% for file in media %}\n <a href=\"{{ file.url }}\">{{ file.title }}</a>\n{% endfor %... | [
5
] | [] | [] | [
"associative_array",
"django",
"hash",
"python"
] | stackoverflow_0002322739_associative_array_django_hash_python.txt |
Q:
How do I change permissions to a socket?
I am trying to run a simple Python based web server given here.
And I get the following error message:
Traceback (most recent call last):
File "webserver.py", line 63, in <module>
main()
File "webserver.py", line 55, in main
server = HTTPServer(('', 80), MyHandl... | How do I change permissions to a socket? | I am trying to run a simple Python based web server given here.
And I get the following error message:
Traceback (most recent call last):
File "webserver.py", line 63, in <module>
main()
File "webserver.py", line 55, in main
server = HTTPServer(('', 80), MyHandler)
File "/usr/lib/python2.5/SocketServer.py... | [
"If you want to bind to port numbers < 1024, you need to be root. It's not a firewall\nissue; it's enforced by the operating system. Here's a reference from w3.org,\nand a FAQ entry specific to Unix.\n",
"If you want to run on a port under 1024, you'll need to be root. You can open the socket and drop root's perm... | [
11,
2
] | [] | [] | [
"firewall",
"python",
"sockets",
"ubuntu",
"webserver"
] | stackoverflow_0002322349_firewall_python_sockets_ubuntu_webserver.txt |
Q:
How do I prevent my Python application from automatically closing once reaching the end of code?
I'm new to programming, especially Python. I'm trying to make an application that converts Fahrenheit to Celsius, but I don't know how to make the program stay open. Whenever it reaches the end of the code, it automati... | How do I prevent my Python application from automatically closing once reaching the end of code? | I'm new to programming, especially Python. I'm trying to make an application that converts Fahrenheit to Celsius, but I don't know how to make the program stay open. Whenever it reaches the end of the code, it automatically closes before the user can see his or her results. I'm using Python 2.6.
| [
"Well, I guess you mean the terminal that Windows opens for you when you run a python file is closed too fast. You can add raw_input('Press Enter to exit') right before your program would exit. It tells Python to wait for input before exiting. \n",
"As the other people say, just ask for input to get it to hold. H... | [
10,
3,
0
] | [] | [] | [
"python",
"python_2.6",
"python_2.x"
] | stackoverflow_0002322868_python_python_2.6_python_2.x.txt |
Q:
Module "duck typing" pitfalls?
I just started experimenting with a new technique I name (for the moment at least) "module duck typing".
Example:
Main Module
import somepackage.req ## module required by all others
import abc
import Xyz
Module abc
__all__=[]
def getBus():
""" Locates the `req` for this applic... | Module "duck typing" pitfalls? | I just started experimenting with a new technique I name (for the moment at least) "module duck typing".
Example:
Main Module
import somepackage.req ## module required by all others
import abc
import Xyz
Module abc
__all__=[]
def getBus():
""" Locates the `req` for this application """
for mod_name in sys.mo... | [
"There might be all kinds of modules imported that contain \"req\" and you don't know if it's the module you are actually looking for:\n>>> import urllib.request\n>>> import tst\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"tst.py\", line 12, in <module>\n Bus=getBus()\n ... | [
4,
1,
0
] | [] | [] | [
"architecture",
"design_patterns",
"duck_typing",
"python"
] | stackoverflow_0002322116_architecture_design_patterns_duck_typing_python.txt |
Q:
Is there a Python equivalent of Ruby's 'any?' function?
In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:
lst.any?{|e| pred(e) }
In Python, there's an any function that does something similar, but on a list of boolean... | Is there a Python equivalent of Ruby's 'any?' function? | In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:
lst.any?{|e| pred(e) }
In Python, there's an any function that does something similar, but on a list of booleans.
Of course, for a reasonably-sized list, I'd just do:
any(m... | [
"any(pred(x) for x in lst)\n\nalternatively\nfrom itertools import imap\nany(imap(pred, lst))\n\n"
] | [
22
] | [] | [] | [
"list",
"python",
"ruby"
] | stackoverflow_0002323147_list_python_ruby.txt |
Q:
SqlAlchemy optimizations for read-only object models
I have a complex network of objects being spawned from a sqlite database using sqlalchemy ORM mappings. I have quite a few deeply nested:
for parent in owner.collection:
for child in parent.collection:
for foo in child.collection:
do l... | SqlAlchemy optimizations for read-only object models | I have a complex network of objects being spawned from a sqlite database using sqlalchemy ORM mappings. I have quite a few deeply nested:
for parent in owner.collection:
for child in parent.collection:
for foo in child.collection:
do lots of calcs with foo.property
My profiling is showing m... | [
"If you reference a single attribute of a single instance lots of times, a simple trick is to store it in a local variable.\nIf you want a way to create cheap pure python clones, share the dict object with the original object:\nclass CheapClone(object):\n def __init__(self, original):\n self.__dict__ = or... | [
10,
0
] | [
"Try using a single query with JOINs instead of the python loops.\n"
] | [
-1
] | [
"performance",
"python",
"readonly",
"sqlalchemy"
] | stackoverflow_0002322437_performance_python_readonly_sqlalchemy.txt |
Q:
What algorithm does buildbot use to assign builders to slaves?
I have a buildbot with some builders and two slave machines.
Some of the builders can run on one slave, and some of them can run on both machines.
What algorithm will buildbot use to schedule the builds? Will it notice that some builders can run on jus... | What algorithm does buildbot use to assign builders to slaves? | I have a buildbot with some builders and two slave machines.
Some of the builders can run on one slave, and some of them can run on both machines.
What algorithm will buildbot use to schedule the builds? Will it notice that some builders can run on just one slave and that it should assign those that can run on both sla... | [
"First it gets a list of all the slaves attached to that builder. Then it picks one at random. If the slave is already running more than slave.max_builds builds, it picks another.\nYou can override the nextSlave method on the Builder to change the way slaves are chosen. The arguments passed to your function will be... | [
11
] | [] | [] | [
"build_automation",
"build_process",
"buildbot",
"project_management",
"python"
] | stackoverflow_0002229481_build_automation_build_process_buildbot_project_management_python.txt |
Q:
How to calculate a value to a certain number of decimal places?
Using numpy or python's standard library, either or. How can I take a value with several decimal places and truncate it to 4 decimal places? I only want to compare floating point numbers to their first 4 decimal points.
A:
round(a_float, 4)
>>> he... | How to calculate a value to a certain number of decimal places? | Using numpy or python's standard library, either or. How can I take a value with several decimal places and truncate it to 4 decimal places? I only want to compare floating point numbers to their first 4 decimal points.
| [
"round(a_float, 4)\n>>> help(round)\nHelp on built-in function round in module __builtin__:\n\nround(...)\n round(number[, ndigits]) -> floating point number\n\n Round a number to a given precision in decimal digits (default 0 digits).\n This always returns a floating point number. Precision may be negati... | [
6,
3,
2,
1
] | [] | [] | [
"floating_accuracy",
"python"
] | stackoverflow_0002323332_floating_accuracy_python.txt |
Q:
django+flex: Debugging strategies
I love django, and I like flex. Django for it's cool debugging system (those yellow pages helps a lot to find bugs in my code), and flex for it possibilities.
Recently I come across a problem. If I create a form in flex and then communicate with the django server, I can't see any ... | django+flex: Debugging strategies | I love django, and I like flex. Django for it's cool debugging system (those yellow pages helps a lot to find bugs in my code), and flex for it possibilities.
Recently I come across a problem. If I create a form in flex and then communicate with the django server, I can't see any debugging info (when the exception happ... | [
"I've used firebug to debug the flex side of things. But I've been using json or XML for communication between the two. Since flash uses the browser to do the network stuff, the request should be visible in the net tab of firebug.\nTo debug the django side of things, you have a few options.\n\nIf you're using the d... | [
1
] | [] | [] | [
"actionscript_3",
"django",
"python"
] | stackoverflow_0002323371_actionscript_3_django_python.txt |
Q:
zip() alternative for iterating through two iterables
I have two large (~100 GB) text files that must be iterated through simultaneously.
Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to... | zip() alternative for iterating through two iterables | I have two large (~100 GB) text files that must be iterated through simultaneously.
Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to do anything with the lines more than once.
handle1 = open(... | [
"itertools has a function izip that does that\nfrom itertools import izip\nfor i, j in izip(handle1, handle2):\n ...\n\nIf the files are of different sizes you may use izip_longest, as izip will stop at the smaller file.\n",
"You can use izip_longest like this to pad the shorter file with empty lines\nin pytho... | [
22,
16,
0
] | [
"Something like this? Wordy, but it seems to be what you're asking for.\nIt can be adjusted to do things like a proper merge to match keys between the two files, which is often more what's needed than the simplistic zip function. Also, this doesn't truncate, which is what the SQL OUTER JOIN algorithm does, again,... | [
-1
] | [
"python"
] | stackoverflow_0002323394_python.txt |
Q:
Python drawing on screen
I'm coding an application that needs to select an area of the screen. I need to change the cursor to a cross and then draw a rectangle on the user selection. The first thing I searched for is how to manipulate the cursor and I came across wxPython. With wxPython I could easily do this on a... | Python drawing on screen | I'm coding an application that needs to select an area of the screen. I need to change the cursor to a cross and then draw a rectangle on the user selection. The first thing I searched for is how to manipulate the cursor and I came across wxPython. With wxPython I could easily do this on a Frame with a Panel, the thing... | [
"You shouldn't be using wx.TRANSPARENT in window creation, that is mostly used for wxDC paint commands. To make a window transparent just call win.SetTransparent(amount), where amount is from 0-255, 255 means opaque, 0 means totally transparent. see http://www.wxpython.org/docs/api/wx.Window-class.html#SetTranspare... | [
5
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002323640_python_wxpython.txt |
Q:
Is there any difference between cpython and python
I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
A:
Python is a language.
CPython is the default byte-code interpreter of Python, which is written in C.
There is also other ... | Is there any difference between cpython and python | I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
| [
"Python is a language.\nCPython is the default byte-code interpreter of Python, which is written in C.\nThere is also other implementation of Python such as IronPython (for .NET), Jython (for Java), etc.\n",
"\nCPython is Guido van Rossum's\n reference version of the Python\n computing language. It's most often... | [
41,
20
] | [] | [] | [
"python"
] | stackoverflow_0002324208_python.txt |
Q:
Problem originating SSH tunnels from python
The object is to set up n number of ssh tunnels between satellite servers and a centralized registry database. I have already set up public key authentication between my servers so they just log right in without password prompts. Now what ? I've tried Paramiko. It seems ... | Problem originating SSH tunnels from python | The object is to set up n number of ssh tunnels between satellite servers and a centralized registry database. I have already set up public key authentication between my servers so they just log right in without password prompts. Now what ? I've tried Paramiko. It seems decent but gets pretty complicated just to set up... | [
"Here is a cutdown version of the script that Alex pointed you to.\nIt simply connects to 192.168.0.8 and forwards port 3389 from 192.168.0.6 to localhost\nimport select\nimport SocketServer\nimport sys\nimport paramiko\n\nclass ForwardServer(SocketServer.ThreadingTCPServer):\n daemon_threads = True\n allow_r... | [
5,
2
] | [] | [] | [
"paramiko",
"python",
"ssh",
"tunnel"
] | stackoverflow_0002323471_paramiko_python_ssh_tunnel.txt |
Q:
Is line wrap comment possible in Python?
I have a long string that I build with a bunch of calculated values. I then write this string to a file.
I have it formatted like:
string = str(a/b)+\
'\t'+str(c)\
'\t'+str(d)\
...
'\n'
I would like to add comment to what each value rep... | Is line wrap comment possible in Python? | I have a long string that I build with a bunch of calculated values. I then write this string to a file.
I have it formatted like:
string = str(a/b)+\
'\t'+str(c)\
'\t'+str(d)\
...
'\n'
I would like to add comment to what each value represents but commenting with # or ''' doesn't w... | [
"A simple solution is to use parenthesis instead:\nstring = (str(a/b)+ #this value is something\n '\\t'+str(c)+ #this value is another thing\n '\\t'+str(d)+ #and this one too\n ...\n '\\n')\n\n",
"How about\nstring = '\\t'.join(map(str,((a/b), #this value is somethi... | [
7,
1
] | [] | [] | [
"comments",
"python"
] | stackoverflow_0002324483_comments_python.txt |
Q:
What is the official name of this construct?
In python:
>>> a = b or {}
A:
I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to:
a = b if b else {}
or:
if b:
a = b
else:
a = {}
I wrote this as a comment but I think it's worth mentioning here:
You ... | What is the official name of this construct? | In python:
>>> a = b or {}
| [
"I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to:\na = b if b else {}\n\nor:\nif b:\n a = b\nelse:\n a = {}\n\nI wrote this as a comment but I think it's worth mentioning here:\nYou have to be very careful when using this trick. If your intention is... | [
10,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002324453_python.txt |
Q:
How to run a piece of code in every view in django?
I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['adm... | How to run a piece of code in every view in django? | I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin... | [
"Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.\nBTW, why don't you use the built-in auth? You can use it with custom au... | [
6,
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002296117_django_python.txt |
Q:
How do I activate (execute) methods of a class in Python?
I have a program (simple web server) which I try to understand. There is a class called MyHandler. In this class we define 2 methods do_GET and do_POST.
I do not understand several things:
Where do we use the two above defined methods? I would expect to se... | How do I activate (execute) methods of a class in Python? | I have a program (simple web server) which I try to understand. There is a class called MyHandler. In this class we define 2 methods do_GET and do_POST.
I do not understand several things:
Where do we use the two above defined methods? I would expect to see something like that objectname.do_GET() and objectname.do_POS... | [
"I'm quite new to Python, but I will have a go at an answer—it might help me learn too!\n\nWe don't ever call the do_GET() and do_POST() methods from our code, this is done automatically by the HTTPServer class instance when GET and POST requests are made (see point 2).\nThe HTTPServer will create an instance of th... | [
4
] | [] | [] | [
"class",
"methods",
"oop",
"python"
] | stackoverflow_0002324804_class_methods_oop_python.txt |
Q:
Creating Python RPM
I have been reading about creating an RPM for Python 2.6.4. In this page: http://docs.python.org/distutils/builtdist.html it says you can create an RPM of the current Python using python setup.py bdist_rpm. The question's I have are:
Do you have to type this command in your Python installation... | Creating Python RPM | I have been reading about creating an RPM for Python 2.6.4. In this page: http://docs.python.org/distutils/builtdist.html it says you can create an RPM of the current Python using python setup.py bdist_rpm. The question's I have are:
Do you have to type this command in your Python installation directory?
Does this com... | [
"\nThis command has to be typed wherever your setup.py is located.\nIt packages everything that would show up in a bdist tarball.\nErr... sort of. While it works, the package it creates is not of very high quality. It's better to use sdist_rpm, then unpack the resulting SRPM and then apply your distro's Python pack... | [
6,
1
] | [] | [] | [
"checkinstall",
"linux",
"python",
"rpm",
"rpmbuild"
] | stackoverflow_0002324933_checkinstall_linux_python_rpm_rpmbuild.txt |
Q:
Django admin - Restrict user view by permission
I'm starting to learn Django and I have a question.
Is there any way to restric views in the administration interface? I see there are "change, "add" and "delete" permissions, but I wanted to restrict views also.
For example: Two users, "User 1" is superuser and "Us... | Django admin - Restrict user view by permission | I'm starting to learn Django and I have a question.
Is there any way to restric views in the administration interface? I see there are "change, "add" and "delete" permissions, but I wanted to restrict views also.
For example: Two users, "User 1" is superuser and "User 2" is in the editor group. User 1 has access to ev... | [
"If you make sure that User 2 has no permissions for any model related to the app you want to hide away (so no change, add or delete powers for any of the models in that app), then it won't appear in the admin for User 2.\n"
] | [
1
] | [] | [] | [
"admin",
"django",
"django_admin",
"permissions",
"python"
] | stackoverflow_0002325150_admin_django_django_admin_permissions_python.txt |
Q:
Deploying Django with WSGI: App Import Error
I am new in apache, linux and python world. I am trying to deploy django application on apache using WSGI (the recommended way).
My django project directory structure is as follows...
/
/apache/django.wsgi
/apps/ #I put all my apps in this directory
/apps/providers/
/... | Deploying Django with WSGI: App Import Error | I am new in apache, linux and python world. I am trying to deploy django application on apache using WSGI (the recommended way).
My django project directory structure is as follows...
/
/apache/django.wsgi
/apps/ #I put all my apps in this directory
/apps/providers/
/apps/shopping/
/apps/...
/middleware/
...
In apac... | [
"Try this:\nsys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)),'..'))\n\nIt puts your project folder at the first position and it uses os.path.join to go one directory up (which might be better on windows).\nIt might be the case that there is another \"apps\" module on your python path.\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"python",
"wsgi"
] | stackoverflow_0002324219_apache_django_python_wsgi.txt |
Q:
How to handle conditional-imports-dependent exceptions?
I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:
import ldap
try:
...
l = ldap.open(...)
l.simple_bind_s(...)
...
except ldap.INVALID_CREDENTIALS, e:
pass
except ldap.SERVER_... | How to handle conditional-imports-dependent exceptions? | I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:
import ldap
try:
...
l = ldap.open(...)
l.simple_bind_s(...)
...
except ldap.INVALID_CREDENTIALS, e:
pass
except ldap.SERVER_DOWN, e:
pass
In the real-world scenario (the one that m... | [
"Probably somewhere there should be a configuration option in your program that is used to decide which kind of authentication should be used. The imports should be done depending on this option.\nIf you put all the ldap related authentication functions into their own module, like auth_ldap and do the same for your... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002325345_python.txt |
Q:
Python path: Reusing Python module
I have written a small DB access module that is extensively reused in many programs.
My code is stored in a single directory tree /projects for backup and versioning reasons, and so the module should be placed within this directory tree, say at /projects/my_py_lib/dbconn.py.
I w... | Python path: Reusing Python module | I have written a small DB access module that is extensively reused in many programs.
My code is stored in a single directory tree /projects for backup and versioning reasons, and so the module should be placed within this directory tree, say at /projects/my_py_lib/dbconn.py.
I want to easily configure Python to automa... | [
"You can add a PYTHONPATH environment variable to your .bashrc file. eg.\nexport PYTHONPATH=/projects/my_py_lib\n\n",
"on linux, this directory will be added to your sys.path automatically for pythonN.M\n~/.local/lib/pythonN.M/site-packages/\n\nSo you can put your packages in there for each version of python you ... | [
8,
2,
0
] | [] | [] | [
"path",
"python",
"ubuntu"
] | stackoverflow_0002325418_path_python_ubuntu.txt |
Q:
Is there an active Python-Chat?
Is there an active Python-Chat?
A:
If you are asking for an irc channel where people talk about Python, then try http://www.python.org/community/irc/
A:
Python Chat Server
Python Chat Client
A:
My guess is that you are looking for a IRC channel? well this is not related to p... | Is there an active Python-Chat? | Is there an active Python-Chat?
| [
"If you are asking for an irc channel where people talk about Python, then try http://www.python.org/community/irc/\n",
"Python Chat Server\nPython Chat Client\n",
"My guess is that you are looking for a IRC channel? well this is not related to programming so you should not be posting that question here?\nany w... | [
3,
0,
0
] | [] | [] | [
"chat",
"irc",
"python"
] | stackoverflow_0002325938_chat_irc_python.txt |
Q:
Floating Point Modulo Problem
I've stumbled onto a very strange bug. Read the comments in the code to see what the bug is exactly, but essentially a variable modulo 1 is returning 1 (but it doesn't equal 1!). I'm assuming there is a display problem where the float is extremely close to one but not exactly. However... | Floating Point Modulo Problem | I've stumbled onto a very strange bug. Read the comments in the code to see what the bug is exactly, but essentially a variable modulo 1 is returning 1 (but it doesn't equal 1!). I'm assuming there is a display problem where the float is extremely close to one but not exactly. However, it should be moduloing to zero. I... | [
"Welcome to IEEE754, enjoy your stay.\n",
"Print doesn't show the full precision of the number as stored, you can use repr() to do that\n>>> last=72.99999999999999\n>>> print last, 1, type(last), last % 1, last - int(last)\n73.0 1 <type 'float'> 1.0 1.0\n>>> print last % 1 == 1\nFalse\n>>> print repr(last), 1, ty... | [
6,
6,
3,
1,
0
] | [] | [] | [
"floating_accuracy",
"floating_point",
"python"
] | stackoverflow_0002323291_floating_accuracy_floating_point_python.txt |
Q:
How to redefine a wx.GridSizer?
I have this code:
class SoundLog(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, size=(500, 350), *args, **kwargs)
self.SetBackgroundColour((110,110,110))
self.sizer = wx.BoxSizer(wx.VERTICAL)
pluginsNumber = len(plugins) ... | How to redefine a wx.GridSizer? | I have this code:
class SoundLog(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, size=(500, 350), *args, **kwargs)
self.SetBackgroundColour((110,110,110))
self.sizer = wx.BoxSizer(wx.VERTICAL)
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs... | [
"If you're using something like the AUI framework, you can simply create a new grid sizer, and swap out the one you've already got.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002325007_python_wxpython.txt |
Q:
Creating a forward compatible OpenGL 3.x context in Python
I am using wxPython and I want to use an OpenGL based canvas, but I don't want the context to support deprecated functionality. I've navigated through pyopengl and pyglet in Eclipse, but it did not look like they support this. I'm saying this because I cou... | Creating a forward compatible OpenGL 3.x context in Python | I am using wxPython and I want to use an OpenGL based canvas, but I don't want the context to support deprecated functionality. I've navigated through pyopengl and pyglet in Eclipse, but it did not look like they support this. I'm saying this because I could not find WGL functions used in assigning attributes to a cont... | [
"I can't categorically say that there's no way of doing this but I can point out that given the largely negative response to recent revisions of OpenGL that I doubt there will be a rush for developers to incorporate this sort of thing into their libraries. \nFor example, pyglet's core rendering functionality mainly... | [
1
] | [] | [] | [
"opengl",
"openglcontext",
"python"
] | stackoverflow_0002325996_opengl_openglcontext_python.txt |
Q:
Why can't I break into a running test with the pdb interactive debugger?
How can I break into a running test with the pdb interactive debugger?
This is the test:
class UserTestCase(TestCase):
def test_register_should_create_UserProfile(self):
c = Client()
response = c.post('/account/register/', {u'userna... | Why can't I break into a running test with the pdb interactive debugger? | How can I break into a running test with the pdb interactive debugger?
This is the test:
class UserTestCase(TestCase):
def test_register_should_create_UserProfile(self):
c = Client()
response = c.post('/account/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']})... | [
"Have you tried ipdb instead of vanilla pdb? I use ipdb and what you're trying to do works fine.\nAlternatively, as a fallback, why not try the pdb call inside the method you're testing, just before the response is returned? \n"
] | [
1
] | [] | [] | [
"django",
"pdb",
"python",
"testing"
] | stackoverflow_0002326472_django_pdb_python_testing.txt |
Q:
Opinion about Glashammer App engine Web framework
I am having to look into some code and consider working in a Python framework called Glashammer.
I know and love Django. I have some experience with Appengine native framework and Django on Appengine.
I'd like to know from you that have used one or more of those, h... | Opinion about Glashammer App engine Web framework | I am having to look into some code and consider working in a Python framework called Glashammer.
I know and love Django. I have some experience with Appengine native framework and Django on Appengine.
I'd like to know from you that have used one or more of those, how Glahammer compares and contrasts with others. What a... | [
"After a bit of googling (and finding your question:) and half an hour of reading docs and code I can say that\nGlashammmer is great because it:\n\nis well-documented;\nis lightweight and very flexible;\nprovides almost everything to rapidly build a complex web app -- unlike Werkzeug itself;\ndoes not suffer from N... | [
3,
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002283616_django_google_app_engine_python.txt |
Q:
Adding a constant tuple value to a list of tuples
I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.
For example
[(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]
xk,yk are constants
How do I do this
Thanks
A:
Use numpy, e... | Adding a constant tuple value to a list of tuples | I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.
For example
[(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]
xk,yk are constants
How do I do this
Thanks
| [
"Use numpy, e.g.,\n>>> import numpy as np\n>>> a = np.array([[1,2],[2,3]])\n>>> print a\n[[1 2]\n [2 3]]\n>>> print a + 2\n[[3 4]\n [4 5]]\n\n",
">>>> l = [(1,2), (3,4)]\n>>>> for i, e in enumerate(l):\n.... l[i] = (e[0]+xk, e[1]+yk)\n\nAs always, untested. ;-)\nIf you don't need to do it in place, it's even ... | [
4,
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002326359_python.txt |
Q:
How to print contents of a tkinter.Canvas widget?
How would I print contents of a Python Tkinter.Canvas widget?
I've read that it's possible to print to a postscript printer from this control but examples are hard to come by.
So, any ideas what is needed to print the contents (including images)?
If you've got a cr... | How to print contents of a tkinter.Canvas widget? | How would I print contents of a Python Tkinter.Canvas widget?
I've read that it's possible to print to a postscript printer from this control but examples are hard to come by.
So, any ideas what is needed to print the contents (including images)?
If you've got a cross-platform method all the better!
| [
"AFAIK it can only be done using the postscript method from the Canvas. This generates a postscript file with the canvas contents.\nCheck the documentation for details about this method.\n"
] | [
0
] | [] | [] | [
"printing",
"python",
"tkinter_canvas"
] | stackoverflow_0002326753_printing_python_tkinter_canvas.txt |
Q:
Python template help
I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_... | Python template help | I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_name))
output = template.... | [
"The webapp framework uses Django 0.9.6 templates. If you're loading templates from a string as you describe above, you need to configure the template loader so it can find dependencies loaded from files. Here's how webapp configures them.\n",
"{% include 'dirname/helloworld.html' %}\n\nshould work!\n"
] | [
3,
0
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0002322069_django_django_templates_google_app_engine_python.txt |
Q:
String templates in Python: what are legal characters?
I can't quite figure out what's going on with string templates:
t = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
print t.safe_substitute({'dog.old': 'old dog', 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% N... | String templates in Python: what are legal characters? | I can't quite figure out what's going on with string templates:
t = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
print t.safe_substitute({'dog.old': 'old dog', 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'})
This prints:
cannot teach an ${dog.old} ${tricks.new}... | [
"From the documentation...\n\n$identifier names a substitution placeholder matching a mapping key of \"identifier\". By default, \"identifier\" must spell a Python identifier. The first non-identifier character after the $ character terminates this placeholder specification.\n\nThe period is a non-identifier char... | [
5,
5,
1
] | [] | [] | [
"python",
"string",
"templates"
] | stackoverflow_0002326757_python_string_templates.txt |
Q:
Why is 'join' faster than normal concatenation?
I've seen several examples from different languages that unambiguously prove that joining elements of a list (array) is many times faster than just concatenating string. Why?
What is the inner algorithm that works under both operations and why is the one faster than ... | Why is 'join' faster than normal concatenation? | I've seen several examples from different languages that unambiguously prove that joining elements of a list (array) is many times faster than just concatenating string. Why?
What is the inner algorithm that works under both operations and why is the one faster than another?
Here is a Python example of what I mean:
# T... | [
"The code in a join function knows upfront all the strings it’s being asked to concatenate and how large those strings are, and hence it can calculate the final string length before beginning the operation.\nHence it needs only allocate memory for the final string once and then it can place each source string (and ... | [
15,
14,
3,
3,
2,
0,
0
] | [] | [] | [
"javascript",
"performance",
"python",
"string_concatenation"
] | stackoverflow_0002324963_javascript_performance_python_string_concatenation.txt |
Q:
Class level return/exit in Python
In my application I have a loop that in each turn creates an instance of a class which performs some operations. In this class I have a signal timer that when invoked is supposed to exit the current turn in the loop gracefully and allow the next operation to continue without any i... | Class level return/exit in Python | In my application I have a loop that in each turn creates an instance of a class which performs some operations. In this class I have a signal timer that when invoked is supposed to exit the current turn in the loop gracefully and allow the next operation to continue without any interruption.
In it's current state it r... | [
"If you're talking about signals as in the signal module, then the handlers aren't called in a standard fashion.\nYou can't throw an exception out of them and expect it to appear in your normal code. Indeed you should try to do as little as possible in your handler - set a global flag, or send a message on a pipe p... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002327077_python.txt |
Q:
It is said best way to deploy django is using wsgi, I am wondering why?
We are deploying django application, I found in the documentation that it is recommended to use WSGI appoach for doing that.
Before deploying I wanted to know, why it is recommended over other two approaches i.e. using mod_python and fastcgi.... | It is said best way to deploy django is using wsgi, I am wondering why? | We are deploying django application, I found in the documentation that it is recommended to use WSGI appoach for doing that.
Before deploying I wanted to know, why it is recommended over other two approaches i.e. using mod_python and fastcgi...
Thanks a lot.
| [
"wsgi is usually preferred because it decouples your choice of framework from your choice of web server: if tomorrow you want to move, say, from Apache to nginx, or whatever, the move is trivially easy with wsgi, not so easy otherwise.\nFurthermore, using wsgi affords you the option to add some middleware that's fr... | [
15,
5,
0
] | [] | [] | [
"django",
"django_wsgi",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0002327355_django_django_wsgi_mod_wsgi_python_wsgi.txt |
Q:
Outlook contacts using Python client
I want to write a script which permits a user to modify his Contacts, can you help me ?
thanks,
A:
You can use Python-COM bindings to use Outlook's COM object and achieve what you want.
Here's a nice tutorial on how to use Python with COM.
| Outlook contacts using Python client | I want to write a script which permits a user to modify his Contacts, can you help me ?
thanks,
| [
"You can use Python-COM bindings to use Outlook's COM object and achieve what you want.\nHere's a nice tutorial on how to use Python with COM.\n"
] | [
3
] | [] | [] | [
"outlook",
"python"
] | stackoverflow_0002327584_outlook_python.txt |
Q:
Where should sys.path.append('...') statement go?
Just after standard pythonmodule imports?
If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
A:
It should go before the impo... | Where should sys.path.append('...') statement go? | Just after standard pythonmodule imports?
If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
| [
"It should go before the import or from statements that need it (which as you say is obvious). So for example a module could start with:\nimport sys\nimport os\nimport math\ntry:\n import foo\nexcept ImportError:\n if 'foopath' in sys.path: raise\n sys.path.append('foopath')\n import foo\n\nNote that I've made... | [
8,
4,
1,
0,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0002327322_coding_style_python.txt |
Q:
How to best use GPS data?
I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc...
My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time bet... | How to best use GPS data? | I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc...
My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time between two points to get the valu... | [
"Except using rather complicated data signal processing techniques, or by using an accelerometer and dead reckoning (which is highly inaccurate), a GPS device cannot measure its own velocity. Due to this, the velocity data provided by a GPS unit is interpolated using the exact same method you want to use. The two p... | [
9
] | [] | [] | [
"android",
"filtering",
"gps",
"python"
] | stackoverflow_0002327813_android_filtering_gps_python.txt |
Q:
How to make PowerBuilder UI testing application?
I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from ... | How to make PowerBuilder UI testing application? | I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it).
Any ideas how to re... | [
"I'm experimenting with code for a tool for automating PowerBuilder-based GUIs as well. From what I can see, your best bet would be to use the PowerBuilder Native Interface (PBNI), and call PowerScript code from within your NVO.\nIf you like, feel free to send me an email (see my profile for my email address), I'd ... | [
2,
1,
1,
1
] | [] | [] | [
"powerbuilder",
"python",
"testing"
] | stackoverflow_0001741023_powerbuilder_python_testing.txt |
Q:
How to run a clone of reddit.com website. Reddit.com source code gives error while implementing on Ubuntu 9.10 (karmic)
I am implementing the reddit.com source code on ubuntu karmic 9.10.
I have followed all the steps and in one step where i am using paster command it throws an error.
$paster shell example.ini
Fi... | How to run a clone of reddit.com website. Reddit.com source code gives error while implementing on Ubuntu 9.10 (karmic) | I am implementing the reddit.com source code on ubuntu karmic 9.10.
I have followed all the steps and in one step where i am using paster command it throws an error.
$paster shell example.ini
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/middleware.py", line 11, in
from webhelpers.... | [
"You need to ensure that all the libraries needed by your Reddit clone are on Python's module search path. There are a lot of different ways to accomplish this. The easiest is probably to just use setuptools' easy_install command to install them (though this is my own personal least favorite way to install Python... | [
1
] | [] | [] | [
"paster",
"pylons",
"python",
"reddit"
] | stackoverflow_0002326905_paster_pylons_python_reddit.txt |
Q:
Interrupt all running signals in Python?
How can I interrupt all running signals in a Python script? I would like something like signal.interrupt_all().
Is there any way to do that?
Thanks
A:
What exactly do you mean? Do you want to temporairly ignore a signal, or to completely ignore some kinds of signals?
Gene... | Interrupt all running signals in Python? | How can I interrupt all running signals in a Python script? I would like something like signal.interrupt_all().
Is there any way to do that?
Thanks
| [
"What exactly do you mean? Do you want to temporairly ignore a signal, or to completely ignore some kinds of signals?\nGenerally speaking, you can't \"vanish\" a signal once it has been generated. You either set its action to \"ignore\" or you block the signal, preventing it from being delivered, but you need to do... | [
1
] | [] | [] | [
"python",
"signals"
] | stackoverflow_0002318831_python_signals.txt |
Q:
Python and windows filesystem with none-ascii characters
I want to write a folder on a windows system, Vista and Win7 with NTFS file systems.
The folders may contain the characters å, ä and/or ö, "förjävligt" for example.
The python files and every string in it is currently in UTF-8, how do I convert it to suite t... | Python and windows filesystem with none-ascii characters | I want to write a folder on a windows system, Vista and Win7 with NTFS file systems.
The folders may contain the characters å, ä and/or ö, "förjävligt" for example.
The python files and every string in it is currently in UTF-8, how do I convert it to suite the Windows file system?
| [
"If you're working with normal Python 2 strings, you can simply convert them to Unicode\n# -*- coding: utf-8 -*-\nnormalString = \"äöü\"\n\n# Now convert to unicode. Specified encoding must match the file encoding\n# in this example. In general, you must specify how the bytes-only string\n# contained in \"normalStr... | [
3,
1
] | [] | [] | [
"ntfs",
"python",
"windows"
] | stackoverflow_0002327226_ntfs_python_windows.txt |
Q:
Python OOP - Class relationships
Assuming I have a system of three Classes.
The GameClass creates instances of both other classes upon initialization.
class FieldClass:
def __init__( self ):
return
def AnswerAQuestion( self ):
return 42
class PlayerClass:
def __init__( self ):
... | Python OOP - Class relationships | Assuming I have a system of three Classes.
The GameClass creates instances of both other classes upon initialization.
class FieldClass:
def __init__( self ):
return
def AnswerAQuestion( self ):
return 42
class PlayerClass:
def __init__( self ):
return
def DoMagicHere( self )... | [
"I would go with Dependency Injection: instantiate a GameClass with the required FieldClass and PlayerClass in the constructor call etc. (i.e. instead of creating the dependent objects from within GameClass as you are doing at the moment).\nclass GameClass:\n def __init__( self, fc, pc ):\n self.Field = ... | [
6,
4,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002328094_oop_python.txt |
Q:
IOError opening an existing file with Python
Running the following code:
import os
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y %H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
log = open ('/Us... | IOError opening an existing file with Python | Running the following code:
import os
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y %H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
log = open ('/Users/admin/Documents/locatelog.txt','w')
log.wr... | [
"Shouldn't it bef = open('/Users/admin/Documents/%s.txt' % smush,'r') ? notice the / in front of Users\nIf you dont put the first /, the script will think the path to the file is relative to the current directory (where the script is run from)\nEdit:\nI m not too familiar with Python (I wish) but shouldnt it be:\ns... | [
4,
1,
0
] | [] | [] | [
"file_io",
"ftp",
"ftplib",
"macos",
"python"
] | stackoverflow_0002327989_file_io_ftp_ftplib_macos_python.txt |
Q:
Any potential gotchas or things to be aware of for a newcomer to Django?
In other words, what did you not know when you started with Django that you wish someone had told you?
I've dabbled some in Django but nothing really serious. However, I'm hoping to change that, and I'm wondering if there's any gotchas/shortc... | Any potential gotchas or things to be aware of for a newcomer to Django? | In other words, what did you not know when you started with Django that you wish someone had told you?
I've dabbled some in Django but nothing really serious. However, I'm hoping to change that, and I'm wondering if there's any gotchas/shortcomings/whatever that I need to be aware of as I go.
| [
"Be aware of specifying absolute paths in your settings.py file. Django doesn't come with an out-of-the-box solution for making everything relative, and you have to employ Python's utilities. The usual solution is something like:\nimport os\ndef abspath(file):\n return os.path.join(os.path.dirname(__file__), fil... | [
6,
4,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002328767_django_python.txt |
Q:
MATLAB to Python Code conversion (NumPy, SciPy, MatplotLib?)
I'm trying to convert the following code to Python from MATLAB for an EEG Project (partly because Python's slightly cheaper!)
Hopefully someone can point me in the right direction: I've started to alter it but got bogged down: Particularly trying to find... | MATLAB to Python Code conversion (NumPy, SciPy, MatplotLib?) | I'm trying to convert the following code to Python from MATLAB for an EEG Project (partly because Python's slightly cheaper!)
Hopefully someone can point me in the right direction: I've started to alter it but got bogged down: Particularly trying to find equivalent functions.
Tried scipy.org (NumPy_for_Matlab_Users et... | [
"Um... lots of things.\nPython has no end keyword, so you clearly need to read more about Python's syntax.\nPython arrays and slices are indexed with [] not (). Ranges are expressed as range(0,10) for example, but slices in the Matlab sense only exist in extension packages like numpy and each one has its own inter... | [
11,
5,
2
] | [] | [] | [
"matlab",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0002326786_matlab_matplotlib_numpy_python_scipy.txt |
Q:
Change the type of a global variable in a function initializing it
I have a __main__ function where I initialize a lot of variables that are to be used in my program, later on. I have a problem where a variable that I temporarely declare as None in the outer scope, is assigned an object of SomeClass, but due to sc... | Change the type of a global variable in a function initializing it | I have a __main__ function where I initialize a lot of variables that are to be used in my program, later on. I have a problem where a variable that I temporarely declare as None in the outer scope, is assigned an object of SomeClass, but due to scoping rules I cannot access it's content in the outer scope. Because the... | [
"Assuming that setup() is meant to be initialize(), the problem is that the variable myObject in initialize() is a local variable that hides the global myObject, and when initialize() returns, the local name will go out of scope.\nTo update the global myObject variable, you need to change initialize() as follows:\n... | [
2,
2,
0
] | [] | [] | [
"class",
"global_variables",
"python",
"scope"
] | stackoverflow_0002328464_class_global_variables_python_scope.txt |
Q:
Django - Template not complete rendered
I have a website on a django framework, and in a set of pages I use the Paginator. With paginator, my last page sometimes does not render completely.
You can see the problem here.
Code:
view rank - http://code.google.com/p/myps3t/source/browse/views.py
template - http://code... | Django - Template not complete rendered | I have a website on a django framework, and in a set of pages I use the Paginator. With paginator, my last page sometimes does not render completely.
You can see the problem here.
Code:
view rank - http://code.google.com/p/myps3t/source/browse/views.py
template - http://code.google.com/p/myps3t/source/browse/www/Rank.h... | [
"You asked if you can see the template render output. You can.\ndjango.shortcuts.render_to_response is a very short function:\nhttpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}\nreturn HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)\n\nYou can make your own render_to_re... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002318169_django_python.txt |
Q:
Avoiding unnecessary slice copying in Python
Is there a common idiom for avoiding pointless slice copying for cases like this:
>>> a = bytearray(b'hello')
>>> b = bytearray(b'goodbye, cruel world.')
>>> a.extend(b[14:20])
>>> a
bytearray(b'hello world')
It seems to me that there is an unnecessary copy happening w... | Avoiding unnecessary slice copying in Python | Is there a common idiom for avoiding pointless slice copying for cases like this:
>>> a = bytearray(b'hello')
>>> b = bytearray(b'goodbye, cruel world.')
>>> a.extend(b[14:20])
>>> a
bytearray(b'hello world')
It seems to me that there is an unnecessary copy happening when the b[14:20] slice is created. Rather than cre... | [
"Creating a buffer object avoids copying the slice, but for short slices it's more efficient to just make the copy:\n>>> a.extend(buffer(b, 14, 6))\n>>> a\nbytearray(b'hello world')\n\nHere there's only one copy made of the memory, but the cost of creating the buffer object more than obliterates the saving. It shou... | [
5,
2
] | [] | [] | [
"idioms",
"optimization",
"python"
] | stackoverflow_0002328171_idioms_optimization_python.txt |
Q:
Referenced Model Loading in Google App Engine
In Python, say I've got a model of class A that has a ReferenceProperty b to model class B, which has a ReferenceProperty c to model class C.
Assuming an instance of A already exists in the datastore, I can get it by saying:
q = A.all()
a = q.get()
In this scenario, h... | Referenced Model Loading in Google App Engine | In Python, say I've got a model of class A that has a ReferenceProperty b to model class B, which has a ReferenceProperty c to model class C.
Assuming an instance of A already exists in the datastore, I can get it by saying:
q = A.all()
a = q.get()
In this scenario, how does entity loading work? Is a.b retrieved when ... | [
"The models will be dereferenced when you first access them. So calling a.b will get b, and calling a.b.c will get c.\nHave a look at Nick Johnson's blog for some tips about memcahing models:\nhttp://blog.notdot.net/2009/9/Efficient-model-memcaching\n",
"ReferenceProperties are lazily-loaded. b will not be looke... | [
2,
1
] | [] | [] | [
"google_app_engine",
"loading",
"memcached",
"model",
"python"
] | stackoverflow_0002329387_google_app_engine_loading_memcached_model_python.txt |
Q:
how do you specify which python executable to use in Django 1.1.1?
I have a RH system running RHEL 5.3, which comes with python2.4 that can't be removed for numerous reasons.
I have been able to build 64-bit RPMS for python 2.6 as an altinstall. It's called with "python26".
How can I tell Django to use this com... | how do you specify which python executable to use in Django 1.1.1? | I have a RH system running RHEL 5.3, which comes with python2.4 that can't be removed for numerous reasons.
I have been able to build 64-bit RPMS for python 2.6 as an altinstall. It's called with "python26".
How can I tell Django to use this command to get to the proper python version, instead of the default "python... | [
"Look at virtualenv, you can setup your own environment for django (well, anything) with different lib versions, symlinks etc.\n",
"That depends on the deploying method you use. E.g., if you use the django-recommended mod_wsgi deployment, then you must compile it with the correct python version.\n"
] | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002329541_django_python.txt |
Q:
Python:Extend the 'dict' class
I have to solve this exercise:
Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when n... | Python:Extend the 'dict' class | I have to solve this exercise:
Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added.
How do I ext... | [
"You can either subclass dict or UserDict, since van already talked about UserDict, lets look at dict.\nType help(dict) into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.\nMethods that modify the di... | [
40,
11,
6,
5
] | [] | [] | [
"dictionary",
"extend",
"python"
] | stackoverflow_0002328235_dictionary_extend_python.txt |
Q:
Dealing with BACKSLASH character in non-string literals in Python
I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string liter... | Dealing with BACKSLASH character in non-string literals in Python | I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.
\\server\data\uploads\0224.1307.Varallo.mov
when I try and pa... | [
"We need more information. What exactly is in the variable filename? To answer, use print repr(filename) and add the results to your question above.\n\nWild guess\nDISCLAIMER: This is a guess - try:\nimport ntpath\nprint ntpath.basename(filename)\n\n",
"All the downvoting in the world won't change the fact that y... | [
2,
1
] | [] | [] | [
"encoding",
"escaping",
"python",
"string"
] | stackoverflow_0002329719_encoding_escaping_python_string.txt |
Q:
First Order Logic Engine
I'd like to create an application that can do simple reasoning using first order logic. Can anyone recommend an "engine" that can accept an arbitrary number of FOL expressions, and allow querying of those expressions (preferably accessible via Python)?
A:
Don't query using first-order lo... | First Order Logic Engine | I'd like to create an application that can do simple reasoning using first order logic. Can anyone recommend an "engine" that can accept an arbitrary number of FOL expressions, and allow querying of those expressions (preferably accessible via Python)?
| [
"Don't query using first-order logic (FOL) unless you absolutely have to: first-order logic is not decidable, but only semi-decidable, and so queries will often, unavoidably not terminate.\nDescription logic is essentially a decidable fragment of first-order logic, reformulated in a manner that is good for talking ... | [
12,
9,
1
] | [] | [] | [
"logic",
"machine_learning",
"python",
"reasoning"
] | stackoverflow_0002304726_logic_machine_learning_python_reasoning.txt |
Q:
How to set the program title in python
I have been building a large python program for a while, and would like to know how I would go about setting the title of the program? On a mac the title of program, which has focus, is shown in the top left corner of the screen, next the apple menu. Currently this only shows... | How to set the program title in python | I have been building a large python program for a while, and would like to know how I would go about setting the title of the program? On a mac the title of program, which has focus, is shown in the top left corner of the screen, next the apple menu. Currently this only shows the word "Python", but I would of course li... | [
"It depends on what type of application you have. If it's a graphical application, most graphical toolkits allow you to change the title of a window (tk, which comes with python, allows you to do this by calling the title() method of your window object, as does gtk, for which you can use the set_title() method on a... | [
15,
3
] | [] | [] | [
"macos",
"menubar",
"python",
"title"
] | stackoverflow_0002330393_macos_menubar_python_title.txt |
Q:
How to convert ctypes' c_long to Python's int?
int(c_long(1)) doesn't work.
A:
>>> ctypes.c_long(1).value
1
A:
Use the 'value' attribute of c_long object.
c_long(1).value
or
i = c_long(1)
print i.value
A:
>>> type(ctypes.c_long(1).value)
<type 'int'>
| How to convert ctypes' c_long to Python's int? | int(c_long(1)) doesn't work.
| [
">>> ctypes.c_long(1).value\n1\n\n",
"Use the 'value' attribute of c_long object.\n\n\n c_long(1).value\n\n\nor\n\n\n i = c_long(1)\n print i.value\n\n\n",
">>> type(ctypes.c_long(1).value)\n<type 'int'>\n\n"
] | [
52,
11,
9
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002330587_ctypes_python.txt |
Q:
"HTTP Error 409: Conflict" when using urllib.request.urlopen()
Under Python 3.1, when trying to run this code:
from urllib import request
def test():
request.urlopen("http://www.google.com")
test()
I get an HTTP 409 error. The stack trace is:
Traceback (most recent call last):
File "C:\Users\Beau\Python\... | "HTTP Error 409: Conflict" when using urllib.request.urlopen() | Under Python 3.1, when trying to run this code:
from urllib import request
def test():
request.urlopen("http://www.google.com")
test()
I get an HTTP 409 error. The stack trace is:
Traceback (most recent call last):
File "C:\Users\Beau\Python\pokescrape.py", line 6, in <module>
test()
File "C:\Users\Beau... | [
"I was running into this problem too (also from Lancaster, as it happens) and found that if I set the environment variable http_proxy, Python would use it. In this case (on Windows) it would be:\nset http_proxy=http://wwwcache.lancs.ac.uk:8080\n\nand on *nix:\nexport http_proxy=http://wwwcache.lancs.ac.uk:8080/\n\n... | [
2,
1,
0
] | [] | [] | [
"http",
"proxy",
"python",
"python_3.x"
] | stackoverflow_0002247418_http_proxy_python_python_3.x.txt |
Q:
Problem compiling mod_wsgi on Solaris 10 with Cool Stack 1.3.1
I try to compile mod_wsgi with Cool Stack 1.3.1 on the Solaris platform:
export PATH=/usr/sbin:/usr/bin:/usr/local/bin:/usr/sfw/bin:/usr/ccs/bin
FLAGS="-I/opt/coolstack/include" LIBS="-lintl -lgettextlib" \
LD_LIBRARY_PATH=/opt/coolstack/lib LDFLAGS="... | Problem compiling mod_wsgi on Solaris 10 with Cool Stack 1.3.1 | I try to compile mod_wsgi with Cool Stack 1.3.1 on the Solaris platform:
export PATH=/usr/sbin:/usr/bin:/usr/local/bin:/usr/sfw/bin:/usr/ccs/bin
FLAGS="-I/opt/coolstack/include" LIBS="-lintl -lgettextlib" \
LD_LIBRARY_PATH=/opt/coolstack/lib LDFLAGS="-L/opt/coolstack/lib -R/opt/coolstack/lib" \
./configure --prefix=/u... | [
"You don't have SUN C/C++ compiler installed. The Cool Stack packages appear to have been built with that compiler and not gcc and in the case of Apache apxs/libtool, that is probably hardwired into the tools. Thus, when those tools are used, they will fail as can't find that compiler.\nNote that it is not enough j... | [
2
] | [] | [] | [
"apache",
"python"
] | stackoverflow_0002324661_apache_python.txt |
Q:
which is the best way to get the value of 'session_key','uid','expires'
i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
A:
>>> impo... | which is the best way to get the value of 'session_key','uid','expires' | i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
| [
">>> import json\n>>> s=''' {\"session_key\":\"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986\",\"uid\":16423386,\"expires\":12673200,\"secret\":\"sm7WM_rRtjzXeOT_jDoQ__\",\"sig\":\"6a6aeb66 64a1679bbeed4282154b35\"} '''\n>>> d=json.loads(s)\n\n>>> d['session_key']\nu'3.KbRiifBOxY_0ouPag6__.3600.1267063200-1642398... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002330857_python.txt |
Q:
Getting fast translation of string data transmitted via a socket into objects in Python
I currently have a Python application where newline-terminated ASCII strings are being transmitted to me via a TCP/IP socket. I have a high data rate of these strings and I need to parse them as quickly as possible. Currently... | Getting fast translation of string data transmitted via a socket into objects in Python | I currently have a Python application where newline-terminated ASCII strings are being transmitted to me via a TCP/IP socket. I have a high data rate of these strings and I need to parse them as quickly as possible. Currently, the strings are being transmitted as CSV and if the data rate is high enough, my Python app... | [
"You can't make Python faster. But you can make your Python application faster.\nPrinciple 1: Do Less.\nYou can't do less input parsing over all but you can do less input parsing in the process that's also reading the socket and doing everything else with the data.\nGenerally, do this.\nBreak your application into... | [
3,
0
] | [] | [] | [
"parsing",
"performance",
"python",
"sockets",
"string"
] | stackoverflow_0002330834_parsing_performance_python_sockets_string.txt |
Q:
A user management system for a new app?
im using python. is there a widely accepted way of doing it? it deals with some data management things, so i dont want to implement it like in stackoverflow, with anonymous accounts. i also don't want to roll my own system from scratch. any recommendations?
A:
Are you ... | A user management system for a new app? | im using python. is there a widely accepted way of doing it? it deals with some data management things, so i dont want to implement it like in stackoverflow, with anonymous accounts. i also don't want to roll my own system from scratch. any recommendations?
| [
"Are you talking about a web application? If so, OpenId is probably the way to go, and this library probably the most popular way to implement it in Python. If you're talking about user management for a NON-web app, please clarify your requirements and constraints!\n"
] | [
1
] | [] | [] | [
"language_agnostic",
"python"
] | stackoverflow_0002331699_language_agnostic_python.txt |
Q:
How to set a icon file while creating file
I am creating a tar file ( from several files), now while saving this tar file i save this file as my particular extension like (.xyz), so i want whenever i save this type file (.xyz extension) from my tool this file should save with a particular ico file format. This is ... | How to set a icon file while creating file | I am creating a tar file ( from several files), now while saving this tar file i save this file as my particular extension like (.xyz), so i want whenever i save this type file (.xyz extension) from my tool this file should save with a particular ico file format. This is similar like when we save a bmp or jpeg file fro... | [
"To associate a icon with your extension you will have to create a registry entry for that and a icon associated with a extension doesn't mean anything unless you associate some program to open it with you, that too you can do in registry e.g\n\nCreate an entry for your program's icon name, e.g.\nHKCU\\Software\\C... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002331690_python_wxpython.txt |
Q:
How to make a user friendly start of a Python program?
I have a Python program (GUI application). I can run this program from the command prompt on Windows (command line on Linux). But it can be too complicated for users. Is there an easy way to initiate a start of the program with a click (double click) on a pict... | How to make a user friendly start of a Python program? | I have a Python program (GUI application). I can run this program from the command prompt on Windows (command line on Linux). But it can be too complicated for users. Is there an easy way to initiate a start of the program with a click (double click) on a pictogram (a small image on the desktop)?
| [
"I'm not sure if I understood the question well, but if you just need a way to simulate a command line input with a simply clickable icon, just create a simple .bat file (assuming windows) on the desktop, as a new text file containing something like \n\nC:\\[Pythonpath]\\python C:\\[MyPythonAppPath]\\myapp.py\n\nSe... | [
1,
1,
1,
0
] | [] | [] | [
"command_line",
"command_prompt",
"desktop",
"python"
] | stackoverflow_0002311455_command_line_command_prompt_desktop_python.txt |
Q:
PyFacebook: Facebook() instance has no stream methods
I need to update my Facebook Fan Page in a django app so I have this code:
import facebook
from django.conf import settings
def login_facebook():
fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
fb.session_key = settings.... | PyFacebook: Facebook() instance has no stream methods | I need to update my Facebook Fan Page in a django app so I have this code:
import facebook
from django.conf import settings
def login_facebook():
fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
fb.session_key = settings.FACEBOOK_SESSION
fb.secret = settings.FACEBOOK_SECRET_K... | [
"After searching for hours I finally found the solution... not to use stream methods but this:\nfb(method='stream_publish', args={'session_key': settings.FACEBOOK_SESSION, 'uid':PAGE_ID, 'target_id': 'NULL', 'message':'MESSAGE_HERE'})\n\nFound the solution at this blog post: http://danielquinn.org/blog/1578.html\nT... | [
1
] | [] | [] | [
"facebook",
"pyfacebook",
"python"
] | stackoverflow_0002332315_facebook_pyfacebook_python.txt |
Q:
Why am I getting this error in Django (I'm trying to do a 304 not modified)
def list_ajax(reqest):
#q = request.GET.get('q',None)
#get all where var = q.
return ...
list_ajax = condition(etag_func=list_ajax)(list_ajax)
As you can see, I'm trying to return a 304 to the client if the result is the same.... | Why am I getting this error in Django (I'm trying to do a 304 not modified) | def list_ajax(reqest):
#q = request.GET.get('q',None)
#get all where var = q.
return ...
list_ajax = condition(etag_func=list_ajax)(list_ajax)
As you can see, I'm trying to return a 304 to the client if the result is the same. But, I am getting this Django error, why?:
Traceback:
File "/usr/local/lib/pytho... | [
"The correct etag_func would return some serializable data. In your case, the best choice is something like this:\n@etag(_get_list)\ndef list_ajax(request):\n objects = _get_list(request)\n return render_to_response(\"list.html\", {\"objects\": objects})\n\ndef _get_list(request):\n q = request.GET[\"q\"]... | [
0,
0
] | [] | [] | [
"django",
"header",
"http",
"http_status_code_304",
"python"
] | stackoverflow_0002330435_django_header_http_http_status_code_304_python.txt |
Q:
Migrate a SQLite3 database table to MySQL with Python without dump files
I need to migrate information that I created in SQLite3 to a MySQL database on my website. The website is on a hosted server. I have remote access to the MySQL database. I initially thought it would be easy, but I am not finding any good i... | Migrate a SQLite3 database table to MySQL with Python without dump files | I need to migrate information that I created in SQLite3 to a MySQL database on my website. The website is on a hosted server. I have remote access to the MySQL database. I initially thought it would be easy, but I am not finding any good info on it, and everything I read seems to imply that you need to dump the SQLi... | [
"The reason the \"messy\" scripts are required is that it's generally a difficult problem to solve.\nIf you are lucky there won't be too many schema incompatibilities between the databases.\nThese may help\ndb_dump.py\ndbpickle.py\nWhat is your favorite solution for managing database migrations in django? \n",
"H... | [
2,
2
] | [] | [] | [
"django",
"mysql",
"python",
"sqlite"
] | stackoverflow_0002332609_django_mysql_python_sqlite.txt |
Q:
Perform a SQL JOIN on Django models that are not related?
I have 2 Models, User (django.contrib.auth.models.User) and a model named Log. Both contain an "email" field. Log does not have a ForeignKey pointing to the User model. I'm trying to figure out how I can perform a JOIN on these two tables using the email... | Perform a SQL JOIN on Django models that are not related? | I have 2 Models, User (django.contrib.auth.models.User) and a model named Log. Both contain an "email" field. Log does not have a ForeignKey pointing to the User model. I'm trying to figure out how I can perform a JOIN on these two tables using the email field as the commonality.
There are basically 2 queries I want... | [
"You can add an extra method onto the User class, using MonkeyPatching/DuckPunching:\ndef logs(user):\n return Log.objects.filter(email=user.email)\n\nfrom django.contrib.auth.models import User\nUser.logs = property(logs)\n\nNow, you can query a User, and ask for the logs attached (for instance, in a view):\nus... | [
3,
2,
0
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0002328493_django_orm_python.txt |
Q:
Colorize PyLint Output?
Anyone have any tricks/techniques for colorizing PyLint output?
A:
$ pylint --output-format=colorized
Try $ pylint --help | less for more useful tricks.
A:
If you feel up to writing a Pygments lexer then you could use pygmentize.
| Colorize PyLint Output? | Anyone have any tricks/techniques for colorizing PyLint output?
| [
"$ pylint --output-format=colorized\n\nTry $ pylint --help | less for more useful tricks. \n",
"If you feel up to writing a Pygments lexer then you could use pygmentize.\n"
] | [
21,
3
] | [] | [] | [
"colorize",
"pylint",
"python"
] | stackoverflow_0002330608_colorize_pylint_python.txt |
Q:
How to serialize db.Model objects to json?
When using
from django.utils import simplejson
on objects of types that derive from db.Model it throws exceptions. How to circumvent this?
A:
Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution:
add this ut... | How to serialize db.Model objects to json? | When using
from django.utils import simplejson
on objects of types that derive from db.Model it throws exceptions. How to circumvent this?
| [
"Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution:\nadd this utlity class http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55 \n import datetime \n import time \n\n from google.appengine.api import users \n fr... | [
14,
10,
3,
0
] | [
"From what i can understand - and i am new to python - with google app engine the work around is to serialize the model object to a dictioanry python object and then use simple json to dump it as a json string - this makes no sense to me - maybe someone has the know to serialise to a ditionary (pickel?)\nAny help o... | [
-1
] | [
"google_app_engine",
"python",
"simplejson"
] | stackoverflow_0002114659_google_app_engine_python_simplejson.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.