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:
Translating a lambda to a normal function in Python
While trying to understand how to use the lambda, I came across one reply in which the poster said that nothing you can do using lambda you can't do using normal functions.
I have been trying so hard to call a function from within itself in Python, not expert tho... | Translating a lambda to a normal function in Python | While trying to understand how to use the lambda, I came across one reply in which the poster said that nothing you can do using lambda you can't do using normal functions.
I have been trying so hard to call a function from within itself in Python, not expert though, yet I'm learning, and I came across few problems whe... | [
"Python lambdas are simply syntactic sugar. \"Regular\" functions have the same capabilities such as closures, because, remember, you can define them inside another function, just as lambda does.\ndef some_func():\n some_expr_using(lambda args: 42)\n\n# becomes:\n\ndef some_func():\n def unique_name(args):\n ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004777235_python.txt |
Q:
python: sorting two lists of polygons for intersections
I have two big lists of polygons.
Using python, I want to take each polygon in list 1, and find the results of its geometric intersection with the polygons in list 2 (I'm using shapely to do this).
So for polygon i in list 1, there may be several polygons... | python: sorting two lists of polygons for intersections | I have two big lists of polygons.
Using python, I want to take each polygon in list 1, and find the results of its geometric intersection with the polygons in list 2 (I'm using shapely to do this).
So for polygon i in list 1, there may be several polygons in list 2 that would intersect with it.
The problem is tha... | [
"Quadtrees are often used for the purpose of narrowing down the sets of polygons that need to be checked against each other - two polygons only need to be checked against each other if they both occupy at least one of the same regions in the quadtree. How deep you make your quadtree (in the case of polygons, as opp... | [
8,
3
] | [] | [] | [
"geometry",
"gis",
"python",
"sorting"
] | stackoverflow_0004777495_geometry_gis_python_sorting.txt |
Q:
Code Review and Mastermind Game Question
I'm trying to teach myself Python and found a couple of exercises online. One of which is to design a Mastermind type game here.
With the help of SO, I have managed most to do most of the requirements but I'm stuck at the last bit. I don't know how I can persist the display... | Code Review and Mastermind Game Question | I'm trying to teach myself Python and found a couple of exercises online. One of which is to design a Mastermind type game here.
With the help of SO, I have managed most to do most of the requirements but I'm stuck at the last bit. I don't know how I can persist the display of previous guess values, variable msg1, with... | [
"If you want to redisplay the full history of guesses every time, make msg1 a string that grows.\nmsg1 = \"\"\n...\n elif int(b) != int(a):\n msg1 += (\"{0}: position:{1}, exists {2}\\n\").format(b, position(a, b), (exists(a, b) - position(a, b)))\n print msg1,\n ...\n\nNotice that each msg ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004775266_python.txt |
Q:
Easiest way to share work between backend and front end
Hey everyone,
I am expanding my team and I have recently added an additional front end engineer on my site. I am currently using django to run my site but my site is using a lot of plugins, namely: django-celery, django-mailer, django-notification, and djang... | Easiest way to share work between backend and front end | Hey everyone,
I am expanding my team and I have recently added an additional front end engineer on my site. I am currently using django to run my site but my site is using a lot of plugins, namely: django-celery, django-mailer, django-notification, and django-socialregistration.
Let me describe my situation:
He is us... | [
"Another, free option, is to use VirtualBox. I would recommend installing the same OS on it as your production server. Then, he's developing in the same environment as the live site, and can just check into the repo the same as you. Hey, you may want to do the same on your end--then both of your environments are... | [
4,
1,
0
] | [] | [] | [
"django",
"installation",
"python"
] | stackoverflow_0004777262_django_installation_python.txt |
Q:
Python - Getting access to class instance via module property (by string name)
Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:
class Foobar():
def __init__(self, foo, bar, choo):
self.foo = foo
self.bar = bar
self.choo = choo
def do... | Python - Getting access to class instance via module property (by string name) | Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:
class Foobar():
def __init__(self, foo, bar, choo):
self.foo = foo
self.bar = bar
self.choo = choo
def doIt(self):
return self.foo + self.bar
and I want to have a set of 10 possibi... | [
"As the comment suggests, you likely have a name collision between Foobar the class and Foobar the module.\nHowever, it might be clearer to explicitly define a lookup table:\nfoobars = {\n 'label_one': Foobar(\"eenie\", \"meenie\", \"miney\"),\n 'label_two': Foobar(\"teeny\", \"toony\", \"tiny\"),\n ...\n 'labe... | [
4,
1,
1
] | [] | [] | [
"attributes",
"class",
"instance",
"module",
"python"
] | stackoverflow_0004772149_attributes_class_instance_module_python.txt |
Q:
Unicode error trying to call Google search API
I need to perform google search to retrieve the number of results for a query. I found the answer here - Google Search from a Python App
However, for few queries I am getting the below error. I think the query has unicode characters.
UnicodeDecodeError: 'ascii' codec ... | Unicode error trying to call Google search API | I need to perform google search to retrieve the number of results for a query. I found the answer here - Google Search from a Python App
However, for few queries I am getting the below error. I think the query has unicode characters.
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 28: ordinal not i... | [
"You cannot urlencode raw Unicode strings. You need to first encode them to UTF-8 and then feed to it: \nquery = urllib.urlencode({'q': u\"München\".encode('UTF-8')})\nThis returns q=M%C3%BCnchen which Google happily accepts.\n",
"You can't safely convert Unicode to ASCII. Doing so involves throwing away informat... | [
2,
0
] | [] | [] | [
"ascii",
"non_ascii_characters",
"python",
"unicode"
] | stackoverflow_0004777764_ascii_non_ascii_characters_python_unicode.txt |
Q:
Use python select kqueue on OSX to monitor file creation by external application
Typically the transcode of my 1 hr long audio recording sessions to an mp3 file takes twenty odd minutes.
I want to use a python script to execute a series of python code when the OSX application garageband finishes writing that mp3 f... | Use python select kqueue on OSX to monitor file creation by external application | Typically the transcode of my 1 hr long audio recording sessions to an mp3 file takes twenty odd minutes.
I want to use a python script to execute a series of python code when the OSX application garageband finishes writing that mp3 file.
What are the best ways in python to detect that an external application is done ... | [
"You could popen lsof and filter by either the process or file you're interested in...\n"
] | [
1
] | [] | [] | [
"epoll",
"file_io",
"kqueue",
"macos",
"python"
] | stackoverflow_0004777739_epoll_file_io_kqueue_macos_python.txt |
Q:
Query over a db.Model retrieves all the properties of the db.Model whether they are necessary or not. Is there an alternative?
I have db.Model which has several properties as described below:
class Doc(db.Model):
docTitle = db.StringProperty(required=True)
docText = db.TextProperty()
docUser = db.User... | Query over a db.Model retrieves all the properties of the db.Model whether they are necessary or not. Is there an alternative? | I have db.Model which has several properties as described below:
class Doc(db.Model):
docTitle = db.StringProperty(required=True)
docText = db.TextProperty()
docUser = db.UserProperty(required=True)
docDate = db.DateTimeProperty(auto_now_add=True)
In the template I just list the names of these documen... | [
"Entities are stored in the App Engine datastore as serialized protocol buffers, which are returned as a single blob, so it's not possible to just retrieve part of them. In any case, this would only save on RPC overhead between the datastore and your app, so the savings would be minimal.\nIf the size of each entity... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004759544_google_app_engine_google_cloud_datastore_python.txt |
Q:
converting string to long in python
Python provides a convenient method long() to convert string to long:
long('234')
; converts '234' into a long
If user keys in 234.89 then python will raise an error message:
ValueError: invalid literal for long()
with base 10: '234.89'
How should we a python programmer handl... | converting string to long in python | Python provides a convenient method long() to convert string to long:
long('234')
; converts '234' into a long
If user keys in 234.89 then python will raise an error message:
ValueError: invalid literal for long()
with base 10: '234.89'
How should we a python programmer handles scenarios where a string with a decima... | [
"longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just ... | [
38,
17
] | [] | [] | [
"python"
] | stackoverflow_0004777972_python.txt |
Q:
How to make a "top queries" page
A website I am making revolves around a search utility, and a want to have something on the homepage that lists the top 10 (or something) most searched queries of the day.
What would be the easiest / most efficient way of doing this?
Should I use a sql database, or just a text file... | How to make a "top queries" page | A website I am making revolves around a search utility, and a want to have something on the homepage that lists the top 10 (or something) most searched queries of the day.
What would be the easiest / most efficient way of doing this?
Should I use a sql database, or just a text file containing the top 10 queries and a c... | [
"Put the queries in a table, with one row per distinct query, and a column to count. Insert if the query doesn't exist already, or otherwise increment the query row counter. \nPut a cron job together than empties the table at 12 midnight. Use transactions to prevent two different requests from colliding.\n",
"If ... | [
2,
0
] | [] | [] | [
"multithreading",
"python",
"sql"
] | stackoverflow_0004778058_multithreading_python_sql.txt |
Q:
GAE and Facebook Connect: How to get age and gender of user?
I'm working with Google App Engine and Facebook Connect.
I have found Facebook Python SDK at https://github.com/facebook/python-sdk/tree/master/examples/appengine and it has some examples for basic user login and getting their names and friends.
How can ... | GAE and Facebook Connect: How to get age and gender of user? | I'm working with Google App Engine and Facebook Connect.
I have found Facebook Python SDK at https://github.com/facebook/python-sdk/tree/master/examples/appengine and it has some examples for basic user login and getting their names and friends.
How can I get the user's other information? I would like to have their ag... | [
"You dont need any permission for Gender property of the user and for the Age you can calculate by Subtracting the User's Date of birth by current Date.\nFor Date of Birth you need user_birthday Extended Permission\nIf you want to know how to request permissions specify them in scope query parameter like this\nhttp... | [
2
] | [] | [] | [
"facebook",
"facebook_graph_api",
"google_app_engine",
"python"
] | stackoverflow_0004777518_facebook_facebook_graph_api_google_app_engine_python.txt |
Q:
Ways to store and access large (~10 GB) lists in Python?
I have a large set of strings that I'm using for natural language processing research, and I'd like a nice way to store it in Python.
I could use pickle, but loading the entire list into memory would then be an impossibility (I believe), as it's about 10 GB ... | Ways to store and access large (~10 GB) lists in Python? | I have a large set of strings that I'm using for natural language processing research, and I'd like a nice way to store it in Python.
I could use pickle, but loading the entire list into memory would then be an impossibility (I believe), as it's about 10 GB large, and I don't have that much main memory. Currently I hav... | [
"Depending upon how you intend to get at the data, SQLite3 might be the best approach. SQLite3 is excellent at random access to relational data, but if your data is not very relational, it might not make as much sense. (Even if all your have is an 'id' number and then your string, I think SQLite3 for underlying sto... | [
9,
3,
1
] | [] | [] | [
"list",
"nlp",
"pickle",
"python",
"shelve"
] | stackoverflow_0004778089_list_nlp_pickle_python_shelve.txt |
Q:
Python 3.1 - Grid simulation
I'm hoping to get some tips on what direction I should take, to complete the following;
I need to take a 1D list of integers, and convert it into a grid; where the integers are randomly placed (multi-dimensional array?). I then need a function, where when I select and then modify one ... | Python 3.1 - Grid simulation | I'm hoping to get some tips on what direction I should take, to complete the following;
I need to take a 1D list of integers, and convert it into a grid; where the integers are randomly placed (multi-dimensional array?). I then need a function, where when I select and then modify one of the grid elements, all surround... | [
"Well, here's a quick one:\n1d_list = [45, 18, 77, 24, 47, 88, 61, 96, 46, 97, 16, 65, 39, 56, 14, 48, 87, 44, 91, 22, 21, 38, 59, 95, 75, 80, 20, 51, 66, 62, 50, 82, 60, 57, 10, 23, 6, 8, 28, 83, 71, 76, 36, 32, 90, 29, 40, 37] // I didn't write this ;)\n\n2d_list = []\n\nfor y in range(6):\n holder = []\n\n for... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004778167_python.txt |
Q:
How does one get the output of fabric execution (fab.exe) on windows 7?
I am am interested in using Fabric as a deployment tool and I am having trouble making it through the tutorial. I believe I have it installed correctly (I used easy-install)
I have defined the sample function in fabfile.py:
def hello():
p... | How does one get the output of fabric execution (fab.exe) on windows 7? | I am am interested in using Fabric as a deployment tool and I am having trouble making it through the tutorial. I believe I have it installed correctly (I used easy-install)
I have defined the sample function in fabfile.py:
def hello():
print("Hello world!")
I then open a command window and run
C:\dev>fab hello
... | [
"DiggyF's suggestion worked great for taming the cmd shell\nfab hello > output.txt 2>&1\n\nI now get the output of the instantaneous shell execution piped to a file.\nThe output: ImportError: No module named win32api. This led me on a much longer goose chase that needs to be placed in another question.\nThe soluti... | [
2
] | [] | [] | [
"cmd",
"fabric",
"python",
"windows_7"
] | stackoverflow_0004777503_cmd_fabric_python_windows_7.txt |
Q:
Making a .deb file from a Python file
After following http://ubuntuforums.org/showthread.php?t=406069 I got to know how to make a .deb file which automatically places the Python file as an executable to /usr/bin directory. I want my program to have a structure like that of "grep". Which libraries should I use, and... | Making a .deb file from a Python file | After following http://ubuntuforums.org/showthread.php?t=406069 I got to know how to make a .deb file which automatically places the Python file as an executable to /usr/bin directory. I want my program to have a structure like that of "grep". Which libraries should I use, and what should be the structure of the progra... | [
"There are lots of examples of Debian packaging for Python packages at http://svn.debian.org/wsvn/python-modules/packages. Many of the projects include man page support, such as http://svn.debian.org/wsvn/python-modules/packages/python-paver/trunk/debian/\n"
] | [
0
] | [] | [] | [
"deb",
"eps",
"package",
"python"
] | stackoverflow_0004770883_deb_eps_package_python.txt |
Q:
(How) can you add methods to a collection of entities in Google App Engine python?
In GAE-python, you can model a one-to-many relationship by assigning a reference property to the child model.
class Book(db.Model):
title = db.StringProperty()
class Author(db.Model):
book = db.ReferenceProperty(Book, collecti... | (How) can you add methods to a collection of entities in Google App Engine python? | In GAE-python, you can model a one-to-many relationship by assigning a reference property to the child model.
class Book(db.Model):
title = db.StringProperty()
class Author(db.Model):
book = db.ReferenceProperty(Book, collection_name = 'authors')
is_primary = db.BooleanProperty()
name = db.StringProperty()
... | [
"What you are looking for is one to many realtionship. There is no db.Referencelist property.I guess this will help you out.\nclass Book(db.Model):\n title = db.StringProperty()\nclass Author(db.Model):\n is_primary = db.BooleanProperty()\n name = db.StringProperty()\n\nbook = Book(title=\"what is life\")\nb... | [
0
] | [] | [] | [
"collections",
"google_app_engine",
"model",
"python"
] | stackoverflow_0003505745_collections_google_app_engine_model_python.txt |
Q:
How do I detect symbols in a string using regular expressions?
I am developing a web application for a school and the have things like class_name and course_name. A course_name is the parent of a class_name, hence the class_name must contain the course_name. For instance:
course_name = "Weeklies"
class_name = "... | How do I detect symbols in a string using regular expressions? | I am developing a web application for a school and the have things like class_name and course_name. A course_name is the parent of a class_name, hence the class_name must contain the course_name. For instance:
course_name = "Weeklies"
class_name = "Weeklies talks with Superstars"
The above case would be perfect and... | [
"re.escape()\n",
"This is sort of a general purpose solution... Just replace the regular expression with a suitable grammar.\nif not re.match(str, r'[\\w\\d\\ ]+'):\n # valid\n\n"
] | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004778931_python_regex.txt |
Q:
Accessing http upload data before upload completion
Is there any way to access a file being uploaded over http using a CGI script before the upload finishes? For example, say a 10 megabyte file is being uploaded, and is exactly 10% done, meaning the server has 1 megabyte of data. Is it possible to read that 1 mega... | Accessing http upload data before upload completion | Is there any way to access a file being uploaded over http using a CGI script before the upload finishes? For example, say a 10 megabyte file is being uploaded, and is exactly 10% done, meaning the server has 1 megabyte of data. Is it possible to read that 1 megabyte of data without waiting for the upload to finish?
My... | [
"CGI is the specification of communication between the web server and the external application. It does not allow for this.\nIn fact, most web servers won't do anything with an upload until it finishes, but there's no reason you couldn't write/change one (or MAYBE find one, but I don't know which it would be) to a... | [
2
] | [] | [] | [
"cgi",
"http",
"python",
"upload"
] | stackoverflow_0004779272_cgi_http_python_upload.txt |
Q:
ArcGIS and ACCESS table
I'm new to Python in combination with ArcGIS.
I have a shape file with different regions A,B and C and an Access table :
feature region
1 A
1 B
2 C
3 A
3 B
Now I'm trying to select one of the features and corresponding regions to give same a different color. Is there a good way doing this w... | ArcGIS and ACCESS table | I'm new to Python in combination with ArcGIS.
I have a shape file with different regions A,B and C and an Access table :
feature region
1 A
1 B
2 C
3 A
3 B
Now I'm trying to select one of the features and corresponding regions to give same a different color. Is there a good way doing this with python?
Thanks a lot for... | [
"I think I got it by my own. \nHere are some important hints:\n1)Join the table and shape file with the corresponding row:\narcpy.AddJoin_management(\"regionsshape\",\"NAME\",\"region_table\",\"NAME\")\n\n2)Loop over the table and do selection:\nrows = arcpy.SearchCursor(\"region_table\")\n for row in rows:\n ... | [
0
] | [] | [] | [
"arcgis",
"ms_access",
"python"
] | stackoverflow_0004646268_arcgis_ms_access_python.txt |
Q:
ARCGIS: open feature into TOC
I'm trying to open 1000 maps automated with python script and export one by one.
Can some tell me how to open them to the TOC with the python script instead of doing by hand.
Also how do I change the visibility with python instead of doing by hand.
cheers
eactor
A:
part one is done... | ARCGIS: open feature into TOC | I'm trying to open 1000 maps automated with python script and export one by one.
Can some tell me how to open them to the TOC with the python script instead of doing by hand.
Also how do I change the visibility with python instead of doing by hand.
cheers
eactor
| [
"part one is done with:\naddLayer = arcpy.mapping.Layer(r\"C:/example.lyr\")\n\npart two you only open the ones you would like to see and remove the other ones:\narcpy.Delete_management(layername)\n\nnote: layername does not have to be the same as the lyr file name! It is the name which occurs in the TOC. \n"
] | [
1
] | [] | [] | [
"arcgis",
"arcpy",
"python"
] | stackoverflow_0004720353_arcgis_arcpy_python.txt |
Q:
tagging dictionary data
I would like to do something equivalent to "tagging" a dictionary element.
Here is some pseudo-code to illustrate the idea:
mydict = dict()
mydict['thiskey'] = 'myvalue'
#then i would like to do this:
mydict['thiskey'].tag = 1
is there anything like this?
or maybe i could just append to th... | tagging dictionary data | I would like to do something equivalent to "tagging" a dictionary element.
Here is some pseudo-code to illustrate the idea:
mydict = dict()
mydict['thiskey'] = 'myvalue'
#then i would like to do this:
mydict['thiskey'].tag = 1
is there anything like this?
or maybe i could just append to the value somehow?
but i would ... | [
"Two possibilities I can think of are either creating a simple TaggedData class containing just a tag and value. Or using a dictionary as the value with only the keys 'tag' and 'value'.\n",
">>> class MyStr(str):pass\n... \n>>> mydict = dict()\n>>> mydict['thiskey'] = MyStr('myvalue')\n>>> mydict['thiskey'].tag ... | [
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004779608_python.txt |
Q:
Python - py2exe - DeprecationWarning
I've installed python 2.6 and new version of py2exe.
hello.py
print "Hello from py2exe"
setup.py
from distutils.core import setup
import py2exe
setup(
# The first three parameters are not required, if at least a
# 'version' is given, then a versioninfo resource is bui... | Python - py2exe - DeprecationWarning | I've installed python 2.6 and new version of py2exe.
hello.py
print "Hello from py2exe"
setup.py
from distutils.core import setup
import py2exe
setup(
# The first three parameters are not required, if at least a
# 'version' is given, then a versioninfo resource is built from
# them and added to the execut... | [
"Its not an error, its just a warning about a deprecated class; in this case the sets module is deprecated and the new code should use built-in set class now.\n"
] | [
4
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0004779887_py2exe_python.txt |
Q:
Finding connections between objects to the nth degree
For the following models:
class Entity(models.Model):
name = models.CharField(max_length=256)
class Entry(models.Model):
""" A <subj> has a <connection> to an <obj>
"""
subj = models.ForeignKey(Entity, related_name='subject')
connection = m... | Finding connections between objects to the nth degree | For the following models:
class Entity(models.Model):
name = models.CharField(max_length=256)
class Entry(models.Model):
""" A <subj> has a <connection> to an <obj>
"""
subj = models.ForeignKey(Entity, related_name='subject')
connection = models.CharField(max_length=512)
obj = models.ForeignKey... | [
"This is a graph theory problem. Your model represents edges connecting nodes, and you want to find paths between nodes. There are python libs for this kind of thing, such as the python interface to the Boost library.\nread up on graph theory, and check out relevant python packages. The search algorithm you need wi... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004728831_django_python.txt |
Q:
python MySQLdb error?
while i am trying to connect with python MySQLdb, i get an 'Invalid Arguments' error.
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = "test")
what is the reason for getting such a error?.
But, the following code with _mysql works fine.
db=_mysql.conne... | python MySQLdb error? | while i am trying to connect with python MySQLdb, i get an 'Invalid Arguments' error.
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = "test")
what is the reason for getting such a error?.
But, the following code with _mysql works fine.
db=_mysql.connect("localhost","root","","t... | [
"import MySQLdb.cursors\n\nDATABASE= MySQLdb.connect(host='localhost', user='username', passwd='password', db='databasename', cursorclass=MySQLdb.cursors.DictCursor)\n\nHope it helps.\n",
"Shouldn't that be\nconn = MySQLdb.connect (\"localhost\",\"root\",\"\",\"test\")\n\n?\n(random reference: http://www.tutorial... | [
2,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004779552_mysql_python.txt |
Q:
What does preceding a string literal with "r" mean?
I first saw it used in building regular expressions across multiple lines as a method argument to re.compile(), so I assumed that r stands for RegEx.
For example:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]$', re.IGNORECASE
)
So what does r me... | What does preceding a string literal with "r" mean? | I first saw it used in building regular expressions across multiple lines as a method argument to re.compile(), so I assumed that r stands for RegEx.
For example:
regex = re.compile(
r'^[A-Z]'
r'[A-Z0-9-]'
r'[A-Z]$', re.IGNORECASE
)
So what does r mean in this case? Why do we need it?
| [
"The r means that the string is to be treated as a raw string, which means all escape codes will be ignored.\nFor an example:\n'\\n' will be treated as a newline character, while r'\\n' will be treated as the characters \\ followed by n.\n\nWhen an 'r' or 'R' prefix is present,\n a character following a backslash ... | [
240,
45
] | [] | [] | [
"literals",
"python",
"rawstring",
"string",
"syntax"
] | stackoverflow_0004780088_literals_python_rawstring_string_syntax.txt |
Q:
Good django middleware/example source for adding "reviews" to models?
I've become extremely frustrated trying to use django-reviews. I've looked through the documentation, which is very sparse, and the source code, but I can't for the life of me figure out how to use it. To boot, none of the templates are included... | Good django middleware/example source for adding "reviews" to models? | I've become extremely frustrated trying to use django-reviews. I've looked through the documentation, which is very sparse, and the source code, but I can't for the life of me figure out how to use it. To boot, none of the templates are included.
Are there any other alternatives or perhaps some opensource projects that... | [
"If you need examples - django has great coverage of generic relations in docs. Also, bundled comments framework is \"review app\" of some sort. You can attach a comment to any object in the system, add field for a rating and you have review system :)\n",
"Paperino, if you want to review a particular model, could... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004776012_django_python.txt |
Q:
Converting video files uploaded by user & serving it using django, python
I need to take any video file uploaded by the user, convert it into flv or webM & then display it to the user. Now after doing some research I came to the conclusion that I must use ffmpeg to do the conversion but I am unsure on how to take ... | Converting video files uploaded by user & serving it using django, python | I need to take any video file uploaded by the user, convert it into flv or webM & then display it to the user. Now after doing some research I came to the conclusion that I must use ffmpeg to do the conversion but I am unsure on how to take care of the entire pipeline. Namely,
Get the just uploaded file by the user.
I... | [
"If a conversion is going to take a long time, you might want to consider passing them off to a task handler:\nhttp://celeryproject.org/\nmight be just the thing. System calls in python can be done with functions in the os module, such as os.system:\n>>> os.system(\"/bin/ls\")\napi-manual.pdf C++ GUI Java READM... | [
3
] | [] | [] | [
"django",
"ffmpeg",
"python",
"video",
"video_encoding"
] | stackoverflow_0004778607_django_ffmpeg_python_video_video_encoding.txt |
Q:
Several many to many table joins with sqlalchemy
New with SQLalchemy, here is my problem:
My model is:
user_group_association_table = Table('user_group_association', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('group_id', Integer, ForeignKey('group.id'))
)
department_grou... | Several many to many table joins with sqlalchemy | New with SQLalchemy, here is my problem:
My model is:
user_group_association_table = Table('user_group_association', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('group_id', Integer, ForeignKey('group.id'))
)
department_group_association_table = Table('department_group_associat... | [
"session.query(User).join((Group, User.groups)) \\\n .join((Department, Group.departments)).filter(Department.name == 'R&D')\n\nThis also works, but uses a sub-select:\nsession.query(User).join((Group, User.groups)) \\\n .filter(Group.departments.any(Department.name == 'R&D'))\n\n",
"Why don't you create a ... | [
27,
1
] | [] | [] | [
"join",
"python",
"sqlalchemy"
] | stackoverflow_0004679846_join_python_sqlalchemy.txt |
Q:
Vim : Moving Through Code
I want to be able to navigate the cursor across functions using Vim. Mainly, I want a command to allow me to go to the next function, like } allows me to go to the next paragraph. I found this:
Go to the end of the C++ function in Vim
Unfortunately, it doesn't seem to work fine in JavaScr... | Vim : Moving Through Code | I want to be able to navigate the cursor across functions using Vim. Mainly, I want a command to allow me to go to the next function, like } allows me to go to the next paragraph. I found this:
Go to the end of the C++ function in Vim
Unfortunately, it doesn't seem to work fine in JavaScript. Also, I believe it would a... | [
"In a Python file I find:\n\n} will take me to the end of a block,\n]] will take me to the start of the next function.\n[[ takes me to the start of the current function, or the one above if I keep pressing.\n\n]} didn't seem to work though.\n"
] | [
8
] | [] | [] | [
"code_navigation",
"javascript",
"python",
"vim"
] | stackoverflow_0004780429_code_navigation_javascript_python_vim.txt |
Q:
Python Tutorial Question: Ends With Function
I have a python tutorial question which i couldn't get past. The question as follow:
Ends With
Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation sho... | Python Tutorial Question: Ends With Function | I have a python tutorial question which i couldn't get past. The question as follow:
Ends With
Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive").
My solution:
def end... | [
"What about using python's builtin str.endswith() method?\ndef end_other(a, b):\n a_lower = a.lower()\n b_lower = b.lower()\n return a_lower.endswith(b_lower) or b_lower.endswith(a_lower)\n\n",
"I think this is what you were actually trying to do:\ndef end_other ( a, b ):\n a = a.lower()\n b = b.lo... | [
17,
7,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004779790_python.txt |
Q:
python relative inclusion
I have created a little framework and my directory structure is this
myframework -> contrib -> jinja2
myframework -> contrib -> session
myframework -> start.py
the problem is for package under contrib, infact jinjia2 like session have subdirectory and in the __init__.py of jinja2 there'r... | python relative inclusion | I have created a little framework and my directory structure is this
myframework -> contrib -> jinja2
myframework -> contrib -> session
myframework -> start.py
the problem is for package under contrib, infact jinjia2 like session have subdirectory and in the __init__.py of jinja2 there're some imports relative to root... | [
"You are going to have a hard time if you are going to redesign the structure of package where relative imports are already used. Just use the package in the way it was designed to and for multiple packages, just make sure that they are all in PYTHONPATH.\nrelative imports work best under the following directory st... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004780505_google_app_engine_python.txt |
Q:
python - get attribute to subclass
How to get attribute to subclass?
I mean the part age=age
def method(name='thomas', age=27):
submethod(age=age)
A:
I'm not totally sure what you mean by this code, is the submethod abstract?
Anyway, you're missing self, that's not a method. This should work:
def method(self... | python - get attribute to subclass | How to get attribute to subclass?
I mean the part age=age
def method(name='thomas', age=27):
submethod(age=age)
| [
"I'm not totally sure what you mean by this code, is the submethod abstract?\nAnyway, you're missing self, that's not a method. This should work:\ndef method(self, name='Thomas', age=27):\n self.submethod(name, age)\n\nIf the submethod argument is keyword only, you could rename the local argument value for clarity... | [
3
] | [] | [] | [
"attributes",
"python"
] | stackoverflow_0004780785_attributes_python.txt |
Q:
How to use lxml to find element text in XHTML document
I've been bashing my head at this for ages, I must be doing something stupid.
I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.
Here is my python code so far... | How to use lxml to find element text in XHTML document | I've been bashing my head at this for ages, I must be doing something stupid.
I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.
Here is my python code so far, which is simply trying to retrieve one of the tables:
impo... | [
"I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias\n\nYour problem is that the element names in the document are in a default namespace. How to write XPath expressions that involve such element names is the most FA... | [
3,
3,
0
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0004771754_lxml_python_xpath.txt |
Q:
N dimensional arrays - Python/Numpy
just wondering if there is any clever way to do the following.
I have an N dimensional array representing a 3x3 grid
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
In order to get the first row I do the following:
grid[0][0:3]
>> [1,2,3]
In order to get the first column I ... | N dimensional arrays - Python/Numpy | just wondering if there is any clever way to do the following.
I have an N dimensional array representing a 3x3 grid
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
In order to get the first row I do the following:
grid[0][0:3]
>> [1,2,3]
In order to get the first column I would like to do something like this (eve... | [
"Yes, there is something like that in Numpy:\nimport numpy as np\n\ngrid = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\ngrid[0,:]\n# array([1, 2, 3])\n\ngrid[:,0]\n# array([1, 4, 7])\n\n",
"You can use zip to transpose a matrix represented as a list of lists:\n>>> zip(*grid)[... | [
10,
2,
1
] | [] | [] | [
"math",
"numpy",
"python",
"scipy"
] | stackoverflow_0004780791_math_numpy_python_scipy.txt |
Q:
python unicode beginner : how to print out a series of letters?
I'de like to iterate through a list and print it out (for later use with the curses library) :
U+0080 ... U+00FF: Latin-1 Supplement
U+0100 ... U+017F: Latin Extended-A
U+0180 ... U+024F: Latin Extended-B
U+0250 ... U+02AF: IPA Extensions
U+02B0 ... ... | python unicode beginner : how to print out a series of letters? | I'de like to iterate through a list and print it out (for later use with the curses library) :
U+0080 ... U+00FF: Latin-1 Supplement
U+0100 ... U+017F: Latin Extended-A
U+0180 ... U+024F: Latin Extended-B
U+0250 ... U+02AF: IPA Extensions
U+02B0 ... U+02FF: Spacing Modifier Letters
U+0300 ... U+036F: Combining Diacrit... | [
"What about : http://docs.python.org/howto/unicode.html\nfor i in xrange(0x80, 0xFF):\n print unichr(i)\n\n"
] | [
9
] | [] | [] | [
"iteration",
"python",
"unicode"
] | stackoverflow_0004780985_iteration_python_unicode.txt |
Q:
Which language should I stick with
I've got good experience in Java and web development with some experience in C++ also. Lately, I've been thinking of leaving Java (bored with it) for C++. Then came Python(didn't like Ruby). I find it too good to resist and started using it. But the C++ still stays in my mind.
N... | Which language should I stick with | I've got good experience in Java and web development with some experience in C++ also. Lately, I've been thinking of leaving Java (bored with it) for C++. Then came Python(didn't like Ruby). I find it too good to resist and started using it. But the C++ still stays in my mind.
Now I want to "stick" with one language t... | [
"I suggest you don't worry about \"sticking\" with a language and learn to move in and out of whatever is the best solution for your problem. \nThe best programmers are simply great problem solvers - the particular language doesn't really matter.\n",
"I am of the opinion that you don't \"leave\" a language. It'... | [
13,
4,
3,
3,
2,
2,
1
] | [] | [] | [
"c++",
"choice",
"python"
] | stackoverflow_0004778978_c++_choice_python.txt |
Q:
Matplotlib + sockets = Hangup?
I am trying to plot data that I receive over a socket. I am using "Matplotlib" as the plotting library and "cPickle" to serialize python objects.
When I run my code, plot window opens and hangs up. I have tried a couple of ways to get around it, but no help
Don't know if this might h... | Matplotlib + sockets = Hangup? |
I am trying to plot data that I receive over a socket. I am using "Matplotlib" as the plotting library and "cPickle" to serialize python objects.
When I run my code, plot window opens and hangs up. I have tried a couple of ways to get around it, but no help
Don't know if this might help, but...I am using "Python 2.7 -... | [
"I think you just need to change pylab.show() to pylab.draw()\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003994066_matplotlib_python.txt |
Q:
using python 2.6?
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine.
will i still be able to find host that supports python 2.6?
is using python 2.6 still consider outdated or bad practice?
A:
2.6 will be around for a long time. There are many machines that s... | using python 2.6? | i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine.
will i still be able to find host that supports python 2.6?
is using python 2.6 still consider outdated or bad practice?
| [
"2.6 will be around for a long time. There are many machines that still run even 2.4, so you're fine.\n",
"Python 2.6 will probably still be around for a while, as Python 2.7 was released only a few months ago.\nYou can always use from __future__ import ... to make use of some of the newer features from Python 3.... | [
4,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004778679_python.txt |
Q:
Speedier/less resource-demolishing way to strip html from large files than BeautifulSoup? Or, a better way to use BeautifulSoup?
Currently I am having trouble typing this because, according to top, my processor is at 100% and my memory is at 85.7%, all being taken up by python.
Why? Because I had it go through a ... | Speedier/less resource-demolishing way to strip html from large files than BeautifulSoup? Or, a better way to use BeautifulSoup? | Currently I am having trouble typing this because, according to top, my processor is at 100% and my memory is at 85.7%, all being taken up by python.
Why? Because I had it go through a 250-meg file to remove markup. 250 megs, that's it! I've been manipulating these files in python with so many other modules and things... | [
"lxml.html is FAR more efficient.\nhttp://lxml.de/lxmlhtml.html\n\nhttp://blog.ianbicking.org/2008/03/30/python-html-parser-performance/\n\nLooks like this will do what you want.\nimport lxml.html\nt = lxml.html.fromstring(\"...\")\nt.text_content()\n\nA couple of other similar questions: python [lxml] - cleaning o... | [
13,
0
] | [] | [] | [
"beautifulsoup",
"html",
"parsing",
"performance",
"python"
] | stackoverflow_0004781833_beautifulsoup_html_parsing_performance_python.txt |
Q:
How to create a variable containing input from a list in Python
I've a lists containing .las Files of different length. I couldn't figure out how it is possible to create a variable containing all the list entries separated by a ";" ?
Thanks for your help,
Mauro
A:
Well am not sure if I get you but:
some_list ... | How to create a variable containing input from a list in Python | I've a lists containing .las Files of different length. I couldn't figure out how it is possible to create a variable containing all the list entries separated by a ";" ?
Thanks for your help,
Mauro
| [
"Well am not sure if I get you but:\nsome_list = ['file.las', 'another_file.las', 'something.las']\ne = ';'.join(some_list)\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004782028_python.txt |
Q:
Python references
I have come across a situation that I believe has revealed a gap in my understanding of how references work in Python.
Suppose that we have two classes:
class A:
def __init__(self):
self.x = [1,2,3]
def modify(self):
self.x.append(4)
def reset(self):
self.x =... | Python references | I have come across a situation that I believe has revealed a gap in my understanding of how references work in Python.
Suppose that we have two classes:
class A:
def __init__(self):
self.x = [1,2,3]
def modify(self):
self.x.append(4)
def reset(self):
self.x = []
class B:
def _... | [
"The reset() method\ndef reset(self):\n self.x = []\n\ndoes not modify the object stored in self.x -- it rather creates a new empty list, which is then stored in self.x. The old list is not altered (and since it is still referenced by b._x, it is also not garbage collected). To get the behaviour you are after,... | [
10,
3,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004782272_list_python.txt |
Q:
Start long running process using subprocess module
I am trying to start a java process that is meant to take a long time, using python's subprocess module.
What I am actually doing is using the multiprocessing module to start a new Process, and using that process, use subprocess module to run java -jar.
This works... | Start long running process using subprocess module | I am trying to start a java process that is meant to take a long time, using python's subprocess module.
What I am actually doing is using the multiprocessing module to start a new Process, and using that process, use subprocess module to run java -jar.
This works fine, but when I start the new process, the java proces... | [
"I think you should show some code, it's not clear how you are using subprocess and multiprocessing together. \nFrom the documentation it looks like subprocess should spawn and not replace your new Process-started process. Are you sure that isn't happening ? A test case showing it doesn't would be good.\nYou may ... | [
0
] | [] | [] | [
"multiprocessing",
"process",
"python",
"subprocess"
] | stackoverflow_0004781716_multiprocessing_process_python_subprocess.txt |
Q:
How can I tell Pychecker to ignore an imported library?
One of the modules I import into my python project triggers lots of warnings under Pychecker. Fixing up this external module isn't really an option, so I want to tell Pychecker to ignore it.
Does anyone know how to do this? I'm sure it's possible, and probabl... | How can I tell Pychecker to ignore an imported library? | One of the modules I import into my python project triggers lots of warnings under Pychecker. Fixing up this external module isn't really an option, so I want to tell Pychecker to ignore it.
Does anyone know how to do this? I'm sure it's possible, and probably quite simple, but after trawling Google for a while I've no... | [
"Per the docs, \n\nIf you want to suppress warnings on a\n module/function/class/method, you can\n define a suppressions dictionary in\n .pycheckrc. Examples of keys are:\n 'module', 'module.function',\n 'module.class', 'module.class.method',\n etc.etc.\n\nIOW, in your .pycheckrc, if the troublesome module is... | [
1,
1,
1
] | [] | [] | [
"pychecker",
"python"
] | stackoverflow_0003736311_pychecker_python.txt |
Q:
Problem with accented characters
I'm having a problem on the accentuation of Python regular expression, I'm doing the following attempt:
import re
ER = re.compile(r'\w', re.L)
print(ER.sub('.','Maçã'))
..çã
Even using the re.compile passing the locale as an argument, the accents are not recognized.
Has anyone ha... | Problem with accented characters | I'm having a problem on the accentuation of Python regular expression, I'm doing the following attempt:
import re
ER = re.compile(r'\w', re.L)
print(ER.sub('.','Maçã'))
..çã
Even using the re.compile passing the locale as an argument, the accents are not recognized.
Has anyone had this problem?
Thanks!
| [
"You're better off using re.U unicode flag.\nIf using Python 2.x you also need to specify the string as unicode, i.e. \nprint(ER.sub('.', u'Maçã'))\n\n",
"From http://www.regular-expressions.info/python.html\n\nBy default, Python's regex engine only considers the letters A through Z, the digits 0 through 9, and t... | [
4,
4,
0
] | [] | [] | [
"python",
"regex",
"unicode"
] | stackoverflow_0004782023_python_regex_unicode.txt |
Q:
Calculate all possible factors of a prime
Was going through a Python Tutorial and came across an example to check whether a number is prime or not. I changed a few things so that the result would display a list of all possible factors of the number, if the number is not a prime, However, the code didn't work.
Code... | Calculate all possible factors of a prime | Was going through a Python Tutorial and came across an example to check whether a number is prime or not. I changed a few things so that the result would display a list of all possible factors of the number, if the number is not a prime, However, the code didn't work.
Code:
def isprime(number):
print "Reticulating... | [
"Your final if notprime ... and the three lines following it are indented too far and as such is executed inside the loop, instead of outside. \n",
"You return after testing only one number. Move the if tests and the returns to outside of the for loop.\nAlso, returning True if it is a prime, and a string if it is... | [
1,
1,
1,
1
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0004781841_primes_python.txt |
Q:
How to move old libraries of previous version python to new version of python
I am using Ubuntu. I install newer version of python. But all my installed libraries such as imdbPy, NumPy, Cython etc. can run in previous version of python whose version number is 2.6.6.
When I import Cython in 2.6.6, tt works, but I ... | How to move old libraries of previous version python to new version of python | I am using Ubuntu. I install newer version of python. But all my installed libraries such as imdbPy, NumPy, Cython etc. can run in previous version of python whose version number is 2.6.6.
When I import Cython in 2.6.6, tt works, but I try same thing in 2.7.0+ version of python
import cython
occurs an error as follow... | [
"Don't mess with your system installs - the package manager should be responsible for that. Make sure that when you install from source, you do it in a separate directory.\nI install things in my home directory. I like jhbuild so this is what I use to maintain different versions of python side by side: https://th... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0004781500_python_pythonpath.txt |
Q:
How can my code tell if it's running on Google's server or my local development server?
Possible Duplicate:
In Python, how can I test if I'm in Google App Engine SDK?
Is there an environment flag that will tell if my code is running in production or on the development server?
I'd like to be able to use an if sta... | How can my code tell if it's running on Google's server or my local development server? |
Possible Duplicate:
In Python, how can I test if I'm in Google App Engine SDK?
Is there an environment flag that will tell if my code is running in production or on the development server?
I'd like to be able to use an if statement to do something different depending on this flag.
(Specific case: newlines in a text ... | [
"if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):\n DEBUG = True\n logging.debug(\"[*] Debug info activated\")\n\n",
"For Google App Engine, since I've been told that you can't import socket you could probably use that fact to determine if you're running on GAE. This solution isn't 100% f... | [
17,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004782332_google_app_engine_python.txt |
Q:
django default foreign key value for users
I've had a read through http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/ but still am having problems migrating my new db schema with a ForeignKey for a user in a list of products
a simplified version of my code is:
from django.contrib.auth.model... | django default foreign key value for users | I've had a read through http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/ but still am having problems migrating my new db schema with a ForeignKey for a user in a list of products
a simplified version of my code is:
from django.contrib.auth.models import User
# other imports
class Product(mod... | [
"If you want it to be possible to have an empty value for author, you need to define the ForeignKey with null=True. You'll probably want blank=True as well, as that controls the validation in Django forms.\nauthor = models.ForeignKey(User, null=True, blank=True)\n\n",
"Ended up taking the easy route and totally r... | [
0,
0
] | [] | [] | [
"django",
"mysql_error_1067",
"python"
] | stackoverflow_0004782438_django_mysql_error_1067_python.txt |
Q:
Beginning (python) regex question
I'm having trouble figuring out why the following regex doesn't seem to work.
I know that I can form other regular expressions to make this work, but I thought this one should work.
re.search ("(\d*)", "prefix 1234 suffix").groups()
('',)
Interestingly, findall seems to work:
re.... | Beginning (python) regex question | I'm having trouble figuring out why the following regex doesn't seem to work.
I know that I can form other regular expressions to make this work, but I thought this one should work.
re.search ("(\d*)", "prefix 1234 suffix").groups()
('',)
Interestingly, findall seems to work:
re.findall("(\d*)", "prefix 1234 suffix")
... | [
"Because .search runs the search once, and matches in the first place it can. Since \\d* can match no characters at all, the first place it can match is at the beginning of the string, capturing no characters -- so the first capture group is ''. It's doing exactly what you asked it to.\nIf you had made the regex (\... | [
6,
3,
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004783275_python_regex.txt |
Q:
wxPython PopUp notifications
We are building an app where in there will be a need to display the updates/notification (ex : like status updates/wall posts on FB). These needs to be displyed at the lower right corner of the window(like any other notifications). So was trying on some alternatives to best display the... | wxPython PopUp notifications | We are building an app where in there will be a need to display the updates/notification (ex : like status updates/wall posts on FB). These needs to be displyed at the lower right corner of the window(like any other notifications). So was trying on some alternatives to best display the updates. Some option explored are... | [
"FWIW, you can check out ToasterBox - MSN style popups, which should be perfect for your case. (And yes, it is cross platform)\n",
"Check out the source code for my RSS notifier application. Example screenshot shown below. Yes, this is implemented with wxPython.\nhttp://www.feednotifier.com/\n\nThe modules to loo... | [
4,
4,
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004755963_python_user_interface_wxpython.txt |
Q:
Calculating non-prime divisors from primes
Having a number e.g. 510510
The prime divisors are: [2, 3, 5, 7, 11, 13, 17]
Using the list of primes, what could an efficient way to calculate the non-prime divisors be?
A:
Assuming that the list of prime factors contains all factors according to there multiplicity, yo... | Calculating non-prime divisors from primes | Having a number e.g. 510510
The prime divisors are: [2, 3, 5, 7, 11, 13, 17]
Using the list of primes, what could an efficient way to calculate the non-prime divisors be?
| [
"Assuming that the list of prime factors contains all factors according to there multiplicity, you can use\nprime_factors = [2, 3, 5, 7, 11, 13, 17]\nnon_prime_factors = [reduce(operator.mul, f)\n for k in range(2, len(prime_factors) + 1)\n for f in itertools.combinations(pri... | [
3,
1,
1,
0,
0
] | [] | [] | [
"factorization",
"math",
"python"
] | stackoverflow_0004783261_factorization_math_python.txt |
Q:
Split and take n words from the end
How would you take the last n end words from a split line? For example I have these lines:
1. 123.by2.gateway.edge.messenger.live.com
2. messenger.com
3. 10.17.123.45
4. 126.by2.gateway.edge.messenger.live.com
5. 14.messenger.live.com
I want to take the 3 last words from the ad... | Split and take n words from the end | How would you take the last n end words from a split line? For example I have these lines:
1. 123.by2.gateway.edge.messenger.live.com
2. messenger.com
3. 10.17.123.45
4. 126.by2.gateway.edge.messenger.live.com
5. 14.messenger.live.com
I want to take the 3 last words from the addresses so that for lines 1, 4 & 5 I have... | [
"You want to take\nplink = link[-3:]\n\nTo ignore the numeric IP you can use this:\nlink = line.split('.')\nif len(link) > 3 and link[-1].isalpha():\n plink = link[-3:]\n\nThis will ignore 2. and 3., while proceeding the 5. correctly (as SilentGhost correctly noted, your code ignores the 5.)\n"
] | [
4
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0004783394_list_python_slice.txt |
Q:
How does polling a file for changes work?
The problem
I expected the script below to print at most one event and then stop (it's written only to illustrate the problem).
#!/usr/bin/env python
from select import poll, POLLIN
filename = "test.tmp"
# make sure file exists
open(filename, "a").close()
file = open(f... | How does polling a file for changes work? | The problem
I expected the script below to print at most one event and then stop (it's written only to illustrate the problem).
#!/usr/bin/env python
from select import poll, POLLIN
filename = "test.tmp"
# make sure file exists
open(filename, "a").close()
file = open(filename, "r+")
p = poll()
p.register(file.file... | [
"You'll have better luck using pipes rather than files. Try this instead:\n#!/usr/bin/env python\nimport os\nfrom select import poll, POLLIN\n\nr_fd, w_fd = os.pipe()\n\np = poll()\np.register(r_fd, POLLIN)\n\nos.write(w_fd, 'X') # Put something in the pipe so p.poll() will return\n\nwhile True:\n events = p.p... | [
5
] | [] | [] | [
"polling",
"python",
"udev"
] | stackoverflow_0004782756_polling_python_udev.txt |
Q:
Django: Best practice for marking model fields as safe for templates
Right now I have to do something like (template code):
object.name|safe
There's many times where I just simply forget to add the safe filter. My questions:
These objects are user submitted and cleaned at the form level. Is there a reason why I ... | Django: Best practice for marking model fields as safe for templates | Right now I have to do something like (template code):
object.name|safe
There's many times where I just simply forget to add the safe filter. My questions:
These objects are user submitted and cleaned at the form level. Is there a reason why I should be more careful about marking them safe?
If the answer for above is... | [
"In regards to #2, there is a poorly documented function called mark_safe that you can use. For example, in a custom form field I've written I need to return a string with HTML code for the label_from_instance method, so I return using mark_safe:\nreturn mark_safe( '<span class=\"foo\">Some HTML output</span>' )\n... | [
5,
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0004781952_django_django_models_django_templates_python.txt |
Q:
Django session cookie lost because of multiple concurrent requests
I'm building an application in which the client pings the server every now and then (let's not get into why). When the server handles these requests, it checks whether the client is logged in or not using request.user.is_authenticated()
It looks so... | Django session cookie lost because of multiple concurrent requests | I'm building an application in which the client pings the server every now and then (let's not get into why). When the server handles these requests, it checks whether the client is logged in or not using request.user.is_authenticated()
It looks something like this:
def handle_ping_request(request):
if request.user... | [
"It's probably too messy to handle this on the server because you'll have to create some kind of a semaphore system that will also try to guess if any ping is currently from a client that is also being authenticated. My suggestion would be simply to change the client code not to ping while it's waiting for a respo... | [
1,
0
] | [] | [] | [
"cookies",
"django",
"python",
"session"
] | stackoverflow_0004783206_cookies_django_python_session.txt |
Q:
Why list indices must be integers, not tuple?
I have this simple program:
x = {}
x[1,2] = 3
print x
print x[1,2]
It works fine. The fist print generates {(1,2):3} and the second one generates 3.
But in my "big" program I seems to do the same but get a list indices must be integers, not tuple error. What this erro... | Why list indices must be integers, not tuple? | I have this simple program:
x = {}
x[1,2] = 3
print x
print x[1,2]
It works fine. The fist print generates {(1,2):3} and the second one generates 3.
But in my "big" program I seems to do the same but get a list indices must be integers, not tuple error. What this error message can mean and how I can resolve this probl... | [
"If you're getting that error, then you are trying to index a list, and not a dictionary.\nA Python list, like [1, 2, 3], must be indexed with integer values. A dictionary, which is what you have in your example, can be indexed by a wider range of different values.\n",
"Note that x={} defines x to be a dictionary... | [
13,
6,
2
] | [] | [] | [
"dictionary",
"list",
"python",
"tuples"
] | stackoverflow_0004784054_dictionary_list_python_tuples.txt |
Q:
How to draw Grid World using Python
I want to draw a Grid World (similar to a table), where cells may contain robots or obstacles. A dot/arrow would do to represent the robot and colouring the cells in black for examples could represent the obstacles.
I am not looking for anything complicated, just a simple pytho... | How to draw Grid World using Python | I want to draw a Grid World (similar to a table), where cells may contain robots or obstacles. A dot/arrow would do to represent the robot and colouring the cells in black for examples could represent the obstacles.
I am not looking for anything complicated, just a simple python library that would help me do this. Any... | [
"tkinter has a canvas widget that is pretty easy to work with. It has primitives for lines and filled polygons and circles and so on. And with the event loop its pretty easy to do simple animations.\n"
] | [
1
] | [] | [] | [
"draw",
"grid",
"python"
] | stackoverflow_0004783462_draw_grid_python.txt |
Q:
Write error while trying to save a int into a text fil, how would I fix this?
Alright, I'm trying to save three raw input variables to a text file. Every thing works fine until it gets to appending (I think that's what it's called) the information to the text file.
It gets down to the 2nd variable on the list, wh... | Write error while trying to save a int into a text fil, how would I fix this? | Alright, I'm trying to save three raw input variables to a text file. Every thing works fine until it gets to appending (I think that's what it's called) the information to the text file.
It gets down to the 2nd variable on the list, which is age, and then prints this error:
Traceback (most recent call last):
File "... | [
"The buffer probably expect a string. It should be:\nage = raw_input(\"How old are you?\")\n\nYou can still cast it as an integer to make sure it is an int before writing the value to the buffer, but if python can't convert it, it will raise an error. \n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004784218_python.txt |
Q:
how to detect blobs and crop them into png files?
i've been working on a webapp. i got stuck here in a problematic issue.
i'll try to explain what im trying to do.
here you see first big image which has green shapes in it.
what i want to do is to crop those shapes into different png files and make their background... | how to detect blobs and crop them into png files? | i've been working on a webapp. i got stuck here in a problematic issue.
i'll try to explain what im trying to do.
here you see first big image which has green shapes in it.
what i want to do is to crop those shapes into different png files and make their background transparent like the example cropped images below the ... | [
"A really easy way to do this is to use Flood Fill/Connected Component Labeling. Basically, this would just be using a greedy algorithm by grouping any pixels that were the same or similar in color.\nThis is definitely not the ideal way to detect blobs and is only going to be effective in limited situations. Howe... | [
5,
4,
1,
1
] | [] | [] | [
"c#",
"computer_vision",
"gd",
"opencv",
"python"
] | stackoverflow_0004783857_c#_computer_vision_gd_opencv_python.txt |
Q:
Imagemagick or similar for scripted image enhancement
I found the following algorithm to work fairly well for enhancement of various images of whiteboards, etc:
duplicate the layer, make sure the top layer is active
(gaussian)blur the new layer. You shouldn't be able to read the text anymore.
set the layer mode ... | Imagemagick or similar for scripted image enhancement | I found the following algorithm to work fairly well for enhancement of various images of whiteboards, etc:
duplicate the layer, make sure the top layer is active
(gaussian)blur the new layer. You shouldn't be able to read the text anymore.
set the layer mode to dodge
invert the layer
I tried it out in gimp and it lo... | [
"There is a ImageMagick script for whiteboard cleanup here - http://www.fmwconcepts.com/imagemagick/whiteboard/index.php\n"
] | [
2
] | [] | [] | [
"gimp",
"image_enhancement",
"image_processing",
"imagemagick",
"python"
] | stackoverflow_0003145227_gimp_image_enhancement_image_processing_imagemagick_python.txt |
Q:
Python logging module logs on Mac, but not Linux
I am experiencing an issue where I am using the logging module in my app. I am working in Eclipse against the LDT Python (Py 2.7) interface (rather than Pydev) on my MacBook Pro. The logging module works through Eclipse; however, when I transfer my app over to a R... | Python logging module logs on Mac, but not Linux | I am experiencing an issue where I am using the logging module in my app. I am working in Eclipse against the LDT Python (Py 2.7) interface (rather than Pydev) on my MacBook Pro. The logging module works through Eclipse; however, when I transfer my app over to a RHEL5 2.7, logging does not seem to be working at all. ... | [
"The default threshold for logging is WARNING, so INFO and DEBUG messages are not output by default. To do so, add e.g.\nlogging.getLogger().setLevel(logging.DEBUG)\n\nto get DEBUG and INFO messages.\nYou can confirm this is your problem by doing\nlog.warning('This is a test3')\n\nbefore adding that setLevel, and c... | [
3
] | [] | [] | [
"logging",
"python",
"python_2.7"
] | stackoverflow_0004782208_logging_python_python_2.7.txt |
Q:
How to Represent a 2D Orthogonal Grid (Python)
Basically I have a set of "rooms" (custom class). All the rooms are connected and each room is defined in relation to one or more other rooms. I'm looking for some system to organize these rooms in a 2D grid and designate an arbitrary room as the origin.
class room(ex... | How to Represent a 2D Orthogonal Grid (Python) | Basically I have a set of "rooms" (custom class). All the rooms are connected and each room is defined in relation to one or more other rooms. I'm looking for some system to organize these rooms in a 2D grid and designate an arbitrary room as the origin.
class room(exits={}) :
#Other code in here, not relevant
... | [
"Although the question is not very clear, it appears that you need something like GraphViz [1]. It is basically a program to automate the layout of block diagrams, which is completely isomorphic to your problem. There is a Python interface, PyGraphViz [2],that may be useful for you.\nIf you want to generate your ow... | [
2
] | [] | [] | [
"grid",
"python"
] | stackoverflow_0004778550_grid_python.txt |
Q:
How to deal with wrong parameters types in dynamic-languages?
I can't find the answer on SO but it's very likely that the argument has been already discussed.
I'm trying to write a quite small size program using the Python language. It's my first "real" experience with a dynamic language and I would prefer to do ... | How to deal with wrong parameters types in dynamic-languages? | I can't find the answer on SO but it's very likely that the argument has been already discussed.
I'm trying to write a quite small size program using the Python language. It's my first "real" experience with a dynamic language and I would prefer to do everything in the right way. One of the practice that I would try t... | [
"You shouldn't test for specific types. According to the docs, you should simply use the passed-in object as needed and give the user the opportunity to supply a custom implementation.\nDepending on what your function does, it may be appropriate to convert the arguments to the expected type:\ndef my_func(a):\n ... | [
3,
3,
1
] | [] | [] | [
"dynamic_languages",
"python",
"unit_testing"
] | stackoverflow_0004783257_dynamic_languages_python_unit_testing.txt |
Q:
How to improve QGraphicsView performance in a 2D static scene with many items? (no way to solve it?)
If understood correctly, QGraphicsView is supposed to handle million items efficiently.
In my application, I only have some few thousand and the performance is already very bad. When the View is showing the whole ... | How to improve QGraphicsView performance in a 2D static scene with many items? (no way to solve it?) | If understood correctly, QGraphicsView is supposed to handle million items efficiently.
In my application, I only have some few thousand and the performance is already very bad. When the View is showing the whole scene, zooming, hoverEnvents and any other stuff becomes impossible.
I have tried to create a parent-chil... | [
"Basically, what you can play with are cache modes and update modes, but also the size of the bsp-tree of the scene. Also, this speech from DevDays 2010 gives some hints and tips: http://qt.nokia.com/developer/learning/online/talks/developerdays2010/tech-talks/qt-graphics-view-in-depth .\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python",
"qgraphicsitem",
"qgraphicsview",
"qt4"
] | stackoverflow_0004758041_pyqt4_python_qgraphicsitem_qgraphicsview_qt4.txt |
Q:
How would I tell Python to write to a new line if the previous line is occupied with other text?
Let's suppose I had text on line one of a text file created via to a Python script. I exit out of the script and then access it a few days later. I go to add another entry of information but it overwrites line one. How... | How would I tell Python to write to a new line if the previous line is occupied with other text? | Let's suppose I had text on line one of a text file created via to a Python script. I exit out of the script and then access it a few days later. I go to add another entry of information but it overwrites line one. How would I tell Python to check line x before adding to it? My code is below, you don't need to add to m... | [
"You need to open the file in \"append\" mode, like this:\nwith open(\"filename\", \"a\") as f:\n f.write(\"Next line\\n\")\n\nUsing the mode \"w\" in the open()call will overwrite your file.\n"
] | [
5
] | [] | [] | [
"line",
"new_operator",
"python"
] | stackoverflow_0004784766_line_new_operator_python.txt |
Q:
How do I use Django groups and permissions?
I understand the basic user stuff. I know authentication, login, creating accounts, etc. But now I want to work on groups and permissions.
Where is the documentation for django groups/permissions? This is not it: http://docs.djangoproject.com/en/dev/topics/auth/
A:
I ... | How do I use Django groups and permissions? | I understand the basic user stuff. I know authentication, login, creating accounts, etc. But now I want to work on groups and permissions.
Where is the documentation for django groups/permissions? This is not it: http://docs.djangoproject.com/en/dev/topics/auth/
| [
"I suppose the first question you need to ask are what permissions do you need and what sort. By what sort, I mean do you want Model- or Object-level. To clarify the difference say you have a model Car. If you want to give permissions on all cars, then Model-level is appropriate, but if you want to give permissi... | [
122
] | [] | [] | [
"django",
"django_permissions",
"python"
] | stackoverflow_0004778685_django_django_permissions_python.txt |
Q:
Getting Poorly Formatted Output (Python)
When I use the below code I get a very poorly formatted output. One of the main output problems are the /n. The /n don't show up in the real text file, but viewing it from the Python script it's all "unformatted".
The code:
def start():
command = raw_input('''
1) Add
2)... | Getting Poorly Formatted Output (Python) | When I use the below code I get a very poorly formatted output. One of the main output problems are the /n. The /n don't show up in the real text file, but viewing it from the Python script it's all "unformatted".
The code:
def start():
command = raw_input('''
1) Add
2) Look Up
3) See All
4) Delete Entry
''')
i... | [
"print line\n\nYou are printing a list and that is why the elements get printed.\nTry iterating over it and then printing:\nfor ele in line:\n print ele\n\n",
"Try .read() instead of .readlines():\ndef look_up():\n fileObj = open(\"employees.txt\")\n contents = fileObj.read()\n print contents\n sta... | [
3,
1
] | [] | [] | [
"format",
"python"
] | stackoverflow_0004785074_format_python.txt |
Q:
SWIG build debugging tools/tips
I am trying to build M2Crypto 0.21.1 with OpenSSL 1.0.0c (or 0.9.7m) for Python 2.5.4 on windows, but SWIG is conspiring against me. I've tried both SWIG 2.0.1 and SWIG 1.3.40 and I get the same error:
swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c
C:\Development\swigwin-1.3.40... | SWIG build debugging tools/tips | I am trying to build M2Crypto 0.21.1 with OpenSSL 1.0.0c (or 0.9.7m) for Python 2.5.4 on windows, but SWIG is conspiring against me. I've tried both SWIG 2.0.1 and SWIG 1.3.40 and I get the same error:
swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c
C:\Development\swigwin-1.3.40\swig.exe -python -IC:\Development\Py... | [
"Actually the problem here isn't SWIG, but I'll leave this question/answer for the next M2Crypto user that comes along - maybe it will help them.\nThe problem is that the M2Crypto setup.py by default points to <your openssl dir>/include, but if that openssl directory is the source tree, include/ isn't the right pla... | [
2
] | [] | [] | [
"m2crypto",
"openssl",
"python",
"swig"
] | stackoverflow_0004785410_m2crypto_openssl_python_swig.txt |
Q:
python: Searching strings in one list in another list, then appending an entire list entry to a new list
Example:
L1=['cat', 'dog', 'fish', 'bird', 'rabbit', 'horse']
L2=[('cat', 'a', 'b', 'c'), ('cat', 'c', 'd', 'e'), ('cat', 'e', 'f', 'g'), ('fish', 'x', 'y', 'z'), ('dog', 'w', 'x', 'y'), ('dog', 'z', 'y', 'x')... | python: Searching strings in one list in another list, then appending an entire list entry to a new list | Example:
L1=['cat', 'dog', 'fish', 'bird', 'rabbit', 'horse']
L2=[('cat', 'a', 'b', 'c'), ('cat', 'c', 'd', 'e'), ('cat', 'e', 'f', 'g'), ('fish', 'x', 'y', 'z'), ('dog', 'w', 'x', 'y'), ('dog', 'z', 'y', 'x'), ('horse', '1', '2', '3'), ('monkey', 'a', 'b', 'c'), ('kitten', 'h', 'i', 'j'), ('bird', '4', '5', '6')]
I ... | [
"Try\ns = set(L1)\nnew_list = [a for a in L2 if any(b in s for b in a)]\n\n",
"Maybe\ns = set(L1)\nnew_list = [a for a in L2 if s.intersection([w.strip() for w in set(a.split(\",\"))])]\n\n"
] | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004785403_python.txt |
Q:
Exception Passing In Python
I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.
Example A:
>>> 3/0
Traceback (most recent call last):
File "<st... | Exception Passing In Python | I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.
Example A:
>>> 3/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDi... | [
"When you re-raise an exception that you caught, such as\nexcept Exception as e: raise e\n\nit resets the stack trace. It's just like re-raising a new exception. What you want is this:\nexcept Exception as e: raise\n\n",
"For reference, the solution is approximately as follows:\ndef getException():\n return sy... | [
42,
6
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0004730435_exception_handling_python.txt |
Q:
Relevancy between two sentences in python/C++/C#/Java?
When you see the news from multiple sources, there could be chances for multiple sources(websites) might talk about same stuffs.
Is there any Python/C++/C#/Java library to compare the multiple sentences from different sources and identify the relevancy between... | Relevancy between two sentences in python/C++/C#/Java? | When you see the news from multiple sources, there could be chances for multiple sources(websites) might talk about same stuffs.
Is there any Python/C++/C#/Java library to compare the multiple sentences from different sources and identify the relevancy between them so that the result could be used for grouping of news?... | [
"Have a look at the ntlk. They have a classify module for various types of classifications.\n",
"Refer here : Web page content analysis with \"SmartBrowser\"\nHere is an interesting sample, but you'll need to cantact author.\n"
] | [
1,
0
] | [] | [] | [
"c#",
"c++",
"java",
"python",
"string"
] | stackoverflow_0004785674_c#_c++_java_python_string.txt |
Q:
process memory search in python equivalent to Win32::Process::Memory
Win32::Process::Memory for Perl has a nice function to search a process's memory for arrays of uint, int, etc... Can the same be done with pydbg or other module for Python?
Here is an autohotkey script for fetching a list of all the memory pages... | process memory search in python equivalent to Win32::Process::Memory | Win32::Process::Memory for Perl has a nice function to search a process's memory for arrays of uint, int, etc... Can the same be done with pydbg or other module for Python?
Here is an autohotkey script for fetching a list of all the memory pages that can then be searched individually. This is how the perl module work... | [
"I got it working with autohotkey.\nLooking throught the pydbg examples in grayhat python and looking at the source of the snapshot functions in pydbg.py, should be straightforward with python as well.\n"
] | [
0
] | [] | [] | [
"debugging",
"perl",
"python"
] | stackoverflow_0004770164_debugging_perl_python.txt |
Q:
python: automatically printing representation of each component in an expression
I find myself writing assertions like these:
if f(x, y) != z:
print(repr(x))
print(repr(y))
print(repr(z))
raise MyException('Expected: f(x, y) == z')
I was wondering if there's a way to write a function that would accept a v... | python: automatically printing representation of each component in an expression | I find myself writing assertions like these:
if f(x, y) != z:
print(repr(x))
print(repr(y))
print(repr(z))
raise MyException('Expected: f(x, y) == z')
I was wondering if there's a way to write a function that would accept a valid Python expression and an exception class as an input, evaluate the expression, an... | [
"What about assertions ?\nassert f(x, y) != z, 'Expected: f(%r, %r) == %r'%(x,y,z)\n\nEdit\nto add %r to print repr's - thanks for the comment.\n",
"Here's an implementation:\nimport inspect, keyword, pprint, sys, tokenize\n\ndef value_in_frame(name, frame):\n try:\n return frame.f_locals[name]\n ex... | [
2,
2,
1,
1,
1,
1
] | [] | [] | [
"exception",
"parsing",
"python"
] | stackoverflow_0004777154_exception_parsing_python.txt |
Q:
Django - view, url weirdness
I've noticed a strange behavior with how Django is processing my url patterns. A user should login and then be redirected to their profile page. I also have the ability for a user to edit their profile.
Here are my URL patterns for one of my apps:
urlpatterns=patterns('student.views'... | Django - view, url weirdness | I've noticed a strange behavior with how Django is processing my url patterns. A user should login and then be redirected to their profile page. I also have the ability for a user to edit their profile.
Here are my URL patterns for one of my apps:
urlpatterns=patterns('student.views',
(r'profile/$', login_require... | [
"These two patterns: \n(r'profile/$', login_required(profile,'student')),\n(r'editprofile/$', login_required(editprofile,'student')),\n\nBoth match http://your-site/student/editprofile.\nTry: \n(r'^profile/$', login_required(profile,'student')),\n(r'^editprofile/$', login_required(editprofile,'student')),\n\nDjango... | [
2,
2,
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0004785605_django_django_urls_python.txt |
Q:
wxpython support for chat like window
I have been searching through for a while -how to go about making the gui for chat like window.
The basic need is to show the FB wall post sort of thing (constantly updating). (co-relating it with chat window) where there are multiple post and each post have demarking line.
i... | wxpython support for chat like window | I have been searching through for a while -how to go about making the gui for chat like window.
The basic need is to show the FB wall post sort of thing (constantly updating). (co-relating it with chat window) where there are multiple post and each post have demarking line.
img post 1
------------
img post 2
---------... | [
"I would use one of the text control widgets. The RichText ones or the StyledText controls would allow font manipulations fairly easily. Or you could create a custom widget using something like wx.ClientDC to draw the text and write some scrolling code yourself. The latter is harder, but more flexible. \nI think th... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004769872_python_wxpython.txt |
Q:
cherrypy.tree.mount and mod_wsgi
I used to use cherrypy with mod_python and I built my controller trees with cherrypy.tree.mount calls and I would like to keep them (they are spread through the code).
Now I have to use mod_wsgi. Example: from cherrypy wiki
import sys
sys.stdout = sys.stderr
import atexit
import t... | cherrypy.tree.mount and mod_wsgi | I used to use cherrypy with mod_python and I built my controller trees with cherrypy.tree.mount calls and I would like to keep them (they are spread through the code).
Now I have to use mod_wsgi. Example: from cherrypy wiki
import sys
sys.stdout = sys.stderr
import atexit
import threading
import cherrypy
cherrypy.con... | [
"Finally! Got it myself - from the manual...\ncherrypy.tree is itself a WSGI object so you simply do:\ncherrypy.tree.mount(...)\ncherrypy.tree.mount(...)\ncherrypy.tree.mount(...)\napplication = cherrypy.tree\n\n"
] | [
9
] | [] | [] | [
"apache",
"cherrypy",
"mod_wsgi",
"python"
] | stackoverflow_0004785228_apache_cherrypy_mod_wsgi_python.txt |
Q:
Python: Won't Connect to Server
I'm not able to connect to the server it will print out
"Connecting to port..." then it will just say "Sockets timed out."
My program is due tomorrow and it'd be nice to have this actually work.
EDITED CODE: Now it will only use Connecting to Port....
nothing else printed.
import ... | Python: Won't Connect to Server | I'm not able to connect to the server it will print out
"Connecting to port..." then it will just say "Sockets timed out."
My program is due tomorrow and it'd be nice to have this actually work.
EDITED CODE: Now it will only use Connecting to Port....
nothing else printed.
import socket, string, time, random, re, url... | [
"It seems you're never passing the connection information to the socket:\n self.irc = socket.socket()\n\nI think it should be something like this:\n self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.irc.connect((self.server, self.port))\n\n",
"In iCon... | [
1,
0,
0
] | [] | [] | [
"irc",
"networking",
"python"
] | stackoverflow_0004786489_irc_networking_python.txt |
Q:
Appengine reverse reference problem
According to the docs: http://code.google.com/appengine/docs/python/datastore/datamodeling.html#References
the automatically created reverse reference object is a Query object, so there is possible iteration over it and making fetch calls.
But:
I have one model:
class User(db.Mo... | Appengine reverse reference problem | According to the docs: http://code.google.com/appengine/docs/python/datastore/datamodeling.html#References
the automatically created reverse reference object is a Query object, so there is possible iteration over it and making fetch calls.
But:
I have one model:
class User(db.Model):
name = db.StringProperty()
..... | [
"Both methods (iterating and fetch) should work. To debug, you might want to log (or print):\nprint dir(user)\n[..., 'thing_set', ...]\n\nprint dir(user.thing_set)\n[..., '__iter__', ... , 'fetch', ...]\n\njust to see what the objects contain... and that might give you a hint of what could be going wrong.\nA couple... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004780653_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I split this string up?
...
1947q2 -0.6
1947q3 -0.3
1947q4 6.2
1948q1 16.5
...
How do I get this text file into a list? I'm having problems with the spacing between the year and corresponding values.
This is what I have so far:
data = []
for line in open("f... | How do I split this string up? | ...
1947q2 -0.6
1947q3 -0.3
1947q4 6.2
1948q1 16.5
...
How do I get this text file into a list? I'm having problems with the spacing between the year and corresponding values.
This is what I have so far:
data = []
for line in open("file"):
if '1947' in line:
... | [
"Just using split() without arguments splits by whitespace, and eats consecutive whitespace:\n>>> s=' 1947q2 -0.6'\n>>> s.split()\n['1947q2', '-0.6']\n\n",
"data = []\n\nwith open(\"file\") as fin:\n for line in fin:\n data.append(tuple(line.split()))\n\nprint data\n\n",
"One liner using a l... | [
8,
2,
0
] | [] | [] | [
"io",
"python"
] | stackoverflow_0004786765_io_python.txt |
Q:
mintty terminal, python, curses, and utf8 : incorrect display
I've asked here but I'm pretty sure I won't get an answer.
copy - paste this python code :
execute it
in a classical utf8 shell it work properly and displays "Coordonnées" but in my mintty terminal at home it displays "CoordonnM-CM-)es". Any idea how I... | mintty terminal, python, curses, and utf8 : incorrect display | I've asked here but I'm pretty sure I won't get an answer.
copy - paste this python code :
execute it
in a classical utf8 shell it work properly and displays "Coordonnées" but in my mintty terminal at home it displays "CoordonnM-CM-)es". Any idea how I could make it work, or where I should look (mintty has no characte... | [
"Your locales preferred encoding and your tty's encoding doesn't have to be the same.\nCheck what sys.stdin.encoding and sys.stdout.encoding is and try to use that.\nWild guesses is that the default encoding for mintty is UTF8, but your locales preferred encoding is (since it's windows) cp1252.\n",
"It's solved. ... | [
0,
0
] | [] | [] | [
"curses",
"python"
] | stackoverflow_0004780591_curses_python.txt |
Q:
Getting the name & extension of an uploaded file using python (google app engine)
I am using a form to upload files to the google app engine and store them in the datastore. l would also like to store the original file name and extension for presentation purposes.
Is there a way of retrieving this data from the po... | Getting the name & extension of an uploaded file using python (google app engine) | I am using a form to upload files to the google app engine and store them in the datastore. l would also like to store the original file name and extension for presentation purposes.
Is there a way of retrieving this data from the post sever side or can it only be gathered client side and sent as separate fields (e.g. ... | [
"Does the snippet from this email work?\n self.request.params[<form element name with file>].filename\n\n",
"Try this...\nIf your form looks like this:\nself.response.out.write('''<form action=\"/upload\" enctype=\"multipart/form-data\" method=\"post\"><input type=\"file\" name=\"file\"/><input type=\"submit\" />... | [
3,
0
] | [] | [] | [
"filenames",
"google_app_engine",
"python",
"upload"
] | stackoverflow_0001184110_filenames_google_app_engine_python_upload.txt |
Q:
How do I correctly use Or with strings in an if statement
This is a function I wrote. If I enter Wednesday as the day of the week, the program can't get to it to execute the print code. What is the correct syntax for that line of code to make Wednesday work correctly?
def day(dayOfWeek):
if dayOfWeek == ("Mond... | How do I correctly use Or with strings in an if statement | This is a function I wrote. If I enter Wednesday as the day of the week, the program can't get to it to execute the print code. What is the correct syntax for that line of code to make Wednesday work correctly?
def day(dayOfWeek):
if dayOfWeek == ("Monday" or "Wednesday"):
print("Poetry: 6-7:15 in Chem 131"... | [
"The expression (\"Monday\" or \"Wednesday\") in your code is always evaluated to \"Monday\". The operator or is a logical or that first tries if its first operand evaluates to True. If yes, it returns the first operand, otherwise it returns the second operand. Since \"Monday\" is \"trucy\", your comparison alwa... | [
8,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004787645_python.txt |
Q:
How do I achieve the following Tkinter GUI layout with either pack or grid?
Here's my current GUI layout for my checkers game:
As you can see, it consists of a Menu along the top, a Canvas on the left where I draw the checkerboard, a toolbar (Frame) on the top right where I have various formatting/navigation butt... | How do I achieve the following Tkinter GUI layout with either pack or grid? | Here's my current GUI layout for my checkers game:
As you can see, it consists of a Menu along the top, a Canvas on the left where I draw the checkerboard, a toolbar (Frame) on the top right where I have various formatting/navigation buttons, and a Text widget that is used to annotate moves. Currently, I am using a gr... | [
"For this simple layout you could use grid, pack or both. Neither has a clear advantage in this particular case. Both have the resize behavior you desire.\nOff the top of my head I would use a horizontal frame to hold the buttons, and pack the buttons in it. I would then probably use grid to place the toolbar, text... | [
6
] | [] | [] | [
"grid",
"layout",
"pack",
"python",
"tkinter"
] | stackoverflow_0004785856_grid_layout_pack_python_tkinter.txt |
Q:
Python Library/Module for (simple) Undirected Graphs
I've been searching the web for the past hour trying to find a library for python that will help me create and draw simple undirected graphs. It looks like NetworkX (http://networkx.lanl.gov/index.html) is by far the most popular one but unfortunately it doesn't... | Python Library/Module for (simple) Undirected Graphs | I've been searching the web for the past hour trying to find a library for python that will help me create and draw simple undirected graphs. It looks like NetworkX (http://networkx.lanl.gov/index.html) is by far the most popular one but unfortunately it doesn't support drawing for Python 3.
Any suggestions? I don't ne... | [
"NetworkX mentions quite a few ways to draw graphs using Graphviz.\n",
"Have you looked at python-graph library? It is a library and you can use it to draw graphs as you might find it useful. Simple Undirected Graphs is very much possible. I see that they mention about Python3.1 support too. It uses Graphviz to y... | [
1,
1,
0
] | [] | [] | [
"graph",
"python",
"python_3.x",
"python_module"
] | stackoverflow_0004786208_graph_python_python_3.x_python_module.txt |
Q:
Why is this code not accepting this png images transparency?
I've isolated the cause of the problem to be the image, since the code seems to work with other png images with transparency. However, it doesn't seem to work with the one image I need it to. This would be of great help seeing as I'm trying to make a nic... | Why is this code not accepting this png images transparency? | I've isolated the cause of the problem to be the image, since the code seems to work with other png images with transparency. However, it doesn't seem to work with the one image I need it to. This would be of great help seeing as I'm trying to make a nice shaped window.
The image:
The code:
import wx
class PictureW... | [
"wx.RegionFromBitmap uses the bitmap's mask to set the shape. If your source image has an alpha channel then it won't have a mask and so wx.RegionFromBitmap will not be able to determine what shape to use. You can convert the source image such that all pixels are either fully opaque or fully transparent, and then... | [
7,
0,
0,
0
] | [] | [] | [
"png",
"python",
"shaped_window",
"transparency",
"wxpython"
] | stackoverflow_0003279144_png_python_shaped_window_transparency_wxpython.txt |
Q:
python filter string only showing tags less than 2 words
Trying to take a string of tags and only save the first 10 that only have less than 2 words. Don't know if this code is the right direction or not...
mystring = 'one, two, three, three three three, four four four, five, six'
for text in mystring:
number... | python filter string only showing tags less than 2 words | Trying to take a string of tags and only save the first 10 that only have less than 2 words. Don't know if this code is the right direction or not...
mystring = 'one, two, three, three three three, four four four, five, six'
for text in mystring:
number = len(mystring.split())
if text >= 2:
print number
... | [
">>> mystring = 'one, two, three, three three three, four four four, five, six'\n# first separate the string into into a list and strip the extraneous spaces off..\n>>> str_list = map(lambda s: s.strip(), mystring.split(','))\n# then create a new list where the number of \"numbers\" in each list item are less or eq... | [
3,
1,
1
] | [] | [] | [
"count",
"if_statement",
"python"
] | stackoverflow_0004787479_count_if_statement_python.txt |
Q:
How can I install a PyPi equivalent from scratch?
I need to build an internal python package index server, starting from scratch. In house right now we use Python 2.6 and 2.7, and prefer installing packages using pip.
We don't require authentication, but it would help.
What's the easiest way to get a PyPi equivale... | How can I install a PyPi equivalent from scratch? | I need to build an internal python package index server, starting from scratch. In house right now we use Python 2.6 and 2.7, and prefer installing packages using pip.
We don't require authentication, but it would help.
What's the easiest way to get a PyPi equivalent running internally?
I am aware of the existence of m... | [
"Best is a relative term but I myself created ClueReleaseManager to deal with this need locally - http://pypi.python.org/pypi/ClueReleaseManager\n"
] | [
5
] | [] | [] | [
"pypi",
"python"
] | stackoverflow_0004787274_pypi_python.txt |
Q:
Python 3.2 skip a line in csv.DictReader
How do I skip a line of records in a CSV when using a DictReader?
Code:
import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
print(row)
Error:
Traceback (most recent call last):
File "learn.py", line 3, in <module>
... | Python 3.2 skip a line in csv.DictReader | How do I skip a line of records in a CSV when using a DictReader?
Code:
import csv
reader = csv.DictReader(open('test2.csv'))
# Skip first line
reader.next()
for row in reader:
print(row)
Error:
Traceback (most recent call last):
File "learn.py", line 3, in <module>
reader.next()
AttributeError: 'DictReader'... | [
"You use next(reader) instead.\nSource: csv.DictReader documentation\n",
"Since Python 2.6 you should use next(foo) instead of foo.next().\n",
"It was considered a mistake in python2 to have the method called next() instead of __next__()\nnext(obj) now calls obj.__next__() just like str, len etc. as it should.\... | [
27,
7,
6
] | [] | [] | [
"csv",
"python",
"python_3.x"
] | stackoverflow_0004787723_csv_python_python_3.x.txt |
Q:
Encode string data between PHP and Python
What would be the best way or a simple and good way to encode string data in python for later reading in php?
Failed examples:
1: In Python:
>>> encoded = u'test ö'.encode('utf-8')
'text \xc3\xb6'
In PHP:
>>> $decoded = utf8_decode('test \xc3\xb6');
test \xc3\xb6
???
2: ... | Encode string data between PHP and Python | What would be the best way or a simple and good way to encode string data in python for later reading in php?
Failed examples:
1: In Python:
>>> encoded = u'test ö'.encode('utf-8')
'text \xc3\xb6'
In PHP:
>>> $decoded = utf8_decode('test \xc3\xb6');
test \xc3\xb6
???
2: In Python:
>>> encoded = u'test ö'.encode('lati... | [
"You have to use double quotes to get backslash escape sequences parsed in PHP.\n# php -r 'echo utf8_decode(\"test \\xc3\\xb6\");'\ntest ö\n\nAnd using UTF8 is certainly one of the most interoperable ways to pass string data between programming languages / systems / etc.\n"
] | [
3
] | [] | [] | [
"character_encoding",
"php",
"python"
] | stackoverflow_0004788272_character_encoding_php_python.txt |
Q:
Python web framework with CRUD powered by AJAX
I am looking for a Python web framework which will allow me to rapidly build a CRUD application with automatic AJAX support.
The framework should be able to generate a nice table which is sortable and filterable, which works via AJAX and without JS support at all as w... | Python web framework with CRUD powered by AJAX | I am looking for a Python web framework which will allow me to rapidly build a CRUD application with automatic AJAX support.
The framework should be able to generate a nice table which is sortable and filterable, which works via AJAX and without JS support at all as well.
I have looked at TurboGears2 and it seems promi... | [
"Most of the modern frameworks, like TG, Django or Flask support CRUD-style applications. But none of those are that much abstract, that you can give them a model, and there you have your ajaxy db manipulation templates and validations. \nDjango has django-admin and a great form builder and helper module; Flask can... | [
6,
6
] | [] | [] | [
"ajax",
"crud",
"python",
"turbogears",
"web_frameworks"
] | stackoverflow_0004774641_ajax_crud_python_turbogears_web_frameworks.txt |
Q:
Python web framework - other than Django
Are there any other good Python web frameworks? I'm looking to try something new, I have already used Django, web.py and pylons. Also, what frameworks are AJAX-oriented or have better support for AJAX?
I'm looking for something more agile, light weight.
A:
Here is a reall... | Python web framework - other than Django | Are there any other good Python web frameworks? I'm looking to try something new, I have already used Django, web.py and pylons. Also, what frameworks are AJAX-oriented or have better support for AJAX?
I'm looking for something more agile, light weight.
| [
"Here is a really long list of python web frameworks\n",
"more than a framework, ToscaWidgets2 http://toscawidgets.org/documentation/tw2.core/\nTW2 is a widget framework for any wsgi compliant python web framework, originally born for TurboGears, i use TW2 with Pylons, and i presume that can be used without probl... | [
2,
2,
1,
1,
0
] | [] | [] | [
"ajax",
"django",
"python",
"web_frameworks"
] | stackoverflow_0004700588_ajax_django_python_web_frameworks.txt |
Q:
Django - modelform inheritance
On the Django website this sample code is given:
>>> class RestrictedArticleForm(EnhancedArticleForm):
... class Meta(ArticleForm.Meta):
... exclude = ('body',)
My understanding of this is that there's a modelform called EnhancedArticleForm (or ArticleForm and EnhancedAr... | Django - modelform inheritance | On the Django website this sample code is given:
>>> class RestrictedArticleForm(EnhancedArticleForm):
... class Meta(ArticleForm.Meta):
... exclude = ('body',)
My understanding of this is that there's a modelform called EnhancedArticleForm (or ArticleForm and EnhancedArticleForm) and that this should excl... | [
"This is actually a bug in Django:\nhttp://code.djangoproject.com/ticket/8620 (See the comment in the ticket further down for your situation)\nUnfortunately, it looks like it hasn't seen any action in over a year.\nOne way around this is to override the forms __init__ method and simply remove that field from self.f... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004788402_django_django_forms_django_models_python.txt |
Q:
Python Tuple Operations
[('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2',
'4.2', '4.3', ' \n')]
How can I sum up the values from position [1] to [12]?
A:
Convert to float and sum using a list comprehension:
sum(float(x) for x in my_list[0][1:13])
edit: eeks, range was wrong. edite... | Python Tuple Operations | [('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2',
'4.2', '4.3', ' \n')]
How can I sum up the values from position [1] to [12]?
| [
"Convert to float and sum using a list comprehension:\nsum(float(x) for x in my_list[0][1:13])\n\nedit: eeks, range was wrong. edited per comments.\n",
"L=[('1950', '6.5', '6.4', '6.3', '5.8', '5.5', '5.4', '5.0', '4.5', '4.4', '4.2', '4.2', '4.3', ' \\n')]\nsum(map(float,L[0][1:13]))\n\n",
"If you want to avoi... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0004788433_python_tuples.txt |
Q:
can't access new variables in HTMLParser
I can't seem to add access any new variables in HTMLParser. I'm following the examples I've seen here. I don't get any errors adding a variable inside __init__, but when I try to access it in a method I'm told it doesn't exist.
#!/usr/bin/env python
from HTMLParser import H... | can't access new variables in HTMLParser | I can't seem to add access any new variables in HTMLParser. I'm following the examples I've seen here. I don't get any errors adding a variable inside __init__, but when I try to access it in a method I'm told it doesn't exist.
#!/usr/bin/env python
from HTMLParser import HTMLParser
import urllib
class parse(HTMLParse... | [
"You just have to swap the two lines\nself.feed(data)\nself.foo = 'err'\n\nCalling .feed() implicitly calls .handle_starttag(), but this is done before the creation of the attribute in your code.\nProbably an even better idea would be not to feed data to the constructor at all, but rather call .feed() explicitly.\n... | [
2,
1
] | [] | [] | [
"html_parsing",
"oop",
"python"
] | stackoverflow_0004788561_html_parsing_oop_python.txt |
Q:
Using pyparsing to match against a specific ending of a string
How can I build a python pyparsing structure that matches against a particular string ending. For example, suppose I want to find all words that end in 'ing'. The following does NOT work:
ing_ending = Word(alphas) + Literal("ing") + White();
ing_ending... | Using pyparsing to match against a specific ending of a string | How can I build a python pyparsing structure that matches against a particular string ending. For example, suppose I want to find all words that end in 'ing'. The following does NOT work:
ing_ending = Word(alphas) + Literal("ing") + White();
ing_ending.parseString("jumping")
This would be pretty easy to do in python an... | [
"Just use regex\n>>> import pyparsing\n>>> ing_ending = pyparsing.Regex(r'(?i)\\b[a-z]+ing\\b')\n>>> ing_ending.parseString(\"jumping\")\n(['jumping'], {})\n\n"
] | [
5
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004788535_pyparsing_python.txt |
Q:
Dynamic importing of modules followed by instantiation of objects with a certain baseclass from said modules
I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a clas... | Dynamic importing of modules followed by instantiation of objects with a certain baseclass from said modules | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
class PluginBase(object):
def on_load(self):
pass
def on_unload... | [
"You might do something like this:\nfor c in candidates:\n modname = os.path.splitext(c)[0]\n try:\n module=__import__(modname) #<-- You can get the module this way\n except (ImportError,NotImplementedError):\n continue\n for cls in dir(module): #<-- Loop over all objects in the... | [
5,
3,
2,
0
] | [] | [] | [
"plugins",
"python"
] | stackoverflow_0004787291_plugins_python.txt |
Q:
Creating Java DataInputStream data in Python
I have a Java program that uses a DataInputStream for storing object data.
Example:
DataInputStream tInput = new DataInputStream(getClass().getResourceAsStream(aDirectory + "/ResultItemInfo.dat"));
this._text = tInput.readUTF();
this._image = tInput.readUTF();
... | Creating Java DataInputStream data in Python | I have a Java program that uses a DataInputStream for storing object data.
Example:
DataInputStream tInput = new DataInputStream(getClass().getResourceAsStream(aDirectory + "/ResultItemInfo.dat"));
this._text = tInput.readUTF();
this._image = tInput.readUTF();
this._audio = tInput.readUTF();
this._random... | [
"For a string to be readUTF-able, it must contain two bytes of counter and then exactly as many bytes of UTF-8 encoded data as counter says.\nSo I suggest this piece of code should write a unicode string data the way what readUTF() could read:\nencoded = data.encode('UTF-8')\ncount = len(encoded)\nmsb, lsb = divmod... | [
4
] | [] | [] | [
"java",
"python"
] | stackoverflow_0004788052_java_python.txt |
Q:
Code Golf: Finite-state machine!
Finite state machine
A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected... | Code Golf: Finite-state machine! | Finite state machine
A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A ru... | [
"Python 2.7+, 201 192 187 181 179 175 171 chars\nPS. After the problem was relaxed (no need to output state line on empty input), here is new code that's notably shorter. If you are on version <2.7, there is no dict comprehension, so instead of {c+o:s for o,c,s in i[1:-1]} try dict((c+o,s)for o,c,s in i[1:-1]) for ... | [
23,
21,
19,
8,
5,
4,
4,
4,
4,
4,
3,
3,
2,
2,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"code_golf",
"language_agnostic",
"python",
"state_machine"
] | stackoverflow_0004661818_code_golf_language_agnostic_python_state_machine.txt |
Q:
Grabbing & displaying the current time
I'm very new to python and trying to build a simple web app in pieces.
I'm using the datetime library for the first time so please be patient with me.
All I'm trying to do is to get and display the current time and date so that I can cross-reference it with a target time & da... | Grabbing & displaying the current time | I'm very new to python and trying to build a simple web app in pieces.
I'm using the datetime library for the first time so please be patient with me.
All I'm trying to do is to get and display the current time and date so that I can cross-reference it with a target time & date later.
I'm getting some colossal errors. ... | [
"The format of the date_string doesn't match the format you're trying to parse it with. The following format string should allow you to parse the date.\n format = \"%I:%M %p %m.%d.%Y\"\n\nAnd afterwards, if you want to print it using the other format\nprint(my_date.strftime(\"%I.%M %p %m %d, %Y\"))\n\n",
"You're ... | [
3,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004788945_datetime_python.txt |
Q:
How to login / logout Facebook users to Facebook app?
I have a Google App Engine application that uses the Facebook login button to log Facebook Users in and out. This works great. Now I want to serve some content to a Facebook Application as an iFrame. I have a separate branch of templates to serve content to ... | How to login / logout Facebook users to Facebook app? | I have a Google App Engine application that uses the Facebook login button to log Facebook Users in and out. This works great. Now I want to serve some content to a Facebook Application as an iFrame. I have a separate branch of templates to serve content to the iFrame (the Facebook Application) and want to handle au... | [
"You could just use the Facebook Javascript client library. It will pop up a login dialog if they haven't logged in, or just give you their session info if they are already logged in.\nFB.init({ appId: yourAppId });\n\nFB.login(function (response) {\n if (response.session) {\n var authToken = response.se... | [
1
] | [] | [] | [
"facebook",
"oauth",
"python"
] | stackoverflow_0004788517_facebook_oauth_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.