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:
Python UTF-8 can't decode byte on 32-bit machine
it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.
i get the error
'utf8' codec can't decode bytes in position 76-79: invalid data
for the code
try:
str(sourceresult.sourcename).encode('utf8','repla... | Python UTF-8 can't decode byte on 32-bit machine | it works fine on 64 bit machines but for some reason will not work on python 2.4.3 on a 32-bit instance.
i get the error
'utf8' codec can't decode bytes in position 76-79: invalid data
for the code
try:
str(sourceresult.sourcename).encode('utf8','replace')
except:
raise Exception( repr(sourceresult.s... | [
"We need the following, and we need the exact output:\ntype(sourceresult.sourcename) # I suspect it's already a UTF-8 encoded string\n\nrepr(sourceresult.sourcename)\n\nLike I said, I'm almost certain that your sourceresult.sourcename is already a UTF-8 encoded string.\nPerhaps this might help a little.\nEDIT: it s... | [
7,
0,
0,
0
] | [] | [] | [
"encoding",
"python",
"string",
"utf_8"
] | stackoverflow_0002562674_encoding_python_string_utf_8.txt |
Q:
Django - some permissions are missing in admin tool
I'm not quite sure what to make of this. I'm using Django in eclipse. I made a new django project, and copied the code from a previous django project into this one. I ran syncdb to set up the database. I went to the admin page to recreate my groups, but I not... | Django - some permissions are missing in admin tool | I'm not quite sure what to make of this. I'm using Django in eclipse. I made a new django project, and copied the code from a previous django project into this one. I ran syncdb to set up the database. I went to the admin page to recreate my groups, but I noticed that some of the permissions were missing from the l... | [
"\nWhere did it go?\n\nWhen you incrementally change your database by dropping tables and running syncdb, the PK of the application table are reflected in the auth_permission table can change.\nDon't do \"incremental\" surgery if you can avoid it.\n\nExtract your data.\nDrop your database.\nRerun syncdb to rebuild... | [
3
] | [] | [] | [
"django",
"django_admin",
"django_permissions",
"eclipse",
"python"
] | stackoverflow_0004596817_django_django_admin_django_permissions_eclipse_python.txt |
Q:
Submitting form (Python)
I have a page full of links like this:
<a href="javascript:Window('args')"> text here </a>
When the link is clicked a window pops up (using Javascript). The Javascript also creates the contents of the new window. (with innerHTML)
The content consists of a form like this:
<form method="pos... | Submitting form (Python) | I have a page full of links like this:
<a href="javascript:Window('args')"> text here </a>
When the link is clicked a window pops up (using Javascript). The Javascript also creates the contents of the new window. (with innerHTML)
The content consists of a form like this:
<form method="post" action="/doaction.php">
... | [
"You can use urllib2.urlopen to make a POST request to the script the form is submitting to.\nimport urllib, urllib2\nurl = '/doaction.php'\ndata= {'hashcode': 'blah', 'name':'blahblah', 'type':'blahblahblah'}\nrequest = urllib2.Request(url, urllib.urlencode(data))\nresponse = urllib2.urlopen(request)\n\n"
] | [
5
] | [] | [] | [
"forms",
"javascript",
"python"
] | stackoverflow_0004596966_forms_javascript_python.txt |
Q:
Django - permissions and profiles
I have a couple of different profiles. I want to associate permissions with these profiles. I've done so like this:
class StudentProfile(UserProfile):
school = models.CharField(max_length=30)
class Meta:
permissions = (
("is_student","Can access stude... | Django - permissions and profiles | I have a couple of different profiles. I want to associate permissions with these profiles. I've done so like this:
class StudentProfile(UserProfile):
school = models.CharField(max_length=30)
class Meta:
permissions = (
("is_student","Can access student pages"),
)
however, when I ... | [
".has_perm is a method on the User object, not on a UserProfile object. If you are trying to validate that a user has the permission has_student, you'd need to do something like this:\nuser.has_perm('profiles.is_student')\n\nassuming that your StudentProfile model is in a profiles application.\nEDIT: To address you... | [
4
] | [] | [] | [
"django",
"django_models",
"django_permissions",
"django_profiles",
"python"
] | stackoverflow_0004597185_django_django_models_django_permissions_django_profiles_python.txt |
Q:
Scapy ConditionalField Help
I need help with the ConditionalField in Scapy. I am having trouble with the lambda function, how can I get the lambda function to check for a specific layer in the packet?
At present I have the code
lamda pkt: pkt.haslayer(RTP) == 1
This doesnt appear to work, I dont think pkt contain... | Scapy ConditionalField Help | I need help with the ConditionalField in Scapy. I am having trouble with the lambda function, how can I get the lambda function to check for a specific layer in the packet?
At present I have the code
lamda pkt: pkt.haslayer(RTP) == 1
This doesnt appear to work, I dont think pkt contains the contents of the pkt, how ca... | [
"Try lambda pkt: pkt.haslayer(RTP). My guess is that haslayer() returns something that is seen by Python as True but is not equal to 1, so your comparison to 1 is always returning False.\n"
] | [
1
] | [] | [] | [
"packet",
"python",
"scapy"
] | stackoverflow_0004597233_packet_python_scapy.txt |
Q:
registration django 0.8
use django registration 0.8 alpha from Bennet!
When I click on the activation link the user switches from inactive to active! But the the website says a different thing.
{% if account %}
Thanks activation complete! You may now using the username and password you set at registration.
{% e... | registration django 0.8 | use django registration 0.8 alpha from Bennet!
When I click on the activation link the user switches from inactive to active! But the the website says a different thing.
{% if account %}
Thanks activation complete! You may now using the username and password you set at registration.
{% else %}
Oops it seems that you... | [
"On my site there isn't just one activation page. \"activate.html\" is used when activation fails and \"activation_complete.html\" is used when activation works.\nQuickstart Documentation mirrors this.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"web"
] | stackoverflow_0004596888_django_python_web.txt |
Q:
Gnome-Screensaver with Python?
I've created a little screensaver-type program with Python, and I'd like to get it working properly under gnome-screensaver. The documentation is all written for C, and there don't appear to be libraries for Python. Is there any way to get this working?
A:
gnome-screensaver doesn't... | Gnome-Screensaver with Python? | I've created a little screensaver-type program with Python, and I'd like to get it working properly under gnome-screensaver. The documentation is all written for C, and there don't appear to be libraries for Python. Is there any way to get this working?
| [
"gnome-screensaver doesn't integrate with the screensavers any more than with a small config file that sets the name, some other properties, and a command to execute to start the screensaver. This is documented in the gnome-screensaver FAQ.\nThe program that gets started needs to get the Window ID from the environm... | [
2
] | [] | [] | [
"gnome",
"python",
"screensaver"
] | stackoverflow_0004597080_gnome_python_screensaver.txt |
Q:
how to rewrite python dicts to get default values
I want to rewrite Python's dictionary access mechanism "getitem" to be able to return default values.
The functionality I am looking for is something like
a = dict()
a.setdefault_value(None)
print a[100] #this would return none
any hints ?
Thanks
A:
There is alr... | how to rewrite python dicts to get default values | I want to rewrite Python's dictionary access mechanism "getitem" to be able to return default values.
The functionality I am looking for is something like
a = dict()
a.setdefault_value(None)
print a[100] #this would return none
any hints ?
Thanks
| [
"There is already a collections.defaultdict:\nfrom collections import defaultdict\n\na = defaultdict(lambda:None)\nprint a[100]\n\n",
"There is a defaultdict built-in starting with Python 2.6. The constructor takes a function which will be called when a value is not found. This gives more flexibility than simply ... | [
11,
3,
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004596994_dictionary_python.txt |
Q:
String formatting python
I am trying to understand what option value n exactly does in string formatting for the type flag.
PEP 3101 says (in the section on available integer types):
'n' - Number. This is the same as 'd', except that it uses the
current locale setting to insert the appropriate
... | String formatting python | I am trying to understand what option value n exactly does in string formatting for the type flag.
PEP 3101 says (in the section on available integer types):
'n' - Number. This is the same as 'd', except that it uses the
current locale setting to insert the appropriate
number separator char... | [
"import locale\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\nprint('{0:n}'.format(1234))\n\nyields\n1,234\n\nYou can find your current locale with locale.getlocale():\nIn [31]: locale.getlocale()\nOut[31]: ('en_US', 'UTF8')\n\nand the default locale with locale.getdefaultlocale().\nOn *nix systems, you can get a... | [
10,
3,
1,
1
] | [] | [] | [
"locale",
"python",
"string"
] | stackoverflow_0004597772_locale_python_string.txt |
Q:
Django SQLite testing oddity: Different path of execution?
This is merely a theory that I would like to figure out based on others feedback and perhaps similar experiences.
Been using mySQL for running tests, but of course an in-memory SQLite database is much faster. However, it seems to have run into some problem... | Django SQLite testing oddity: Different path of execution? | This is merely a theory that I would like to figure out based on others feedback and perhaps similar experiences.
Been using mySQL for running tests, but of course an in-memory SQLite database is much faster. However, it seems to have run into some problems.
When DATABASE_ENGINE is set to use django.db.backends.sqlite3... | [
"Is there some reason you are not mocking access to the database? Your UT boundary gets enormously wide when you add a database (no matter what database) to the mixture. It starts to look more like an integration test rather than a unit test.\n",
"Are you loading your Site objects from a fixture?\nIf so, perhaps ... | [
1,
0
] | [] | [] | [
"django",
"python",
"sqlite",
"unit_testing"
] | stackoverflow_0004410898_django_python_sqlite_unit_testing.txt |
Q:
Cast passed arg to string
Newbie at Python and maybe I'm not stating the question right, but how do I cast a passed arg to string in python?
Here is what I'm trying:
#!/usr/bin/python
# Python Wrapper to Call XMLRPC service
import xmlrpclib
import sys
# Set the Server
servAddr = "http://127.0.0.1/xmlrpc.server... | Cast passed arg to string | Newbie at Python and maybe I'm not stating the question right, but how do I cast a passed arg to string in python?
Here is what I'm trying:
#!/usr/bin/python
# Python Wrapper to Call XMLRPC service
import xmlrpclib
import sys
# Set the Server
servAddr = "http://127.0.0.1/xmlrpc.server.php"
# Start the Client
clien... | [
"The values from sys.argv already are strings. I think the problem is that you are passing sys.argv[0] which is the script name. Try this:\nfor arg in sys.argv[1:]:\n print client.service.setId(arg)\n\n",
"Your args in sys.argv should already be strings. What makes you think you need to cast it o a string?\nDo... | [
9,
1,
0
] | [] | [] | [
"arguments",
"casting",
"python",
"string_formatting"
] | stackoverflow_0004598125_arguments_casting_python_string_formatting.txt |
Q:
Python + SQlite3, using foreign keys
Hi
I'm writing this little frontend for a customer database for my workplace. We just needed something light and simple to keep track of customers and tasks and stuff.
This is getting kind of confusing because I'm learning python and SQL at the same time, but I'd like to get ... | Python + SQlite3, using foreign keys | Hi
I'm writing this little frontend for a customer database for my workplace. We just needed something light and simple to keep track of customers and tasks and stuff.
This is getting kind of confusing because I'm learning python and SQL at the same time, but I'd like to get the whole foreign key relations part worki... | [
"Don't indent\n for row in cur:\n for i in row:\n print i\n\nbelow cur.execute('''SELECT * FROM tasks WHERE taskcust=1''') \nBesides that, I think it all works the way you want. Foreign keys are useful because now if you want to find the customer who requested you \"replace RAM, add 2 gigs\" y... | [
2
] | [] | [] | [
"foreign_keys",
"python",
"sqlite"
] | stackoverflow_0004598300_foreign_keys_python_sqlite.txt |
Q:
convert cURL command line into python script
I'm trying to convert these sequence of CURL commands into python script. Can someone assist me on this please? There should be function/method for command 3 and 4 below which will accept the parameter as "data" to pass to command 3 below and note to process as query ar... | convert cURL command line into python script | I'm trying to convert these sequence of CURL commands into python script. Can someone assist me on this please? There should be function/method for command 3 and 4 below which will accept the parameter as "data" to pass to command 3 below and note to process as query argument in command 4 below(eg. of node in command 4... | [
"Well, without doing it all for you, start with urllib2. The relevant function is urllib2.urlopen(\"http://www.example.com\"). If you pass a second parameter, it is treated as the data in a POST request. To do a GET request, just add url encoded parameters to the URL. urllib (without the 2) has a urlencode function... | [
3
] | [] | [] | [
"curl",
"python"
] | stackoverflow_0004598217_curl_python.txt |
Q:
python CGI email dynamic output as a text file attachment
I am trying to send an email using python that has the standard To From, body, etc. However this is where my question comes in. My python script takes information in a string and manipulates it(adds,removes, formats, etc) I am trying to take this output and... | python CGI email dynamic output as a text file attachment | I am trying to send an email using python that has the standard To From, body, etc. However this is where my question comes in. My python script takes information in a string and manipulates it(adds,removes, formats, etc) I am trying to take this output and send it as an attachment on-the-fly. I know I can dump the out... | [
"The last example on this page shows how to create and send multi-part MIME message that contains text and HTML parts using the smtplib andemail modules. It should be easily adaptable to your need to send a message as an attachment (ideally the attachment should have a content-type of message/rfc822).\n",
"Are yo... | [
1,
0
] | [] | [] | [
"attachment",
"cgi",
"email",
"python",
"text"
] | stackoverflow_0004598204_attachment_cgi_email_python_text.txt |
Q:
Is there a way to set all db queries to only retrieve a given user's entries, or would each query throughout the app have to include "AND user..."?
I created an app that lets users input products and compare them. I am at the point where i need to consider scaling and multiple users, and I want to only show users ... | Is there a way to set all db queries to only retrieve a given user's entries, or would each query throughout the app have to include "AND user..."? | I created an app that lets users input products and compare them. I am at the point where i need to consider scaling and multiple users, and I want to only show users the items that they've created (instead of the entire db, which may be an option at some point, but for now each user has to create their own lists).
Is... | [
"I would suggest looking into namespaces, it is exactly the type of use-case they are well suited for.\nOne note, if you want to be able to query users all users' products, you may be better off adding an owner property and using query filters. You can't currently query across namespaces -- only within a single na... | [
5
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0004598516_google_app_engine_gql_python.txt |
Q:
is there a simple class/library which uses pyQT/webkit to scrape websites with javascript support?
i'm looking at using pyQT to scrape websites with javascript support, after dabbling with all the static html alternatives (beautifulsoup, mechanize etc.)
clearly pyQT is a much more generic tool and as such is not o... | is there a simple class/library which uses pyQT/webkit to scrape websites with javascript support? | i'm looking at using pyQT to scrape websites with javascript support, after dabbling with all the static html alternatives (beautifulsoup, mechanize etc.)
clearly pyQT is a much more generic tool and as such is not optimised for my needs.
is there any classes/libraries which give me simple functions for using pyQT for ... | [
"You might want to take a look at spynner--it's a programmatic browser module based on QtWebKit. It might meet your needs.\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"web_scraping",
"webkit"
] | stackoverflow_0004187301_pyqt_python_web_scraping_webkit.txt |
Q:
GAE db.ReferenceProperty Self referencing
Is it possible to reference self via the db.ReferenceProperty, and is it possible to construct a list?
For example I have a class for User and I want a property for his/her friends that references the User class?
I'm currently using Python.
Edit:
So if I have this class:
c... | GAE db.ReferenceProperty Self referencing | Is it possible to reference self via the db.ReferenceProperty, and is it possible to construct a list?
For example I have a class for User and I want a property for his/her friends that references the User class?
I'm currently using Python.
Edit:
So if I have this class:
class Node(db.Model):
name = db.StringProper... | [
"Yes.\n\nclass SelfReferenceProperty(verbose_name=None, collection_name=None, ...)\nA reference to another model instance of the same class. See ReferenceProperty.\nValue type: db.Key (see above)\n\n",
"See also this related SO question: SelfReferenceProperty vs. ListProperty Google App Engine\n"
] | [
6,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004598666_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I show line breaks in Django template without using the "linebreaksbr" template filter?
Let's say I have this:
first \n\n\n second
I want to display that on my page. However, I don't want to use linebreaksbr filter because I'm using JQuery jeditable (edit in place).
When I click on my div, it'll turn it ... | How do I show line breaks in Django template without using the "linebreaksbr" template filter? | Let's say I have this:
first \n\n\n second
I want to display that on my page. However, I don't want to use linebreaksbr filter because I'm using JQuery jeditable (edit in place).
When I click on my div, it'll turn it into a text are box. In this case, it'll be first<br><br><br> second
I don't want that. I want it ... | [
"You can use the preformatted (<pre>) tag.\nOr you can replace the <br> with \\n in jQuery while converting it to a textbox.\n"
] | [
3
] | [] | [] | [
"django",
"html",
"javascript",
"jquery",
"python"
] | stackoverflow_0004598877_django_html_javascript_jquery_python.txt |
Q:
How come my Django filter isn't working?
Submitted on {{ post.date|date:"D. M d, P" }}
Submitted {{ post.date|timesince }} ago
The timesince filter does not work.
Submitted on Tue. Jan 04, 9:45 p.m.
Submitted 0 minutes ago
As you can see , the date filter works, but timesince does not.
A:
Maybe post.date in t... | How come my Django filter isn't working? | Submitted on {{ post.date|date:"D. M d, P" }}
Submitted {{ post.date|timesince }} ago
The timesince filter does not work.
Submitted on Tue. Jan 04, 9:45 p.m.
Submitted 0 minutes ago
As you can see , the date filter works, but timesince does not.
| [
"Maybe post.date in the future?\n"
] | [
1
] | [] | [] | [
"django",
"filter",
"javascript",
"python",
"templates"
] | stackoverflow_0004598982_django_filter_javascript_python_templates.txt |
Q:
Pyparsing: space as a valid token
I'm using pyparser to process the output of a hex-to-text converter. It prints out 16 characters per line, separated by spaces. If the hex value is an ASCII-printable character, that character is printed, otherwise the converter outputs a period (.)
Mostly the output looks like ... | Pyparsing: space as a valid token | I'm using pyparser to process the output of a hex-to-text converter. It prints out 16 characters per line, separated by spaces. If the hex value is an ASCII-printable character, that character is printed, otherwise the converter outputs a period (.)
Mostly the output looks like this:
. a . v a l i d . s t r i n g .
.... | [
"Since this has significant whitespace, you'll need to tell your character expression to leave leading whitespace alone. See how this is done below in the definition of dumpchar:\nhexdump = \"\"\"\\\n. a . v a l i d . s t r i n g . \n. a n o t h e r . s t r i n g . \n. e t c . . . . . . . . . . . . \nl i n e . w .... | [
7,
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004598764_pyparsing_python.txt |
Q:
How do you convert a decimal number into a list of bytes in python
How do you turn a long unsigned int into a list of four bytes in hexidecimal?
Example...
777007543 = 0x2E 0x50 0x31 0xB7
A:
The simplest way I can think of is to use the struct module from within a list comprehension:
import struct
print [hex(or... | How do you convert a decimal number into a list of bytes in python | How do you turn a long unsigned int into a list of four bytes in hexidecimal?
Example...
777007543 = 0x2E 0x50 0x31 0xB7
| [
"The simplest way I can think of is to use the struct module from within a list comprehension:\nimport struct\nprint [hex(ord(b)) for b in struct.pack('>L',777007543)]\n# ['0x2e', '0x50', '0x31', '0xb7']\n\nIt's a little bit more complicated to get uppercase hex digits, but not that bad:\nimport string\nimport str... | [
4,
3,
3,
1,
1
] | [] | [] | [
"byte",
"python"
] | stackoverflow_0004594899_byte_python.txt |
Q:
BeautifulSoup nested tags
I'm trying to parse an XML with Beautifulsoup, but hit a brick wall when trying to use the "recursive" attribute with findall()
I have a pretty odd xml format shown below:
<?xml version="1.0"?>
<catalog>
<book>
<author>Gambardella, Matthew</author>
<title>XML Developer's G... | BeautifulSoup nested tags | I'm trying to parse an XML with Beautifulsoup, but hit a brick wall when trying to use the "recursive" attribute with findall()
I have a pretty odd xml format shown below:
<?xml version="1.0"?>
<catalog>
<book>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Compu... | [
"It appears the problem lies in the nested book tags. BautifulSoup has a predefined set of tags that can be nested (BeautifulSoup.NESTABLE_TAGS), but it doesn't know that book can be nested, so it goes wonkers.\nCustomizing the parser, explains what's going on and how you can subclass BeautifulStoneSoup to customi... | [
4,
3,
0
] | [] | [] | [
"beautifulsoup",
"nested",
"python",
"xml"
] | stackoverflow_0004598234_beautifulsoup_nested_python_xml.txt |
Q:
Python: Compiling Script Safely?
Greetings!
So contrary to my last question I think I was pursuing the wrong method. Basically I need to be able to compile a Python script without fear of any common leecher to obtain my source code and begin usage of it themselves. Now I know Python is a open source language not m... | Python: Compiling Script Safely? | Greetings!
So contrary to my last question I think I was pursuing the wrong method. Basically I need to be able to compile a Python script without fear of any common leecher to obtain my source code and begin usage of it themselves. Now I know Python is a open source language not meant for being protected but there mus... | [
"You can search for a Python obfuscator or scrumbler but there will be no solution that will protect you intellectual property anyway. If you have developed something completely new go for a patent and try to control it.\nIn the meantime continue reading at How do I protect python code?.\n",
"There's no way to pr... | [
3,
2,
1,
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0004599166_py2exe_python.txt |
Q:
How to optimize for Django's paginator module
I have a question about how Django's paginator module works and how to optimize it. I have a list of around 300 items from information that I get from different APIs on the internet. I am using Django's paginator module to display the list for my visitors, 10 items at ... | How to optimize for Django's paginator module | I have a question about how Django's paginator module works and how to optimize it. I have a list of around 300 items from information that I get from different APIs on the internet. I am using Django's paginator module to display the list for my visitors, 10 items at a time. The pagination does not work as well as I w... | [
"The paginator will in this case need the full list in order to do its job.\nMy advice would be to update a cache of the feeds at a regular interval, and then use that cache as the input to the paginator module. Doing an intensive or length task on each and every request is always a bad idea. If not for the page lo... | [
1,
0
] | [] | [] | [
"django",
"paginator",
"python"
] | stackoverflow_0004599189_django_paginator_python.txt |
Q:
Extended slice that goes to beginning of sequence with negative stride
Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.
In python, you can index lists using slice notation. Here's an example:
>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2... | Extended slice that goes to beginning of sequence with negative stride | Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.
In python, you can index lists using slice notation. Here's an example:
>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
You can also include a stride, which acts like a "step":
>>> A[0:5:... | [
"It is error-prone to change the semantics of start and stop. Use None or -(len(a) + 1) instead of 0 or -1. The semantics is not arbitrary. See Edsger W. Dijkstra's article \"Why numbering should start at zero\".\n>>> a = range(10)\n>>> start, stop, step = 4, None, -1\n\nOr \n>>> start, stop, step = 4, -(len(a) + ... | [
5,
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0000399067_list_python_slice.txt |
Q:
Changing the packet data with pcapy/impacket
I'm writing a small program in Python on Linux that will intercept packets flying over the wire on specific port from host A to host B. Host C will act as a man in the middle so all traffic will be going through host C (arp poisoning method). I've written successfuly th... | Changing the packet data with pcapy/impacket | I'm writing a small program in Python on Linux that will intercept packets flying over the wire on specific port from host A to host B. Host C will act as a man in the middle so all traffic will be going through host C (arp poisoning method). I've written successfuly the part with interception so I can see all the data... | [
"I prefer scapy for this kind of application. It's a powerful python package that allows you to capture, manipulate and transmit packets at various layers of the protocol stack.\nThere are several ways to perform your man-in-the-middle attack. I'd probably use the \"sniff\" function with a filter that captures pack... | [
1
] | [] | [] | [
"impacket",
"pcapy",
"python"
] | stackoverflow_0004233744_impacket_pcapy_python.txt |
Q:
Tex markup, how to render it in Html with Python?
The Tex markup support has been recently added to the following Stack Exchange sites:
Mathematics
Statistical Analysis
Theoretical Computer Science
These sites are using the client side Mathjax library to correctly format the submitted formulas to the user.
Sin... | Tex markup, how to render it in Html with Python? | The Tex markup support has been recently added to the following Stack Exchange sites:
Mathematics
Statistical Analysis
Theoretical Computer Science
These sites are using the client side Mathjax library to correctly format the submitted formulas to the user.
Since this new feature was added, the StackExchange API re... | [
"You could try combining a TeX-to-DVI tool (such as tex.latex2dvi or pytex) with a DVI-to-image tool (such as dvipng). To implement this on the server side, you would need an API endpoint that takes TeX code as input and serves an image as output. This way, you can render math formulas as images by pointing their s... | [
2
] | [] | [] | [
"html",
"python",
"tex"
] | stackoverflow_0004592501_html_python_tex.txt |
Q:
SQL Alchemy ORM Getter
I am using the declarative style for Sql Alchemy mappings. I have a column on my table that will be storing portions of the object as JSON. I have a nice method responsible for creating the JSON and that's what I want stored in my DB.
I have mapped the field in my class as a column and tri... | SQL Alchemy ORM Getter | I am using the declarative style for Sql Alchemy mappings. I have a column on my table that will be storing portions of the object as JSON. I have a nice method responsible for creating the JSON and that's what I want stored in my DB.
I have mapped the field in my class as a column and tried to provided a synonym for... | [
"It's actually quite easy to create a custom type like this when using the TypeDecorator: \nhttp://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html#sqlalchemy.types.TypeDecorator\nHowever... if you don't have anything that specifically depends on json, I would recommend using the PickleType instead of you... | [
2
] | [] | [] | [
"getter",
"properties",
"python",
"sqlalchemy"
] | stackoverflow_0004599060_getter_properties_python_sqlalchemy.txt |
Q:
Error creating table named 0e7cc62d5339491aa701b67453405ccb in MySQL
So I'm running a Python script that's making some tables in my MySQL database, and I keep getting the following error:
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "build/bdis... | Error creating table named 0e7cc62d5339491aa701b67453405ccb in MySQL | So I'm running a Python script that's making some tables in my MySQL database, and I keep getting the following error:
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
... | [
"The problem lies in the table name 0e7cc62d5339491aa701b67453405ccb starting with 0e7. Escape the table name with backticks (`) and it should work. However, as @Randy says this naming scheme is a bad idea. Unless you have very good reason, I'd seriously consider improving it.\nQuoting the docs:\n\nIt is recommende... | [
4
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004599739_mysql_python.txt |
Q:
Counting combinations in c or in python
Hello I looked a bit on this topic here but I found nothing that could help me.
I need a program in Python or in C that will give me all possible combinations of a and b that will meet the requirement n=2*a+b, for n from 0 to 10. a, b and n are integers.
For example if n=0 b... | Counting combinations in c or in python | Hello I looked a bit on this topic here but I found nothing that could help me.
I need a program in Python or in C that will give me all possible combinations of a and b that will meet the requirement n=2*a+b, for n from 0 to 10. a, b and n are integers.
For example if n=0 both a and b must be 0. For n=1 a must be zero... | [
"The C version isn't working because you've used the comma operator. The comma operator evaluates all operands and the result is the last evaluation, for example:\nint i = 4;\nint j = 3;\n\nint k = (i += 4, i + j);\n\n// k is now 11 because i += 4 was done first (making i = 8)\n// and then i + j is evaluated to 11 ... | [
2,
1,
1,
0,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0004578787_c_python.txt |
Q:
Simple edit to a binary file in python
THIS SHOULD BE EASY! But i've been unable to find the answer to this question.
Using python, I want to read a binary file into memory, modify the first four bytes of the file, and then write the file back.
There has to be a simple way to edit four measly bytes! right?
A:
... | Simple edit to a binary file in python | THIS SHOULD BE EASY! But i've been unable to find the answer to this question.
Using python, I want to read a binary file into memory, modify the first four bytes of the file, and then write the file back.
There has to be a simple way to edit four measly bytes! right?
| [
"Why read the entire file to change four bytes at the beginning? Shouldn't this work?\nwith open(\"filename.txt\", \"r+b\") as f:\n f.write(chr(10) + chr(20) + chr(30) + chr(40))\n\nEven if you need to read these bytes from the file to calculate the new values, you could still do:\nwith open(\"filename.txt\", \... | [
17,
6,
2,
1,
1,
0
] | [] | [] | [
"binary",
"io",
"python"
] | stackoverflow_0004599835_binary_io_python.txt |
Q:
Sorting ManyToMany field automatically in Django model
I currently have a set of models that look similar to this contrived code:
class Pizza(models.Model):
price = models.FloatField()
topping = models.ManyToManyField(Topping, through="PizzaToppings")
class Topping(models.Model):
name = models.CharFie... | Sorting ManyToMany field automatically in Django model | I currently have a set of models that look similar to this contrived code:
class Pizza(models.Model):
price = models.FloatField()
topping = models.ManyToManyField(Topping, through="PizzaToppings")
class Topping(models.Model):
name = models.CharField(max_length=50)
class PizzaToppings(models.Model):
cl... | [
"Your model is fine you just need to query the relationship since now you have a \"through\" relationship with extra fields. The relationship is created automatically as topping_relationship in your case, so your query should be:\npizza.toppings.order_by('topping_relationship__order_to_add_topping')\n\n"
] | [
7
] | [] | [] | [
"django",
"django_models",
"manytomanyfield",
"python"
] | stackoverflow_0004599512_django_django_models_manytomanyfield_python.txt |
Q:
Simple command line handling equivalent of Perl in Python
I have done some basic Perl coding but never something in python. I would like to do the equivalent of sending the file to be read from in the command line option. This file is tab delimited, so split each column and then be able to perform some operation i... | Simple command line handling equivalent of Perl in Python | I have done some basic Perl coding but never something in python. I would like to do the equivalent of sending the file to be read from in the command line option. This file is tab delimited, so split each column and then be able to perform some operation in those columns.
The perl code for doing this is
#!/usr/bin/per... | [
"#file: process_columns.py\n#!/usr/bin/python\n\nimport fileinput\n\nfor line in fileinput.input():\n cols = l.split('\\t')\n # do something with the columns\n\nThe snippet above can be used this way\n./process_columns.py < data\n\nor just \n./process_columns.py data\n\n",
"Related to: Python equivalent of ... | [
3,
2
] | [] | [] | [
"command_line_arguments",
"perl",
"python"
] | stackoverflow_0004600064_command_line_arguments_perl_python.txt |
Q:
Django datefield filter by weekday/weekend
I've got a date_created field in my database:
date_created = models.DateField(auto_now_add=True)
Is there some way I could filter date_created by weekend/weekday? I know that python's date.weekday() returns 0 - 6 depending on days of the week, so I'd like to use something... | Django datefield filter by weekday/weekend | I've got a date_created field in my database:
date_created = models.DateField(auto_now_add=True)
Is there some way I could filter date_created by weekend/weekday? I know that python's date.weekday() returns 0 - 6 depending on days of the week, so I'd like to use something like:
apps.objects.filter(date_created__weekday... | [
"Django comes with a weekday field lookup.\n\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#week-day\n\n"
] | [
27
] | [] | [] | [
"datetime",
"django",
"django_models",
"python"
] | stackoverflow_0004600325_datetime_django_django_models_python.txt |
Q:
QGraphicsScene and positioning
How to put QGraphicsScene's (0,0) to top-left corner of QGraphicsView?
A:
Try doing setCenterOn(0,0) on the QGraphicsView?
A:
QGraphicsScene will be filled in the whole QGraphicsView but You have the setSceneRect function to choose the QGraphicsScene part you want to see in the Q... | QGraphicsScene and positioning | How to put QGraphicsScene's (0,0) to top-left corner of QGraphicsView?
| [
"Try doing setCenterOn(0,0) on the QGraphicsView?\n",
"QGraphicsScene will be filled in the whole QGraphicsView but You have the setSceneRect function to choose the QGraphicsScene part you want to see in the QGraphicsView.\n"
] | [
1,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0001737624_pyqt_python_qt.txt |
Q:
IronPython and Nodebox in C#
My plan:
I'm trying to setup my C# project to communicate with Nodebox to call a certain function which populates a graph and draws it in a new window.
Current situation: [fixed... see Update2]
I have already included all python-modules needed, but im still getting a
Library 'GL' not... | IronPython and Nodebox in C# | My plan:
I'm trying to setup my C# project to communicate with Nodebox to call a certain function which populates a graph and draws it in a new window.
Current situation: [fixed... see Update2]
I have already included all python-modules needed, but im still getting a
Library 'GL' not found
it seems that the pyglet m... | [
"-X:Frames enables the frames option as runtime (it slows code down a little to have access to the Python frames all the time). \nTo enable frames when hosting you just need to do:\nScriptRuntimeSetup setup = Python.CreateRuntimeSetup(new Dictionary<string, object>() {\n { \"Frames\", true }\n});\n\nInstead of ... | [
0
] | [] | [] | [
"c#",
"ironpython",
"nodebox",
"opengl",
"python"
] | stackoverflow_0004579210_c#_ironpython_nodebox_opengl_python.txt |
Q:
Google App Engine Key Class
What exactly is google app engine's key class? I'm looking at the documentation but it's not really helping. (Python)
A:
Every entity has either an integer id or a name (string) that uniquely identifies it. The key is made up of four basic parts: your app id, the namespace, the kind... | Google App Engine Key Class | What exactly is google app engine's key class? I'm looking at the documentation but it's not really helping. (Python)
| [
"Every entity has either an integer id or a name (string) that uniquely identifies it. The key is made up of four basic parts: your app id, the namespace, the kind name, and the integer id or name. If an entity is a child entity (ie a member of an entity group) the key also contains the parent's kind and id / na... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004600520_google_app_engine_python.txt |
Q:
Using blob properties in GAE
I need to save some binary data coming from post request. I'm doing:
obj.data=self.request.get('data')
And having the error: "Blob() argument should be str instance, not unicod"
I'm trying:
obj.data=str(self.request.get('data'))
And having: "ascii' codec can't encode character ...". ... | Using blob properties in GAE | I need to save some binary data coming from post request. I'm doing:
obj.data=self.request.get('data')
And having the error: "Blob() argument should be str instance, not unicod"
I'm trying:
obj.data=str(self.request.get('data'))
And having: "ascii' codec can't encode character ...". What am I doing wrong? How to save... | [
"If you have binary data it's usually http post. I use a form class to save a submitted form to an entity:\ndata = AForm(data=self.request.POST)\nentity = data.save(commit=False)\n\n",
"I solved the problem using base64 enconding for the parameter.\n",
"You're using a blob property, but attempting to store text... | [
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004528401_google_app_engine_python.txt |
Q:
Opening a image file - BLACKBERRY/J2ME
I am trying to open an image in blackberry.
I got this in python - myImage = graphics.Image.open(jobDirectory + "\" + name) and I wish to use this similar thing in Blackberry/ J2ME.
A:
In J2ME you can display image in following two ways:
Image image = Image.createImage... | Opening a image file - BLACKBERRY/J2ME | I am trying to open an image in blackberry.
I got this in python - myImage = graphics.Image.open(jobDirectory + "\" + name) and I wish to use this similar thing in Blackberry/ J2ME.
| [
"In J2ME you can display image in following two ways:\nImage image = Image.createImage(path_to_img+\"/img.PNG\");\n\ng.drawImage(image, x, y, Graphics.TOP | Graphics.LEFT); // 1) Use drawImage function.\n\nSprite mainSprite = new Sprite(image); // 2) Use Sprite to display your image.\nmainSprite.setRefPixelPositi... | [
4
] | [] | [] | [
"blackberry",
"java",
"java_me",
"python"
] | stackoverflow_0004600548_blackberry_java_java_me_python.txt |
Q:
International Data Encryption Algorithm(IDEA) in C/Python
I wish to implement IDEA algorithm in one of my programs for encryption purposes. I thought of implementing it at first but quickly gave up the idea as it seemed too complex for me to implement. I searched over the net for any library implementation of the ... | International Data Encryption Algorithm(IDEA) in C/Python | I wish to implement IDEA algorithm in one of my programs for encryption purposes. I thought of implementing it at first but quickly gave up the idea as it seemed too complex for me to implement. I searched over the net for any library implementation of the same and stuck upon mcrypt. But idea is a non-free package of m... | [
"2015 Update:\nThe last of the IDEA patents apparently expired in 2012. However, as a 64-bit block size cipher its design is quite outdated, so it should not be considered for new system designs.\n\nThe \"non-free\" description of IDEA is because the cipher is patent-encumbered in Europe, the US and Japan.\nYou ca... | [
3,
2
] | [] | [] | [
"c",
"encryption",
"mcrypt",
"python"
] | stackoverflow_0004600819_c_encryption_mcrypt_python.txt |
Q:
python __import__() imports from 2 different directories when same module exists in 2 locations
I have a python application , which has directory structure like this.
-pythonapp
-mainpython.py
-module1
-submodule1
-file1.py
-file2.py
-submodule2
-file3.py
... | python __import__() imports from 2 different directories when same module exists in 2 locations | I have a python application , which has directory structure like this.
-pythonapp
-mainpython.py
-module1
-submodule1
-file1.py
-file2.py
-submodule2
-file3.py
-file3.py
-submodule3
-file1.py
-file2.py
-file5.py
... | [
"Try to create packages out of your directory by having a having an empty __init__.py file in each and whenever you want to reference a particular module from a package using \nfrom submodule import mymodule\n\nSyntax. Creating packages are a good way to separate the modules into different namespaces. And name your... | [
3
] | [] | [] | [
"python",
"python_2.1"
] | stackoverflow_0004601185_python_python_2.1.txt |
Q:
Same question to multiple remote users with different login
I am very new to Google App Engine and Python. I am building a web application using Python and Django which is based on questions and multiple answers. Once the users are logged in to the website, they will be provided with random questions from a datast... | Same question to multiple remote users with different login | I am very new to Google App Engine and Python. I am building a web application using Python and Django which is based on questions and multiple answers. Once the users are logged in to the website, they will be provided with random questions from a datastore.
What my requirement is, if certain users want to form a grou... | [
"Yes, this should be possible. Your solution might look something like this:\n\nA user creates a new group.\n\nYou generate some random questions and store them in a list for that group.\n\nMore users join that group.\nYou start showing the questions to the users by selecting the first question in that groups list... | [
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004596093_django_google_app_engine_python.txt |
Q:
Reflection in python
I'm trying to find some info on reflection in python. I found a wikipedia article which gave this as a code snippet:
# without reflection
Foo().hello()
# with reflection
getattr(globals()['Foo'](), 'hello')()
I wasn't able to get this to work. What I really need is a way to just instantiat... | Reflection in python | I'm trying to find some info on reflection in python. I found a wikipedia article which gave this as a code snippet:
# without reflection
Foo().hello()
# with reflection
getattr(globals()['Foo'](), 'hello')()
I wasn't able to get this to work. What I really need is a way to just instantiate the object. So if I hav... | [
"\nWhat I really need is a way to just instantiate the object. \n\nThat's what the globals()['Foo']() part does.\nAnd it works for me:\n>>> class Foo:\n... def __init__(self): print \"Created a Foo!\"\n...\n>>> globals()['Foo']()\nCreated a Foo!\n<__main__.Foo instance at 0x02A33350>\n>>>\n\n"
] | [
12
] | [] | [] | [
"django",
"python",
"reflection"
] | stackoverflow_0004601571_django_python_reflection.txt |
Q:
python run multi command in the same time
Prior to this,I run two command in for loop,like
for x in $set:
command
In order to save time,i want to run these two command in the same time,like parallel method in makefile
Thanks
Lyn
A:
The threading module won't give you much performance-wise because of the Glo... | python run multi command in the same time | Prior to this,I run two command in for loop,like
for x in $set:
command
In order to save time,i want to run these two command in the same time,like parallel method in makefile
Thanks
Lyn
| [
"The threading module won't give you much performance-wise because of the Global Interpreter Lock.\nI think the best way to do this is to use the subprocess module and open each command with it's own stdout.\nprocesses = {}\nfor cmd in ['cmd1', 'cmd2', 'cmd3']:\n p = subprocess.Popen('cmd1', stdout=subprocess.PI... | [
3,
1,
0
] | [] | [] | [
"command",
"python"
] | stackoverflow_0004600460_command_python.txt |
Q:
any gae framework for GAE User registry without Google Accounts
i want to find a webapp framework for validation user , store user,
and has ajax Effect of jquery ,
so ,did you know this simply framework ?
thanks
like this page : http: //digu.com/reg
A:
OpenID is now supported (experimentally) in App Engine 1... | any gae framework for GAE User registry without Google Accounts | i want to find a webapp framework for validation user , store user,
and has ajax Effect of jquery ,
so ,did you know this simply framework ?
thanks
like this page : http: //digu.com/reg
| [
"OpenID is now supported (experimentally) in App Engine 1.3.4. See Nick's Blog for a nice tutorial about setting it up.\n",
"Try to use http://gaeframework.com - with local user registration\n"
] | [
3,
1
] | [] | [] | [
"google_app_engine",
"jquery",
"python",
"validation",
"web_applications"
] | stackoverflow_0002963167_google_app_engine_jquery_python_validation_web_applications.txt |
Q:
any gae framework that handle file uploads on google-app-engine
which is the best framework to handle file uploads on gae ,
thanks
A:
I wrote a series of posts about how to handle file uploads to the blobstore - here's the last one (which links to previous ones).
A:
You can use the blobstore api for handling... | any gae framework that handle file uploads on google-app-engine | which is the best framework to handle file uploads on gae ,
thanks
| [
"I wrote a series of posts about how to handle file uploads to the blobstore - here's the last one (which links to previous ones).\n",
"You can use the blobstore api for handling file uploads.\nRefer http://groups.google.com/group/google-appengine-python/msg/8798f6f7aa7fc5b7?pli=1\nIt uses Django on Gae\n",
"Tr... | [
2,
0,
0
] | [] | [] | [
"file_upload",
"google_app_engine",
"python"
] | stackoverflow_0002972516_file_upload_google_app_engine_python.txt |
Q:
Choose 5 different elements from a list?
What is the best way to choose 5 different elements from a python list and add them to a new list?
Thanks for the help!
A:
Assuming that you want them chosen randomly and that new_list is already defined,
import random
new_list += random.sample(old_list, 5)
If new_list ... | Choose 5 different elements from a list? | What is the best way to choose 5 different elements from a python list and add them to a new list?
Thanks for the help!
| [
"Assuming that you want them chosen randomly and that new_list is already defined,\nimport random\n\nnew_list += random.sample(old_list, 5)\n\nIf new_list is not already defined, then you can just do\nnew_list = random.sample(old_list, 5)\n\nIf you don't want to change new_list but want to instead create new_new_li... | [
15,
3,
1,
1
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0004601346_arrays_list_python.txt |
Q:
Signal handlers and logging in Python
Documentation for logging module says that
If you are implementing asynchronous signal handlers using the signal module, you may not be able to use logging from within such handlers. This is because lock implementations in the threading module are not always re-entrant, and s... | Signal handlers and logging in Python | Documentation for logging module says that
If you are implementing asynchronous signal handlers using the signal module, you may not be able to use logging from within such handlers. This is because lock implementations in the threading module are not always re-entrant, and so cannot be invoked from such signal handle... | [
"Signal handlers need special handling in UNIX programming at all. Only a defined list of POSIX C functions are declared as reentrant and can be called within a POSIX signal handler. IEEE Std 1003.1 lists 118 reentrant UNIX functions you find at https://www.opengroup.org/ (login required).\nBut Python signals are a... | [
9,
2
] | [] | [] | [
"logging",
"python",
"signals"
] | stackoverflow_0004601674_logging_python_signals.txt |
Q:
django problem - install the xxx package by putting it on your python path?
I'm trying to deploy Everyblock specifically its ebblog package on my OSX. I already have both Python and Django installed, unfortunately I am fairly new to both Python and Django.
The readme says something like this:
Install the ebblog p... | django problem - install the xxx package by putting it on your python path? | I'm trying to deploy Everyblock specifically its ebblog package on my OSX. I already have both Python and Django installed, unfortunately I am fairly new to both Python and Django.
The readme says something like this:
Install the ebblog package by putting it on your Python path.
Here is the complete readme if you nee... | [
"Usually, installing to the python path means making a python package or module importable, so that when you do\nimport someapp\n\nyou can then use someapp in your code.\nIn order to do that you can\n\nput the package's path into sys.path (import sys;sys.path.append(\"path/to/package\"))\nput the path into a file s... | [
2,
0
] | [] | [] | [
"django",
"package",
"python"
] | stackoverflow_0004602244_django_package_python.txt |
Q:
Append to JSON in Python (Optimally due to RAM constraint)
I'm trying to find the optimal way to append some data to a json file using Python. Basically what happens is I have about say 100 threads open storing data to an array. When they are done they send that to a json file using json.dump. However since this c... | Append to JSON in Python (Optimally due to RAM constraint) | I'm trying to find the optimal way to append some data to a json file using Python. Basically what happens is I have about say 100 threads open storing data to an array. When they are done they send that to a json file using json.dump. However since this can take a few hours for the array to build up I end up running o... | [
"Output the individual items as an array as they're created, creating the JSON formatting for the array around it manually. JSON is a simple format, so this is trivial to do.\nHere's a simple example that prints out a JSON array, without having to hold the entire contents in memory; only a single element in the ar... | [
3,
1
] | [] | [] | [
"append",
"json",
"python",
"ram",
"twitter"
] | stackoverflow_0004602262_append_json_python_ram_twitter.txt |
Q:
Python: Problem Importing Function From Another Module
I have a module called nbemail.py and in this module I want to use the function package_post defined in the module main.py. I am using this statement:
from api.main import package_post
But I am getting this error:
ImportError: cannot import name package_post
... | Python: Problem Importing Function From Another Module | I have a module called nbemail.py and in this module I want to use the function package_post defined in the module main.py. I am using this statement:
from api.main import package_post
But I am getting this error:
ImportError: cannot import name package_post
I really don't know why I am getting this error! I do have ... | [
"I suspect you have a circular dependency error. Do you import nbemail from main as well? If so, Python won't be able to resolve the dependency. The best way to fix this is to move one of the imports into a function, so it doesn't happen when the module is first imported.\n",
"If nbemail.py and main.py are in the... | [
4,
0
] | [] | [] | [
"google_app_engine",
"import",
"python"
] | stackoverflow_0004602595_google_app_engine_import_python.txt |
Q:
Issues running python scripts in Command Prompt (Specifically with command line arguments)?
I am trying to run my python scripts in the command-prompt without calling python.exe first. I am specifically doing this in relation to running django-admin.py. I have C:\Python26 and C:\Python26\Scripts in my PATH. Howeve... | Issues running python scripts in Command Prompt (Specifically with command line arguments)? | I am trying to run my python scripts in the command-prompt without calling python.exe first. I am specifically doing this in relation to running django-admin.py. I have C:\Python26 and C:\Python26\Scripts in my PATH. However, if I try running django-admin.py by doing:
django-admin.py startproject helloworld
I get... | [
"Check assoc and ftype. If properly set, you can run a .py with arguments.\n\n> assoc .py\n.py=Python.File\n> ftype Python.File\nPython.File=\"C:\\Python26\\python.exe\" \"%1\" %*\n\nDepending on how your Python was installed, these may or may not be in place. You can set them with assoc and ftype.\n\n> assoc .py... | [
4,
1
] | [] | [] | [
"command_prompt",
"python",
"scripting"
] | stackoverflow_0002437167_command_prompt_python_scripting.txt |
Q:
How to convert utf-8 string to big5 with python?
I use Python 2.6.6
My locale is ('en_US', 'UTF8')
I try many ways to convert utf-8 string to big5, but it can't work.
If you know how to do that, please give me some advice, thanks a lot.
A chinese word called '單車', it mean 'bicycle'
It's unicode is \u55ae\u8eca
st... | How to convert utf-8 string to big5 with python? | I use Python 2.6.6
My locale is ('en_US', 'UTF8')
I try many ways to convert utf-8 string to big5, but it can't work.
If you know how to do that, please give me some advice, thanks a lot.
A chinese word called '單車', it mean 'bicycle'
It's unicode is \u55ae\u8eca
str_a = u'\u55ae\u8eca'
str_b = '\u55ae\u8eca'
print str... | [
"str_b is a sequence of bytes:\nIn [19]: list(str_b)\nOut[19]: ['\\\\', 'u', '5', '5', 'a', 'e', '\\\\', 'u', '8', 'e', 'c', 'a']\n\nThe backslash and u and so forth all are just separate characters. Compare that to sequence of unicode code points in the unicode object str_a:\nIn [24]: list(str_a)\nOut[24]: [u'\\u5... | [
5,
3
] | [] | [] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0004603327_python_unicode_utf_8.txt |
Q:
Union and Intersect in Django
class Tag(models.Model):
name = models.CharField(maxlength=100)
class Blog(models.Model):
name = models.CharField(maxlength=100)
tags = models.ManyToManyField(Tag)
Simple models just to ask my question.
I wonder how can i query blogs using tags in two different ways.
Blog en... | Union and Intersect in Django | class Tag(models.Model):
name = models.CharField(maxlength=100)
class Blog(models.Model):
name = models.CharField(maxlength=100)
tags = models.ManyToManyField(Tag)
Simple models just to ask my question.
I wonder how can i query blogs using tags in two different ways.
Blog entries that are tagged with "tag1" o... | [
"You could use Q objects for #1:\n# Blogs who have either hockey or django tags.\nfrom django.db.models import Q\nBlog.objects.filter(\n Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')\n)\n\nUnions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to... | [
23,
17,
10,
5
] | [] | [] | [
"django",
"django_models",
"django_views",
"python",
"tagging"
] | stackoverflow_0000108193_django_django_models_django_views_python_tagging.txt |
Q:
How is a python egg different from a regular package?
It seems like just adding a package path to your PYTHONPATH gives you access to all of its modules and functions, similar to installing an egg. Is the difference just that the egg is zip compressed?
A:
Python Eggs is a package distribution system that does a ... | How is a python egg different from a regular package? | It seems like just adding a package path to your PYTHONPATH gives you access to all of its modules and functions, similar to installing an egg. Is the difference just that the egg is zip compressed?
| [
"Python Eggs is a package distribution system that does a lot more than simply copy files and change $PYTHONPATH.\nEDIT: A lot more meaning e.g. runtime dependency resolution and plugin support. See http://en.wikipedia.org/wiki/EasyInstall.\n",
"yes, and zip egg files are decompressed on the fly when you referenc... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004009781_python.txt |
Q:
Delete certain cookies on logout
I am using some cookies to store the state of some sections. jQuery is used to set the cookies. I need to have the right path in order to delete the cookie. This code works but I've provided the values for the paths. Function len returns 0. How can I obtain the cookies with the pat... | Delete certain cookies on logout | I am using some cookies to store the state of some sections. jQuery is used to set the cookies. I need to have the right path in order to delete the cookie. This code works but I've provided the values for the paths. Function len returns 0. How can I obtain the cookies with the path values?
def mylogout(request, next_p... | [
"You can't. Server receives only name and value of the cookie. You can set additional cookie parameters only during cookie creation. After that, user agent is responsible for managing cookies.\nSetting cookie without a path will implicitly use current url path as cookie path.\nIf it's not an issue, you can set cons... | [
1,
0
] | [] | [] | [
"cookies",
"django",
"jquery",
"path",
"python"
] | stackoverflow_0004603800_cookies_django_jquery_path_python.txt |
Q:
How to concatenate strings and integer in a variable
I have a variable of int type.
I am running for loop on it and making a variable with adding some string info.
a = 5 // variable with integer value
list = '' // empty variable
for x in range(a):
list.append('MA[' + x + '] |')
Expected output:
MA[5] | MA[4] | ... | How to concatenate strings and integer in a variable | I have a variable of int type.
I am running for loop on it and making a variable with adding some string info.
a = 5 // variable with integer value
list = '' // empty variable
for x in range(a):
list.append('MA[' + x + '] |')
Expected output:
MA[5] | MA[4] | MA[3] | MA[2] | MA[1] | MA[0]
| [
"As @Frank points out, list is a string which has no .append() method. You seriously should rename it to something more meaningful, but at the very least don't confuse the reader of your code (yourself included!) by naming a string list. Renaming it to string and using str() to cast x to a string:\nstring += 'MA['... | [
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004602807_python.txt |
Q:
In Python: How to Return "Windows" Created Time of a File?
Thsi question is edited with new information further below:
I am on Windows 7 Machine using Cygwin.. and I have both Python 2.6 and 3.1 installed.
I can see the following using my short python script.. for Created Time, Modified Time, Access Time and Crea... | In Python: How to Return "Windows" Created Time of a File? |
Thsi question is edited with new information further below:
I am on Windows 7 Machine using Cygwin.. and I have both Python 2.6 and 3.1 installed.
I can see the following using my short python script.. for Created Time, Modified Time, Access Time and Created Time using stat.
But, the problem is that.. Windows 7 File ... | [
"I tried to do this once again at home.. using 1) cygwin python 2.6 and 2) windows python 3.1\non the same file.. and with both ntpath and os.path\nThe conclusion is that.. windows python 3.1 results match with Windows Properties for all 3 times.\nFor, cygwin python, the created time do not match with windows prope... | [
1
] | [] | [] | [
"creation",
"cygwin",
"file",
"python",
"stat"
] | stackoverflow_0004594452_creation_cygwin_file_python_stat.txt |
Q:
How do I configure Warming Requests avoiding errors 404 on app's log?
I have enabled Warming Requests to my app, adding the following directive in app.yaml.
inbound_services:
- warmup
Looking at app's log I see several entries of this kind:
1.
01-05 02:49PM 50.037 /_ah/warmup 404 300ms 280cpu_ms 1kb
... | How do I configure Warming Requests avoiding errors 404 on app's log? | I have enabled Warming Requests to my app, adding the following directive in app.yaml.
inbound_services:
- warmup
Looking at app's log I see several entries of this kind:
1.
01-05 02:49PM 50.037 /_ah/warmup 404 300ms 280cpu_ms 1kb
See details
0.1.0.3 - - [05/Jan/2011:05:49:50 -0800] "GET /_ah/warmup HTTP/... | [
"Urls starting with /_ah/ work just fine, despite what the documentation might lead you to believe.\nSo, yes, just map a handler to /_ah/warmup to make the warmup requests work. I'm not sure how much benefit you'll get from using an empty handler, though. Usually you'd want to import all of your important modules... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004605228_google_app_engine_python.txt |
Q:
Python and sqlite trouble
I can't show the data from database sqlite in python.
connection = sqlite3.connect('db')
connection.cursor().execute('CREATE TABLE IF NOT EXISTS users ( \
id TEXT, \
name TEXT, ... | Python and sqlite trouble | I can't show the data from database sqlite in python.
connection = sqlite3.connect('db')
connection.cursor().execute('CREATE TABLE IF NOT EXISTS users ( \
id TEXT, \
name TEXT, \
... | [
"INSERT does not return data. To get the data back out, you'll have to issue a SELECT statement.\n",
"Because the create table string as displayed is syntactically invalid Python, as is the insert into string.\n",
"import sqlite3\n\ncon = sqlite3.connect(\"db\")\n\ncon.execute(\"create table users(id, name, av... | [
3,
0,
0,
0
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0003378971_database_python_sqlite.txt |
Q:
Creating a Scheduled Task in Windows Server 2008
I'm used to using Windows Server 2003 and to run my Python scripts as a scheduled task I simply followed the below steps: Opened Scheduled Tasks > Add Scheduled Task > Next > select Python > Next > Name the task, daily > supplied start time > supplied username and p... | Creating a Scheduled Task in Windows Server 2008 | I'm used to using Windows Server 2003 and to run my Python scripts as a scheduled task I simply followed the below steps: Opened Scheduled Tasks > Add Scheduled Task > Next > select Python > Next > Name the task, daily > supplied start time > supplied username and password to run the task.
Server 2008 looks a bit diffe... | [
"You could set python.exe as the program, and pass your script to it as an argument.\n"
] | [
1
] | [] | [] | [
"python",
"scheduled_tasks",
"windows"
] | stackoverflow_0004605884_python_scheduled_tasks_windows.txt |
Q:
Aptana; What does the ">" in front of file/folder names mean in the File explorer?
I'w wondering what it means when Aptana IDE displays an > in the beginning of file and folder names in the File explorer?
A:
In Eclipse, this indicates an outgoing uncommitted change in CVS. Since Aptana is Eclipse based, I assum... | Aptana; What does the ">" in front of file/folder names mean in the File explorer? | I'w wondering what it means when Aptana IDE displays an > in the beginning of file and folder names in the File explorer?
| [
"In Eclipse, this indicates an outgoing uncommitted change in CVS. Since Aptana is Eclipse based, I assume its the same thing. \nYou can change the decorator to something else (e.g. I have mine change the text to a different color) but that's the default.\nSee Window -> Preferences -> Team -> CVS -> Label Decorat... | [
2,
2
] | [] | [] | [
"aptana",
"eclipse",
"python"
] | stackoverflow_0004605870_aptana_eclipse_python.txt |
Q:
Is it possible to use different technologies in one website
I was watching the tutorials for python and the guy told that he coded the Address books and spell checker for yahoo mail in python.
Now initially i was thinking that if i build the website then i have to use one language either php or java or asp or anyt... | Is it possible to use different technologies in one website | I was watching the tutorials for python and the guy told that he coded the Address books and spell checker for yahoo mail in python.
Now initially i was thinking that if i build the website then i have to use one language either php or java or asp or anything.
But i am confused how can we make make separate modules in ... | [
"Phisical architecture of web application can be different from the logical one visible through browser. Basically it is achieved by putting front web server (think of apache with mod_proxy, but it can be any other moder web server supporting reverse proxying) and mounting web application servers (java/python/whate... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"web",
"yahoo"
] | stackoverflow_0004605243_python_web_yahoo.txt |
Q:
How can I create a single log-in and profile for a network of three sites using Django?
How can I create a single log-in and profile for a network of three sites using Django?
I have a network of three sites and instead of having the user create a profile at each of the three sites, I'd like the user to only need ... | How can I create a single log-in and profile for a network of three sites using Django? | How can I create a single log-in and profile for a network of three sites using Django?
I have a network of three sites and instead of having the user create a profile at each of the three sites, I'd like the user to only need to register one time, and then be able to use all three.
Is there an elegant solution to this... | [
"Let the sites share the databases. Hence they will have a common user table.\nTake a look at the django sites framework: http://docs.djangoproject.com/en/dev/ref/contrib/sites/\n",
"Depends on your server(s). \nDo all the sites have access to the same DB? Then use dcrodjer's answer.\nIf not, you can implement ... | [
3,
1,
0
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0004601148_django_pinax_python.txt |
Q:
win32api: get bitmap palette
I'm basically doing this but for 8-bit. I can get the bitmap bits correctly using "P" as the mode bit. However, I have all these bitmap bits, but no palette - PIL just uses a default gray-scale palette. How do I get the correct palette from the image?
A:
I'm not sure how to convert W... | win32api: get bitmap palette | I'm basically doing this but for 8-bit. I can get the bitmap bits correctly using "P" as the mode bit. However, I have all these bitmap bits, but no palette - PIL just uses a default gray-scale palette. How do I get the correct palette from the image?
| [
"I'm not sure how to convert Windows API calls into Python, nor do I know how to update a palette in PIL, but here goes.\nWindows bitmaps don't have a color palette attached to them. The palette is selected into the DC and merged with the reserved system colors; the bitmap is then displayed using the currently sele... | [
1,
0
] | [] | [] | [
"8_bit",
"image",
"python",
"pywin32",
"winapi"
] | stackoverflow_0004605913_8_bit_image_python_pywin32_winapi.txt |
Q:
pywin32: GetSystemPaletteEntries
Is there an equivalent of GetSystemPaletteEntries for pywin32? if not, how can I make this call?
A:
This works, returning a PIL-compatible palette:
import ctypes, win32gui
def getPalette(hwnd):
#hwnd = win32gui.GetDesktopWindow() #if you want desktop window palette?
hwnd... | pywin32: GetSystemPaletteEntries | Is there an equivalent of GetSystemPaletteEntries for pywin32? if not, how can I make this call?
| [
"This works, returning a PIL-compatible palette:\nimport ctypes, win32gui\ndef getPalette(hwnd):\n #hwnd = win32gui.GetDesktopWindow() #if you want desktop window palette?\n\n hwndDC = win32gui.GetWindowDC(hwnd)\n\n buff = ctypes.c_buffer(\"0\"*(256*4)) #R, G, B, and flags\n ctypes.windll.gdi32.GetSyste... | [
1
] | [] | [] | [
"python",
"pywin32",
"winapi"
] | stackoverflow_0004606075_python_pywin32_winapi.txt |
Q:
Alternative results in doctests
I have a doctest where I test a float conversion:
>>> float('fish')
In Python < 2.7 this results in:
ValueError: invalid literal for float(): fish
In Python 2.7 the result is
ValueError: could not convert string to float: fish
Can I make both these results acceptable in my doctes... | Alternative results in doctests | I have a doctest where I test a float conversion:
>>> float('fish')
In Python < 2.7 this results in:
ValueError: invalid literal for float(): fish
In Python 2.7 the result is
ValueError: could not convert string to float: fish
Can I make both these results acceptable in my doctest?
| [
"You are looking for the doctest.IGNORE_EXCEPTION_DETAIL option. The documentation has a good example of how to use it. You can also use the ellipsis constant in the doctest like a wildcard.\nSomething like this as the doctest:\n>>> float('fish')\nValueError:...\n\nYou can see Alex Martellis post about this same ... | [
4,
3
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0004606324_doctest_python.txt |
Q:
Why is the speed difference between these 2 functions so large?
I've been reading through some of the MIT opencourseware quizes and they had a question that goes like this:
6) Consider the two functions specified below that are used to play a “guess a number game.”
def cmpGuess(guess):
"""Assumes that guess is ... | Why is the speed difference between these 2 functions so large? | I've been reading through some of the MIT opencourseware quizes and they had a question that goes like this:
6) Consider the two functions specified below that are used to play a “guess a number game.”
def cmpGuess(guess):
"""Assumes that guess is an integer in range(maxVal). returns -1 if guess is < than the magic ... | [
"The most obvious thing I can see is that every time you call the teacher's function it creates a list of 1,000,000 integers (assuming Python 2.x), and then when it returns it destroys that list again.\nThat is going to take a while.\n",
"You said that you tested both scripts to make sure that they give the same ... | [
7,
4,
3,
3,
0
] | [] | [] | [
"function",
"performance",
"python"
] | stackoverflow_0004602242_function_performance_python.txt |
Q:
Django Querying Datetimes Incorrectly?
Basically I have two datetimes, one from each model. According to python, the datetimes are equal. When I try to query one type of object with the other's datetime, no results are returned. However when I try to do the reverse and query the other by the first's datetime, a re... | Django Querying Datetimes Incorrectly? | Basically I have two datetimes, one from each model. According to python, the datetimes are equal. When I try to query one type of object with the other's datetime, no results are returned. However when I try to do the reverse and query the other by the first's datetime, a result is returned. The examples below should ... | [
"Try looking at the SQL generating the Tables themselves. Based on the comments on your question, It sounds like SQLite is using different datatypes to store the null vs. non-null data, and this is causing a formatting error. \n"
] | [
0
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0004599758_datetime_django_python.txt |
Q:
CGI not executing python - 500 internal server error
I have a few python scripts that I'd like to execute and the following configuration:
Ubuntu 10.04, Apache2, Python 2.6, mod_python and mod_wsgi installed.
I've followed the instructions on the following sites:
http://bytes.com/topic/python/answers/474462-apa... | CGI not executing python - 500 internal server error | I have a few python scripts that I'd like to execute and the following configuration:
Ubuntu 10.04, Apache2, Python 2.6, mod_python and mod_wsgi installed.
I've followed the instructions on the following sites:
http://bytes.com/topic/python/answers/474462-apache-python-ubuntu
http://apache.active-venture.com/cgi-con... | [
"You're not loading the wsgi module.\nLoadModule wsgi_module modules/mod_wsgi.so\n\nAlso, you need only mod_wsgi OR mod_python installed. Not both unless you have a specific need to do so.\n",
"If parms.getfirst('zoom') or parms.getfirst('zsize') return None, you are probably not providing these in your URL (? d... | [
1,
1
] | [] | [] | [
"apache2",
"cgi",
"cgi_bin",
"python"
] | stackoverflow_0004605702_apache2_cgi_cgi_bin_python.txt |
Q:
error handling with imaplib in python
When I use this line:
m = imaplib.IMAP4("some host")
I get this error:
m = imaplib.IMAP4("some host")
File "C:\Python25\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "C:\Python25\lib\imaplib.py", line 230, in open
self.sock.connect((host, port... | error handling with imaplib in python | When I use this line:
m = imaplib.IMAP4("some host")
I get this error:
m = imaplib.IMAP4("some host")
File "C:\Python25\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "C:\Python25\lib\imaplib.py", line 230, in open
self.sock.connect((host, port))
File "<string>", line 1, in connect
er... | [
"Use a standard try/except block:\nimport socket\n\ntry:\n m = imaplib.IMAP4(\"some host\")\nexcept socket.error, e:\n print \"Error opening IMAP connection: \", e\n\n"
] | [
2
] | [] | [] | [
"error_handling",
"imaplib",
"python"
] | stackoverflow_0004606537_error_handling_imaplib_python.txt |
Q:
static effect on python
how we can construct static effect on python instead of using class and global ?
not like that one :
global a
a = []
#simple ex ;
fonk ( a , b , d)
x = 1
a.append ( x)
EDIT:
I want to create temporary memory , if I exit the function namely fonk , I want to save change as lis... | static effect on python | how we can construct static effect on python instead of using class and global ?
not like that one :
global a
a = []
#simple ex ;
fonk ( a , b , d)
x = 1
a.append ( x)
EDIT:
I want to create temporary memory , if I exit the function namely fonk , I want to save change as list on temporary memory .
We ca... | [
"Default values for function arguments are evaluated once, at function definition time, so if you put a mutable object there, it will live across calls. Can be a gotcha, but very useful for caches and similar things static is often used for in other languages. Of course callers can override your cache in this case... | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004606455_list_python.txt |
Q:
How to retrieve the list of exceptions of a function or a method
How can I have a clean list of exceptions that a standard function/method can raise ? Without that, how can I anticipate the behavior of a function ?
Thanks.
A:
There is no way to get a full list of exception a function can raise. You can look in t... | How to retrieve the list of exceptions of a function or a method | How can I have a clean list of exceptions that a standard function/method can raise ? Without that, how can I anticipate the behavior of a function ?
Thanks.
| [
"There is no way to get a full list of exception a function can raise. You can look in the documentation, some functions list the exceptions they raise.\n"
] | [
3
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0004606986_exception_exception_handling_python.txt |
Q:
How come ScrolledPanel in wxpython not working this way?
I don't know why the following code not working, please help me out:
import wx
import wx.lib.scrolledpanel as scrolled
class TaskFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title="ScrolledPanel", size = (... | How come ScrolledPanel in wxpython not working this way? | I don't know why the following code not working, please help me out:
import wx
import wx.lib.scrolledpanel as scrolled
class TaskFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title="ScrolledPanel", size = (500, 600))
MainPanel = wx.Panel(self)
NewPanel... | [
"Try using a sizer. You have to place an object larger than the ScrolledPanel inside it to activate the scrolling (as far as I know), so this should do what I think you're trying to do:\nclass TaskFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, parent = None, id = -1, title=\"ScrolledPan... | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004605989_python_wxpython.txt |
Q:
rb plugin the hot key not working
def activate(self,shell):
self.shell = shell
self.action = gtk.Action ('foo','bar','baz',None)
self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell)
self.action_group = gtk.ActionGroup ('hot_key_action_group')
self.... | rb plugin the hot key not working | def activate(self,shell):
self.shell = shell
self.action = gtk.Action ('foo','bar','baz',None)
self.activate_id = self.action.connect ('activate', self.call_bk_fn,self.shell)
self.action_group = gtk.ActionGroup ('hot_key_action_group')
self.action_group.add_action_with_accel (sel... | [
"One thing that i did remark is that your callback should be like this:\ndef call_bk_fn(self, event, shell):\n print('hello world')\n\nhope this can help :), if you still have some problem i think you should give us more info about the errors that are raised .\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python",
"rhythmbox"
] | stackoverflow_0004607140_gtk_pygtk_python_rhythmbox.txt |
Q:
ImproperlyConfigured: You need to specify NAME in your Django settings file
I'm almost there!! in deploying EveryBlock's ebcode in my mac OSX - here is my settings.py:
http://pastebin.com/ndQ57LCH
This is the entire error:
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/django/core/s... | ImproperlyConfigured: You need to specify NAME in your Django settings file | I'm almost there!! in deploying EveryBlock's ebcode in my mac OSX - here is my settings.py:
http://pastebin.com/ndQ57LCH
This is the entire error:
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/django/core/servers/basehttp.py", line 280, in run
self.result = application(self.environ,... | [
"\nUse either the one-database setup (DATABASE_xxx = ...) or the multiple-database (DATABASES dict) setup\nDon't prepend \"DATABASE_\" to the dictionary keys, e.g. in DATABASES[\"users\"]). This is where the error comes from.\nDon't share your database password on SO\n\n",
"I think you might have forgotten to set... | [
5,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004607455_django_python.txt |
Q:
python class namespace and init function
class Complex:
realpart,imagpart=0,0
def __init__(self):
self.r = Complex.realpart
self.i = Complex.imagpart
x = Complex()
the above code works, x.r,x.i = (0,0), but when the class name is big, Class_name.Data_member way of accessing class da... | python class namespace and init function | class Complex:
realpart,imagpart=0,0
def __init__(self):
self.r = Complex.realpart
self.i = Complex.imagpart
x = Complex()
the above code works, x.r,x.i = (0,0), but when the class name is big, Class_name.Data_member way of accessing class data looks very redundant, is there any way to i... | [
"This is what you want to do:\nclass Complex(object):\n def __init__(self, realpart=0, imagpart=0):\n self.realpart = realpart\n self.imagpart = imagpart\n\nAccessing the member variables is the \"self.realpart\" call. What you were using is class attributes which are accessed like this:\nComplex.s... | [
1,
0
] | [] | [] | [
"class",
"namespaces",
"python",
"scope"
] | stackoverflow_0004607543_class_namespaces_python_scope.txt |
Q:
gdalinfo does not work
The gdalinfo does not work in my Python script
Can anyone tell me what the prblem is?
I imported all the packages from osgeo, all the other functions work except gdal
A:
gdalinfo is a utility that works outside of the Python environment. It is used via the command line.
| gdalinfo does not work | The gdalinfo does not work in my Python script
Can anyone tell me what the prblem is?
I imported all the packages from osgeo, all the other functions work except gdal
| [
"gdalinfo is a utility that works outside of the Python environment. It is used via the command line.\n"
] | [
1
] | [] | [] | [
"gdal",
"geotiff",
"latitude_longitude",
"python",
"syntax_error"
] | stackoverflow_0004581764_gdal_geotiff_latitude_longitude_python_syntax_error.txt |
Q:
.NET DataSet equivalent in python
I'm wondering if there is a dataSet object library in python like in c# dataSet objects.
Any good links of tutorials and suggestions will be greatly appreciated.
A:
If you use the IronPython implementation of python, then you can use exactly the same DataSet object that is used ... | .NET DataSet equivalent in python | I'm wondering if there is a dataSet object library in python like in c# dataSet objects.
Any good links of tutorials and suggestions will be greatly appreciated.
| [
"If you use the IronPython implementation of python, then you can use exactly the same DataSet object that is used in C#.\n",
"Use SQLAlchemy's Object Relational Mapper.\nSQLAlchemy\n"
] | [
1,
1
] | [] | [] | [
"c#",
"dataset",
"python"
] | stackoverflow_0004607044_c#_dataset_python.txt |
Q:
Building a wordle with Python program output
My program generates a set of words from which I intend to build a wordle. I don't know how I can build the wordle part? How can I run this program on a server and then send the output to some website that generates wordles?
A:
Send a POST request to http://www.wordl... | Building a wordle with Python program output | My program generates a set of words from which I intend to build a wordle. I don't know how I can build the wordle part? How can I run this program on a server and then send the output to some website that generates wordles?
| [
"Send a POST request to http://www.wordle.net/advanced with the parameter text set to the text you want.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004607803_python.txt |
Q:
What is the best format to save an image in Python, and why does pydot save invalid images?
I am using pydot to save an image file on my machine and then use the Image module to open the file. However, I get an error using Windows Photo viewer. The image cannot be opened because it is deleted or is in unavailable ... | What is the best format to save an image in Python, and why does pydot save invalid images? | I am using pydot to save an image file on my machine and then use the Image module to open the file. However, I get an error using Windows Photo viewer. The image cannot be opened because it is deleted or is in unavailable location. This is incorrect as the image gets saved to my Desktop.
Sometimes, randomly, the pictu... | [
"This looks like a known bug in the image viewer of PIL on Windows Vista/7. You can try to fix PIL/ImageShow.py as follows: \ndiff -r 142e08f1b589 PIL/ImageShow.py\n--- a/PIL/ImageShow.py Sun Aug 01 22:00:26 2010 +0200\n+++ b/PIL/ImageShow.py Wed Jan 05 10:46:47 2011 -0800\n@@ -97,7 +97,7 @@\n class WindowsVi... | [
5
] | [] | [] | [
"image",
"python"
] | stackoverflow_0004607633_image_python.txt |
Q:
Opencv 2.2 not recognized on Python 2.7 (Ubuntu/Windows XP)
I've been trying to connect opencv and python in both Ubuntu and Windows XP. I've failed on both.
I've read many webpages and threads about "how to install" it but none has worked (the worst part is that they all say kind of the same).
Steps (windows xp)... | Opencv 2.2 not recognized on Python 2.7 (Ubuntu/Windows XP) | I've been trying to connect opencv and python in both Ubuntu and Windows XP. I've failed on both.
I've read many webpages and threads about "how to install" it but none has worked (the worst part is that they all say kind of the same).
Steps (windows xp):
Installed Python 2.7 by default (works perfectly)
Installed PI... | [
"For windows see my web page: http://www.modernmind.org/wiki/OpenCV\nFor Ubuntu you should just need to apt-get install python-dev then generate the make files with Cmake, build it and then make install. In order to build the python bindings you need to have the python header files on your system and you probably d... | [
1,
0
] | [] | [] | [
"installation",
"integration",
"opencv",
"python"
] | stackoverflow_0004593529_installation_integration_opencv_python.txt |
Q:
Is there a Django template language equivalent to Python’s range()?
Possible Duplicate:
Numeric for loop in Django templates
In Python, if I want to run a loop nine times, I can do:
for i in range(1,10):
Is there an equivalent for the {% for %} tag in Django’s template language?
A:
See this question.
Basicall... | Is there a Django template language equivalent to Python’s range()? |
Possible Duplicate:
Numeric for loop in Django templates
In Python, if I want to run a loop nine times, I can do:
for i in range(1,10):
Is there an equivalent for the {% for %} tag in Django’s template language?
| [
"See this question.\nBasically there is no support for it directly and you will need to write your own template tag for it or add it to the context your self. Either way isn't too big of a deal.\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004607907_django_python.txt |
Q:
Help with thinking MVC while programming
I am trying to convert this application i created into MVC style.
This is my original source:
http://pastebin.com/xELEt0yi
Below is my attempt to create above source into MVC
http://pastebin.com/B21cskhA
My issues:
I don't understand how to call from
another class. I tried... | Help with thinking MVC while programming | I am trying to convert this application i created into MVC style.
This is my original source:
http://pastebin.com/xELEt0yi
Below is my attempt to create above source into MVC
http://pastebin.com/B21cskhA
My issues:
I don't understand how to call from
another class. I tried making
"_init _" under each class to call mod... | [
"My Application using MVC:\nhttp://pastebin.com/0CiTqiwu\nI was rather close in completing this task. I had it as\nclass Controller:\n def __init__(self):\n self.model = Model()\n self.view = View()\n def main(self):\n self.model.filename()\n self.view.tcpdump()\n\ninstead of:\ncla... | [
0
] | [] | [] | [
"class",
"model_view_controller",
"python"
] | stackoverflow_0004586928_class_model_view_controller_python.txt |
Q:
Can't make GAE Channel API work on local computer
I am creating a small application to test how GAE Channel API works. I think I have done all as it's described in the documentation but when I launch it, it shows an error in FireFox error log about syntax in the beginning and then another repeating error that an e... | Can't make GAE Channel API work on local computer | I am creating a small application to test how GAE Channel API works. I think I have done all as it's described in the documentation but when I launch it, it shows an error in FireFox error log about syntax in the beginning and then another repeating error that an element wasn't found that.
Here is the first error info:... | [
"It seems that Channel API works on localhost different way than on GAE hosting. I uploaded it to the cloud and it works well now. Though it looks like it working fine on the local computer, it shows permanent JS error repeating in the error log.\n",
"You could try removing the handler argument and adding the han... | [
1,
0
] | [] | [] | [
"ajax",
"channel",
"google_app_engine",
"json",
"python"
] | stackoverflow_0004562762_ajax_channel_google_app_engine_json_python.txt |
Q:
Directory tree in a QTreeWidget
I'm using zipfile and tarfile Python modules to open, extract and compress archives.
I need to display the archive structure in a QTreeWidget, and I don't know how to go on. To get the infos I use the function infos(path) from this file.
I would like to obtain something like this (f... | Directory tree in a QTreeWidget | I'm using zipfile and tarfile Python modules to open, extract and compress archives.
I need to display the archive structure in a QTreeWidget, and I don't know how to go on. To get the infos I use the function infos(path) from this file.
I would like to obtain something like this (from Ark):
For example, if I receive ... | [
"I'm not sure how QTreeWidget wants it's data offhand, but here is a (possibly bad way) to build the structure in memory.\nx = ('GCI/PyFiles/prova3.py', 'GCI/', \\\n 'GCI/PyFiles/', 'GCI/Screenshots/', \\\n 'GCI/prova2.py', 'prova.py')\n\nstructure = {}\nfor fn in x:\n path = fn.split('/')\n\n tmpd = ... | [
1
] | [] | [] | [
"directory",
"pyqt4",
"python",
"qtreewidget"
] | stackoverflow_0004606386_directory_pyqt4_python_qtreewidget.txt |
Q:
Subprocess with variables & Command from different class
============================================
Fixed
Manage to get this corrected heres the correct way of doing this for future viewers: http://pastebin.com/uM0z8Q2v
============================================
source:
http://pastebin.com/utL7Ebeq
My thinking... | Subprocess with variables & Command from different class | ============================================
Fixed
Manage to get this corrected heres the correct way of doing this for future viewers: http://pastebin.com/uM0z8Q2v
============================================
source:
http://pastebin.com/utL7Ebeq
My thinking is that if i run from controller class "main"
it will allow m... | [
"You're not returning anything from filename(). When you don't return anything, None is returned instead, so the parameter command to tcpdump is None, which gives you the error: you can't call split() on the None object.\nChange the filename() function in the Model class to return a string.\n",
"After line 20, a... | [
2,
1,
0
] | [] | [] | [
"model_view_controller",
"python",
"subprocess"
] | stackoverflow_0004587717_model_view_controller_python_subprocess.txt |
Q:
How to sleep a python script running as a cronjob?
I wrote a python script to monitor a log file on a CentOS server for a specific value and send an email when it finds it. It runs as a cron every 5 minutes.
My question is what is the best way to put this script to sleep after it has sent the first email. I don'... | How to sleep a python script running as a cronjob? | I wrote a python script to monitor a log file on a CentOS server for a specific value and send an email when it finds it. It runs as a cron every 5 minutes.
My question is what is the best way to put this script to sleep after it has sent the first email. I don't want it to be sending emails every 5 mins, but it need... | [
"cron will absolutely run the script again. You need to think this through a little more carefully than just \"sleep\" and \"email every 10 minutes.\"\nYou need to write out your use cases.\n\nSystem sends message and user does something.\nSystem sends message and user does nothing. Why email the user again? Wh... | [
4,
3,
1,
0,
0,
0
] | [] | [] | [
"cron",
"python"
] | stackoverflow_0004607343_cron_python.txt |
Q:
Compiling a SWIG Python wrapper for a static library?
This is a noob question. I'm trying to learn how to use SWIG to make a python interface for a C++ library. The library is a proprietary 3rd party library; it comes to me in the form of a header file (foo.h) and a static archive (libfoo.a).
To simplify matter... | Compiling a SWIG Python wrapper for a static library? | This is a noob question. I'm trying to learn how to use SWIG to make a python interface for a C++ library. The library is a proprietary 3rd party library; it comes to me in the form of a header file (foo.h) and a static archive (libfoo.a).
To simplify matters, I've cooked up an example which I think has the same pat... | [
"I'm not really sure if it's the case for you but in general the order of object files and static libraries matters. The order defines the order of initialisation.\nYou have to put the most general objects and/or static archives as last parameters. The objects/archives with the most dependencies have to be placed a... | [
7
] | [] | [] | [
"c++",
"python",
"static_libraries",
"swig",
"undefined_symbol"
] | stackoverflow_0004608780_c++_python_static_libraries_swig_undefined_symbol.txt |
Q:
Serializing ReferenceProperty in Appengine Datastore to JSON
I am using the following code to serialize my appengine datastore to JSON
class DictModel(db.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
class commonWordTweets(DictModel):
commonWo... | Serializing ReferenceProperty in Appengine Datastore to JSON | I am using the following code to serialize my appengine datastore to JSON
class DictModel(db.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
class commonWordTweets(DictModel):
commonWords = db.StringListProperty(required=True)
venue = db.Referen... | [
"Firstly, although it's not exactly your question, it's strongly recommended to use simplejson to produce json, rather than trying to turn structures into json strings yourself.\nTo answer your question, the ReferenceProperty just acts as a reference to your Venue object. So you just use its attributes as per norma... | [
3
] | [] | [] | [
"google_cloud_datastore",
"json",
"python",
"serialization"
] | stackoverflow_0004608273_google_cloud_datastore_json_python_serialization.txt |
Q:
How can I do two-stage authentication to an Active Directory server in Python?
I'm running Python 2.6 on a FreeBSD machine, and I would like to do (and I don't know the correct term for this) two-stage authentication against an active directory.
Basically, the process to log in user 'myuserid' is:
Bind to the AD ... | How can I do two-stage authentication to an Active Directory server in Python? | I'm running Python 2.6 on a FreeBSD machine, and I would like to do (and I don't know the correct term for this) two-stage authentication against an active directory.
Basically, the process to log in user 'myuserid' is:
Bind to the AD LDAP server using a system account created for this purpose (call it DOMAIN\gatekeep... | [
"Your in multiple troubles there:\n\nSIMPLE Auth without SSL is usually disable on AD (and even the SSL version is often off)\nSIMPLE Auth does not really specify the password encoding (usually utf-8 works though)\nSIMPLE Auth might bring troubles with referrals\nYour AD user probably has a different CN when its Ga... | [
1,
0
] | [] | [] | [
"active_directory",
"authentication",
"ldap",
"python",
"unix"
] | stackoverflow_0003551804_active_directory_authentication_ldap_python_unix.txt |
Q:
Zed Shaw's Learn Python the Hard way Tutorial
I'm new to programming and currently going through the exercises in Zed Shaw's Python book.
In Zed's Ex41, there is this function:
def runner(map, start):
next = start
while True:
room = map[next]
print "\n-------"
next = room()
M... | Zed Shaw's Learn Python the Hard way Tutorial | I'm new to programming and currently going through the exercises in Zed Shaw's Python book.
In Zed's Ex41, there is this function:
def runner(map, start):
next = start
while True:
room = map[next]
print "\n-------"
next = room()
My question is, why did he have to assign 'start' to... | [
"The second example works, yes, but he's trying to write a Python tutorial style book, and I think the first one is much more clear about exactly what's going on. start as a variable name loses meaning when it's no longer the actual start, but instead the next room that we're going into.\n",
"I think it was done ... | [
18,
10,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004609373_python.txt |
Q:
"ImportError: No module named ekeet.models" When setting up Pylons with mongokit
I tried setting up a default pylons project to use mongokit as directed here:
http://namlook.github.com/mongokit/pylons.html
However it gives me the error:
>Traceback (most recent call last):
File "/usr/bin/paster", line 18, in
>comm... | "ImportError: No module named ekeet.models" When setting up Pylons with mongokit | I tried setting up a default pylons project to use mongokit as directed here:
http://namlook.github.com/mongokit/pylons.html
However it gives me the error:
>Traceback (most recent call last):
File "/usr/bin/paster", line 18, in
>command.run()
File "/usr/lib/pymodules/python2.6/paste/script/command.py", line 84, in run... | [
"Apparently ekeet just an example. You're supposed to make up your own name. The point is that register_models should be a list of all the modules you want to register. You need to tweak the names for your own needs.\n"
] | [
0
] | [] | [] | [
"mongodb",
"mongokit",
"pylons",
"python"
] | stackoverflow_0004609439_mongodb_mongokit_pylons_python.txt |
Q:
Getting the total number of lines in a Tkinter Text widget?
I have a Tkinter Text widget, and I'd like to know how many lines it contains.
I know of the text.cget("height") method, however that only tells me how many lines are displayed. I'd like to know how many lines there are total.
I'm using this info to try... | Getting the total number of lines in a Tkinter Text widget? | I have a Tkinter Text widget, and I'd like to know how many lines it contains.
I know of the text.cget("height") method, however that only tells me how many lines are displayed. I'd like to know how many lines there are total.
I'm using this info to try to make my own custom scrollbar, so any help would be much appre... | [
"Use the index method to find the value of 'end' which is the position just after the last character in the buffer.\n>>> text_widget.index('end') # returns line.column \n'3.0'\n\n>>> int(text_widget.index('end').split('.')[0]) - 1 # returns line count\n2 \n\nUpdate per Bryan Oakley's comment:\n>>> int(text_widget... | [
15
] | [] | [] | [
"lines",
"python",
"text",
"tkinter"
] | stackoverflow_0004609382_lines_python_text_tkinter.txt |
Q:
Python 3.0 - Dynamic Class Instance Naming
I want to use a while loop to initialize class objects with a simple incremented naming convention. The goal is to be able to scale the number of class objects at will and have the program generate the names automatically. (ex. h1...h100...h1000...) Each h1,h2,h3... bei... | Python 3.0 - Dynamic Class Instance Naming | I want to use a while loop to initialize class objects with a simple incremented naming convention. The goal is to be able to scale the number of class objects at will and have the program generate the names automatically. (ex. h1...h100...h1000...) Each h1,h2,h3... being its own instance.
Here is my first attempt...... | [
"If you want to generate a number of objects, why not simply put them in an array / hash where they can be looked up later on:\nobjects = {}\nfor b in range(1,11):\n objects['h'+str(b)] = Korker(\"test\", 2)\n\n# then access like this:\nobjects['h3']\n\nOf course there are ways to make the names available locall... | [
3,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004608739_python_python_3.x.txt |
Q:
Finding outliers in a data set
I have a python script that creates a list of lists of server uptime and performance data, where each sub-list (or 'row') contains a particular cluster's stats. For example, nicely formatted it looks something like this:
------- ------------- ------------ ---------- ------------... | Finding outliers in a data set | I have a python script that creates a list of lists of server uptime and performance data, where each sub-list (or 'row') contains a particular cluster's stats. For example, nicely formatted it looks something like this:
------- ------------- ------------ ---------- -------------------
Cluster %Availability Requ... | [
"One good way of identifying outliers visually is to make a boxplot (or box-and-whiskers plot), which will show the median, and a couple of quartiles above and below the median, and the points that lie \"far\" from this box (see Wikipedia entry http://en.wikipedia.org/wiki/Box_plot). In R, there's a boxplot functio... | [
8,
7,
5,
1
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0004606288_python_statistics.txt |
Q:
Retrying on Connection Reset
I'm using urllib.request to download files from the internet. However sometimes I get Connection Reset by Peer and I want to retry.
I tried the following, but it seems that e.errno contains socket error and not an actual errno:
while True:
try:
filename, headers = urllib.request.... | Retrying on Connection Reset | I'm using urllib.request to download files from the internet. However sometimes I get Connection Reset by Peer and I want to retry.
I tried the following, but it seems that e.errno contains socket error and not an actual errno:
while True:
try:
filename, headers = urllib.request.urlretrieve(url)
break
excep... | [
"Well this part is not needed, first of all.\nexcept Exception as e:\n raise\n\nAnd the arguments of the IOError is the type of error (socket error) and the error given to it. This error, in turn, is not the original error, but that error is in the args, so...\nexcept IOError as e:\n if e.args[1].args[0].errn... | [
3
] | [] | [] | [
"python",
"python_3.x",
"urllib"
] | stackoverflow_0004605929_python_python_3.x_urllib.txt |
Q:
Are there such things as Django gems - plugins , like there are Ruby gems
Are there such things as Django gems - plugins , like there are Ruby gems ,
like auth management plugin, etc.
A:
It's called Apps in the Django-world.
You can find some of them here: https://www.djangopackages.com/
A:
To add a little mor... | Are there such things as Django gems - plugins , like there are Ruby gems | Are there such things as Django gems - plugins , like there are Ruby gems ,
like auth management plugin, etc.
| [
"It's called Apps in the Django-world.\nYou can find some of them here: https://www.djangopackages.com/\n",
"To add a little more detail to the other answers, the equivalent of Ruby gems are Python \"eggs\". I don't know Ruby so I'm not sure how exact that equivalence is, but eggs are basically the install files... | [
5,
5,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004601788_django_python.txt |
Q:
Fixing tostring() in Python's lxml
lxml's tostring() function seems quite broken when printing only parts of documents. Witness:
from lxml.html import fragment_fromstring, tostring
frag = fragment_fromstring('<p>This stuff is <em>really</em> great!')
em = frag.cssselect('em').pop(0)
print tostring(em)
I expect <e... | Fixing tostring() in Python's lxml | lxml's tostring() function seems quite broken when printing only parts of documents. Witness:
from lxml.html import fragment_fromstring, tostring
frag = fragment_fromstring('<p>This stuff is <em>really</em> great!')
em = frag.cssselect('em').pop(0)
print tostring(em)
I expect <em>really</em> but instead it prints <em>... | [
"How about xml = lxml.etree.tostring(e, with_tail=False)?\nfrom lxml.html import fragment_fromstring\nfrom lxml.etree import tostring\nfrag = fragment_fromstring('<p>This stuff is <em>really</em> great!')\nem = frag.cssselect('em').pop(0)\nprint tostring(em, with_tail=False)\n\nLooks like with_tail was added in v2.... | [
14
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0004610019_lxml_python_xml.txt |
Q:
Inline Forms in Django 1.1 Admin Panel
How do you display forms for the children of a specific model in the Django Admin Panel?
class Matchup(models.Model):
name = models.CharField(max_length=30)
winner = models.ForeignKey('players.player',blank=True)
class Slot(models.Model):
play... | Inline Forms in Django 1.1 Admin Panel | How do you display forms for the children of a specific model in the Django Admin Panel?
class Matchup(models.Model):
name = models.CharField(max_length=30)
winner = models.ForeignKey('players.player',blank=True)
class Slot(models.Model):
player = models.ForeignKey('players.player',bla... | [
"from models import *\n\nclass SlotInline(admin.StackedInline):\n model = Slot\n\nclass MatchupAdmin(admin.ModelAdmin):\n model = Matchup\n inlines = [SlotInline]\n\nadmin.site.register(Matchup, MatchupAdmin)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004610119_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.