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:
How do I use regex to do this in Python?
def symbolsReplaceDashes(text):
I want to replace all spaces and symbols with hyphens. Because I want to use this with URL.
A:
import re
text = "this isn't alphanumeric"
result = re.sub(r'\W','-',text) # result will be "this-isn-t-alphanumeric"
The \W class is the inver... | How do I use regex to do this in Python? | def symbolsReplaceDashes(text):
I want to replace all spaces and symbols with hyphens. Because I want to use this with URL.
| [
"import re\ntext = \"this isn't alphanumeric\"\nresult = re.sub(r'\\W','-',text) # result will be \"this-isn-t-alphanumeric\"\n\nThe \\W class is the inverse of the \\w class, which consists of alphanumeric characters and underscores ([a-zA-Z0-9_]). Thus, replacing any character that doesn't match \\W with a dash w... | [
4,
1,
1
] | [] | [] | [
"python",
"regex",
"url"
] | stackoverflow_0002589068_python_regex_url.txt |
Q:
How can I remove all words that end in ":" from a string in Python?
I'm wondering how to remove a dynamic word from a string within Python.
It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:".
Thanks! :-)
A:
Use re... | How can I remove all words that end in ":" from a string in Python? | I'm wondering how to remove a dynamic word from a string within Python.
It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:".
Thanks! :-)
| [
"Use regular expressions.\nimport re\nblah = \"word word: monty py: thon\"\nanswer = re.sub(r'\\w+:\\s?','',blah)\nprint answer\n\nThis will also pull out a single optional space after the colon.\n",
"This removes all words which end with a \":\":\ndef RemoveDynamicWords(s):\n L = []\n for word in s.split()... | [
12,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002589200_python_regex.txt |
Q:
Loading SQL dump before running Django tests
I have a fairly complex Django project which makes it hard/impossible to use fixtures for loading data.
What I would like to do is to load a database dump from the production database server after all tables has bene created by the testrunner and before the actual tests... | Loading SQL dump before running Django tests | I have a fairly complex Django project which makes it hard/impossible to use fixtures for loading data.
What I would like to do is to load a database dump from the production database server after all tables has bene created by the testrunner and before the actual tests start running.
I've tried various "magic" in MyTe... | [
"Django supports loading SQL files when doing syncdb, reset, or starting a test runner -- this does exactly what you describe: \nhttp://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data\nYou need to create an \"sql\" directory in your app directory, and then put a file named \"mymodel.sql... | [
8,
1
] | [
"Fixtures are the best option. Have you tried using ./manage.py dumpdata to create a fixture from your current database? I have not seen that fail on complex models, but I guess it's possible.\nAssuming you're using mysql, you should be able to script this by using mysqldump.\n"
] | [
-1
] | [
"django",
"django_testing",
"python"
] | stackoverflow_0001979692_django_django_testing_python.txt |
Q:
How to get msn contact list with Python?
How can I get msn contact list with a Python script having username and password?
A:
There are lots and lots and lots of MSN client modules for Python.
| How to get msn contact list with Python? | How can I get msn contact list with a Python script having username and password?
| [
"There are lots and lots and lots of MSN client modules for Python.\n"
] | [
1
] | [] | [] | [
"msn",
"python"
] | stackoverflow_0002589480_msn_python.txt |
Q:
Using Complex datatype with python SUDS client
I am trying to call webservice from python client using SUDS. When I call a function with a complex data type as input parameter, it is not passed correctly, but complex data type is getting returned correctly froma webservice call.
Webservice Type:
Soap Binding 1... | Using Complex datatype with python SUDS client | I am trying to call webservice from python client using SUDS. When I call a function with a complex data type as input parameter, it is not passed correctly, but complex data type is getting returned correctly froma webservice call.
Webservice Type:
Soap Binding 1.1
Document/Literal
Webserver:
Weblogic 10... | [
"From the looks of it the server-side operation printParamBean is only printing what you're passing it, but is not returning anything. Compared to modifyParamBean which is both printing and returning value. Could this be your problem? \nI surmise that renaming (strictly for the sake of clarity) printParamBean to ... | [
0
] | [] | [] | [
"python",
"suds",
"web_services"
] | stackoverflow_0002588768_python_suds_web_services.txt |
Q:
How do I sort this list in Python, if my date is in a String?
[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}]
Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But,... | How do I sort this list in Python, if my date is in a String? | [{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}]
Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...
| [
".sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d'))\n\n",
"Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well as strings! So you need nothing fancy:\nimport operator\nyourlistofdicts.sort(key=operator.itemgetter('date'))\n\n",
"Satoru.Logic's solution i... | [
45,
27,
18,
4,
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0002589479_dictionary_list_python.txt |
Q:
Creating a method that is simultaneously an instance and class method
In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example:
>>> ... | Creating a method that is simultaneously an instance and class method | In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example:
>>> class Thing(object):
#...
>>> Thing.to_json()
'A'
>>> Thing().to_json()... | [
"Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.\n"
] | [
8
] | [] | [] | [
"methods",
"python"
] | stackoverflow_0002589690_methods_python.txt |
Q:
Command-line input causes SyntaxError
I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:
# Compare phone number
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'
# phoneNumber = str(input("Plea... | Command-line input causes SyntaxError | I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:
# Compare phone number
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'
# phoneNumber = str(input("Please enter a phone number: "))
if re.search... | [
"You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:\nphoneNumber = raw_input(\"Please enter a phone number: \")\n\n",
"In Python version 2.x, input() does two things:\n\nReads a string of data. (You want this.)\nThen it evaluates the string of... | [
17,
10,
4,
2
] | [] | [] | [
"command_line",
"input",
"python",
"python_2.x"
] | stackoverflow_0002589309_command_line_input_python_python_2.x.txt |
Q:
FOSS HTML to PDF in Python, .Net or command line?
I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good html to pdf converter that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of... | FOSS HTML to PDF in Python, .Net or command line? | I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good html to pdf converter that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open sou... | [
"I've wkhtmltopdf used on a couple of projects. http://code.google.com/p/wkhtmltopdf/. It uses the webkit rendering engine, which powers the Safari browser. You'll get completely up to date rendering just like a web browser with CSS and all.\nOh, and it's open source.\n",
"I haven't found a good FOSS solution, bu... | [
5,
2,
1,
0,
0
] | [] | [] | [
".net",
"c#",
"html_to_pdf",
"python"
] | stackoverflow_0000597348_.net_c#_html_to_pdf_python.txt |
Q:
GAE and Django: What are the benefits?
Currently I have a website on the Google App Engine written in Google's webapp framework. What I want to know is what are the benefits of converting my app to run with django? And what are the downsides? Also how did you guys code your GAE apps? Did you use webapp or django? ... | GAE and Django: What are the benefits? | Currently I have a website on the Google App Engine written in Google's webapp framework. What I want to know is what are the benefits of converting my app to run with django? And what are the downsides? Also how did you guys code your GAE apps? Did you use webapp or django? Or did you go an entirely different route an... | [
"With Django on GAE, you get all the benefits (and also the non-benefits) of GAE. The benefits are mainly automatic scalability and high reliability at a very low cost.\nYou may want to start by checking out the following:\n\nStack Overflow: Django on Google App Engine \nStack Overflow: Django and App Engine\nGoogl... | [
7,
5,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002034684_django_google_app_engine_python.txt |
Q:
Histogram in Matplotlib with input file
I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ?
I am not asking for the code, some inputs should put ... | Histogram in Matplotlib with input file | I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ?
I am not asking for the code, some inputs should put me on the right way !
| [
"i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.\nHere's how it works:\nfrom matplotlib import pyplot as PLT\n\nwith open('name_of_your_file.csv') as f:\n v = NP.loadtxt(f, delimiter=\... | [
9,
0
] | [] | [] | [
"histogram",
"matplotlib",
"python"
] | stackoverflow_0002590328_histogram_matplotlib_python.txt |
Q:
MySQLdb not INSERTING, _mysql does fine
Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I cha... | MySQLdb not INSERTING, _mysql does fine | Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MySQLd... | [
"You can use db.commit() to submit data or set db.autocommit() after _mysql.connect(...) to autocommit requests.\n",
"I think they use different autocommit settings. Use commit() after inserting data.\n"
] | [
17,
4
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002590480_mysql_python.txt |
Q:
How to define and use Python generators appropriately
I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner.
a = ["Hello", "world", "!"]
b = (x for x in a)
c = next(b, None)
while c != None:
print c,
c = next(b, None)
... | How to define and use Python generators appropriately | I want to define a generator from a list that will output the elements one at a time, then use this generator object in an appropriate manner.
a = ["Hello", "world", "!"]
b = (x for x in a)
c = next(b, None)
while c != None:
print c,
c = next(b, None)
Is there anything wrong or improvable with the while appro... | [
"Why would you use a while loop? In Python, for loops are absolutely designed for this:\na = [\"Hello\", \"world\", \"!\"]\nb = (x for x in a)\nfor c in b:\n print c,\n\nIf you are stuck on a while implementation for whatever reason, your current implementation is probably the best you can do, but it's a bit clu... | [
7,
3
] | [] | [] | [
"generator",
"python",
"while_loop"
] | stackoverflow_0002589812_generator_python_while_loop.txt |
Q:
How to localize static content in database with Django
My app has tables for languages and countries (actually django-countries at the moment, but open for suggestions). The tables are populated when I initialize the database and remain static after that.
What would be the ideal localization mechanism for the con... | How to localize static content in database with Django | My app has tables for languages and countries (actually django-countries at the moment, but open for suggestions). The tables are populated when I initialize the database and remain static after that.
What would be the ideal localization mechanism for the contents of these tables, so that I can show the country and la... | [
"Maybe I'm missing something here, but why just not use [un]gettext, i.e. {% trans lang_from_db %} and _(lang_from_db)?\nAlternatively, hardcode language names translated in their own language into database, e.g \"English\", \"Svenska\", \"Suomi\", etc.\n"
] | [
0
] | [] | [] | [
"django",
"localization",
"python"
] | stackoverflow_0002590632_django_localization_python.txt |
Q:
Matplotlib: plotting discrete values
I am trying to plot the following !
from numpy import *
from pylab import *
import random
for x in range(1,500):
y = random.randint(1,25000)
print(x,y)
plot(x,y)
show()
However, I keep getting a blank graph (?). Just to make sure that the program logic is cor... | Matplotlib: plotting discrete values | I am trying to plot the following !
from numpy import *
from pylab import *
import random
for x in range(1,500):
y = random.randint(1,25000)
print(x,y)
plot(x,y)
show()
However, I keep getting a blank graph (?). Just to make sure that the program logic is correct I added the code print(x,y), just the... | [
"First of all, I have sometimes had better success by doing\nfrom matplotlib import pyplot\n\ninstead of using pylab, although this shouldn't make a difference in this case.\nI think your actual issue might be that points are being plotted but aren't visible. It may work better to plot all points at once by using a... | [
5
] | [] | [] | [
"data_visualization",
"matplotlib",
"python"
] | stackoverflow_0002590768_data_visualization_matplotlib_python.txt |
Q:
Configuration problems with django and mod_wsgi
I've got problems on getting django to work on apache 2.2 with mod_wsgi.
Django is installed and mod_wsgi too.
I can even see a 404 page when accessing the path and I can login to django admin.
But if I want to install the tagging module I get the following error:
T... | Configuration problems with django and mod_wsgi | I've got problems on getting django to work on apache 2.2 with mod_wsgi.
Django is installed and mod_wsgi too.
I can even see a 404 page when accessing the path and I can login to django admin.
But if I want to install the tagging module I get the following error:
Traceback (most recent call last):
File "setup.py",... | [
"Have you read Graham Dumpleton's blog post on Django and WSGI? It does a pretty good job of describing some common configuration problems, and specifically touches on mysite.settings vs. settings.\nUPDATE: Please read Graham Dumpleton's excellent comments below.\nUPDATE 2: As both Graham and becomingGuru have poin... | [
4,
4
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0002587251_apache_django_mod_wsgi_python.txt |
Q:
How to read formatted input in python?
I want to read from stdin five numbers entered as follows:
3, 4, 5, 1, 8
into seperate variables a,b,c,d & e.
How do I do this in python?
I tried this:
import string
a=input()
b=a.split(', ')
for two integers, but it does not work. I get:
Traceback (most recent call last):
... | How to read formatted input in python? | I want to read from stdin five numbers entered as follows:
3, 4, 5, 1, 8
into seperate variables a,b,c,d & e.
How do I do this in python?
I tried this:
import string
a=input()
b=a.split(', ')
for two integers, but it does not work. I get:
Traceback (most recent call last):
File "C:\Users\Desktop\comb.py", line 3, in... | [
"Use raw_input() instead of input().\n# Python 2.5.4\n>>> a = raw_input()\n3, 4, 5\n>>> a\n'3, 4, 5'\n>>> b = a.split(', ')\n>>> b\n['3', '4', '5']\n>>> [s.strip() for s in raw_input().split(\",\")] # one liner\n3, 4, 5\n['3', '4', '5']\n\nThe misleadingly names input function does not do what you'd expect it to. I... | [
16,
2,
0
] | [
"in = eval(input())\n\na, b, c, d, e = in\n\n"
] | [
-3
] | [
"input",
"python"
] | stackoverflow_0001397827_input_python.txt |
Q:
How do I reverse the direction that my rectangles travel?
I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three b... | How do I reverse the direction that my rectangles travel? | I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't k... | [
"When two objects 'collide' they basically exist in the same physical space and therefore you have to check for this. In 2d this is nice and easy, especially for rectangular shapes. Basically write a function called 'overlap' that returns a true value if two of the balls collide. For example:\nfor (i = 0; i < numbe... | [
3,
1,
1
] | [] | [] | [
"collision_detection",
"python"
] | stackoverflow_0000788966_collision_detection_python.txt |
Q:
Setting A Generator As The Argument Of A PyQt4 Signal
I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i)))), but this just looks ugly. Any suggestions?
A:
You can ... | Setting A Generator As The Argument Of A PyQt4 Signal | I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i)))), but this just looks ugly. Any suggestions?
| [
"You can use the types module to make the code look less ugly.\nfrom types import GeneratorType\n\nelementChosen = QtCore.pyqtSignal(GeneratorType)\n\ndocumentation: http://docs.python.org/library/types.html\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0002590909_pyqt4_python.txt |
Q:
How do I write this Django model in SQL?
I want to create a new column. How do I write this in SQL?
class mytable(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
A:
If you don't want to use South to manage this automatically - which is highly recommended, by the way - you can easily see w... | How do I write this Django model in SQL? | I want to create a new column. How do I write this in SQL?
class mytable(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
| [
"If you don't want to use South to manage this automatically - which is highly recommended, by the way - you can easily see what SQL you need by running ./manage.py sqlall <appname>. This will show you all the SQL to create the models in your app, so you can find the definition of your new field there.\n",
"ALTER... | [
1,
0
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002591360_database_django_mysql_python.txt |
Q:
Itertools group by functionality
I want to group by on dict key
>>> x
[{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}]
>>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])]
[(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])]
This must group on key 10 :(
A... | Itertools group by functionality | I want to group by on dict key
>>> x
[{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}]
>>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])]
[(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])]
This must group on key 10 :(
| [
"docs say:\n\nitertools.groupby:\n It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input orde... | [
4
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0002591621_python_python_itertools.txt |
Q:
What are the common patterns in web programming?
I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).
* Validations and input sanitizat... | What are the common patterns in web programming? | I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).
* Validations and input sanitizations
* Object versioning (to avoid edit conflicts. I d... | [
"If this is actually a big web app that will be deployed for general consumption, then I'd add on Rate Limiting.\n",
"The Model-View-Controller (MVC) design pattern: decouples users inputs and the presentation layer from your application data.\n",
"Almost all of your list is \"Framework\".\nAlmost none of that ... | [
4,
3,
3,
1
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0002589932_design_patterns_python.txt |
Q:
strip only html anchor tags
i have following code that strip all tags. now i want to strip only anchor tags.
x = re.compile(r'<[^<]*?/?>')
how to modify so that only anchor tags stripped.
A:
following code that strip all tags.
Not really. <div title="a>b"> is valid HTML and gets mangled. <div title="<" onmouse... | strip only html anchor tags | i have following code that strip all tags. now i want to strip only anchor tags.
x = re.compile(r'<[^<]*?/?>')
how to modify so that only anchor tags stripped.
| [
"\nfollowing code that strip all tags.\n\nNot really. <div title=\"a>b\"> is valid HTML and gets mangled. <div title=\"<\" onmouseover=\"script()\" class=\"<\">\"> is invalid HTML but the kind of thing you will often find on real web pages. Your regexp leaves an active tag with dangerous scripting in it.\nYou can't... | [
5,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002591465_python_regex.txt |
Q:
Search a variable for an address
I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is:
r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76')
m = r.match(str(serv))
if m1:
print'Found'
The string serv contains is:
urn:uuid:7FD... | Search a variable for an address | I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is:
r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76')
m = r.match(str(serv))
if m1:
print'Found'
The string serv contains is:
urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'htt... | [
"r = re.compile(r\"urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:\\[u'(.*)'\\]\")\nm = r.search(str(serv))\nif m:\n print 'Found', m.group(1)\n\n",
"your regex is very simple, so much so that there's no need to use regular expression at all.\n>>> serv=\"\"\"\n... urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'ht... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002591832_python_regex.txt |
Q:
call a server side python script from javascript
how to call a server side python script from javascript. if test.py is the python script file in server, and if the parameter to be passed to python is another url , then how this can be executed from javascript, how the return string from python script is obtained ... | call a server side python script from javascript | how to call a server side python script from javascript. if test.py is the python script file in server, and if the parameter to be passed to python is another url , then how this can be executed from javascript, how the return string from python script is obtained to the javascript.
| [
"You can directly call the python script from javascript. You need to use an appropriate server-side technology (asp.net, php, servlet). The best solution will be to create a REST service, by defining a URL, which when called (through ajax for example) will execute the python script and write the output to the body... | [
3
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002591846_javascript_python.txt |
Q:
Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn)
Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think.
Supposing that I'm using nginx as front end to apache mod_wsgi.
UPDATE:
I'm comparing django bui... | Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn) | Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think.
Supposing that I'm using nginx as front end to apache mod_wsgi.
UPDATE:
I'm comparing django built in fastcgi(./manage.py method=threaded maxchildren=15) and mod_... | [
"Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want.\nFor more background on mod_wsgi process/threading models see:\nhttp://code.google.com/p/modwsgi/wiki/ProcessesAndThreading\nThe mode... | [
10
] | [] | [] | [
"deployment",
"django",
"fastcgi",
"mod_wsgi",
"python"
] | stackoverflow_0002591715_deployment_django_fastcgi_mod_wsgi_python.txt |
Q:
Python: Converting a tuple to a string
Given this :
import os
import subprocess
def check_server():
cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE)
result = cl.communicate()
print result
check_server()
check_server() returns this tuple:
('\nStarting Nmap 4.53 ( http://insecure... | Python: Converting a tuple to a string | Given this :
import os
import subprocess
def check_server():
cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE)
result = cl.communicate()
print result
check_server()
check_server() returns this tuple:
('\nStarting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:26 EDT\nInteresting ... | [
"cl.communicate() is still returning a tuple. The assignment result, err = ... has the effect of unpacking the tuple into the variables result (a string) and err (an integer).\nWhen you print the tuple, it uses the repr(...) of each element, but when you print the string, it just prints the string, hence the absenc... | [
6,
4,
1
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0002592045_python_string_tuples.txt |
Q:
How can I skip the current item and the next in a Python loop?
This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.
Is there a simple way to do something like this?
lines = open('something.txt', 'r').readlines()
for line in lines:
if line == '!':
... | How can I skip the current item and the next in a Python loop? | This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.
Is there a simple way to do something like this?
lines = open('something.txt', 'r').readlines()
for line in lines:
if line == '!':
# force iteration forward twice
line.next().next()
<e... | [
"Try:\nlines = iter(open('something.txt', 'r'))\nfor val in lines:\n if val == \"!\":\n lines.next()\n continue\n <etc>\n\nYou may want to catch StopIteration somewhere. It'll occur if the iterator is finished.\n",
"The file.readlines method returns a list of strings, and iterating over a list... | [
47,
8,
8,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0002592798_python.txt |
Q:
Running Java, Python, Ruby and Perl programs in .NET
I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console?
Do I need to install something else also, for running these language files?
In case there is a need for somet... | Running Java, Python, Ruby and Perl programs in .NET | I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console?
Do I need to install something else also, for running these language files?
In case there is a need for something extra to be installed and after i have all of them, w... | [
"Do you want to run programs in these languages inside the .NET platform? You'd need IronPython or IronRuby (I don't think anything like IronPerl exists).\nIf you want to run \"normal\" Python/Ruby/Perl/Java programs, then yes, you'll need to install a Python interpreter, a Ruby interpreter, a Perl interpreter and ... | [
7,
3,
3,
1
] | [] | [] | [
".net",
"java",
"perl",
"python",
"ruby"
] | stackoverflow_0002593519_.net_java_perl_python_ruby.txt |
Q:
Rewriting a for loop in pure NumPy to decrease execution time
I recently asked about trying to optimise a Python loop for a scientific application, and received an excellent, smart way of recoding it within NumPy which reduced execution time by a factor of around 100 for me!
However, calculation of the B value is ... | Rewriting a for loop in pure NumPy to decrease execution time | I recently asked about trying to optimise a Python loop for a scientific application, and received an excellent, smart way of recoding it within NumPy which reduced execution time by a factor of around 100 for me!
However, calculation of the B value is actually nested within a few other loops, because it is evaluated a... | [
"One obvious thing you can do is replace the line\nr_test_fast = reshape_vector(r_test)\n\nwith\nr_test_fast = r_test.reshape((3,1))\n\nProbably won't make any big difference in performance, but in any case it makes sense to use the numpy builtins instead of reinventing the wheel.\nGenerally speaking, as you probab... | [
2,
2
] | [] | [] | [
"numpy",
"optimization",
"physics",
"python"
] | stackoverflow_0002592696_numpy_optimization_physics_python.txt |
Q:
Process a set of files from a source directory to a destination directory in Python
Being completely new in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick convert as in the example below).
I can supply both sou... | Process a set of files from a source directory to a destination directory in Python | Being completely new in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick convert as in the example below).
I can supply both source and destination directories, however I can't figure out how to easily retain the dire... | [
"Change your loop to:\nfor root, dirs, files in os.walk(srcdir):\n destroot = os.path.join(destdir, root[len(srcdir):])\n for adir in dirs:\n os.makedirs(os.path.join(destroot, adir))\n for filename in files:\n sourceFile = os.path.join(root, filename)\n destFile = os.path.join(destroo... | [
2,
1,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0002593399_path_python.txt |
Q:
Is there a way to backup everything in an app-engine blobstore?
bulkloader.py is very handy.
But as far as I can tell it doesn't appear to fetch items from the blobstore, so you can be left with broken entity relationships if you needed to dump/restore your application.
Does anyone know a method for completely ba... | Is there a way to backup everything in an app-engine blobstore? | bulkloader.py is very handy.
But as far as I can tell it doesn't appear to fetch items from the blobstore, so you can be left with broken entity relationships if you needed to dump/restore your application.
Does anyone know a method for completely backing up their data from app-engine including blobstore data?
| [
"In Java, you would instantiate a BlobInfoFactory and use BlobInfoFactory.queryBlobInfos. \nThen for each blob, you would run BlobstoreService.serve(...) with the BlobKeys returned from the BlobInfos. You still might end up with broken entity relationships - there's no way to guarantee each blob will end up with t... | [
2
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0002593756_blobstore_google_app_engine_python.txt |
Q:
Implement a server that receives and processes client request(cassandra as backend), Python or C++?
I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python c... | Implement a server that receives and processes client request(cassandra as backend), Python or C++? | I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python called tornado, my questions are:
Is Python a good choice for developing such kind of apps?
Is Nginx(or S... | [
"Twisted framework is a good starting point for develop backend servers. It is fast and scalable. \n",
"Python is unlikely to allow you to write the most efficient server possible. However, it may just be that it will be fast enough, because for most applications it is.\nTherefore, one path you could take is star... | [
1,
0,
0
] | [] | [] | [
"c++",
"full_text_search",
"python",
"search"
] | stackoverflow_0002582892_c++_full_text_search_python_search.txt |
Q:
Eclipse + PyDev: Eclipse telling me that this is an invalid import?
I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import.
How do I "tell" ecl... | Eclipse + PyDev: Eclipse telling me that this is an invalid import? | I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import.
How do I "tell" eclipse where twython is so that it will let me import and use it?
| [
"I believe I have had this problem before - try going into the menu: Window_Preferences and then select Pydev and Interpreter-Python. Then try to click Auto-config - it should update its search paths to include everything installed in Python. If that doesn't work, you should at least be able to manually add the fol... | [
3,
0
] | [] | [] | [
"eclipse",
"pydev",
"python",
"twython"
] | stackoverflow_0002590435_eclipse_pydev_python_twython.txt |
Q:
Automatically execute commands on launching python shell
I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everyt... | Automatically execute commands on launching python shell | I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell.
Thanks,
| [
"Yup you can use the PYTHONSTARTUP environment variable to do this as outlined here\n",
"Also consider using ipython if you're doing a lot of interactive work. Your options for this kind of automation expand significantly.\n"
] | [
12,
1
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0002587709_python_shell.txt |
Q:
Exit to command line in Python
I have a script that I want to exit early under some condition:
if not "id" in dir():
print "id not set, cannot continue"
# exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]
I run this script using execfile("foo.py") from the P... | Exit to command line in Python | I have a script that I want to exit early under some condition:
if not "id" in dir():
print "id not set, cannot continue"
# exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]
I run this script using execfile("foo.py") from the Python interactive prompt and I would... | [
"In the interactive interpreter; catch SystemExit raised by sys.exit and ignore it:\ntry:\n execfile(\"mymodule.py\")\nexcept SystemExit:\n pass\n\n",
"Put your code block in a method and return from that method, like such:\ndef do_the_thing():\n if not \"id\" in dir():\n print \"id not set, cann... | [
7,
3,
2,
0
] | [] | [] | [
"command_line",
"execfile",
"exit",
"python",
"scripting"
] | stackoverflow_0002587083_command_line_execfile_exit_python_scripting.txt |
Q:
How should I write this string-prefix check so that it's idiomatic Python?
I have a couple of lists of items:
specials = ['apple', 'banana', 'cherry', ...]
smoothies = ['banana-apple', 'mocha mango', ...]
I want to make a new list, special_smoothies, consisting of elements in smoothies that start with the elemen... | How should I write this string-prefix check so that it's idiomatic Python? | I have a couple of lists of items:
specials = ['apple', 'banana', 'cherry', ...]
smoothies = ['banana-apple', 'mocha mango', ...]
I want to make a new list, special_smoothies, consisting of elements in smoothies that start with the elements in specials. However, if specials is blank, special_smoothies should be ident... | [
"Since you want the behavior for empty specials to be different from the natural limit of the behavior for non-empty, you do need to special-case:\nif specials:\n specialsmoothies = [x for x in smoothies\n if any(x.startswith(y) for y in specials)]\nelse:\n specialsmoothies = list(smoot... | [
4,
3,
1,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0002593496_list_python_string.txt |
Q:
How to write a shell in Python
I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and aut... | How to write a shell in Python | I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has a c... | [
"You should check out the cmd and cmd2 modules. I think they will do what you want. There was a PyCon talk about these.\n",
"If you need an administrative shell to be accessed via network Twisted python framework's manhole is a good solution. Example:\nhttp://www.devshed.com/c/a/Python/SSH-with-Twisted/3/\n"
] | [
22,
3
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0002594560_python_shell.txt |
Q:
sqlite3.OperationalError: database is locked - non-threaded application
I have a Python application which throws the standard sqlite3.OperationalError: database is locked error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading go... | sqlite3.OperationalError: database is locked - non-threaded application | I have a Python application which throws the standard sqlite3.OperationalError: database is locked error. I have looked around the internet and could not find any solution which worked (please note that there is no multiprocesses/threading going on, and as you can see I have tried raising the timeout parameter). The ... | [
"You might particularly check for functions that keep a read-lock (unfinished cursor). That would block the commit from the update function. Note that there is a dedicated mailing list for Python-sqlite problems: http://groups.google.com/group/python-sqlite \n",
"Do you really need to continuously open and close ... | [
2,
1
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0002569233_python_sql_sqlite.txt |
Q:
Trying to set up nested while loops using a boolean switch
I'm trying to set up a while loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The prob... | Trying to set up nested while loops using a boolean switch | I'm trying to set up a while loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The problem is once the main while loop executes once, it just stops. Do... | [
"The problem is that after the first loop, employeeName and the other variables will already have values, so your inner while loops will be skipped. This leads to the outer loop repeating infinitely without doing anything.\nI would just remove the inner while loops: you don't really need them, because you already d... | [
3,
1
] | [] | [] | [
"nested_loops",
"python",
"while_loop"
] | stackoverflow_0002594735_nested_loops_python_while_loop.txt |
Q:
Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem)
I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment.
The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this informati... | Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem) | I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment.
The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a _template_data dictionary, for convenience of subclasses.
class BasePage(webapp.... | [
"I believe the problem is the _user attribute.\nCurrently, the _user attribute is bound when the module containing the class is imported (probably when the application starts). You need to get the current user for each request.\nI would rewrite into something like:\nclass BasePage(webapp.RequestHandler):\n def r... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"syntax"
] | stackoverflow_0002595073_google_app_engine_python_syntax.txt |
Q:
How to display specific cookie?
I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages.
I'd like to display a given cookie from the cookiejar instead of the whole thing:
#OK to display all the cookies
for index, cookie in enumerate(cj):
print index, ' : ', cookie
#How to displa... | How to display specific cookie? | I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages.
I'd like to display a given cookie from the cookiejar instead of the whole thing:
#OK to display all the cookies
for index, cookie in enumerate(cj):
print index, ' : ', cookie
#How to display just PHPSESSID?
#AttributeError: Co... | [
"The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself.\nI am not sure what cookie attribute you want do do the lookup on. Example, using name:\ndef get_cookie_by_name(cj, name):\n return [cookie for cookie in cj if cookie.name == name][... | [
5
] | [] | [] | [
"cookielib",
"python"
] | stackoverflow_0002594947_cookielib_python.txt |
Q:
Iterating over a database column in Django
I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:
import My... | Iterating over a database column in Django | I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:
import MySQLdb
import sys
try:
conn = MySQLdb.connec... | [
"Database microoptimalisation is not a strong part of Django ORM. However, when speed is so important, I wonder if the exec is the right way to do it.\nAnyways, You write \"iterate through the values of a column\", this means you have multiple values in single column separated by a separator (not seen in your code)... | [
2,
1,
1
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002595296_database_django_mysql_python.txt |
Q:
Asynchronous subprocess on Windows
First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.
I have several applications which... | Asynchronous subprocess on Windows | First of all, the overall problem I am solving is a bit more complicated than I am showing here, so please do not tell me 'use threads with blocking' as it would not solve my actual situation without a fair, FAIR bit of rewriting and refactoring.
I have several applications which are not mine to modify, which take data... | [
"How bad is it to have to use threads? I encountered much the same problem and eventually decided to use threads to gather up all the data on a sub-process's stdout and stderr and put it onto a thread-safe queue which which the main thread can read in a blocking fashion, without having to worry about the threading ... | [
4,
1,
0
] | [] | [] | [
"asynchronous",
"python",
"subprocess"
] | stackoverflow_0002554514_asynchronous_python_subprocess.txt |
Q:
Good way to flatten a multiple file python program for distribution?
I am writing a console application in python that will consist of a handful of modules, each with a couple hundred lines of code.
For development it would be nice to modularize the program, but for distribution I like the idea of being able to po... | Good way to flatten a multiple file python program for distribution? | I am writing a console application in python that will consist of a handful of modules, each with a couple hundred lines of code.
For development it would be nice to modularize the program, but for distribution I like the idea of being able to post the program as a single python script.
Are there any good scripts out t... | [
"A zipfile (with just the .pyc or .pyo files in it, ideally) would suffice, especially if you're distributing code supporting a specific X.Y version of Python (any Z in X.Y.Z will do, i.e., if you support Python 2.6, that will work in 2.6.1, 2.6.2, and so on). Just make the zipfile part of the PYTHONPATH, just as ... | [
4,
0
] | [] | [] | [
"distribution",
"python"
] | stackoverflow_0002444165_distribution_python.txt |
Q:
Why does `print foo.communicate()[0]` differ from `print foo.communicate()`"
Here is the situation:
I've got a command I'm running:
import subprocess
foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\
stderr=subprocess.STDOUT)
Pretty basic, right? And I've figured out that I can do stuff with the... | Why does `print foo.communicate()[0]` differ from `print foo.communicate()`" | Here is the situation:
I've got a command I'm running:
import subprocess
foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\
stderr=subprocess.STDOUT)
Pretty basic, right? And I've figured out that I can do stuff with the output with .communicate(), like this:
print foo.communicate()
Which works great... | [
"In Python when you call something like print obj, you're actually calling the __str__ on the object and then interpreting the result as a string.\nSo for example say you have:\n >>> a = ('foo\\nbar', '5')\n >>> print a\n ('foo\\nbar', '5')\n\nAs you've noticed. But if you do something like:\n >... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002596261_python.txt |
Q:
NoneType has no attribute Append
I'm new to Python. I can't understand why a variable is None at a certain point in my code:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserI... | NoneType has no attribute Append | I'm new to Python. I can't understand why a variable is None at a certain point in my code:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).... | [
"Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points:\nIs the UserInRoom instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the put() ing the instance would require that ... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python",
"syntax"
] | stackoverflow_0002595727_google_app_engine_python_syntax.txt |
Q:
Behavior of object in set operations
I'm trying to create a custom object that behaves properly in set operations.
I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not includ... | Behavior of object in set operations | I'm trying to create a custom object that behaves properly in set operations.
I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems t... | [
"Nope, it's not deterministic. The problem is that you've broken equals' and hash's invariant, that two objects are equivalent when they are equal. Fix your object, don't try to be clever and abuse how set's implementation works. If the meta value is part of MyObject's identity, it should be included in eq and hash... | [
4,
1,
0
] | [] | [] | [
"object",
"python",
"set"
] | stackoverflow_0002594920_object_python_set.txt |
Q:
Best Python module for Berkeley DB?
According to the Python 2.6.5 docs [1], the bsddb module has been deprecated for removal in Python 3.0.
What module/wrapper should I be using instead?
[1] http://docs.python.org/library/bsddb.html
A:
I recommend pyBSDdb (from which the version currently in Python standard's li... | Best Python module for Berkeley DB? | According to the Python 2.6.5 docs [1], the bsddb module has been deprecated for removal in Python 3.0.
What module/wrapper should I be using instead?
[1] http://docs.python.org/library/bsddb.html
| [
"I recommend pyBSDdb (from which the version currently in Python standard's library was taken -- but the stand-alone project is more actively maintained and far from deprecated;-).\n"
] | [
15
] | [] | [] | [
"berkeley_db",
"python"
] | stackoverflow_0002597068_berkeley_db_python.txt |
Q:
Make dictionary from list with python
I need to transform a list into dictionary as follows.
The odd elements has the key, and even number elements has the value.
x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'}
def set(self, val_):
i = 0
for val in val_:
if i == 0:
i = 1
... | Make dictionary from list with python | I need to transform a list into dictionary as follows.
The odd elements has the key, and even number elements has the value.
x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'}
def set(self, val_):
i = 0
for val in val_:
if i == 0:
i = 1
key = val
else:
... | [
"dict(x[i:i+2] for i in range(0, len(x), 2))\n\n",
"Here are a couple of ways for Python3 using dict comprehensions\n>>> x = (1,'a',2,'b',3,'c')\n>>> {k:v for k,v in zip(*[iter(x)]*2)}\n{1: 'a', 2: 'b', 3: 'c'}\n>>> {x[i]:x[i+1] for i in range(0,len(x),2)}\n{1: 'a', 2: 'b', 3: 'c'}\n\n",
"dict(zip(*[iter(val_)]... | [
41,
12,
11,
11,
4
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0002597166_dictionary_list_python.txt |
Q:
Pylons paginator question
Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator.
from http://pylonsbook.com... | Pylons paginator question |
Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator.
from http://pylonsbook.com/en/1.1/simplesite-tutorial-pa... | [
"You need to pass the pageid to the method url_for because the pageid is required by the route.\nmap.connect('/page/{pageid}/{controller}/{action}', requirements={'pageid':'\\d+'})\nmap.connect('/page/{pageid}/{controller}/{action}/{id}', requirements={'pageid':'\\d+', 'id':'\\d+'})\n\nThe pageid is then processed ... | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002594604_pylons_python.txt |
Q:
deletion of folders
how can i delete a folder using python script?and what are the return values??
A:
If you want to delete a folder that's empty use os.rmdir:
import os
os.rmdir('/mypath')
If you want to delete a folder that's not empty use shutil.rmtree:
import shutil
shutil.rmtree('/mypath')
A:
you can u... | deletion of folders | how can i delete a folder using python script?and what are the return values??
| [
"If you want to delete a folder that's empty use os.rmdir:\nimport os\nos.rmdir('/mypath')\n\nIf you want to delete a folder that's not empty use shutil.rmtree:\nimport shutil \nshutil.rmtree('/mypath')\n\n",
"you can use os.rmdir() to remove a directory. To remove a directory tree recursively, you can use shuti... | [
4,
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0002597501_directory_python.txt |
Q:
How to "uninstantiate" an object?
I wrote a function in Python:
def instantiate(c):
if inspect.isclass(c): return c()
elif isinstance(c, object): return c
else: raise Exception, '%s is not an object or class.' % c
Now I want to do the opposite: get the class from an already instantiated object so that... | How to "uninstantiate" an object? | I wrote a function in Python:
def instantiate(c):
if inspect.isclass(c): return c()
elif isinstance(c, object): return c
else: raise Exception, '%s is not an object or class.' % c
Now I want to do the opposite: get the class from an already instantiated object so that I can re-instantiate it with different... | [
"To get the class of x\nx.__class__\n\n",
"The class of object c is type(c).\n"
] | [
3,
2
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002597596_python_syntax.txt |
Q:
Encoding in XML declaration python
I have created an XML file using python. But the XML declaration has only version info. How can I include encoding with XML declaration like:
<?xml version="1.0" encoding="UTF-8"?>
A:
>>> from xml.dom.minidom import Document
>>> a=Document()
>>> a.toprettyxml(encoding="utf-8")... | Encoding in XML declaration python | I have created an XML file using python. But the XML declaration has only version info. How can I include encoding with XML declaration like:
<?xml version="1.0" encoding="UTF-8"?>
| [
">>> from xml.dom.minidom import Document\n>>> a=Document()\n>>> a.toprettyxml(encoding=\"utf-8\")\n'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'\n\nor\n>>> a.toxml(encoding=\"utf-8\")\n'<?xml version=\"1.0\" encoding=\"utf-8\"?>'\n\nyou can set the encoding for the document.writexml() function in the same way.\n... | [
11
] | [] | [] | [
"declaration",
"encoding",
"python",
"xml"
] | stackoverflow_0002597622_declaration_encoding_python_xml.txt |
Q:
random.randint(1,n) in Python
Most of us know that the command random.randint(1,n) in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?
A:
randint() works with long integers, so there is no upper limit:
>>> random.randint(... | random.randint(1,n) in Python | Most of us know that the command random.randint(1,n) in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?
| [
"randint() works with long integers, so there is no upper limit:\n>>> random.randint(1,123456789012345678901234567890)\n113144971884331658209492153398L\n\n",
"No doubt you have a bounded amount of memory, and address space, on your machine; for example, for a good 64-bit machine, 64 GB of RAM [[about 2**36 bytes]... | [
12,
4
] | [] | [] | [
"python",
"random"
] | stackoverflow_0002597444_python_random.txt |
Q:
Memcache in python
I want to memcache an xmldata using python,also needs to update the cache with the refreshed xmldata retreived from webserver,could any one help me with sample code.
A:
This could be of some help:
http://code.google.com/appengine/docs/python/memcache/
Quite a few nice code samples are include... | Memcache in python | I want to memcache an xmldata using python,also needs to update the cache with the refreshed xmldata retreived from webserver,could any one help me with sample code.
| [
"This could be of some help:\nhttp://code.google.com/appengine/docs/python/memcache/\nQuite a few nice code samples are included.\n"
] | [
2
] | [] | [] | [
"memcached",
"python"
] | stackoverflow_0002597738_memcached_python.txt |
Q:
Is it an MD5 digest in this Python script?
I am trying to understand this simple hashlib code in Python that has been given to me the other day on Stackoverflow:
import hashlib
m = hashlib.md5()
m.update("Nobody inspects")
m.update(" the spammish repetition here")
m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\... | Is it an MD5 digest in this Python script? | I am trying to understand this simple hashlib code in Python that has been given to me the other day on Stackoverflow:
import hashlib
m = hashlib.md5()
m.update("Nobody inspects")
m.update(" the spammish repetition here")
m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
m.digest_size
16
m.bloc... | [
"The hashlib.hash object doesn't implement its own __str__, so the default to-string operation is used, which prints the class name followed by its id (address).\n(Use .hexdigest() to get the hex MD5 string.)\n",
"print m.hexdigest()\n\nUPADATE: hexdigest() gives another representation of digest(). Every characte... | [
3,
3
] | [] | [] | [
"digest",
"hashlib",
"md5",
"python"
] | stackoverflow_0002597863_digest_hashlib_md5_python.txt |
Q:
how to change [1,2,3,4] to '1234' using python
How do I convert a list of ints to a single string, such that:
[1, 2, 3, 4] becomes '1234'
[10, 11, 12, 13] becomes '10111213'
... etc...
A:
''.join(map(str, [1,2,3,4] ))
map(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1',... | how to change [1,2,3,4] to '1234' using python | How do I convert a list of ints to a single string, such that:
[1, 2, 3, 4] becomes '1234'
[10, 11, 12, 13] becomes '10111213'
... etc...
| [
"''.join(map(str, [1,2,3,4] ))\n\n\nmap(str, array) is equivalent to [str(x) for x in array], so map(str, [1,2,3,4]) returns ['1', '2', '3', '4'].\ns.join(a) concatenates all items in the sequence a by the string s, for example,\n>>> ','.join(['foo', 'bar', '', 'baz'])\n'foo,bar,,baz'\n\nNote that .join can only jo... | [
20,
12
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0002597932_list_python_string.txt |
Q:
why egrep's stdout did not go through pipe?
i got a weird problem regarding egrep and pipe
I tried to filter a stream containing some lines who start with a topic name, such as
"TICK:this is a tick message\n"
When I try to use egrep to filter it :
./stream_generator | egrep 'TICK' | ./topic_processor
It seems tha... | why egrep's stdout did not go through pipe? | i got a weird problem regarding egrep and pipe
I tried to filter a stream containing some lines who start with a topic name, such as
"TICK:this is a tick message\n"
When I try to use egrep to filter it :
./stream_generator | egrep 'TICK' | ./topic_processor
It seems that the topic_processor never receives any messages... | [
"Have you allowed the command ./stream_generator | egrep 'TICK' | ./topic_processor to run to completion? If the command has completed without producing output then the problem does not lie with buffering since, upon the termination of ./stream_generator, egrep will flush any of its buffers and in turn terminate.... | [
3
] | [] | [] | [
"grep",
"pipe",
"python",
"shell"
] | stackoverflow_0002598147_grep_pipe_python_shell.txt |
Q:
Pass logger instance to class
I'm using a open-source Python library in my project. This library logs a lot of information using the logging class.
...but I can't see the output or log it to file. I know that i would have to create a logger instance and add a file-handler or a console-handler to it but how can i p... | Pass logger instance to class | I'm using a open-source Python library in my project. This library logs a lot of information using the logging class.
...but I can't see the output or log it to file. I know that i would have to create a logger instance and add a file-handler or a console-handler to it but how can i pass this logger instance to the cla... | [
"Simplest way will be to use basicConfig function in logging module. Here's what docs are saying:\n\nDoes basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The function does nothing if any handlers have been defined for the root logger.... | [
1,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0002598169_logging_python.txt |
Q:
What does this python line mean?
abc = [0, ] * datalen;
"datalen" is an Integer.
Then I see referencing like this:
abc[-1]
Any ideas?
A:
creates a list with datalen references to the object 0:
>>> datalen = 10
>>> print [0,] * datalen
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
You don't really need the comma in there:
>>... | What does this python line mean? | abc = [0, ] * datalen;
"datalen" is an Integer.
Then I see referencing like this:
abc[-1]
Any ideas?
| [
"creates a list with datalen references to the object 0:\n>>> datalen = 10\n>>> print [0,] * datalen\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nYou don't really need the comma in there:\n>>> print [0] * datalen\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n",
"As everyone else has said, [0] * n will give you a list of n zeros, and ... | [
8,
5,
3,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002598069_python_syntax.txt |
Q:
how to get firefox address bar url for python (pywin32)
i need grab to firefox address bar. how to get address bar url for python ? (i need second part other browsers chrome and safari grabbing address bar but firefox is urgently).
Thanks.
A:
You will need to go thru all top windows, and see if title contains fi... | how to get firefox address bar url for python (pywin32) | i need grab to firefox address bar. how to get address bar url for python ? (i need second part other browsers chrome and safari grabbing address bar but firefox is urgently).
Thanks.
| [
"You will need to go thru all top windows, and see if title contains firefox or check window class of firefox using spy++, then go thru all child windows to find URL, as a starting point do something like this\nimport win32gui\n\ndef enumerationCallaback(hwnd, results):\n text = win32gui.GetWindowText(hwnd)\n ... | [
3
] | [] | [] | [
"firefox",
"python",
"pywin32"
] | stackoverflow_0002598404_firefox_python_pywin32.txt |
Q:
Python float copy question
I'm puzzled by some behaviour I'm seeing when copying a float array member into
another variable - please help!
For example
data_entry[1] = 9.6850069951
new_value = data_entry[1]
<comment> #print both
9.6850069951
9.6850663300
I'm aware of the problem of binary storage of floats b... | Python float copy question | I'm puzzled by some behaviour I'm seeing when copying a float array member into
another variable - please help!
For example
data_entry[1] = 9.6850069951
new_value = data_entry[1]
<comment> #print both
9.6850069951
9.6850663300
I'm aware of the problem of binary storage of floats but I thought
with a direct co... | [
"After an assignment the variable new_value is not a copy of the float, it's just another reference to the exact same object. Therefore it cannot possibly have a different printed representation. So there's definitely some detail omitted in the original question.\nStuart - can you please try the following and post ... | [
5,
3,
0,
0,
0
] | [] | [] | [
"floating_point",
"python",
"variable_assignment"
] | stackoverflow_0002524998_floating_point_python_variable_assignment.txt |
Q:
HTTPSConnection module missing in Python 2.6 on CentOS 5.2
I'm playing around with a Python application on CentOS 5.2.
It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.
When I try running my application I get an error regarding HTTPSConnection... | HTTPSConnection module missing in Python 2.6 on CentOS 5.2 | I'm playing around with a Python application on CentOS 5.2.
It uses the Boto module to communicate with Amazon Web Services, which requires communication through a HTTPS connection.
When I try running my application I get an error regarding HTTPSConnection being missing:
"AttributeError: 'module' object has no attribut... | [
"citing from the python documentation (http://docs.python.org/library/httplib.html):\nNote HTTPS support is only available if the socket module was compiled with SSL support.\nYou should find out how python on the CentOS you are using was built.\n",
"Please install openssl and openssl-devel before you install pyt... | [
7,
7,
0
] | [] | [] | [
"centos",
"python"
] | stackoverflow_0000877072_centos_python.txt |
Q:
Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace
I'm looking for info on howto get a google appengine app onto the newly
announced google apps marketplace.
The page at
http://code.google.com/googleapps/marketplace/sso.html
does not have a python openid apps-discovery... | Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace | I'm looking for info on howto get a google appengine app onto the newly
announced google apps marketplace.
The page at
http://code.google.com/googleapps/marketplace/sso.html
does not have a python openid apps-discovery library which seems
to be the stumbling block.
Has anyone ported an appengine app to the marketplace... | [
"I answered an almost the same question at Google apps login in django. Check it out.\nEdited:\nActually, your question can be separated into two related questions.\n\nHow to build an application for Google Marketplace?\nHow to authenticate with Google Apps Account to login into your application?\n\nYou don't reall... | [
3,
0
] | [] | [] | [
"google_app_engine",
"marketplace",
"python"
] | stackoverflow_0002422220_google_app_engine_marketplace_python.txt |
Q:
Python recursion with list returns None
def foo(a):
a.append(1)
if len(a) > 10:
print a
return a
else:
foo(a)
Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong.
In [263]: x = []
In [264]: y = foo(x)
[1, 1, 1, 1, 1,... | Python recursion with list returns None | def foo(a):
a.append(1)
if len(a) > 10:
print a
return a
else:
foo(a)
Why this recursive function returns None (see transcript below)? I can't quite understand what I am doing wrong.
In [263]: x = []
In [264]: y = foo(x)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [265]: print y
None
| [
"You don't return anything in the else clause:\n else:\n return foo(a)\n\n"
] | [
20
] | [] | [] | [
"list",
"python",
"recursion"
] | stackoverflow_0002599149_list_python_recursion.txt |
Q:
Django templates check condition
If there are are no values in the table how can should the code be to indicate no name found else show the drop down box in the below code
{% for name in dict.names %}
<option value="{{name.id}}" {% for selected_id in selected_name %}{% ifequal name.id selected_id %} {{ selecte... | Django templates check condition | If there are are no values in the table how can should the code be to indicate no name found else show the drop down box in the below code
{% for name in dict.names %}
<option value="{{name.id}}" {% for selected_id in selected_name %}{% ifequal name.id selected_id %} {{ selected }} {% endifequal %} {% endfor %}>{{n... | [
"I'm guessing that you want for...empty pair of tags. \n<select>\n {% for name in dict.names %}\n <option value=\"{{name.id}}\" \n {% for selected_id in selected_name %}\n {% ifequal name.id selected_id %} {{ selected }} {% endifequal %} \n {% endfor %}>\n {{name.firstname}}\n </optio... | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002599203_django_django_templates_python.txt |
Q:
Python (pdb) - Queueing up commands to execute
I am implementing a "breakpoint" system for use in my Python development that will allow me to call a function that, in essence, calls pdb.set_trace();
Some of the functionality that I would like to implement requires me to control pdb from code while I am within a se... | Python (pdb) - Queueing up commands to execute | I am implementing a "breakpoint" system for use in my Python development that will allow me to call a function that, in essence, calls pdb.set_trace();
Some of the functionality that I would like to implement requires me to control pdb from code while I am within a set_trace context.
Example:
disableList = []
def break... | [
"You could invoke lower-level methods to get more control over the debugger:\ndef debug():\n import pdb\n import sys\n\n # set up the debugger\n debugger = pdb.Pdb()\n debugger.reset()\n\n # your custom stuff here\n debugger.do_where(None) # run the \"where\" command\n\n # invoke the interac... | [
5
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0002596738_debugging_pdb_python.txt |
Q:
Using zc.buildout, how do I install a tarball from a website?
I'm trying to get zc.buildout to install Gunicorn from source. Using the following configuration:
[gunicorn]
recipe = collective.recipe.distutils
url = http://github.com/benoitc/gunicorn/tarball/master
results in the following error:
SystemError: ('Fai... | Using zc.buildout, how do I install a tarball from a website? | I'm trying to get zc.buildout to install Gunicorn from source. Using the following configuration:
[gunicorn]
recipe = collective.recipe.distutils
url = http://github.com/benoitc/gunicorn/tarball/master
results in the following error:
SystemError: ('Failed', '"/usr/bin/python" setup.py -q install --install- purelib="/... | [
"You can \"just\" install it. On the command line, \"easy_install http://github.com/benoitc/gunicorn/tarball/master\" works fine.\nThe buildout equivalent would be to have a dependency on \"gunicorn\" (so that buildout attempts installing it) and to tell buildout that your github link is actually gunicorn. You do ... | [
3
] | [] | [] | [
"buildout",
"python",
"recipe"
] | stackoverflow_0002572160_buildout_python_recipe.txt |
Q:
Designing a Tag table that tells how many times it's used
I am trying to design a tagging system with a model like this:
Tag:
content = CharField
creator = ForeignKey
used = IntergerField
It is a many-to-many relationship between tags and what's been tagged.
Everytime I insert a record into the assoticat... | Designing a Tag table that tells how many times it's used | I am trying to design a tagging system with a model like this:
Tag:
content = CharField
creator = ForeignKey
used = IntergerField
It is a many-to-many relationship between tags and what's been tagged.
Everytime I insert a record into the assotication table,
Tag.used is incremented by one, and decremented by ... | [
"I don't think it's a good idea to denormalize your data like that.\nI think a more elegant solution is to use django aggregation to track how many times the tag has been used http://docs.djangoproject.com/en/dev/topics/db/aggregation/\nYou could attach the used count to your tag object by calling something like th... | [
1,
1
] | [] | [] | [
"database_design",
"django",
"python",
"tagging"
] | stackoverflow_0002597751_database_design_django_python_tagging.txt |
Q:
Generate fixed length hash in python for url parameter
I am working in python on appengine.
I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=XhMN0wlITLk) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 di... | Generate fixed length hash in python for url parameter | I am working in python on appengine.
I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=XhMN0wlITLk) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with hashlib to build my own, but... | [
"You can use the auto generated integer id of the key to generate the hash. A simple way to generate the hash would be to convert the integer id to base62 (alphanumeric). To fetch the object simply convert to decimal back from base62 and use get_by_id to retrieve the object.\nHere is a simple base62 conversion func... | [
8,
7
] | [] | [] | [
"google_app_engine",
"hash",
"python",
"url"
] | stackoverflow_0002597833_google_app_engine_hash_python_url.txt |
Q:
Does python have one way of doing things?
I have always seen in python articles/books that python is simple and it has only one way of doing things. I would like someone to explain to me this concept keeping in mind the example below, if I wanted to get the min and max values of sequence I would do the following;
... | Does python have one way of doing things? | I have always seen in python articles/books that python is simple and it has only one way of doing things. I would like someone to explain to me this concept keeping in mind the example below, if I wanted to get the min and max values of sequence I would do the following;
seq=[1,2,3,4,5,6]
min(seq) #1
max(seq) #6
bu... | [
"Not that it \"has one way of doing things\" as more \"There should be one-- and preferably only one --obvious way to do it.\" (from Zen of Python).\nThis doesn't exclude possibility of having more than one way of doing things. We're talking about programming where creativity is one of the most important skills and... | [
30,
15,
7,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002599410_python.txt |
Q:
appcfg.py upload_data entity kind problem
I am developing application on app-engine-path and I would like to upload some data to datastore.
For example I have a model
models/places.py:
class Place(db.Model):
name = db.StringProperty()
longitude = db.FloatProperty()
latitude = db.FloatProperty()
If I... | appcfg.py upload_data entity kind problem | I am developing application on app-engine-path and I would like to upload some data to datastore.
For example I have a model
models/places.py:
class Place(db.Model):
name = db.StringProperty()
longitude = db.FloatProperty()
latitude = db.FloatProperty()
If I save this in view, kind() of this entity is "m... | [
"I found resolution:\nplaces_loader.py:\nfrom google.appengine.ext import bulkload\n\nclass PlaceLoader(bulkload.Loader):\n def __init__(self):\n bulkload.Loader.__init__(self, 'models_place',\n [('name', lambda x: x.decode('utf-8')),\n ('longit... | [
1
] | [] | [] | [
"app_engine_patch",
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002599937_app_engine_patch_django_google_app_engine_google_cloud_datastore_python.txt |
Q:
Problem building a complete binary tree of height 'h' in Python
Here is my code. The complete binary tree has 2^k nodes at depth k.
class Node:
def __init__(self, data):
# initializes the data members
self.left = None
self.right = None
self.data = data
root = Node(data_root)
... | Problem building a complete binary tree of height 'h' in Python | Here is my code. The complete binary tree has 2^k nodes at depth k.
class Node:
def __init__(self, data):
# initializes the data members
self.left = None
self.right = None
self.data = data
root = Node(data_root)
def create_complete_tree():
row = [root]
for i in r... | [
"The main problem here is that you are using deepcopy on the temporary list. Consider what happens each iteration:\n\nYour initial root gets inspected, and child nodes get created\nThese child nodes are placed in newrow\nCopies of these child nodes are copied into row for the next iteration.\n\nThis means the subs... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002600426_python.txt |
Q:
Types in Python - Google Appengine
Getting a bit peeved now;
I have a model and a class thats just storing a get request in the database; basic tracking.
class SearchRec(db.Model):
WebSite = db.StringProperty()#required=True
WebPage = db.StringProperty()
CountryNM = db.StringProperty()
PrefMailing = db.Boo... | Types in Python - Google Appengine | Getting a bit peeved now;
I have a model and a class thats just storing a get request in the database; basic tracking.
class SearchRec(db.Model):
WebSite = db.StringProperty()#required=True
WebPage = db.StringProperty()
CountryNM = db.StringProperty()
PrefMailing = db.BooleanProperty()
DateStamp = db.DateTime... | [
"You've added a lot of layers of complication to understanding what the bool() build-in function does. Why don't you test it out directly on the command-line, before embedding it deep in your google app engine code.\nWhat you'd discover is that the bool() function uses python's truth values:\nhttp://docs.python.org... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002600907_google_app_engine_python.txt |
Q:
Executing / Running a python script from ubuntu server
Can anybody help me how to run a python script through command line?
My python script http://buffis.com/2007/07/25/getting-info_hash-for-xbt-tracker/comment-page-1/
I am using this command /var/www/hash_info.py /var/www/Muha_Album.7912.torrent
I have copied de... | Executing / Running a python script from ubuntu server | Can anybody help me how to run a python script through command line?
My python script http://buffis.com/2007/07/25/getting-info_hash-for-xbt-tracker/comment-page-1/
I am using this command /var/www/hash_info.py /var/www/Muha_Album.7912.torrent
I have copied dependency file bencode.py mentioned in article link above. Wh... | [
"python /var/www/hash_info.py /var/www/Muha_Album.7912.torrent\n\n",
"Maybe it says:\nbad interpreter: No such file or directory\n\nThen, the first line, so called shebang line is the issue here. I guess you need to change it to where your python is really installed. On my Ubuntu installation it's /usr/bin/python... | [
4,
3,
0
] | [] | [] | [
"bash",
"linux",
"python"
] | stackoverflow_0002601714_bash_linux_python.txt |
Q:
Return unicode string from python via ajax
I have a small webapp that runs Python on the server side and javascript (jQuery) on the client side.
Now upon a certain request my Python script returns a unicode string and the client is supposed to put that string inside a div in the browser. However i get a unicode en... | Return unicode string from python via ajax | I have a small webapp that runs Python on the server side and javascript (jQuery) on the client side.
Now upon a certain request my Python script returns a unicode string and the client is supposed to put that string inside a div in the browser. However i get a unicode encode error from Python.
If i run the script from... | [
"If the python interpreter can't determine the encoding of sys.stdout ascii is used as a fallback however the characters in the string are not part of ascii, therefore a UnicodeEncodeError exception is raised.\nA solution would be to encode the string yourself using something like .encode(sys.stdout.encoding or \"u... | [
3
] | [] | [] | [
"ajax",
"python",
"unicode"
] | stackoverflow_0002601306_ajax_python_unicode.txt |
Q:
How to use methods defined in a python scipt from a console like ipython
I have written a python script with methods in it. Now I want to use methods from that script in ipython. How do I import it for use in ipython?
Cheers
A:
If the file with your functions in it is called mod.py, just:
>>> import mod
>>> mod.... | How to use methods defined in a python scipt from a console like ipython | I have written a python script with methods in it. Now I want to use methods from that script in ipython. How do I import it for use in ipython?
Cheers
| [
"If the file with your functions in it is called mod.py, just:\n>>> import mod\n>>> mod.myfunction()\n\n",
"There are several options and all of them work with specific advantages and disadvantages:\nfrom module import *\nimport module\n%edit module.py\n\n",
"Inside IPython:\ncd folder/containing/module\nimport... | [
2,
1,
0
] | [] | [] | [
"import",
"ipython",
"python",
"scripting"
] | stackoverflow_0002602188_import_ipython_python_scripting.txt |
Q:
Scope of "library" methods
I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.
Background:
I'm using the
if __name__ == "__main__"
construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visu... | Scope of "library" methods | I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.
Background:
I'm using the
if __name__ == "__main__"
construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their results for visual checking as I develop the mod... | [
"\"Global scope\" doesn't actually exist in Python. What is commonly called \"global scope\" is actually module scope. That is to say, names defined at the module level. Putting the function in another module means that its module scope changes.\n",
"In python each file is its own namespace. A function, when call... | [
2,
2,
1,
0,
0
] | [] | [] | [
"import",
"module",
"python",
"scope"
] | stackoverflow_0002596610_import_module_python_scope.txt |
Q:
Looking for a Python IDE with good support for libraries (Twisted)
I'm looking for a Python IDE that can help me easily locate and manage and use the libraries on my system (Ubuntu). Specifically Twisted.
Code completion is important including the symbols I import.
(I've so far had a look at PyDev as well as Open... | Looking for a Python IDE with good support for libraries (Twisted) | I'm looking for a Python IDE that can help me easily locate and manage and use the libraries on my system (Ubuntu). Specifically Twisted.
Code completion is important including the symbols I import.
(I've so far had a look at PyDev as well as OpenKomodo, but while both offer code completion for default Python concepts... | [
"Using Wing IDE with Twisted discusses how to debug twisted using their IDE - although unfortunately WingWare is not free.\nAre you sure you have given PyDev a fair look? It seems to be the most popular Python IDE, and I have always had good experiences with it in the past.\n",
"I've just downloaded the preview o... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"code_completion",
"ide",
"import",
"libraries",
"python"
] | stackoverflow_0002586274_code_completion_ide_import_libraries_python.txt |
Q:
Python Tkinter Tix: How to use ScrolledWindow with grid in Tix NoteBook
I'm adding several widgets to a Frame which is located in a tix.NoteBook. When there are too much widgets to fit in the window, I want to use a scrollbar, so I put tix.ScrolledWindow inside that Frame and add my widgets to this ScrolledWindow ... | Python Tkinter Tix: How to use ScrolledWindow with grid in Tix NoteBook | I'm adding several widgets to a Frame which is located in a tix.NoteBook. When there are too much widgets to fit in the window, I want to use a scrollbar, so I put tix.ScrolledWindow inside that Frame and add my widgets to this ScrolledWindow instead.
The problem is that when using the grid() geometry manager, the scro... | [
"I solved it without using ´tix.scrolledWindow´. Instead, I went for the autoscrollbar suggested by Fred Lundh here.\nThe main problem was the adaption to the NoteBook widget. First, I tried to put the scrollbar to the root, so that they would surround the whole window. Now, I wanted to change the hook for the scro... | [
2
] | [] | [] | [
"grid",
"python",
"scrolledwindow",
"tix"
] | stackoverflow_0002575451_grid_python_scrolledwindow_tix.txt |
Q:
What is the better error handling method for decoding Python bytes to unicode strings?
I have an old C# program that is being ported to Python 3 for different reasons. Basically, what the program does is to fetch a website and search its content (and process it, but that is not really relevant). I have never reall... | What is the better error handling method for decoding Python bytes to unicode strings? | I have an old C# program that is being ported to Python 3 for different reasons. Basically, what the program does is to fetch a website and search its content (and process it, but that is not really relevant). I have never really had any issues with the actual fetch-and-search routine, but once I ported it to Python it... | [
"According to http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8.aspx the default UTF-8 decoder of C# ignores invalid bytes.\nPython's 'ignore' option for decoding unicode is the same as this.\n"
] | [
2
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002601294_python_unicode.txt |
Q:
Is it possible to install SSL on Google app engine for iPhone application?
I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ss... | Is it possible to install SSL on Google app engine for iPhone application? | I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urg... | [
"See the App Engine Python documentation on setting up secure URLs. Note that this will only work when accessed via your appspot.com domain - it's not possible to have SSL on a custom domain through App Engine, currently.\n",
"Nick Johnson has already provided a link and mentioned that this functionality is not c... | [
5,
0
] | [] | [] | [
"google_app_engine",
"python",
"ssl"
] | stackoverflow_0001191936_google_app_engine_python_ssl.txt |
Q:
shelve gives strange error
I'm trying to put some sites i crawled into a shelve, but the shelve won't accept any Site-objects. It will accept lists, strings, tuples, what have you, but as soon as i put in a Site-object, it crashes when i try to get the contents of the shelve
So when i fill up my shelve like this: ... | shelve gives strange error | I'm trying to put some sites i crawled into a shelve, but the shelve won't accept any Site-objects. It will accept lists, strings, tuples, what have you, but as soon as i put in a Site-object, it crashes when i try to get the contents of the shelve
So when i fill up my shelve like this:
def add_to_shelve(self, site):
... | [
"It looks like you refactored your code after saving objects in the shelve. When retrieving objects from the shelve, Python rebuilds the object, and it needs to find the original class that, presumably, you have moved. This problem is typical when working with pickle (as the shelve module does).\nThe solution, as p... | [
5,
0
] | [] | [] | [
"python",
"shelve"
] | stackoverflow_0002601081_python_shelve.txt |
Q:
Removing duplicates (within a given tolerance) from a Numpy array of vectors
I have an Nx5 array containing N vectors of form 'id', 'x', 'y', 'z' and 'energy'. I need to remove duplicate points (i.e. where x, y, z all match) within a tolerance of say 0.1. Ideally I could create a function where I pass in the array... | Removing duplicates (within a given tolerance) from a Numpy array of vectors | I have an Nx5 array containing N vectors of form 'id', 'x', 'y', 'z' and 'energy'. I need to remove duplicate points (i.e. where x, y, z all match) within a tolerance of say 0.1. Ideally I could create a function where I pass in the array, columns that need to match and a tolerance on the match.
Following this thread o... | [
"You might look at scipy.spatial.KDTree.\nHow big is N ?\nAdded: oops, tree.query_pairs is not in scipy 0.7.1 .\nWhen in doubt, use brute force: split the space (here side^3) into little cells,\none point per cell:\n\"\"\" scatter points to little cells, 1 per cell \"\"\"\nfrom __future__ import division \n... | [
2,
1,
0
] | [] | [] | [
"numpy",
"python",
"sorting"
] | stackoverflow_0002433882_numpy_python_sorting.txt |
Q:
Python's Popen cleanup
I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").
I go to the subprocess module and try this:
p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE)
This works for reading... | Python's Popen cleanup | I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").
I go to the subprocess module and try this:
p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE)
This works for reading the output the same way I w... | [
"The issue is that the pipe is full. The subprocess stops, waiting for the pipe to empty out, but then your process (the Python interpreter) quits, breaking its end of the pipe (hence the error message).\np.wait() will not help you:\n\nWarning This will deadlock if the child process generates enough output to a std... | [
11,
3,
0,
0
] | [] | [] | [
"popen",
"python",
"resource_cleanup"
] | stackoverflow_0002595602_popen_python_resource_cleanup.txt |
Q:
Problem with VIM - "f" calling the "fold" command instead of "find"
This is happening in python files.
For example, I want to do type "fC" in normal mode, and instead of finding the first "C" character, it is just doing code fold toggling.
A:
Real answer:
Are you using this plugin? Under 4, it says that pressing... | Problem with VIM - "f" calling the "fold" command instead of "find" | This is happening in python files.
For example, I want to do type "fC" in normal mode, and instead of finding the first "C" character, it is just doing code fold toggling.
| [
"Real answer:\nAre you using this plugin? Under 4, it says that pressing \"f\" toggles the fold (in certain conditions).\nOriginal answer:\nI'm not sure what fC does, because it doesn't do anything in my version of vim, but normally to use find \"C,\" you can use \"/C\" followed by enter.\n"
] | [
3
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0002603389_python_vim.txt |
Q:
Python lxml screen scraping?
I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and ja... | Python lxml screen scraping? | I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me w... | [
"No screen-scraping library I know \"does well with Javascript\" -- it's just too hard to anticipate all ways in which JS could alter the HTML DOM dynamically, conditionally &c.\n",
"scrape.py can do this for you.\nIt's as simple as:\nimport scrape\ns = scrape.Session()\ns.go('yoursite.com')\nprint s.doc.text\n\n... | [
4,
2,
0,
0,
0
] | [] | [] | [
"html",
"lxml",
"parsing",
"python",
"screen_scraping"
] | stackoverflow_0000814227_html_lxml_parsing_python_screen_scraping.txt |
Q:
Mako templates use old version until I manually update template files
I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using
./manage.py runserver
I think it's usu... | Mako templates use old version until I manually update template files | I periodically get this problem where all of a sudden mako is using old versions of templates, and it's not until I manually go and update the template files that they'll use the current version. I'm using
./manage.py runserver
I think it's usually after I update using source control, but it's intermittent, and I can'... | [
"It kinda feels like there some caching going on. You don't give a very specific description of the process, so it's hard to go any deeper than that.\n",
"In your settings.py file you can use the MAKO_TEMPLATE_OPTS setting to specify where the temporary compiled templates go.\nimport os\nimport tempfile\nMAKO_TEM... | [
0,
0
] | [] | [] | [
"django",
"mako",
"python"
] | stackoverflow_0001949516_django_mako_python.txt |
Q:
Django repeating vars/cache issue?
I'm trying to build a better/more powerful form class for Django. It's working well, except for these sub-forms. Actually, it works perfectly right after I re-start apache, but after I refresh the page a few times, my HTML output starts to look like this:
<input class="text" type... | Django repeating vars/cache issue? | I'm trying to build a better/more powerful form class for Django. It's working well, except for these sub-forms. Actually, it works perfectly right after I re-start apache, but after I refresh the page a few times, my HTML output starts to look like this:
<input class="text" type="text" id="pickup_addr-pickup_addr-pick... | [
"You're probably declaring your forms like this:\nclass SomeForm(Form):\n someField = Field(....)\n ...\n\nNow, this means that one instance of someField will actually be shared among all your SomeForm instances. In your __init__ you're changing the attributes of the field, which will affect all forms, not ju... | [
1
] | [] | [] | [
"django",
"python",
"wsgi"
] | stackoverflow_0002603937_django_python_wsgi.txt |
Q:
Pre-generating GUIDs for use in python?
I have a python program that needs to generate several guids and hand them back with some other data to a client over the network. It may be hit with a lot of requests in a short time period and I would like the latency to be as low as reasonably possible.
Ideally, rather th... | Pre-generating GUIDs for use in python? | I have a python program that needs to generate several guids and hand them back with some other data to a client over the network. It may be hit with a lot of requests in a short time period and I would like the latency to be as low as reasonably possible.
Ideally, rather than generating new guids on the fly as the cli... | [
"Are you certain that the uuid module would in fact be too slow to handle the requests you expect in a timely manner? I would be very surprised if UUID generation accounted for a bottleneck in your application.\nI would first build the application to simply use the uuid module and then if you find that this module... | [
6,
4,
0
] | [] | [] | [
"guid",
"linux",
"performance",
"python",
"uuid"
] | stackoverflow_0002603951_guid_linux_performance_python_uuid.txt |
Q:
Obtaining IP addresses in Bittorrent
I am trying to get a list of IP addresses serving or downloading a file. What I did was to contact a tracker like openbittorrent.com to get the following (as part of the scrape file):
B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE:0:1
Now, the long string in the beginning is t... | Obtaining IP addresses in Bittorrent | I am trying to get a list of IP addresses serving or downloading a file. What I did was to contact a tracker like openbittorrent.com to get the following (as part of the scrape file):
B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE:0:1
Now, the long string in the beginning is the info hash. As a next step, I did this:
... | [
"That's not a torrent file, that's an announce response. They're both bencode (use bencode to decode them), but the announce response contains only peer information. That's not enough information to be able to download the contents of the torrent: to do that you will need the torrent file itself.\nThe peers member ... | [
3
] | [] | [] | [
"bittorrent",
"language_agnostic",
"p2p",
"prototype",
"python"
] | stackoverflow_0002604153_bittorrent_language_agnostic_p2p_prototype_python.txt |
Q:
Why don't these class attributes register?
I have a factory method that generates django form classes like so:
def get_indicator_form(indicator, patient):
class IndicatorForm(forms.Form):
#These don't work!
indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())
... | Why don't these class attributes register? | I have a factory method that generates django form classes like so:
def get_indicator_form(indicator, patient):
class IndicatorForm(forms.Form):
#These don't work!
indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())
patient_id = forms.IntegerField(initial=pati... | [
"Try this:\ndef get_indicator_form(indicator, patient):\n class IndicatorForm(forms.Form):\n indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())\n patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput())\n\n def __init__(self, *args, **k... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002604230_django_django_forms_python.txt |
Q:
Why does easy_install extract some python eggs and not others?
Looking in my /usr/local/lib/python.../dist-package directory, I have .egg directories and .egg files.
Why does the installer choose to extra packages to the .egg directory, yet leave other files with .egg extensions?
A:
If the package contains onl... | Why does easy_install extract some python eggs and not others? | Looking in my /usr/local/lib/python.../dist-package directory, I have .egg directories and .egg files.
Why does the installer choose to extra packages to the .egg directory, yet leave other files with .egg extensions?
| [
"If the package contains only pure-Python code, it can stay as just an egg file. The Python interpreter can load the Python modules directly from the egg. If the package contains modules written in C or other data, then egg needs to be extracted so the C modules and/or data can be accessed. That's the default be... | [
32,
5
] | [] | [] | [
"egg",
"python"
] | stackoverflow_0002604600_egg_python.txt |
Q:
Enable PyGTK Eventbox motion-notify-event while is a Layout child
I noticed when a Eventbox is added into a Layout some events are missed, this does not happend for example adding it to a Fixed (very similar widget), I tried to restore the event mask in this way with no sucess:
import pygtk
import gtk
def foo(wid... | Enable PyGTK Eventbox motion-notify-event while is a Layout child | I noticed when a Eventbox is added into a Layout some events are missed, this does not happend for example adding it to a Fixed (very similar widget), I tried to restore the event mask in this way with no sucess:
import pygtk
import gtk
def foo(widget, event):
print event
pygtk.require('2.0')
window = gtk.Wind... | [
"The code you pasted works fine for me. When I press button 1 on the mouse and drag on the window, it generates and prints motion events to the terminal.\nI've even removed the eventbox.set_events(...) call and it still works.\nSo what's the problem?\n"
] | [
1
] | [] | [] | [
"gnome",
"gtk",
"pygtk",
"python"
] | stackoverflow_0002604846_gnome_gtk_pygtk_python.txt |
Q:
How do I do this loop in Django template?
{% for d in mydata %}
{{ d.title }}
{% endfor %}
However, I would like the first one to be bolded. How can I use the loop to say...if the d is the first one, then bold it?
A:
Check out http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for. Looks like:
{%... | How do I do this loop in Django template? | {% for d in mydata %}
{{ d.title }}
{% endfor %}
However, I would like the first one to be bolded. How can I use the loop to say...if the d is the first one, then bold it?
| [
"Check out http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for. Looks like:\n{% for d in mydata %}\n {% if forloop.first %}\n <strong>{{ d.title }}</strong>\n {% else %}\n {{ d.title }}\n {% endif %}\n{% endfor %}\n\n",
"Check if forloop.first is true.\n"
] | [
8,
2
] | [] | [] | [
"django",
"loops",
"python",
"templates"
] | stackoverflow_0002604979_django_loops_python_templates.txt |
Q:
Issue with making python program executable
I'm trying to make a program so that I can run it through the command line with the following format:
./myProgram
I made it executable and put #!/usr/bin/env python in the header, but it's giving me the following error.
env: python\r: No such file or directory
However... | Issue with making python program executable | I'm trying to make a program so that I can run it through the command line with the following format:
./myProgram
I made it executable and put #!/usr/bin/env python in the header, but it's giving me the following error.
env: python\r: No such file or directory
However, when I run "python myProgram", it runs fine. Ca... | [
"Your line endings are wrong. Use dos2unix to fix them.\n",
"+1 on ignacio's suggestion.\nhowever, to answer the 1st part of your question more directly, each OS/system uses a different line termination character:\nPOSIX (any Unix-flavor like Linux, *BSD, Mac OS X, etc.) uses \\n (NEWLINE) while\nDOS/Win uses the... | [
17,
11,
3
] | [] | [] | [
"python"
] | stackoverflow_0002604917_python.txt |
Q:
Google appengine datastore tree structure
I need to be able to make a tree like structure in the appengine database.
I have try to make an object reference itself but have not gotten it to work.
class Item(db.Model):
children = db.ListProperty(db.ReferenceProperty(Item))
A:
Alternatively, you can store refer... | Google appengine datastore tree structure | I need to be able to make a tree like structure in the appengine database.
I have try to make an object reference itself but have not gotten it to work.
class Item(db.Model):
children = db.ListProperty(db.ReferenceProperty(Item))
| [
"Alternatively, you can store references to children in the parent with:\nclass Node(db.Model):\n children = db.ListProperty(db.Key)\n\nThis answer shamelessly stolen (with credit!) from Nick Johnson's answer to this related question\n",
"Here is a related topic from the google-appengine group.\nYou can store ... | [
3,
1
] | [] | [] | [
"database",
"google_app_engine",
"python"
] | stackoverflow_0002604966_database_google_app_engine_python.txt |
Q:
Silence loggers and printing to screen - Python
I'm having a problem with my python script.
It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen.
Edit:
The library I'm using is mechanize, and it's printing a LOT of data on screen.
I have set these to fal... | Silence loggers and printing to screen - Python | I'm having a problem with my python script.
It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen.
Edit:
The library I'm using is mechanize, and it's printing a LOT of data on screen.
I have set these to false with no luck!
br.set_debug_redirects(False)
br.set... | [
"(Based on your 2nd edit)\nIf you don't want to disable all output, you can try to be specific to mechanize itself. http://wwwsearch.sourceforge.net/mechanize/ provides a snippet, which I've modified (though I'm not sure if it will work):\nimport logging\nlogger = logging.getLogger(\"mechanize\")\n# only log really... | [
16,
2,
0
] | [] | [] | [
"logging",
"mechanize",
"printing",
"python"
] | stackoverflow_0002605117_logging_mechanize_printing_python.txt |
Q:
Django: reverse lookup URL of feeds?
I am having trouble doing a reverse URL lookup for Django-generated feeds.
I have the following setup in urls.py:
feeds = {
'latest': LatestEntries,
}
urlpatterns = patterns('',
# ...
# enable feeds (RSS)
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication... | Django: reverse lookup URL of feeds? | I am having trouble doing a reverse URL lookup for Django-generated feeds.
I have the following setup in urls.py:
feeds = {
'latest': LatestEntries,
}
urlpatterns = patterns('',
# ...
# enable feeds (RSS)
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed',
{'feed_dict': feeds}... | [
"Unfortunately, URL reversing is not really possible with the current feed framework. The good news is that the feed framework has been completely refactored and can seamlessly integrate with Django's URL resolving mechanisms. This refactored feed framework will be delivered with Django 1.2, which should arrive at ... | [
3,
1
] | [] | [] | [
"django",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0002604823_django_django_templates_django_urls_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.