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:
Is there a function in Django / Python similar to PHP flush() that lets me send part of the HTTP response to clients?
According to the performance tip from Yahoo:
When users request a page, it can take
anywhere from 200 to 500ms for the
backend server to stitch together the
HTML page. During this time, the
... | Is there a function in Django / Python similar to PHP flush() that lets me send part of the HTTP response to clients? | According to the performance tip from Yahoo:
When users request a page, it can take
anywhere from 200 to 500ms for the
backend server to stitch together the
HTML page. During this time, the
browser is idle as it waits for the
data to arrive. In PHP you have the
function flush(). It allows you to
send you... | [
"http://www.evanfosmark.com/2008/06/simple-output-buffering-in-python/ - Good article on the topic. Should do exactly what you need using either option provided.\n",
"No. Is the short answer.\nThe long answer depends what you're using between the webserver and python:\nYou could implement it with WSGI but it woul... | [
2,
2,
2
] | [] | [] | [
"django",
"http",
"performance",
"php",
"python"
] | stackoverflow_0006300859_django_http_performance_php_python.txt |
Q:
How do I split a huge file into multiple files?
What's the easiest way to do this without running out of memory?
I have a 9GB file that has 100 million lines (each is a URL).
How can I split this up into X files? I tried for f in fileinput.input('...'), but it got "killed" for some reason.
A:
from __future__ im... | How do I split a huge file into multiple files? | What's the easiest way to do this without running out of memory?
I have a 9GB file that has 100 million lines (each is a URL).
How can I split this up into X files? I tried for f in fileinput.input('...'), but it got "killed" for some reason.
| [
"from __future__ import with_statement\n\nYOUR_FILENAME= 'bigfile.log'\nSPLIT_NAME= 'bigfile.part%05d.log'\nSPLIT_SIZE= 10000 # lines\nSPLITTER= lambda t: t[0]//SPLIT_SIZE\n\nimport itertools as it\n\nwith open(YOUR_FILENAME, \"r\") as input_file:\n for part_no, lines in it.groupby(enumerate(input_file), SPLITTE... | [
0
] | [] | [] | [
"file",
"linux",
"memory",
"python",
"unix"
] | stackoverflow_0006274551_file_linux_memory_python_unix.txt |
Q:
How can I return a text file with exact positioning?
I'm creating a text file response with Django. I'm implementing it the normal way with a template file.
def create_file(request):
... create context ...
result = render_to_string('template.txt', context_dict)
response = HttpResponse(result, mimetype... | How can I return a text file with exact positioning? | I'm creating a text file response with Django. I'm implementing it the normal way with a template file.
def create_file(request):
... create context ...
result = render_to_string('template.txt', context_dict)
response = HttpResponse(result, mimetype='text/plain')
response['Content-Disposition'] = 'atta... | [
"Yes, it would be easier to create the response entirely within the view. Templates are just a convenient plug-in for rendering structured text with a static scaffold, but it sounds to me like your structure is in the layout and not the scaffold. \nI would, indeed, do this by creating my own little templating eng... | [
2,
2,
2
] | [] | [] | [
"django",
"file_io",
"python",
"text"
] | stackoverflow_0006300285_django_file_io_python_text.txt |
Q:
python: comparing attributes values in form before and after submit
I fill a form fields (in pygtk) from a class instance that contains its attributes with their values.
Once the form is submitted, I get this instance updated with new values.
What is the best way to determine if the form has returned different val... | python: comparing attributes values in form before and after submit | I fill a form fields (in pygtk) from a class instance that contains its attributes with their values.
Once the form is submitted, I get this instance updated with new values.
What is the best way to determine if the form has returned different values (ie: been modified) ? Do I have to make a copy of the object instance... | [
"You will need to have a copy of the data before and after the form has been submitted. The default __eq__ operator will compare all attributes on of class, so you can probably use before_form == after_form to see if anything has changed. If you need to know what has changed then you will have to iterate over each ... | [
1
] | [] | [] | [
"forms",
"pygtk",
"python",
"validation"
] | stackoverflow_0006304344_forms_pygtk_python_validation.txt |
Q:
zero fill empty spaces at specific locations
I have a small question. I have a file in the following format:
1 2
1 2 3
1 2
1 2 3 4
2 4
The values in the code actually represent numbers(not necessarily single digit), but they can be any number, can be floating point values too.
Input file: For a particular row,... | zero fill empty spaces at specific locations | I have a small question. I have a file in the following format:
1 2
1 2 3
1 2
1 2 3 4
2 4
The values in the code actually represent numbers(not necessarily single digit), but they can be any number, can be floating point values too.
Input file: For a particular row, each number is separated from another by a single... | [
"Assume myfile is the open file. We use izip_longest from itertools to iterate over the columns of the input file, filling in \"0\" for missing values:\n[('1', '1', '1', '1', '2'), ('2', '2', '2', '2', '4'), \n ('0', '3', '0', '3', '0'), ('0', '0', '0', '4', '0')]\n\nThen we simply zip this output again to re... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006302385_python.txt |
Q:
Integrating xPDF in an IOS? (feasibility checking)
I am developing App in which PDF text searching & highlighting is needed. I found like its very difficult to highlight in PDF. So i thought to convert PDF to HTML then by using java-script, Search the string & Highlight it. Actually i got success in searching & hi... | Integrating xPDF in an IOS? (feasibility checking) | I am developing App in which PDF text searching & highlighting is needed. I found like its very difficult to highlight in PDF. So i thought to convert PDF to HTML then by using java-script, Search the string & Highlight it. Actually i got success in searching & highlighting on HTML text using java script.If any1 need s... | [
"Here you can find an example. Still has some problems, but is a good start:\nhttps://github.com/KurtCode/PDFKitten\n"
] | [
1
] | [] | [] | [
"ios",
"iphone",
"pdf",
"python"
] | stackoverflow_0006027382_ios_iphone_pdf_python.txt |
Q:
How can I check with doctest that a program produced certain output?
In one of my functions I'm calling an external program, using subprocess.check_call, which will produce output. How could I use doctest to make sure the output it's producing is the one I'm expecting?
A:
Maybe this can help:
import sys
import t... | How can I check with doctest that a program produced certain output? | In one of my functions I'm calling an external program, using subprocess.check_call, which will produce output. How could I use doctest to make sure the output it's producing is the one I'm expecting?
| [
"Maybe this can help:\nimport sys\nimport tempfile\nimport subprocess\n\n\ndef example(output):\n r\"\"\" Do something ...\n\n >>> output = example('Processing file ...')\n >>> print output # doctest:+ELLIPSIS\n 'Processing file ...'\n\n Check how many file was processed.\n >>> [line.startswith('P... | [
2
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0006303867_doctest_python.txt |
Q:
Pythons global variable
How can I define a global variable.
For example I have Foo1 class and Foo2 class and I want to use FooVariable in this classes as a global variable.
A:
If you wanted a global variable named foo, you would just have to put global foo at the top of any function in which it is used. For exa... | Pythons global variable | How can I define a global variable.
For example I have Foo1 class and Foo2 class and I want to use FooVariable in this classes as a global variable.
| [
"If you wanted a global variable named foo, you would just have to put global foo at the top of any function in which it is used. For example,\ndef do_something():\n global foo\n foo = foo + 1\n print foo\n\nNote that Python \"global\" variables are only global to the module they appear in, not global to t... | [
2
] | [] | [] | [
"global_variables",
"pyqt",
"python"
] | stackoverflow_0006304905_global_variables_pyqt_python.txt |
Q:
Get an object attribute
Simple question but since I'm new to python, comming over from php, I get a few errors on it.
I have the following simple class:
User(object)
fullName = "John Doe"
user = User()
In PHP I could do the following:
$param = 'fullName';
echo $user->$param; // return John Doe
How do I ... | Get an object attribute | Simple question but since I'm new to python, comming over from php, I get a few errors on it.
I have the following simple class:
User(object)
fullName = "John Doe"
user = User()
In PHP I could do the following:
$param = 'fullName';
echo $user->$param; // return John Doe
How do I do this in python?
| [
"To access field or method of an object use dot .:\nuser = User()\nprint user.fullName\n\nIf a name of the field will be defined at run time, use buildin getattr function:\nfield_name = \"fullName\"\nprint getattr(user, field_name) # prints content of user.fullName\n\n",
"Use getattr if you have an attribute in s... | [
101,
17,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0006305061_python.txt |
Q:
how can i check the ipaddress ranges one to another in python networking
how can I find the addresses in python if I have given any IP s range dynamically . I want the range of address from one to another ip and also count the ports which are connected .If the n number of IP s connected
A:
To get all the ... | how can i check the ipaddress ranges one to another in python networking | how can I find the addresses in python if I have given any IP s range dynamically . I want the range of address from one to another ip and also count the ports which are connected .If the n number of IP s connected
| [
"To get all the ips combinations you can try to use the following code:\nimport itertools \n\nips = itertools.product([193], [55,56], xrange(0,256), xrange(1, 256))\n\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"sockets",
"ubuntu"
] | stackoverflow_0006305098_linux_python_sockets_ubuntu.txt |
Q:
How to improve speed of odeint in Python?
I am using Python and odeint from the scipy package to solve a large number (~10e6) coupled ODE's. The system of equations can be formulated as a sum of some matrix multiplications and I use numpy with blas support for this. My problem is that this takes a very long time. ... | How to improve speed of odeint in Python? | I am using Python and odeint from the scipy package to solve a large number (~10e6) coupled ODE's. The system of equations can be formulated as a sum of some matrix multiplications and I use numpy with blas support for this. My problem is that this takes a very long time. When I profile the code I see that most of the ... | [
"This is at least one possible source of the amount of time:\nIf you do not supply a Jacobian to odeint (i.e. LSODA), it will try to compute it via finite differences. Moreover, it may try to invert the Jacobian, which scales as O(m^3), if it thinks the problem is stiff. Both of these steps are expensive when the n... | [
5,
2
] | [] | [] | [
"performance",
"python",
"scipy"
] | stackoverflow_0006304215_performance_python_scipy.txt |
Q:
Why 3D visualization looks difficult in programming languages after half a century?
As my knowledge there is no fully satisfactory 3d visualization package. I mean fully because it is easily can be seen the following problems with available packages:
lack of flexibility
heavy loading and initializations (ETS-Maya... | Why 3D visualization looks difficult in programming languages after half a century? | As my knowledge there is no fully satisfactory 3d visualization package. I mean fully because it is easily can be seen the following problems with available packages:
lack of flexibility
heavy loading and initializations (ETS-Mayavi2,...)
very slow even with OpenGL implementations (VPython,...)
lots of bugs for exampl... | [
"That's probably because \"fully\" is hard to define. \nDo you mean something like \"The C++ of Visualization Libraries\", where you can do boolean modeling, ray tracing, pixel shaders, transparent MAX file loading with acceleration structure compiling under the hood? With realtime LOTR-the-movie-battles animation ... | [
4
] | [] | [] | [
"3d",
"data_visualization",
"python"
] | stackoverflow_0006305186_3d_data_visualization_python.txt |
Q:
To ask permission or apologize?
I come from a python background, where it's often said that it's easier to apologize than to ask permission. Specifically given the two snippets:
if type(A) == int:
do_something(A)
else:
do_something(int(A))
try:
do_something(A)
except TypeError:
do_something(int(A))
Then ... | To ask permission or apologize? | I come from a python background, where it's often said that it's easier to apologize than to ask permission. Specifically given the two snippets:
if type(A) == int:
do_something(A)
else:
do_something(int(A))
try:
do_something(A)
except TypeError:
do_something(int(A))
Then under most usage scenarios the second... | [
"Probably not. .NET exceptions are relatively expensive.\nSeveral .NET functions offer both variants for this reason. (int.TryParse, which returns a success code is often recommended because it is faster than int.Parse which throws an exception on failure)\nBut the only answer that matters is what your own profilin... | [
16,
8,
6,
3,
0
] | [] | [] | [
"c#",
"performance",
"python"
] | stackoverflow_0006305551_c#_performance_python.txt |
Q:
Python new-style-class-related question
I am a python learner and currently hacking up a class with variable number of fields as in the "Bunch of Named Stuff" example here.
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
I also want to write a __setattr__ in this class in order to ... | Python new-style-class-related question | I am a python learner and currently hacking up a class with variable number of fields as in the "Bunch of Named Stuff" example here.
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
I also want to write a __setattr__ in this class in order to check the input attribute name. But, the pyth... | [
"You can use \nclass Bunch:\n def __init__(self, **kwds):\n self.__dict__.update(kwds)\n\n def __setattr__(self, name, value):\n #do your verification stuff\n self.__dict__[name] = value\n\nor with new-style class :\nclass Bunch(object):\n def __init__(self, **kwds):\n self.__di... | [
2,
1
] | [] | [] | [
"new_style_class",
"python"
] | stackoverflow_0006305640_new_style_class_python.txt |
Q:
sqlalchemy get model attribute question
My filters come via get params like so: filterName = 'email', filterValue = 'john@' and I need to build my query based on them.
If I try to use rows.filter( getattr( self.model, filterName ).like( filterValue + '%' ) ) I get an error: AttributeError: 'NoneType' object has no... | sqlalchemy get model attribute question | My filters come via get params like so: filterName = 'email', filterValue = 'john@' and I need to build my query based on them.
If I try to use rows.filter( getattr( self.model, filterName ).like( filterValue + '%' ) ) I get an error: AttributeError: 'NoneType' object has no attribute 'like'
Since both my model and fil... | [
"You don't show what self/self.model is in there. Normally it'd be a class name. \nSo if you have a model User\nfield = 'id'\nfield_val = 3\nqry = Session.query(User).filter(getattr(User, field) == field_val)\n\nshould work out fine. \nYou're not using getattr from an instance (self), but from the class itself. \n"... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006305280_python_sqlalchemy.txt |
Q:
In reportlab add as many empty rows to a long table as fit on the last page
I'm preparing a PDF report of a list of items, which essentially is a long table, with some cells filled with data and some cells empty. This report will be printed out and the user will fill the empty cells on paper. She will also add new... | In reportlab add as many empty rows to a long table as fit on the last page | I'm preparing a PDF report of a list of items, which essentially is a long table, with some cells filled with data and some cells empty. This report will be printed out and the user will fill the empty cells on paper. She will also add new rows and fill in new data.
So I will provide some (e.g. 3) empty rows as a grid ... | [
"I'll have to go retrieve some of my code, but I seem to recall having to do things by measuring the current X / Y Position, calculate that against whatever margin I was using, and then determine whether or not more information could fit or if I needed a new page. My project was word wrapping long blocks of text, ... | [
1,
1
] | [] | [] | [
"python",
"reportlab"
] | stackoverflow_0006297258_python_reportlab.txt |
Q:
How can you use os.chdir to go to a path minus the last step of it?
For example, a method is passed a path as a parameter, this path might be "C:/a/b/c/d", what if I want to use os.chdir() to change to C:/a/b/c (without the last folder)? Can os.chdir() take the ".." command?
A:
os.chdir() can take '..' as argum... | How can you use os.chdir to go to a path minus the last step of it? | For example, a method is passed a path as a parameter, this path might be "C:/a/b/c/d", what if I want to use os.chdir() to change to C:/a/b/c (without the last folder)? Can os.chdir() take the ".." command?
| [
"os.chdir() can take '..' as argument, yes. However, Python provides a platform-agnostic way: by using os.pardir:\nos.chdir(os.pardir)\n\n",
"You could use os.path.dirname:\nIn [1]: import os.path\n\nIn [2]: os.path.dirname('C:/a/b/c/d')\nOut[2]: 'C:/a/b/c'\n\nedit: It's been pointed out that this doesn't remove ... | [
10,
3,
2
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0006306287_operating_system_python.txt |
Q:
Replace 'nnn0n' with 'nnn1n' in Python using regular expressions
I would like to replace a string in form 'nnn0n' with the string in form 'nnn1n' where n is any digit. What the easiest way to do that? So, far I tried the following:
int(re.sub(r'^(\d+?)(0)(\d)$', r'\1???\3', '7001'))
But what ever I insert in pla... | Replace 'nnn0n' with 'nnn1n' in Python using regular expressions | I would like to replace a string in form 'nnn0n' with the string in form 'nnn1n' where n is any digit. What the easiest way to do that? So, far I tried the following:
int(re.sub(r'^(\d+?)(0)(\d)$', r'\1???\3', '7001'))
But what ever I insert in place of '???' either just 1 or \1 returns incorrect result.
Any ideas?
E... | [
"You can do something like:\nre.sub(r'^(\\d{3})0(\\d)$', r'\\g<1>1\\2', '7001')\n\nOr if it's not always three numbers before the 0 you want to replace:\nre.sub(r'^(\\d+)0(\\d)$', r'\\g<1>1\\2', '1234509')\n\nEdit If you know that the number will always be of the same format, you can just use:\nre.sub(r'0(?=\\d$)',... | [
3,
3,
1,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006305631_python_regex.txt |
Q:
I have this function call question in my sample exam it is for my finals and i would like to get your point for view
The question is to consider the following function definition:
def read_value_type(prompt='Enter a Boolean> ', convert=bool):
val = input(prompt)
return convert(val)
as a multiple choice:
... | I have this function call question in my sample exam it is for my finals and i would like to get your point for view | The question is to consider the following function definition:
def read_value_type(prompt='Enter a Boolean> ', convert=bool):
val = input(prompt)
return convert(val)
as a multiple choice:
val = read_value_type(convert=bool, prompt='Enter a boolean>')
val = read_value_type(prompt='Enter a float> ')
val = read_... | [
"All of them. But second will return bool, not float.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006306904_python.txt |
Q:
How to collect django TestCases into TestSuites and run them?
With this question I worked out how to break my tests over multiple files. So now in each file/module I have a series of TestCase classes.
I can still invoke individual TestCases by explicitly naming them from the command line like:
./manage.py test api... | How to collect django TestCases into TestSuites and run them? | With this question I worked out how to break my tests over multiple files. So now in each file/module I have a series of TestCase classes.
I can still invoke individual TestCases by explicitly naming them from the command line like:
./manage.py test api.TokenGeneratorTestCase api.ViewsTestCase
Rather than invoking rel... | [
"One possible approach is to write a custom runner that would extend django.test.simple.DjangoTestSuiteRunner and override the build_suite method. That's where Django generates the suite used by the test command.\nIt gets an argument test_labels which corresponds to the command line arguments passed to the command.... | [
1
] | [] | [] | [
"django",
"python",
"unit_testing"
] | stackoverflow_0006300906_django_python_unit_testing.txt |
Q:
what is the equivalent of 'x' in perldb but for python's pdb in emacs?
I am just starting to use pdb to debug python in emacs, and I find the 'x' command missing that is available in perldb. Is there something similar in pdb?
A:
You can find all the debugger commands here
pp comes closest I think...
| what is the equivalent of 'x' in perldb but for python's pdb in emacs? | I am just starting to use pdb to debug python in emacs, and I find the 'x' command missing that is available in perldb. Is there something similar in pdb?
| [
"You can find all the debugger commands here\npp comes closest I think...\n"
] | [
1
] | [] | [] | [
"emacs",
"pdb",
"python"
] | stackoverflow_0006307296_emacs_pdb_python.txt |
Q:
How do you add a scrolling div directly to a ModelForm in Django?
I have the following code, but it doesn't put the scrolling div anywhere. All the other combinations I've tried (such as placing the div around the table) results in some or other incorrect placement of the scroll bars.
This is the html:
<form acti... | How do you add a scrolling div directly to a ModelForm in Django? | I have the following code, but it doesn't put the scrolling div anywhere. All the other combinations I've tried (such as placing the div around the table) results in some or other incorrect placement of the scroll bars.
This is the html:
<form action="" method="post">
<table>
<div style="overflow: auto; width : ... | [
"Put the DIV inside a table row like this\n<form action=\"\" method=\"post\">\n <table>\n <tr><td><div style=\"overflow: auto; width : 200px; height : 50px;\">\n {{ form.as_p }}\n </div></td></tr>\n <tr><td colspan=\"2\"><input type=\"submit\" value=\"Save\"/></td></tr>\n </table>\n</form>\n\n",
"... | [
2,
0
] | [] | [] | [
"django",
"forms",
"html",
"python",
"scroll"
] | stackoverflow_0006305673_django_forms_html_python_scroll.txt |
Q:
Best way to extract datetime from string in python
I have a script that is parsing out fields within email headers that represent dates and times. Some examples of these strings are as follows:
Fri, 10 Jun 2011 11:04:17 +0200 (CEST)
Tue, 1 Jun 2011 11:04:17 +0200
Wed, 8 Jul 1992 4:23:11 -0200
Wed, 8 Jul 1992 4:23:... | Best way to extract datetime from string in python | I have a script that is parsing out fields within email headers that represent dates and times. Some examples of these strings are as follows:
Fri, 10 Jun 2011 11:04:17 +0200 (CEST)
Tue, 1 Jun 2011 11:04:17 +0200
Wed, 8 Jul 1992 4:23:11 -0200
Wed, 8 Jul 1992 4:23:11 -0200 EST
Before I was confronted with the CEST/EST ... | [
"From python time to age part 2, timezones:\nfrom email import utils\nutils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200 (CEST)') \nutils.parsedate_tz('Fri, 10 Jun 2011 11:04:17 +0200')\nutils.parsedate_tz('Fri, 10 Jun 2011 11:04:17')\n\nThe output is:\n(2011, 6, 10, 11, 4, 17, 0, 1, -1, 7200)\n(2011, 6, 10, 11, 4... | [
7,
2
] | [] | [] | [
"datetime",
"python",
"regex"
] | stackoverflow_0006307176_datetime_python_regex.txt |
Q:
Google Buzz API - Unable to resolve error: "Required Parameter Missing - grant_type"
I am trying to make a desktop application in python to post messages to Google Buzz. I am not able to exchange the code (the one I am asking the user to copy-paste from the browser after he authorizes the application) with the acc... | Google Buzz API - Unable to resolve error: "Required Parameter Missing - grant_type" | I am trying to make a desktop application in python to post messages to Google Buzz. I am not able to exchange the code (the one I am asking the user to copy-paste from the browser after he authorizes the application) with the access_token.
I am doing a POST to www.google.com4/accounts/o8/oauth2/token in the following ... | [
"[Answering my question in the hope that it helps future readers]\nI managed to solve my problem. I did a POST of the above data using Python's HTTPSConnection. GAE probably does not go well with it. I used google.appengine.api.urlfetch instead, and it worked just fine! :-)\n"
] | [
1
] | [] | [] | [
"access_token",
"google_buzz",
"oauth",
"python"
] | stackoverflow_0006174722_access_token_google_buzz_oauth_python.txt |
Q:
Simple license protection for Python app
Although there are quite a few questions like this, please bear with me as I think mine is different...
I have a $5 Python app that I distribute using py2exe, py2app, and source for Linux. The app has a one-year license so that people need to upgrade to a newer version aft... | Simple license protection for Python app | Although there are quite a few questions like this, please bear with me as I think mine is different...
I have a $5 Python app that I distribute using py2exe, py2app, and source for Linux. The app has a one-year license so that people need to upgrade to a newer version after one year. I would like to add some kind of... | [
"Why doesn't an if statement comparing the date not trivially solve this for you?\nThe best way to do this might be to include data into your software that really does need to be kept up to date to be useful to the end user, like the tax forms in TurboTax. Of course the availability of that business strategy depen... | [
5
] | [] | [] | [
"licensing",
"py2app",
"py2exe",
"python"
] | stackoverflow_0006307372_licensing_py2app_py2exe_python.txt |
Q:
Validation to site.domain fieald
I import
from django.contrib.sites.models import Site in models.py file.
In have this following in admin.py file:
class SitesAdmin(admin.ModelAdmin):
pass
admin.site.unregister(Site)
admin.site.register(Site, SitesAdmin)**
I want to attach validation to the site.domain... | Validation to site.domain fieald | I import
from django.contrib.sites.models import Site in models.py file.
In have this following in admin.py file:
class SitesAdmin(admin.ModelAdmin):
pass
admin.site.unregister(Site)
admin.site.register(Site, SitesAdmin)**
I want to attach validation to the site.domain field in admin.py, How i can accompli... | [
"First, specifying an empty ModelAdmin class is unnecessary, the following will work if you don't need to customize the admin:\nadmin.site.register(Site) # Notice that no ModelAdmin is passed\n\nNow, to your question. You have to create a custom form. Then, you override the clean_domain method of the ModelForm. You... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006306994_django_python.txt |
Q:
Message Routing in AMQP
I'd like to do some routing magic with AMQP. My setup is Python with Pika on the consumer/producer side and RabbitMQ for the AMQP server.
What I'd like to achieve:
send a message to a single exchange
(insert magic here)
consume messages like so:
one set of subscribers should be able to re... | Message Routing in AMQP | I'd like to do some routing magic with AMQP. My setup is Python with Pika on the consumer/producer side and RabbitMQ for the AMQP server.
What I'd like to achieve:
send a message to a single exchange
(insert magic here)
consume messages like so:
one set of subscribers should be able to retrieve based on a routing key... | [
"To start with, you need to use a topic exchange and publish your messages with a different routing key for each queue. The magic happens when the consumer binds the queue with a binding key (or pattern to be matched). Some consumers just use the routing keys as their binding key. But the second set will use a wild... | [
1
] | [] | [] | [
"amqp",
"pika",
"python",
"rabbitmq"
] | stackoverflow_0006284220_amqp_pika_python_rabbitmq.txt |
Q:
How to expose a property from a fluent interface with boost::python?
I have a C++ class which presents a fluent interface, something like:
class Foo
{
public:
int bar() const { return m_bar; };
Foo& bar(int value) { m_bar = value; return *this; };
private:
int m_bar;
};
I'd like to wrap the bar()... | How to expose a property from a fluent interface with boost::python? | I have a C++ class which presents a fluent interface, something like:
class Foo
{
public:
int bar() const { return m_bar; };
Foo& bar(int value) { m_bar = value; return *this; };
private:
int m_bar;
};
I'd like to wrap the bar() functions as a property in my Python class. So I wrote:
class_<Foo>("Foo"... | [
"I ended up writting the following template function:\ntemplate <class BaseClass, typename T, BaseClass& (BaseClass::*method)(T)>\nvoid make_nonfluent_setter(BaseClass& self, T value)\n{\n (self.*method)(value);\n}\n\nAnd now I can type:\nclass_<Foo>(\"Foo\")\n .add_property(\n \"bar\",\n (int (Foo::*)())... | [
2
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0006307954_boost_python_c++_python.txt |
Q:
Debugging unittests
I have some problems with debugging code from unittest in Django.
While I run unittest, I have output
FAIL: test_basket (api.api_1_0.tests.basket_tests.BasketTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/dasm/apps... | Debugging unittests | I have some problems with debugging code from unittest in Django.
While I run unittest, I have output
FAIL: test_basket (api.api_1_0.tests.basket_tests.BasketTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/dasm/apps/filmaster/reloaded/film2... | [
"I'm not entirely sure he's getting more info than you. It might be simply that more stuff is failing for him, due to some missing modules or something on his setup.\nWhat you're seeing is exactly what you should be seeing. It's a failure, so it's not technically a bug in your unittest but rather a bug in your code... | [
1
] | [] | [] | [
"debugging",
"django",
"python",
"unit_testing"
] | stackoverflow_0006307401_debugging_django_python_unit_testing.txt |
Q:
mounting an s3 bucket in ec2 and using transparently as a mnt point
I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com).... | mounting an s3 bucket in ec2 and using transparently as a mnt point | I have a webapp (call it myapp.com) that allows users to upload files. The webapp will be deployed on Amazon EC2 instance. I would like to serve these files back out to the webapp consumers via an s3 bucket based domain (i.e. uploads.myapp.com).
When the user uploads the files, I can easily drop them in into a fold... | [
"I'm not using EC2, but I do have my S3 bucket permanently mounted on my Linux server. The way I did it is with Jungledisk. It isn't a non-commercial solution, but it's very inexpensive.\nFirst I setup the jungledisk as normal. Then I make sure fuse is installed. Mostly you just need to create the configuration fil... | [
5,
2,
2,
2,
0
] | [] | [] | [
"amazon_ec2",
"amazon_s3",
"django",
"python"
] | stackoverflow_0000956904_amazon_ec2_amazon_s3_django_python.txt |
Q:
How do I properly install httplib2 on Google App Engine?
I copied my httplib2 directory into my GAE project, and now I'm getting the following error:
line 64, in <module> _ssl_wrap_socket = ssl.wrap_socket
Is this an issue with Google App Engine, or did I somehow install my httplib2 incorrectly?
Full error dump, ... | How do I properly install httplib2 on Google App Engine? | I copied my httplib2 directory into my GAE project, and now I'm getting the following error:
line 64, in <module> _ssl_wrap_socket = ssl.wrap_socket
Is this an issue with Google App Engine, or did I somehow install my httplib2 incorrectly?
Full error dump, as request(it's big!):
--> --> -->
Traceback (most recent call... | [
"As a workaround:\nCan you use Google App Engine SDK 1.4.3 (this looks like a 1.5.0 regression).\nOr force httplib2 fallback on httplib.FakeSocket with:\nimport sys\nsys.modules['ssl'] = None\nimport httplib2\n\nA new issue has been filled there:\nhttp://code.google.com/p/googleappengine/issues/detail?id=5064\nIt l... | [
4,
2,
0
] | [] | [] | [
"google_app_engine",
"httplib2",
"python"
] | stackoverflow_0006011272_google_app_engine_httplib2_python.txt |
Q:
How to ignore numbers when doing string.startswith() in python?
I have a directory with a large number of files. The file names are similar to the following: the(number)one(number), where (number) can be any number. There are also files with the name: the(number), where (number) can be any number. I was wondering ... | How to ignore numbers when doing string.startswith() in python? | I have a directory with a large number of files. The file names are similar to the following: the(number)one(number), where (number) can be any number. There are also files with the name: the(number), where (number) can be any number. I was wondering how I can count the number of files with the additional "one(number)"... | [
"Use a regex matching 'one\\d+' using the re module.\nimport re\nfor n in list:\n if re.search(r\"one\\d+\", n):\n add one to a counter\n\nIf you want to make it very accurate, you can even do:\nfor n in list:\n if re.search(r\"^the\\d+one\\d+$\", n):\n add one to a counter\n\nWhich will even ta... | [
8,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006308819_python.txt |
Q:
Execute python command in django admin panel
Is it possible to execute python command in admin panel or in django view?I. e. if I would like to sync database in my app using a button.
A:
Write a custom admin view featuring a form, and when the form is submitted in the view call django.core.management.call_comman... | Execute python command in django admin panel | Is it possible to execute python command in admin panel or in django view?I. e. if I would like to sync database in my app using a button.
| [
"Write a custom admin view featuring a form, and when the form is submitted in the view call django.core.management.call_command\nRemark regarding using a form: As your request will change things at the server-side, a post must be preferred over a get.\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006308917_django_python.txt |
Q:
Dealing with IMAP mailbox name case sensitivty
I have a python script using imaplib that connects to a gmail account and sorts emails based on '+' tags found in the email address. For example: emails sent to myaccount+root.foo.bar@gmail.com get moved to root\foo\bar.
My logic goes as follows: extract tags -> attem... | Dealing with IMAP mailbox name case sensitivty | I have a python script using imaplib that connects to a gmail account and sorts emails based on '+' tags found in the email address. For example: emails sent to myaccount+root.foo.bar@gmail.com get moved to root\foo\bar.
My logic goes as follows: extract tags -> attempt to create folders -> copy message to folder.
Ocas... | [
"So Google complains that the folder already exists, but then gives an error when you try to move something into it? Terrific.\nIMAP has a \"LIST\" command to list available mailboxes (folders):\nhttps://www.rfc-editor.org/rfc/rfc3501#section-6.3.8\nHow to access that depends on your IMAP client library. Here are... | [
2
] | [] | [] | [
"gmail_imap",
"imap",
"imaplib",
"python"
] | stackoverflow_0006309072_gmail_imap_imap_imaplib_python.txt |
Q:
Python Debugging: code editing on the fly
I am new to python and haven't been able to find out whether this is possible or not.
I am using the PyDev plugin under Eclipse, and basically all I want to find out is, is it possible to edit code whilst you're sitting at a breakpoint? I.e. Edit code whilst you're debuggi... | Python Debugging: code editing on the fly | I am new to python and haven't been able to find out whether this is possible or not.
I am using the PyDev plugin under Eclipse, and basically all I want to find out is, is it possible to edit code whilst you're sitting at a breakpoint? I.e. Edit code whilst you're debugging.
It allows me to do this at present, but it ... | [
"PyDev supports this to some extend since version 1.4.8, see the change notes and the corresponding blog entry.\n",
"When you start a Python program, it will be compiled into bytecode (and possibly saved as .pyc file). That means you can change the source but since you don't \"open\" the source again, the change ... | [
4,
2,
2
] | [] | [] | [
"debugging",
"pydev",
"python"
] | stackoverflow_0001613927_debugging_pydev_python.txt |
Q:
"Best" way to integrate Django with an Ajax library
Obviously, horses for courses, but what are some good ways to integrate javascript libraries with one's Django application?
I'm planning on using jQuery, mostly because it seems popular and looks powerful (but I'm open to other suggestions).
Are there python-side... | "Best" way to integrate Django with an Ajax library | Obviously, horses for courses, but what are some good ways to integrate javascript libraries with one's Django application?
I'm planning on using jQuery, mostly because it seems popular and looks powerful (but I'm open to other suggestions).
Are there python-side libraries that are very helpful or essential? Or is it b... | [
"Remember, Just because it's ajax does not mean you need to return a json dump. You can indeed return a rendered template.\nIt's true, that the 'right way' is to construct all your tags in javascript, and fill in that data with the json data, but let's face it, that's such a pain in the rump... so much so that they... | [
8,
5,
2,
2,
1
] | [] | [] | [
"ajax",
"django",
"jquery",
"json",
"python"
] | stackoverflow_0006307992_ajax_django_jquery_json_python.txt |
Q:
Testing a C++ library with Python
I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check the output).
While I could do that in C/C++ with a main file that links to the libr... | Testing a C++ library with Python | I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check the output).
While I could do that in C/C++ with a main file that links to the library in question and build my tests, but... | [
"Honestly C++ is a bit messy. You could do something like create a pure C function which wraps the C++ functionality (which you then call from python) but at that point you might as well write your tests in C++. Unfortunately the only tool out there for this (that I know of) is SWIG.\nIt's sad that it's called the ... | [
10,
2
] | [] | [] | [
"c++",
"python",
"shared_libraries"
] | stackoverflow_0006308649_c++_python_shared_libraries.txt |
Q:
Regular expressions and Unicode in Python: difference between sub and findall
I am having difficulty trying to figure out a bug in my Python (2.7) script. I am getting an difference with using sub and findall in recognizing special characters.
Here is the code:
>>> re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.U... | Regular expressions and Unicode in Python: difference between sub and findall | I am having difficulty trying to figure out a bug in my Python (2.7) script. I am getting an difference with using sub and findall in recognizing special characters.
Here is the code:
>>> re.sub(ur"[^-' ().,\w]+", '' , u'Castañeda', re.UNICODE)
u'Castaeda'
>>> re.findall(ur"[^-' ().,\w]+", u'Castañeda', re.UNICODE)
[]
... | [
"The call signature of re.sub is:\nre.sub(pattern, repl, string, count=0)\n\nSo \nre.sub(ur\"[^-' ().,\\w]+\", '' , u'Castañeda', re.UNICODE)\n\nis setting count to re.UNICODE, which has value 32.\nTry instead:\nIn [57]: re.sub(ur\"(?u)[^-' ().,\\w]+\", '', u'Castañeda')\nOut[57]: u'Casta\\xf1eda'\n\nPlacing (?u) a... | [
7
] | [] | [] | [
"python",
"regex",
"unicode"
] | stackoverflow_0006309387_python_regex_unicode.txt |
Q:
Parsing parts of a Large XML File in App Engine using Blobstore?
I'm working on an google app engine app that will have to deal with some largish ( <100 MB) XML files uploaded from a form that will exceed GAE's limits -- either taking longer than 30 seconds to upload the file, or exceeding the 10 MB request size.
... | Parsing parts of a Large XML File in App Engine using Blobstore? | I'm working on an google app engine app that will have to deal with some largish ( <100 MB) XML files uploaded from a form that will exceed GAE's limits -- either taking longer than 30 seconds to upload the file, or exceeding the 10 MB request size.
The current solution I'm envisioning is to upload the file to the blob... | [
"The 30 second limit applies to the execution time of your code, and your code doesn't start executing until the entire user request has been received - so the amount of time the user takes to upload the file is irrelevant.\nThat said, using blobstore does sound like the best idea. You can use BlobReader, which emu... | [
2,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"blobstore",
"google_app_engine",
"python",
"xml"
] | stackoverflow_0004522434_beautifulsoup_blobstore_google_app_engine_python_xml.txt |
Q:
How to use argparse to grab command line arguments in Python?
I want to be able to save integer values after an option is passed through the command line. Ideally it would be:
python thing.py -s 1 -p 0 1 2 3 -r/-w/-c
-s - store the following integer
-p - store the following integers
The final part can be only on... | How to use argparse to grab command line arguments in Python? | I want to be able to save integer values after an option is passed through the command line. Ideally it would be:
python thing.py -s 1 -p 0 1 2 3 -r/-w/-c
-s - store the following integer
-p - store the following integers
The final part can be only one of the three options (-r, -w, or -c), depending on what it is I ... | [
">>> import argparse\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('-s', type=int)\n[...]\n>>> parser.add_argument('-p', type=int, nargs='*')\n[...]\n>>> group = parser.add_mutually_exclusive_group(required=True)\n>>> group.add_argument('-r', action='store_true')\n[...] \n>>> group.add_argumen... | [
4
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0006309552_argparse_python.txt |
Q:
Reading piped output line by line python
I'm using popen to run a subprocess in python. I need to read each line the subprocess outputs as it is being outputted, rather then getting everything once the process terminates. I've tried everything I could find on Google with no success. Any help would be greatly appre... | Reading piped output line by line python | I'm using popen to run a subprocess in python. I need to read each line the subprocess outputs as it is being outputted, rather then getting everything once the process terminates. I've tried everything I could find on Google with no success. Any help would be greatly appreciated.
| [
"The subprocess.Popen documentation describes the available arguments to its call.\nYou want to set the bufsize argument to 1 (line-buffered input/output).\n"
] | [
1
] | [] | [] | [
"pipe",
"python"
] | stackoverflow_0006295509_pipe_python.txt |
Q:
Minimize python to system tray in Windows (Vista)
I would like to know if it is possible to minimise my python program to the system tray.
Basically what it does is at every hour it takes a screenshot but I don't want it to stay on the task bar taking space. Could I make it go to the system tray area next to the c... | Minimize python to system tray in Windows (Vista) | I would like to know if it is possible to minimise my python program to the system tray.
Basically what it does is at every hour it takes a screenshot but I don't want it to stay on the task bar taking space. Could I make it go to the system tray area next to the clock but keep it running?
I am not using tkinter or any... | [
"Since you are running on Windows, you may simply want to rename your script to have a .pyw extension, so there is no console window. If you try to make a system tray application, you will need to pick a GUI toolkit like you've suggested, and your simple script will become a LOT bigger and far more complicated.\n",... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004878093_python.txt |
Q:
Excel parsing in python and forming dictionary
I have an Excel file with a lot of data in it . i would like to get the info like in a dictionary example the first column of the excel will be the key and the rest of the column will be the values
Excel:
No name lastname hobby
1 jhon g fishing
2 mike a ... | Excel parsing in python and forming dictionary | I have an Excel file with a lot of data in it . i would like to get the info like in a dictionary example the first column of the excel will be the key and the rest of the column will be the values
Excel:
No name lastname hobby
1 jhon g fishing
2 mike a boxing
3 tom v sking
is it possible to ... | [
"Given the following CSV file:\nNo,name,lastname,hobby\n1,jhon,g,fishing\n2,mike,a,boxing\n3,tom,v,sking\n\nThe following code appears to do what you're asking for:\nIn [1]: import csv\n\nIn [2]: for d in csv.DictReader(open('file.txt')): print d\n ...: \n{'hobby': 'fishing', 'lastname': 'g', 'name': 'jhon', 'No'... | [
3
] | [] | [] | [
"excel",
"parsing",
"python"
] | stackoverflow_0006309457_excel_parsing_python.txt |
Q:
How do I animate the ticks on the x-axis?
I have a matplotlib axes instance inside which I'm animating an AxesImage via blitting.
What I'd like to do is animate the ticks on the x-axis as well.
I am updating the data on the AxesImage (and subsequently) drawing its artist quite frequently, and on each update I'd li... | How do I animate the ticks on the x-axis? | I have a matplotlib axes instance inside which I'm animating an AxesImage via blitting.
What I'd like to do is animate the ticks on the x-axis as well.
I am updating the data on the AxesImage (and subsequently) drawing its artist quite frequently, and on each update I'd like to move one extra tick placed to highlight t... | [
"The axes bbox doesn't include anything outside of the \"inside\" of the axes (e.g. it doesn't include the tick labels, title, etc.)\nOne quick way around this is to just grab the entire region of the figure when you're blitting. (E.g. background = canvas.copy_from_bbox(fig.bbox))\nThis can cause problems if you ha... | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006299943_matplotlib_python.txt |
Q:
a text file circular buffer in python
I need a python script implementing a circular buffer for rows in a text file limited to N rows like this:
row 1 -> pop
row 2
row 3
|
|
push -> row N
What's the best solution?
EDIT:
This script should create and maintain the text file... | a text file circular buffer in python | I need a python script implementing a circular buffer for rows in a text file limited to N rows like this:
row 1 -> pop
row 2
row 3
|
|
push -> row N
What's the best solution?
EDIT:
This script should create and maintain the text file which only contains the latest N lines. Th... | [
"Use collections.deque. It supports a maxlen parameter.\nd = collections.deque(maxlen=10)\nfor line in f:\n d.append(line)\n # ...\n\n",
"Try my recipe and sorry for italian usage:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# fifo(.py)\n# \n# Copyright 2011 Fabio Di Bernardini <f... | [
9,
2,
1
] | [] | [] | [
"circular_buffer",
"fifo",
"file",
"python"
] | stackoverflow_0006293868_circular_buffer_fifo_file_python.txt |
Q:
Python regex match letter sequences
I want to make a regex to match "AGGH", "TIIK", "6^^?" or whatever but not "AGGA", "ABCD". Basically its the pattern of letters which matters. Is there a way to ask for a character you have or haven't previously had?
A:
You could extract the pattern of your strings like this:... | Python regex match letter sequences | I want to make a regex to match "AGGH", "TIIK", "6^^?" or whatever but not "AGGA", "ABCD". Basically its the pattern of letters which matters. Is there a way to ask for a character you have or haven't previously had?
| [
"You could extract the pattern of your strings like this:\ndef pattern(s):\n d = {}\n return [d.setdefault(c, len(d)) for c in s]\n\nExamples:\n>>> pattern(\"AGGH\")\n[0, 1, 1, 2]\n>>> pattern(\"TKKG\")\n[0, 1, 1, 2]\n>>> pattern(\"AGGA\")\n[0, 1, 1, 0]\n>>> pattern(\"ABCD\")\n[0, 1, 2, 3]\n\nThis function ma... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"sequence"
] | stackoverflow_0006309714_python_regex_sequence.txt |
Q:
How can I hide the console window when freezing wxPython applications with cxFreeze?
I'm developing a Python application using wxPython and freezing it using cxFreeze. All seems to be going fine apart from this following bit:
When I run the executable created by cxFreeze, a blank console window pops up. I don't wa... | How can I hide the console window when freezing wxPython applications with cxFreeze? | I'm developing a Python application using wxPython and freezing it using cxFreeze. All seems to be going fine apart from this following bit:
When I run the executable created by cxFreeze, a blank console window pops up. I don't want to show it. Is there any way I could hide it?
It doesn't seem to be documented on the ... | [
"For Windows:\nYou have to use a line like this (use file folders and names as appropriate)\nC:/Python/Scripts/cxfreeze C:/Python/Code/yourprogram.py --base-name=Win32GUI --target-dir C:/Python/Dist\n\nBy adding the --base-name=Win32GUI option, the console window will not appear.\n",
"This worked to some extent b... | [
21,
20,
3,
3
] | [] | [] | [
"cx_freeze",
"python",
"wxpython"
] | stackoverflow_0002880316_cx_freeze_python_wxpython.txt |
Q:
SWIG error: was declared 'extern' and later 'static'
I'm using swig to produce a python C++ interface such that I can make scripts in python to call my c++ functions. I've gotten as far as:
swig -c++ python filename.i
gcc -c filename.cpp filename_wrap.cxx -shared -Ic:\includepath
Where the include path is my pyt... | SWIG error: was declared 'extern' and later 'static' | I'm using swig to produce a python C++ interface such that I can make scripts in python to call my c++ functions. I've gotten as far as:
swig -c++ python filename.i
gcc -c filename.cpp filename_wrap.cxx -shared -Ic:\includepath
Where the include path is my python27's include directory.
Upon attempting to compile with... | [
"The fact that they appear in a header as a prototype implicitly define them as an extern function. However you're ALSO declaring them as static.\nGiven the C++ tag, I'm going to make an assumption here, so please pardon me if you already know this and it comes off as patronizing. static in C does something complet... | [
7
] | [] | [] | [
"c",
"c++",
"python",
"swig"
] | stackoverflow_0006309768_c_c++_python_swig.txt |
Q:
Using Python subprocess rather than os.system
Following the advice of Ignacio ( Python remove spaces and append ) I am trying to convert the below command to use subprocess rather than os.system.
The script: os.system("/usr/local/bin/growlnotify -n emesene -a emesene -t """+title+""" -m """+text+"""""")
I would of... | Using Python subprocess rather than os.system | Following the advice of Ignacio ( Python remove spaces and append ) I am trying to convert the below command to use subprocess rather than os.system.
The script: os.system("/usr/local/bin/growlnotify -n emesene -a emesene -t """+title+""" -m """+text+"""""")
I would of thought: subprocess.call(['/usr/local/bin/growlnot... | [
"Instead of \nsubprocess.call(['/usr/local/bin/growlnotify', '-n emesene', '-a emesene', '-t \"\"+title+\"\"\"', '-m \"\"\"+text+\"\"\"\"\"'], shell=True)\n\nuse\nsubprocess.call(['/usr/local/bin/growlnotify', '-n', 'emesene', '-a', 'emesene', '-t', title, '-m', text], shell=True)\n\nEverywhere you have an unquote... | [
5,
4
] | [] | [] | [
"os.system",
"python",
"shell",
"subprocess"
] | stackoverflow_0006310114_os.system_python_shell_subprocess.txt |
Q:
datetime.datetime.now() + 1
I would like to add 1 day with 3 hours + datetime.now.
mante = Employee()
mante.usercompany = idnamez
mante.knowledgelost = datetime.datetime.now()+1 day more 3 hours.
mante.seguemplelost = datetime.datetime.now()+1
mante.put()
Someone knows how to do it?
A:
datetime.datetime.now() ... | datetime.datetime.now() + 1 | I would like to add 1 day with 3 hours + datetime.now.
mante = Employee()
mante.usercompany = idnamez
mante.knowledgelost = datetime.datetime.now()+1 day more 3 hours.
mante.seguemplelost = datetime.datetime.now()+1
mante.put()
Someone knows how to do it?
| [
"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)\n\n"
] | [
74
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006310475_django_python.txt |
Q:
How to organize Eclipse - Workspace VS Programming languages
I use Eclipse for programming in PHP (PDT), Python and sometimes Android. Each of this programming languages requires to run many things after Eclipse start.
Of course I do not use all of them at one moment, I have different workspace for each of those. ... | How to organize Eclipse - Workspace VS Programming languages | I use Eclipse for programming in PHP (PDT), Python and sometimes Android. Each of this programming languages requires to run many things after Eclipse start.
Of course I do not use all of them at one moment, I have different workspace for each of those. Is there any way, or recommendation, how to make Eclipse to run on... | [
"The plug-ins are stored in the Eclipse installation, not in the workspace folder. So one solution would be to different Eclipse installations for every task, in this case only the required plug-ins would load (and the others not available), on the other hand, you have to maintain at least three parallel Eclipse in... | [
3,
0
] | [] | [] | [
"android",
"eclipse",
"eclipse_pdt",
"python",
"workspace"
] | stackoverflow_0003429887_android_eclipse_eclipse_pdt_python_workspace.txt |
Q:
Scripting the creation of a database from a backup in SQL Server
I currently have a tediously long process for creating new instances of a CMS we make.
I plan to script as much of the process as I can, using Python.
The first step is creating a database.
Currently it is a manual process where I will create an em... | Scripting the creation of a database from a backup in SQL Server | I currently have a tediously long process for creating new instances of a CMS we make.
I plan to script as much of the process as I can, using Python.
The first step is creating a database.
Currently it is a manual process where I will create an empty database "MyNewSite" and then select restore from backup and resto... | [
"The CMS you make should have a deployment script. All your development process should update upgrade scripts, never touch the database directly. Database updates should be deployed through source code (upgrade scripts) and version control: Version Control and your Database. \n"
] | [
1
] | [] | [] | [
"python",
"scripting",
"sql_server"
] | stackoverflow_0006308760_python_scripting_sql_server.txt |
Q:
PyInstaller: "ImportError: No module named os"
I'm trying to learn PyInstaller. I created two simple files, Test.py:
import os
and Test.spec:
anal = Analysis (["Test.py"])
pyz = PYZ(anal.pure)
exe = EXE(anal.scripts, pyz, name="Test.exe", exclude_binaries=1, debug=1)
coll = COLLECT(exe, anal.binaries, name="dist"... | PyInstaller: "ImportError: No module named os" | I'm trying to learn PyInstaller. I created two simple files, Test.py:
import os
and Test.spec:
anal = Analysis (["Test.py"])
pyz = PYZ(anal.pure)
exe = EXE(anal.scripts, pyz, name="Test.exe", exclude_binaries=1, debug=1)
coll = COLLECT(exe, anal.binaries, name="dist")
Then I ran:
Build.py Test.spec
This ran without ... | [
"For simple files like this, you should use Makespec.py for creating spec's instead of writing manually. For large projects, you could use the Makespec.py's output as a template and edit them.\nhttp://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html#create-a-spec-file-for-your-project\n"
] | [
2
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0006310099_pyinstaller_python.txt |
Q:
date2num , ValueError: ordinal must be >= 1
I'm using the matplotlib candlestick module which requires the time to be passed as a float day format . I`m using date2num to convert it, before :
This is my code :
import csv
import sys
import math
import numpy as np
import datetime
from optparse import OptionParser
im... | date2num , ValueError: ordinal must be >= 1 | I'm using the matplotlib candlestick module which requires the time to be passed as a float day format . I`m using date2num to convert it, before :
This is my code :
import csv
import sys
import math
import numpy as np
import datetime
from optparse import OptionParser
import matplotlib.pyplot as plt
import matplotlib.c... | [
"Read the docstring a bit more carefully :)\n\nquotes is a list of (time, open, close, high, low, ...) tuples.\n\nWhat's happening is that it expects each item of quotes to be a sequence of (time, open, close, high, low). \nYou're passing in 5 long arrays, it expects a long sequence of 5 items.\nYou just need to zi... | [
6,
2,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0006301400_matplotlib_numpy_python.txt |
Q:
Build rabbitmq from source
I try to build rabbitmq-server-2.4.1 from source. But get error:
make
python codegen.py body codegen/amqp-rabbitmq-0.9.1.json
src/rabbit_framing_amqp_0_9_1.erl
Traceback (most recent call last):
File "codegen.py", line 492, in <module>
"body": generateErl})
File "codegen/amqp_codege... | Build rabbitmq from source | I try to build rabbitmq-server-2.4.1 from source. But get error:
make
python codegen.py body codegen/amqp-rabbitmq-0.9.1.json
src/rabbit_framing_amqp_0_9_1.erl
Traceback (most recent call last):
File "codegen.py", line 492, in <module>
"body": generateErl})
File "codegen/amqp_codegen.py", line 283, in do_main_dict... | [
"Your problem may be the python version.\nI was able to compile and install rabbitMQ 2.4.1 using python 2.6.2.\nIf you use Solaris and use pkgutil, the command to get python 2.6.2 would be\n\n# My version of Sun OS (for comparison)\n$ uname -a \nSunOS dev21 5.10 Generic_141445-09 i86pc i386 i86pc \n\n# install pyth... | [
1
] | [] | [] | [
"erlang",
"makefile",
"python",
"rabbitmq"
] | stackoverflow_0006183279_erlang_makefile_python_rabbitmq.txt |
Q:
How can I store user input from command line in Python?
I am trying to run a script with up to 8 arguments. For example:
pythonscript.py hello there howdy do argument5 argument6 argument7 argument8
I want to store arguments 5-8 in an array, however, if arguments 5-8 are not entered, I want a default value assigned... | How can I store user input from command line in Python? | I am trying to run a script with up to 8 arguments. For example:
pythonscript.py hello there howdy do argument5 argument6 argument7 argument8
I want to store arguments 5-8 in an array, however, if arguments 5-8 are not entered, I want a default value assigned to a variable. I don't care if it's a tuple, the data in the... | [
"Here's another way you could do it that doesn't require you to explicitly state the various elements of sys.argv:\nimport sys\n\nif len(sys.argv) > 5:\n values = sys.argv[5:]\nelse:\n values = '127.0.0.1'\n\nThis takes advantage of Python's slicing syntax.\n",
"I don't quite see what's wrong here:\n>>> imp... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006311377_python.txt |
Q:
Experienced Python programmers (ESPECIALLY former php programmers) : How do I debug python?
In PHP, it was extremely easy to start hacking away and figuring out what was going on on a page. Just throw in a bunch of echos and print_r's and that was about it. It appears that this technique is not working for me in... | Experienced Python programmers (ESPECIALLY former php programmers) : How do I debug python? | In PHP, it was extremely easy to start hacking away and figuring out what was going on on a page. Just throw in a bunch of echos and print_r's and that was about it. It appears that this technique is not working for me in python. I am getting practice by hacking around in a python photo upload module, and when a pho... | [
"Use the logging module rather than printing stuff to stdout. \nUsing the interpreter in interactive mode is a great way to try out code, and pdb is very useful for real debugging.\n",
"It's \"pythonic\" to do debugging using the pdb module.\nBut really, if you're just \"hacking around\", then I suggest messing a... | [
4,
0,
0,
0,
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0006311322_debugging_python.txt |
Q:
Create a model from YAML/JSON on the fly
I am trying out MongoEngine, a DRM library for Python to use with MongoDB. I can define a model like this example from the site:
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=5... | Create a model from YAML/JSON on the fly | I am trying out MongoEngine, a DRM library for Python to use with MongoDB. I can define a model like this example from the site:
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
It works like a charm and MongoEngine is r... | [
"If you're going to use YAML, pyyaml is completely painless, and automatically outputs a data structure using python's built-in types (or even more complex types that you define).\nAny way you go, I would also highly recommend Rx as a validator so you can easily verify the integrity of the loaded files.*\nAs for us... | [
5
] | [] | [] | [
"json",
"model",
"mongodb",
"python",
"yaml"
] | stackoverflow_0006311738_json_model_mongodb_python_yaml.txt |
Q:
python .rstrip removes one additional character
I try to remove seconds from date:
>>> import datetime
>>> test1 = datetime.datetime(2011, 6, 10, 0, 0)
>>> test1
datetime.datetime(2011, 6, 10, 0, 0)
>>> str(test1)
'2011-06-10 00:00:00'
>>> str(test1).rstrip('00:00:00')
'2011-06-10 '
>>> str(test1).rstrip(' 00:00:0... | python .rstrip removes one additional character | I try to remove seconds from date:
>>> import datetime
>>> test1 = datetime.datetime(2011, 6, 10, 0, 0)
>>> test1
datetime.datetime(2011, 6, 10, 0, 0)
>>> str(test1)
'2011-06-10 00:00:00'
>>> str(test1).rstrip('00:00:00')
'2011-06-10 '
>>> str(test1).rstrip(' 00:00:00')
'2011-06-1'
Why 0 at end of '10' is removed?
| [
"str.rstrip() doesn't remove an exact string -- it removes all characters that occur in the string. Since you know the length of the string to remove, you can simply use\nstr(test1)[:-9]\n\nor even better\ntest1.date().isoformat()\n\n",
"rstrip takes a set (although the argument can be any iterable, like str in ... | [
12,
7
] | [] | [] | [
"python"
] | stackoverflow_0006311968_python.txt |
Q:
wxPython, multiline label on wxButton
I'm trying to get a label on a button to be on two or more lines. I want to update this at runtime. I did like this:
self.btnGroupOne.SetLabel(u"test\ntest")
Yet, when I run the app, i just get a button with "testtest" on a single line as the label.
Am I forgetting a property... | wxPython, multiline label on wxButton | I'm trying to get a label on a button to be on two or more lines. I want to update this at runtime. I did like this:
self.btnGroupOne.SetLabel(u"test\ntest")
Yet, when I run the app, i just get a button with "testtest" on a single line as the label.
Am I forgetting a property that allows multiline labels or something?... | [
"It appears to be a confirmed bug in wxWidgets:\nhttp://trac.wxwidgets.org/ticket/12491\nIf you give the button a multi-line label at creation, SetLabel will then allow multiple lines.\n"
] | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006311593_python_wxpython.txt |
Q:
Python/Django Patching/Mocking a functions current decorator
I saw you posting around decorators. I am having a hard time finding out how to Mock a decorator. Most searches show me how to write a decorate to help tes, but to be clear, I already have decorators and when I am unittesting a function that HAS a decora... | Python/Django Patching/Mocking a functions current decorator | I saw you posting around decorators. I am having a hard time finding out how to Mock a decorator. Most searches show me how to write a decorate to help tes, but to be clear, I already have decorators and when I am unittesting a function that HAS a decorator I would like to mock it so its response is not part of the tes... | [
"You can't mock a decorator. A decorator replaces your function at compile time with the decorated function. If a function is decorated, you cannot test that function without the decorator without pulling the guts of the function out into another (non-decorated) function.\n"
] | [
0
] | [] | [] | [
"decorator",
"mocking",
"python",
"testing",
"unit_testing"
] | stackoverflow_0006311705_decorator_mocking_python_testing_unit_testing.txt |
Q:
Django - Saving Facebook Information to database from social-registration
So I am fairly new to the whole django / python environment. I have successfully installed the social-registration app with my django application. Users are able to sign in with facebook and it creates a record for a user in the auth_user ... | Django - Saving Facebook Information to database from social-registration | So I am fairly new to the whole django / python environment. I have successfully installed the social-registration app with my django application. Users are able to sign in with facebook and it creates a record for a user in the auth_user table and into my app_customuser table but it does not save the email, first na... | [
"social-registration seems to be a bit simplistic; it's documentation definitely is. It's possible you can subclass the backends or potentially create your own backends based on those to store the additional fields, but that feels clunky even saying it.\nIt's probably not what you want to hear, but django-socialaut... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006311250_django_python.txt |
Q:
How do I get Python XML to stop having wasted Child Nodes
I have a simple XML document I'm trying to read in with Python DOM (see below):
XML File:
<?xml version="1.0" encoding="utf-8"?>
<HeaderLookup>
<Header>
<Reserved>2</Reserved>
<CPU>1</CPU>
<Flag>1</Flag>
<VQI>12</VQI>
... | How do I get Python XML to stop having wasted Child Nodes | I have a simple XML document I'm trying to read in with Python DOM (see below):
XML File:
<?xml version="1.0" encoding="utf-8"?>
<HeaderLookup>
<Header>
<Reserved>2</Reserved>
<CPU>1</CPU>
<Flag>1</Flag>
<VQI>12</VQI>
<Group_ID>16</Group_ID>
<DI>2</DI>
<DE>1</... | [
"Whitespace is significant in XML, but check out ElementTree, which has a different API for processing XML than the DOM.\nExample\nfrom xml.etree import ElementTree as et\n\ndata = '''\\\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<HeaderLookup>\n <Header>\n <Reserved>2</Reserved>\n <CPU>1</CPU>\n... | [
9
] | [] | [] | [
"nodes",
"python",
"whitespace",
"xml"
] | stackoverflow_0006311824_nodes_python_whitespace_xml.txt |
Q:
Customizing exception in read-only property
In a Python program I have a read-only property that I create using
bla = property(fget=_get_bla)
where _get_bla is a method defined in the class. When a program tries to write in this property
obj.bla = 1
I obviously get:
AttributeError: can't set attribute
Is ther... | Customizing exception in read-only property | In a Python program I have a read-only property that I create using
bla = property(fget=_get_bla)
where _get_bla is a method defined in the class. When a program tries to write in this property
obj.bla = 1
I obviously get:
AttributeError: can't set attribute
Is there a way to customize this exception? For example,... | [
"Yes, you can add next method to your class:\ndef set_bla(self, value):\n raise AttributeError(\"'bla' is a read-only property of class X\")\n\nand\nbla = property(fget=get_bla, fset=set_bla)\n\n"
] | [
1
] | [] | [] | [
"customization",
"exception",
"properties",
"python"
] | stackoverflow_0006312116_customization_exception_properties_python.txt |
Q:
Python documentation in wiki-like environment (with some autodoc features)
I have investigated, and have high hopes for, sphinx.
However, it doesn't do everything I want in a documentation framework. Here's what I'm looking for:
A wiki-like (ie, web-editable) environment with revision tracking
Support for auto... | Python documentation in wiki-like environment (with some autodoc features) | I have investigated, and have high hopes for, sphinx.
However, it doesn't do everything I want in a documentation framework. Here's what I'm looking for:
A wiki-like (ie, web-editable) environment with revision tracking
Support for autodoc (ie importing of docstrings, etc.)
(ideally) a connector to version managem... | [
"GitHub's Gollum which is a \"A simple, Git-powered wiki with a sweet API and local frontend\" could be a possible solution. It supports reStructured Text, which as you probably know, is the same markup used by Sphinx. \n"
] | [
1
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0006309389_python_python_sphinx.txt |
Q:
How to find out a^b of very large numbers in python?
I am trying to find out a^b in python, of really large no.s
My code is this:
t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
And I am getting an erro... | How to find out a^b of very large numbers in python? | I am trying to find out a^b in python, of really large no.s
My code is this:
t=raw_input()
c=[]
for j in range(0,int(t)):
n=raw_input()
a=[]
a,b= (int(i) for i in n.split(' '))
c.extend(pow(a,b))
for j in c:
print j
And I am getting an error like this:
raceback (most recent call last):
File "C:/... | [
"You are using extend wrong. A.extend( B ), requires that B is some iterable object( ie a list, tuple ). You really want to use append instead.\nt=raw_input()\nc=[]\nfor j in range(0,int(t)):\n n=raw_input()\n a,b= (int(i) for i in n.split(' '))\n c.append( pow(a,b) ) ## or you could extend c.extend( [ po... | [
3,
2,
2,
1,
1
] | [
"Another way you might want to try calculating exponents is by using logarithm laws.\nx^y = e^(y ln x)\nI can't say for certain but this might reduce the number of operations required to calculate large exponents.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0000961533_python.txt |
Q:
Find all possible combinations
I asked this question earlier but regarding another programming languages.
Let's say I have a couple roots, prefixes, and suffixes.
roots = ["car insurance", "auto insurance"]
prefix = ["cheap", "budget"]
suffix = ["quote", "quotes"]
Is there a simple function in Python which will a... | Find all possible combinations | I asked this question earlier but regarding another programming languages.
Let's say I have a couple roots, prefixes, and suffixes.
roots = ["car insurance", "auto insurance"]
prefix = ["cheap", "budget"]
suffix = ["quote", "quotes"]
Is there a simple function in Python which will allow me to construct all possible co... | [
"Use itertools.product():\nfor p, r, s in itertools.product(prefix, roots, suffix):\n print p, r, s\n\n",
"There's no need to import libraries as Python has builtin syntax for this already. Rather than just printing, it returns a data structure like you asked for, and you get to join the strings together to bo... | [
10,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006312396_list_python.txt |
Q:
Python XCHAT API question
I am writing a script in XCHAT and from reading other scripts I notice use of return xchat.EAT_ALL in most of them. Here is what the documentation for the XCHAT Python API says:
Callback return constants (EAT_)
When a callback is supposed to return one of the EAT_ macros, it is able cont... | Python XCHAT API question | I am writing a script in XCHAT and from reading other scripts I notice use of return xchat.EAT_ALL in most of them. Here is what the documentation for the XCHAT Python API says:
Callback return constants (EAT_)
When a callback is supposed to return one of the EAT_ macros, it is able control how xchat will proceed afte... | [
"Just from what you've pasted in:\nCertain events occur in XChat, which you can register a function to handle. It is possible for there to be more than one callback function registered for each event - either by plugins or by XChat itself.\nSo after your function has done whatever it wants to do, it needs to decide... | [
0
] | [] | [] | [
"callback",
"irc",
"python"
] | stackoverflow_0006311379_callback_irc_python.txt |
Q:
the right expression for ["A" for x in range(0,10) or "B" if x == 9] in python?
I want to express x is in range(0,10), if x == 9 then "B", else "A", what is the right expression for that with in a line? Thanks!
["A" for x in range(0,10) if x == 9 or "B"] # wrong
["A" for x in range(0,10) or "B" if x == 9] ... | the right expression for ["A" for x in range(0,10) or "B" if x == 9] in python? | I want to express x is in range(0,10), if x == 9 then "B", else "A", what is the right expression for that with in a line? Thanks!
["A" for x in range(0,10) if x == 9 or "B"] # wrong
["A" for x in range(0,10) or "B" if x == 9] # wrong
| [
"Try this:\n[\"A\" if x == 9 else \"B\" for x in range(0,10)] \n\n",
"Alternatively:\n>>> ['A']*9+['B']\n['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B']\n\n",
"Another option:\n>>> d = {9:\"B\"}\n>>> [d.get(n, \"A\") for n in range(10)]\n['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B']\n\nThis is a bit mor... | [
3,
2,
2,
0
] | [] | [] | [
"list_comprehension",
"python",
"shortcut"
] | stackoverflow_0006274372_list_comprehension_python_shortcut.txt |
Q:
Websocket Server with twisted and Python doing complex jobs in the background
I want to code a Server which handles Websocket Clients while doing mysql selects via sqlalchemy and scraping several Websites on the same time (scrapy). The received data has to be calculated, saved to the db and then send to the websoc... | Websocket Server with twisted and Python doing complex jobs in the background | I want to code a Server which handles Websocket Clients while doing mysql selects via sqlalchemy and scraping several Websites on the same time (scrapy). The received data has to be calculated, saved to the db and then send to the websocket Clients.
My question ist how can this be done in Python from the logical point... | [
"Cyclone, a Twisted-based 'network toolkit', based on/similar to facebook/friendfeed's Tornado server, contains support for WebSockets: https://github.com/fiorix/cyclone/blob/master/cyclone/web.py#L908\nHere's example code:\n\nhttps://github.com/fiorix/cyclone/blob/master/demos/websocket/websocket.tac\n\nHere's an ... | [
5,
4
] | [] | [] | [
"multithreading",
"python",
"scrapy",
"twisted",
"websocket"
] | stackoverflow_0006250294_multithreading_python_scrapy_twisted_websocket.txt |
Q:
django giving TypeError when using len() on a QuerySet
I am programming a very simple application to store results of soccer matches, and I am stuck with the following problem. When running one of the unit tests, the following code:
listCompetition = Competition.objects.filter(compId=competitionId)
if len(listComp... | django giving TypeError when using len() on a QuerySet | I am programming a very simple application to store results of soccer matches, and I am stuck with the following problem. When running one of the unit tests, the following code:
listCompetition = Competition.objects.filter(compId=competitionId)
if len(listCompetition) == 0:
#some code here
else:
#some code here
... | [
"Simple: in your first case, you're getting back a queryset object, not a list. Querysets are Iterators. List objects are also Iterators, but Iterators are not lists.\nDjango does this to optimize memory and performance: the database keeps the set, and Django reads the response one item at a time, each time you r... | [
10,
8,
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006312906_django_python.txt |
Q:
Enthought Traits names limitations?
I ran into a weird problem while trying to build a Traits GUI that relies on Matplotlib. To summarize it: if, in the example here: http://www.scipy.org/Cookbook/EmbeddingInTraitsGUI, if I replace everywhere the name of the "figure" trait (which, I thought, was just a property I... | Enthought Traits names limitations? | I ran into a weird problem while trying to build a Traits GUI that relies on Matplotlib. To summarize it: if, in the example here: http://www.scipy.org/Cookbook/EmbeddingInTraitsGUI, if I replace everywhere the name of the "figure" trait (which, I thought, was just a property I could name the way I want) by, e.g., "fi... | [
"Did you remember to change the line in the MakePlot function from\nfig = editor.object.figure\n\nto\nfig = editor.object.figu\n\n"
] | [
1
] | [] | [] | [
"python",
"traits"
] | stackoverflow_0006313218_python_traits.txt |
Q:
Pipes and prompts in Python CLI scripts
Is it possible to combine piped input and TTY prompts in Python CLI scripts? E.g., running this:
import sys
piped_text = None
if not sys.stdin.isatty():
piped_text = sys.stdin.read()
user_in = raw_input('Enter something: ')
if piped_text:
sys.stdout.write(piped_... | Pipes and prompts in Python CLI scripts | Is it possible to combine piped input and TTY prompts in Python CLI scripts? E.g., running this:
import sys
piped_text = None
if not sys.stdin.isatty():
piped_text = sys.stdin.read()
user_in = raw_input('Enter something: ')
if piped_text:
sys.stdout.write(piped_text)
sys.stdout.write(user_in + '\n')
Pr... | [
"This works, more or less:\n#!/usr/bin/python\n\nimport sys\n\nsaved_stdin = sys.stdin\nsys.stdin = open('/dev/tty', 'r')\nresult = raw_input('Enter something: ')\nsys.stdout.write('Got: ' + result + '\\n')\nsys.stdin = saved_stdin\nresult2 = sys.stdin.read()\nsys.stdout.write('Also got: ' + result2)\n\nSave as foo... | [
7,
5,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0006312819_linux_python.txt |
Q:
Can I mark variables as transient so they won't be pickled?
Let's say I have a class:
class Thing(object):
cachedBar = None
def __init__(self, foo):
self.foo = foo
def bar(self):
if not self.cachedBar:
self.cachedBar = doSomeIntenseCalculation()
return self.cachedB... | Can I mark variables as transient so they won't be pickled? | Let's say I have a class:
class Thing(object):
cachedBar = None
def __init__(self, foo):
self.foo = foo
def bar(self):
if not self.cachedBar:
self.cachedBar = doSomeIntenseCalculation()
return self.cachedBar
To get bar some intense calculation, so I cache it in memory ... | [
"According to the Pickle documentation, you can provide a method called __getstate__(), which returns something representing the state you want to have pickled (if it isn't provided, pickle uses thing.__dict__). So, you can do something like this:\nclass Thing:\n def __getstate__(self):\n state = di... | [
26,
3
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0006313421_pickle_python.txt |
Q:
hiding console when run in os.startfile()?
I have a .bat file with parameters; I run it using os.startfile(test.bat). Is there a way to hide its console? I tried using subprocess, it works well but when I close the parent program the subprocess that was compiled using py2exe console mode closes too.
info = subproc... | hiding console when run in os.startfile()? | I have a .bat file with parameters; I run it using os.startfile(test.bat). Is there a way to hide its console? I tried using subprocess, it works well but when I close the parent program the subprocess that was compiled using py2exe console mode closes too.
info = subprocess.STARTUPINFO()
info.dwFlags=1
info.wShowWindo... | [
"Use shell=True and creationflags=subprocess.SW_HIDE with subprocess.Popen. This worked for me\nsubprocess.Popen(['test.bat'], shell=True, creationflags=subprocess.SW_HIDE)\n\nIn some releases of Python, SW_HIDE is not available in subprocess module. In that case, you may have to use _subprocess.SW_HIDE\n"
] | [
8
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0006313666_python_windows.txt |
Q:
I want to extract all .tgz and .tar files in a single directory
I'm using the following code to extract .tgz and .tar files into the same directory the archived files reside. It works fine with a single file. But, when I select another file in the same directory to extract, the current folder is overwritten (all o... | I want to extract all .tgz and .tar files in a single directory | I'm using the following code to extract .tgz and .tar files into the same directory the archived files reside. It works fine with a single file. But, when I select another file in the same directory to extract, the current folder is overwritten (all of the files extract a root folder named storage). I imagine this is t... | [
"Why don't you maintain a global counter and append it to 'extract_path' in the extract() method each time a file is extracted? Once extracted (at the end of the extract() method) increment the counter. \nimport os, sys, tarfile\n\nglobal counter\ncounter=1\n\ndef extract(tar_url, extract_path='.'):\n global co... | [
1,
0,
0
] | [] | [] | [
"extract",
"path",
"python"
] | stackoverflow_0006310794_extract_path_python.txt |
Q:
Check that a database file is valid and what the program is expecting?
When connecting to an SQLite database from Python (using Python 2.6), what strategies are there to ensure that a program has opened a valid database file (where valid here means "matches what the program is expecting")?
I'd like to make sure th... | Check that a database file is valid and what the program is expecting? | When connecting to an SQLite database from Python (using Python 2.6), what strategies are there to ensure that a program has opened a valid database file (where valid here means "matches what the program is expecting")?
I'd like to make sure that after some opening checks I can be (reasonably) sure that the program has... | [
"In solutions where I want something similar, I tend to keep a .sql file located at the same directory as my code, containing the build instructions for the database, using constructs similar to the following:\n# setup\nPRAGMA foreign_keys=ON;\nPRAGMA journal_mode=TRUNCATE;\nPRAGMA locking_mode=EXCLUSIVE;\nPRAGMA s... | [
3,
3
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006304495_python_sqlite.txt |
Q:
Segmentation Fault in Python multi-threaded Sqlite use!
I'm developing a python code that uses Sqlite in a multi-threaded program. A remote host calls some xmlrpc functions and new threads are created. Each function which is running in a new thread, uses sqlite for either inserting data into or reading data from t... | Segmentation Fault in Python multi-threaded Sqlite use! | I'm developing a python code that uses Sqlite in a multi-threaded program. A remote host calls some xmlrpc functions and new threads are created. Each function which is running in a new thread, uses sqlite for either inserting data into or reading data from the database.
My problem is that when call the server more th... | [
"If you read the sqlite documentation (http://www.sqlite.org/threadsafe.html), you'll see that it says:\n\nSQLite support three different\n threading modes:\nSingle-thread. In this mode, all\n mutexes are disabled and SQLite is\n unsafe to use in more than a single\n thread at once.\nMulti-thread. In this mode,... | [
2,
1
] | [] | [] | [
"multithreading",
"python",
"sqlite"
] | stackoverflow_0006289821_multithreading_python_sqlite.txt |
Q:
django forms logged in user problem
I am writing an application to help employees track projects the are working on.
Part of the form should allow logged in employees to click a drop down and see all projects they are working on. This is the part I am struggling with; specifically getting ONLY the logged in user's... | django forms logged in user problem | I am writing an application to help employees track projects the are working on.
Part of the form should allow logged in employees to click a drop down and see all projects they are working on. This is the part I am struggling with; specifically getting ONLY the logged in user's projects populated in a drop down. Any h... | [
"You need to put first two lines from ProjectsForm class definition to its initialization method and change them a bit.\nclass ProjectsForm(forms.ModelForm):\n name = forms.ModelChoiceField(queryset=Employee.objects.all(),\n empty_label=\"(Select a Project)\", required=True)\n\n class Meta:\n ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006313800_django_python.txt |
Q:
html post form different destinations
I am developing a django web app in which I would like to have a registration process. In this registration process I have of course a form asking for name, email and password. What I would like to do is, send the form via post to 2 different places. One of which is of course... | html post form different destinations | I am developing a django web app in which I would like to have a registration process. In this registration process I have of course a form asking for name, email and password. What I would like to do is, send the form via post to 2 different places. One of which is of course the registration database which saves the ... | [
"While I agree that the better approach is to handle this on the server side, let me correct that it is very possible to submit the same form to different server side scripts.\nSee the page below for the script and some demos:\nHow to create a multi-submit form\nIt works in IE, Firefox and Chrome.\n",
"You can't.... | [
1,
0,
0,
0,
0
] | [] | [] | [
"django",
"html",
"http_post",
"javascript",
"python"
] | stackoverflow_0006298813_django_html_http_post_javascript_python.txt |
Q:
Extract outer div using BeautifulSoup
If the HTML code looks like this:
<div class="div1">
<p>hello</p>
<p>hi</p>
<div class="nesteddiv">
<p>one</p>
<p>two</p>
<p>three</p>
</div>
</div>
How do I extract just
<div class="div1">
<p>hello</p>
<p>hi</p>
</div>
I already trie... | Extract outer div using BeautifulSoup | If the HTML code looks like this:
<div class="div1">
<p>hello</p>
<p>hi</p>
<div class="nesteddiv">
<p>one</p>
<p>two</p>
<p>three</p>
</div>
</div>
How do I extract just
<div class="div1">
<p>hello</p>
<p>hi</p>
</div>
I already tried parser.find('div', 'div1') but I'm gettin... | [
"You actually want to extract() the nested div from the document and then get the first div. Here is an example (where html is the HTML you provided in the question):\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup(html)\n>>> soup.div.div.extract()\n<div class=\"nesteddiv\">\n<p>one</p>\n<p>t... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006314256_beautifulsoup_python.txt |
Q:
Python - Suppressing creation of __dict__ class variable in a subclass
I'm having a tricky problem in the game I'm working on. I'm using Pygame to develop it. I happen to be one of those developers who never uses the default__dict__ object variable; I always define __slots__ to clarify the variables an object can ... | Python - Suppressing creation of __dict__ class variable in a subclass | I'm having a tricky problem in the game I'm working on. I'm using Pygame to develop it. I happen to be one of those developers who never uses the default__dict__ object variable; I always define __slots__ to clarify the variables an object can have (I have a classmethod that reads the slots to determine the variables n... | [
"The only way to suppress arbitrary attributes and the __dict__ container of them, is to use __slots__ as you are and inherit from a class that does the same. A subclass of a class that has a __dict__ will always have a __dict__. The only way around it is to not inherit from this class (but, for example, use compos... | [
6
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006314205_pygame_python.txt |
Q:
What are my options for MVC, GUI + Interactive Visualization in App Engine (python)?
I'm creating an app that allows users to query, manipulate, and explore a very large graph.
What's the 'best' way to create a gui + visualization for my project?
By best I mean the following:
1. conforms to web standards, no flavo... | What are my options for MVC, GUI + Interactive Visualization in App Engine (python)? | I'm creating an app that allows users to query, manipulate, and explore a very large graph.
What's the 'best' way to create a gui + visualization for my project?
By best I mean the following:
1. conforms to web standards, no flavor of the month solution
2. allows creative flexibility
3. intuitive, won't require weeks t... | [
"App Engine is flexible on the UI side. The Python supports Django templates (0.96 out of the box, and 1.2 with a one-line config change). Django templates are easy to use, and are JavaScript toolkit neutral. I use jQuery, but that's a personal choice that App Engine doesn't impose. On the UI side, it's a safe choi... | [
4,
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"python",
"user_interface",
"visualization"
] | stackoverflow_0006313982_django_google_app_engine_python_user_interface_visualization.txt |
Q:
Dynamic Nested Formsets in Django
I've saw a few blog posts (like the one from yergler) about this but haven't been able to find a good elegant solution.
I have 3 Models:
class Workflow(models.Model):
name = models.CharField(max_length=255)
company = models.ForeignKey(Company)
class Meta:
... | Dynamic Nested Formsets in Django | I've saw a few blog posts (like the one from yergler) about this but haven't been able to find a good elegant solution.
I have 3 Models:
class Workflow(models.Model):
name = models.CharField(max_length=255)
company = models.ForeignKey(Company)
class Meta:
unique_together = ('name', 'company')
... | [
"Personally I think it's easier to do it without using the formset class at all, and just roll your own NestedFormset class which will, for example, parse data with multiple prefixes - ie\n1.title => \"Milestone 1 title\"\n2.title => \"Milestone 2 title\"\n1.1.task => \"Task for milestone 1\"\n1.2.task => \"Task fo... | [
0
] | [] | [] | [
"django",
"django_forms",
"jquery",
"python"
] | stackoverflow_0006314235_django_django_forms_jquery_python.txt |
Q:
ElementTree.write doesn't pretty_print on second pass
I'm having an issue with formatting xml when writing to an xml file. The issue is, the first time I write to the xml file, the xml is formatted properly using pretty_print=True. Any subsequent attempts to append to the xml file are not formatted properly. Th... | ElementTree.write doesn't pretty_print on second pass | I'm having an issue with formatting xml when writing to an xml file. The issue is, the first time I write to the xml file, the xml is formatted properly using pretty_print=True. Any subsequent attempts to append to the xml file are not formatted properly. The xml is written, but not formatted. My code looks like:
#... | [
"The FAQ covers this answer: Why doesn't the pretty print options reformat my XML output\nThis question has also been asked before on StackOverflow as lxml pretty print write file problem.\nIt is unfortunately a side effect of using XML where whitespace (unfortunately) definitely matters.\n"
] | [
1
] | [] | [] | [
"elementtree",
"lxml",
"python"
] | stackoverflow_0006311699_elementtree_lxml_python.txt |
Q:
I don't know how to change an input into integer with decimals
I've made a program that calculates the flat rate interest of a loan based on the amount borrowed, the %/year (interest), and the length of time to pay it back...
here's where my problem starts:
I let the user input the years to pay it back, BUT, if t... | I don't know how to change an input into integer with decimals | I've made a program that calculates the flat rate interest of a loan based on the amount borrowed, the %/year (interest), and the length of time to pay it back...
here's where my problem starts:
I let the user input the years to pay it back, BUT, if the length of time is under a year the user is forced to use a decima... | [
"Maybe float(\"0.5\")? that might be more suited to your problem.\n"
] | [
0
] | [] | [] | [
"decimal",
"python"
] | stackoverflow_0006315109_decimal_python.txt |
Q:
Build Cython and gevent on OSX
When I build gevent, I get an error
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.1/bin/cython", line 7, in
from Cython.Compiler.Main import main
File "/usr/local/Cellar/python/2.7.1/lib/python2.7/site-packages/Cython-0.14.1-py2.7-macosx-10.4-i38... | Build Cython and gevent on OSX | When I build gevent, I get an error
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.1/bin/cython", line 7, in
from Cython.Compiler.Main import main
File "/usr/local/Cellar/python/2.7.1/lib/python2.7/site-packages/Cython-0.14.1-py2.7-macosx-10.4-i386.egg/Cython/Compiler/Main.py", line... | [
"Recompilation gevent-1.0dev and greenlet with flags CFLAGS=\"-arch i386 -arch x86_64\" is a solution to my problem.\n",
"The gevent releases include the generated .c sources so you don't need Cython to build them.\nThe development version (1.0) also has automatically generated tarballs that includes those .c fil... | [
2,
0
] | [] | [] | [
"cython",
"gevent",
"python"
] | stackoverflow_0006277257_cython_gevent_python.txt |
Q:
Date formatting in Django templates
I am trying to use the |date filter and running into some problems. Here is the code that outputs an unformatted way:
{% for the_date in event.date_set.all %}
<p>{{ the_date }}</p>
{% endfor %}
this outputs
<p>2010-10-31</p>
<p>2010-12-01</p>
...etc
When I change the code t... | Date formatting in Django templates | I am trying to use the |date filter and running into some problems. Here is the code that outputs an unformatted way:
{% for the_date in event.date_set.all %}
<p>{{ the_date }}</p>
{% endfor %}
this outputs
<p>2010-10-31</p>
<p>2010-12-01</p>
...etc
When I change the code to
{% for the_date in event.date_set.all %... | [
"I'll guess that your dates aren't really dates, but are strings with formatted dates in them. The |date filter expects a datetime object, not a string.\n",
"That's strange; the following works fine from the interpreter. \nIn [18]: from datetime import datetime\n\nIn [19]: from django.template import Template, ... | [
3,
1,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003663046_django_django_templates_python.txt |
Q:
Save an array as bin in Matlab, pass it to Python and read the bin file in Python
I am currently trying to save an array as bin file in Matlab, send it to Python and read it in Python. However, Matlab is showing errors when I run it. I am using the following codes:
Read the array in Matlab, convert to bin file and... | Save an array as bin in Matlab, pass it to Python and read the bin file in Python | I am currently trying to save an array as bin file in Matlab, send it to Python and read it in Python. However, Matlab is showing errors when I run it. I am using the following codes:
Read the array in Matlab, convert to bin file and pass to Python:
array1 = rand(5,1); %% array1 is the desired array that needs to be se... | [
"There are several problems here.\n\nYou should use double underscore when checking for 'main'. I.e. __main__ == \"__main__\".\nYou are not collecting bytes but rather always storing the last byte read. Therefore, the last byte is always \"\".\nFinally, it seems like indentation is not correct. I assume this is jus... | [
4
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0006314120_matlab_python.txt |
Q:
module object has no attribute type getaddrinfo
I have this really weird python problem and I really need to help to figure this out
When I run
#!/usr/bin/python
import socket
socket.getaddrinfo("www.google.com", 80)
I get this error
socket.getaddrinfo("www.google.com", 80)
AttributeError: 'module' object has n... | module object has no attribute type getaddrinfo | I have this really weird python problem and I really need to help to figure this out
When I run
#!/usr/bin/python
import socket
socket.getaddrinfo("www.google.com", 80)
I get this error
socket.getaddrinfo("www.google.com", 80)
AttributeError: 'module' object has no attribute 'getaddrinfo'
Can anyone help me with th... | [
"Don't you have file named 'socket.py' in your work space?\nIf so, you should rename it, or put it into some subdirectory.\n"
] | [
3
] | [] | [] | [
"import",
"python",
"sockets"
] | stackoverflow_0006315392_import_python_sockets.txt |
Q:
How can I can I programatically post a note to Google Reader?
I use my Google Reader notes as a place to store bookmarks and small snippets of information. I would like to write a small script to let me post notes from the command line (I prefer Python,but an answer using any language will be accepted).
This proje... | How can I can I programatically post a note to Google Reader? | I use my Google Reader notes as a place to store bookmarks and small snippets of information. I would like to write a small script to let me post notes from the command line (I prefer Python,but an answer using any language will be accepted).
This project seemed to be a be a good place to start & some more up-to-date i... | [
"Using Firebug you can see what gets submitted if you add a Google Reader note from a browser. \nThe url it posts to is : http://www.google.co.uk/reader/api/0/item/edit.\nIt seems that the only required parameters are 'T' (for the token retrieve at step 2) and 'snippet' which is the note being posted.\nBased on tha... | [
2
] | [] | [] | [
"google_reader",
"python"
] | stackoverflow_0006239560_google_reader_python.txt |
Q:
How to solve AttributeError when importing igraph?
When I import the igraph package in my project, I get an AttributeError. This only happens in the project directory:
[12:34][~]$ python2
Python 2.7.1 (r271:86832, Apr 15 2011, 12:09:10)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credit... | How to solve AttributeError when importing igraph? | When I import the igraph package in my project, I get an AttributeError. This only happens in the project directory:
[12:34][~]$ python2
Python 2.7.1 (r271:86832, Apr 15 2011, 12:09:10)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import igraph
... | [
"Most likely, there is a module io in ~/projectdir or one of the paths the project configures. The gzip module imported by igraph starts with\nimport io\n\nand expect the built-in io module, not your project's one. Look for an io directory, or io.py or io.pyc. It can also help to scrutinize sys.path for any other d... | [
31
] | [] | [] | [
"igraph",
"import",
"package",
"python"
] | stackoverflow_0006315440_igraph_import_package_python.txt |
Q:
restoring recorded state in l-system code using turtle graphics
I'm using turtle graphics to reproduce l-systems (TurtleWorld library). The rules I have tried to apply work well when they don't involve going back to a previous saved state, but whenever there is a [ and ] (see rule below), things break and the turt... | restoring recorded state in l-system code using turtle graphics | I'm using turtle graphics to reproduce l-systems (TurtleWorld library). The rules I have tried to apply work well when they don't involve going back to a previous saved state, but whenever there is a [ and ] (see rule below), things break and the turtle just draws random bs.
Basically, the IF statement that checks wher... | [
"A couple of ideas:\n\nYou never set angle to the new angle (newa) in your ]-handler.\nYour conditional is wrong according to the comment, newa>0 would turn it left if the angle is positive.\nAre you sure rt handles negative angles well?\nYou could simplify your code a lot if you use pop instead, and pushed a tuple... | [
2
] | [] | [] | [
"l_systems",
"python",
"turtle_graphics"
] | stackoverflow_0006315399_l_systems_python_turtle_graphics.txt |
Q:
Enumerate all IP addresses in domain range from 192.55.22.0 to 192.56.22.0
How can I sort out all the domain range from 192.55.22.0 to 192.56.22.0 through python
I want to perform a set of network tasks on an IP address range. As soon as the range is getting bigger, I fail to enumerate all hosts in the range. I ... | Enumerate all IP addresses in domain range from 192.55.22.0 to 192.56.22.0 | How can I sort out all the domain range from 192.55.22.0 to 192.56.22.0 through python
I want to perform a set of network tasks on an IP address range. As soon as the range is getting bigger, I fail to enumerate all hosts in the range. I want to be able to iterate through all hosts of a network with the net mask
If ... | [
"Your example is a bit confusing. What is between \"192.55.22.0\" and \"192.56.22.0\"? You wrote \"iterate through all hosts of a network with the net mask\", but that range is not one complete network.\nIn a general case, to iterate from some ip to another, you can use:\ndef ip_atoi(ip):\n return struct.unpack(... | [
4,
3
] | [] | [] | [
"cidr",
"ip_address",
"python",
"sockets"
] | stackoverflow_0006315501_cidr_ip_address_python_sockets.txt |
Q:
Deploying Django project on EC2 with BitNami image
I have a complex university project that requires building some specific libraries and the use of threads (AppEngine out of the question), and I want to deploy in on EC2 (Free tier deal).
I was wondering what would be best, to start with a bare linux distribution ... | Deploying Django project on EC2 with BitNami image | I have a complex university project that requires building some specific libraries and the use of threads (AppEngine out of the question), and I want to deploy in on EC2 (Free tier deal).
I was wondering what would be best, to start with a bare linux distribution or the BitNami Django stack ?
I've seen similar question... | [
"The answer is pretty obvious. If you start with the Bitnami stack you'll save yourself the hassle of installing and configuring the various components (web server, gateway, python and the required libs, DB, etc.).\nSo if you app is pretty straight forward (typical web app) then sure, start with the bitnami stack. ... | [
3
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"deployment",
"django",
"python"
] | stackoverflow_0006315654_amazon_ec2_amazon_web_services_deployment_django_python.txt |
Q:
Is there generic inheritance in python?
I was wondering if there is generic inheritance in python.
For example,
Class A(object):
def foo():
Class B(object):
def foo():
Class C(<someParentClass>):
def bar():
so effectively, I would like to do something like
myClass1 = C()<A>
myClass2 = C()<B>
Im gue... | Is there generic inheritance in python? | I was wondering if there is generic inheritance in python.
For example,
Class A(object):
def foo():
Class B(object):
def foo():
Class C(<someParentClass>):
def bar():
so effectively, I would like to do something like
myClass1 = C()<A>
myClass2 = C()<B>
Im guessing this is not possible in python, but is... | [
"There's nothing preventing it. Everything in Python is essentially generic. Everything is runtime, including class statements, so you can do something like:\ndef make_C(parent):\n class C(parent):\n def bar(self):\n ...\n return C\n\nmyClass1 = make_C(A)\nmyClass2 = make_C(B)\n\nIf you want... | [
10,
2
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0006315935_inheritance_python.txt |
Q:
Python Markdown 64 bit installation problems
I'm working with Django for python.
I've tried to install Markdown 2.0.3 for python from here http://pypi.python.org/pypi/Markdown but it only has a windows 32 bit version and I have windows 7 64 bit.
When trying to install the 32 bit version an error appears:
No pytho... | Python Markdown 64 bit installation problems | I'm working with Django for python.
I've tried to install Markdown 2.0.3 for python from here http://pypi.python.org/pypi/Markdown but it only has a windows 32 bit version and I have windows 7 64 bit.
When trying to install the 32 bit version an error appears:
No python installation found in the registry
I do have py... | [
"There is no 64 or 32 bit version of this module. Markdown is a pure-python module and you can install it that way. If the .exe doesn't work for you for some reason, you can always download the .zip version, unpack and run python setup.py install in that directory (provided that python is in your PATH)\n"
] | [
3
] | [] | [] | [
"64_bit",
"django",
"markdown",
"python"
] | stackoverflow_0006315723_64_bit_django_markdown_python.txt |
Q:
lxml, missing doctype when serialized
In [1]: from lxml import etree
I've got an HTML document:
In [2]: root = etree.fromstring(u'''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">\n<HTML></HTML>''', etree.HTMLParser())
Its doctype is parsed correctly:
In [3]: root.getroottree().docinfo.doctype
Out[3]: u'<!DOCTYPE... | lxml, missing doctype when serialized | In [1]: from lxml import etree
I've got an HTML document:
In [2]: root = etree.fromstring(u'''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">\n<HTML></HTML>''', etree.HTMLParser())
Its doctype is parsed correctly:
In [3]: root.getroottree().docinfo.doctype
Out[3]: u'<!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN">'
But... | [
"The only way I've been able to get it to work so far is by using the default XML parser and adding a non-empty system URL to the document:\n>>> html = etree.parse(StringIO('''<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\" \" \">\\n<HTML></HTML>'''))\n>>> etree.tostring(html, method=\"xml\")\n'<!DOCTYPE HTML PUBLI... | [
2,
1
] | [] | [] | [
"doctype",
"lxml",
"python"
] | stackoverflow_0003916766_doctype_lxml_python.txt |
Q:
Indicative Python prints
I would like it if there was some way to generate a more indicative python prints: when printing some value, not only the result will be printed out,
but also the expression that got me that result.
For example, lets say I have:
>>> x = 1
Then, for printing x and its type, we get:
>>> pri... | Indicative Python prints | I would like it if there was some way to generate a more indicative python prints: when printing some value, not only the result will be printed out,
but also the expression that got me that result.
For example, lets say I have:
>>> x = 1
Then, for printing x and its type, we get:
>>> print x ; print type(x)
1
<type '... | [
"You can certainly write a function for this purpose:\ndef print_ex(expr, globals=None, locals=None):\n res = eval(expr, globals, locals)\n print expr + \":\", res\n print \"type(\" + expr + \"):\", type(res)\n\nExample:\n>>> print_ex(\"2 + 3\")\n2 + 3: 5\ntype(2 + 3): <type 'int'>\n\nNote that eval() exec... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006316111_python.txt |
Q:
Is the name of template folder in Django required all lower case?
I'm currently start learning Django after some python basics. When I configure my template dir like this, the app can't file the template folder and files:
TEMPLATE_DIRS = (
"/home/hoangtu/Aptana\ Studio\ 3\ Workspace/django_bookmarks/Template",... | Is the name of template folder in Django required all lower case? | I'm currently start learning Django after some python basics. When I configure my template dir like this, the app can't file the template folder and files:
TEMPLATE_DIRS = (
"/home/hoangtu/Aptana\ Studio\ 3\ Workspace/django_bookmarks/Template",
)
I have to rename the folder to lower case ("templates")... | [
"Did you also rename the folder itself, or only changed the config entry?\nIt shouldn't matter what the folder name is, as long as the name is consistent with the configuration. *nix systems see a difference between \"templates\" and \"Templates\", but both should work when configured properly.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006316346_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.