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:
Fetching just the Key/id from a ReferenceProperty in App Engine
I could use a little help in AppEngine land...
Using the [Python] API I create relationships like this example from the docs:
class Author(db.Model):
name = db.StringProperty()
class Story(db.Model):
author = db.ReferenceProperty(Author)
st... | Fetching just the Key/id from a ReferenceProperty in App Engine | I could use a little help in AppEngine land...
Using the [Python] API I create relationships like this example from the docs:
class Author(db.Model):
name = db.StringProperty()
class Story(db.Model):
author = db.ReferenceProperty(Author)
story = db.get(story_key)
author_name = story.author.name
As I underst... | [
"Answering my own question for the sake of helping fellow searchers...\nAs suspected calling story.author.key().id() or even story.author.id() will result in datastore queries. The correct method dictated by the API docs is:\nstory = db.get(story_key)\nauthor_id = Story.author.get_value_for_datastore(story).id()\n\... | [
27
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003044121_google_app_engine_google_cloud_datastore_python.txt |
Q:
regular expression - function body extracting
in Python script, for every method definition in some C++ code of the form:
return_value ClassName::MethodName(args)
{MehodBody}
I need to extract three parts: the class name, the method name and the method body for further processing. Finding and extracting the Cla... | regular expression - function body extracting | in Python script, for every method definition in some C++ code of the form:
return_value ClassName::MethodName(args)
{MehodBody}
I need to extract three parts: the class name, the method name and the method body for further processing. Finding and extracting the ClassName and MethodName is easy, but is there any sim... | [
">>> s = \"\"\"return_value ClassName::MethodName(args)\n{MehodBody {} } \"\"\"\n>>> re.findall(r'\\b(\\w+)::(\\w+)\\([^{]+\\{(.+)}', s, re.S)\n[('ClassName', 'MethodName', 'MehodBody {} ')]\n\n",
"I would recommend that you use the parser module rather than regexps since it will handle things like multiple line ... | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003044426_python_regex.txt |
Q:
Using python imaplib to "delete" an email from Gmail?
Can you delete emails with imaplib? If so how?
A:
Use the store method (of the IMAP4 object representing your connection) to set the r'\Deleted' flag on the message number you want to delete, as the example in the docs show; then the expunge method to actual... | Using python imaplib to "delete" an email from Gmail? | Can you delete emails with imaplib? If so how?
| [
"Use the store method (of the IMAP4 object representing your connection) to set the r'\\Deleted' flag on the message number you want to delete, as the example in the docs show; then the expunge method to actually perform all deletions so marked.\nGmail's implementation of IMAP has subtly different semantics, by def... | [
22,
19,
11
] | [] | [] | [
"email",
"imap",
"python"
] | stackoverflow_0001777264_email_imap_python.txt |
Q:
Many-to-many relationship on same table with association object
Related (for the no-association-object use case): SQLAlchemy Many-to-Many Relationship on a Single Table
Building a many-to-many relationship is easy. Building a many-to-many relationship on the same table is almost as easy, as documented in the above... | Many-to-many relationship on same table with association object | Related (for the no-association-object use case): SQLAlchemy Many-to-Many Relationship on a Single Table
Building a many-to-many relationship is easy. Building a many-to-many relationship on the same table is almost as easy, as documented in the above question.
Building a many-to-many relationship with an association o... | [
"I guess you are getting an error like Could not determine join condition between parent/child tables...\nIn this case, Change the mapper for Group_To_Group to the following:\nmapper(Group_To_Group, t_group_groups, properties={\n 'parent_group':relationship(Group,\n primaryjoin=(t_group_groups.c.parent_gr... | [
6
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003043770_python_sqlalchemy.txt |
Q:
Python: Using minidom to search for nodes with a certain text
I am currently faced with XML that looks like this:
<ID>345754</ID>
This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".
A:
vartec's answer needs correcting (sorry I'm not sure I can do t... | Python: Using minidom to search for nodes with a certain text | I am currently faced with XML that looks like this:
<ID>345754</ID>
This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".
| [
"vartec's answer needs correcting (sorry I'm not sure I can do that), it should read:\nxmldoc = xml.dom.minidom.parse('your.xml')\nmatchingNodes = [node for node in xmldoc.getElementsByTagName(\"ID\") if \nnode.firstChild.nodeValue == '345754']\n\nTwo things were wrong with it: (i) tag names are case sensitive so m... | [
10,
4
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0000706453_minidom_python_xml.txt |
Q:
Bubble Breaker Game Solver better than greedy?
For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:Bubble Break Game
The random (N,M,C) board consists N rows x M columns with C colors
The goal is to get the highest score by picking the sequ... | Bubble Breaker Game Solver better than greedy? | For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:Bubble Break Game
The random (N,M,C) board consists N rows x M columns with C colors
The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the h... | [
"According to this paper, determining if you can empty the board (which is related to the problem you want to solve) is NP-Complete. That doesn't mean that you won't be able to find a good algorithm, it just means that you likely won't find an efficient one.\n",
"I'm thinking you could try a branch and bound sea... | [
7,
1,
1,
1,
1,
1
] | [
"This isn't my area of expertise, but I would like to recommend a book to you. Get a copy of The Algorithm Design Manual by Steven Skiena. This has a whole list of different algorithms, and once you read through it you can use it as a reference. If nothing else it will help you consider your options.\n"
] | [
-1
] | [
"algorithm",
"language_agnostic",
"python"
] | stackoverflow_0001541101_algorithm_language_agnostic_python.txt |
Q:
Python vs. Java performance (runtime speed)
Possible Duplicate:
is python slower than java/C#?
Ignoring all the characteristics of each languages and focusing SOLELY on speed, which language is better performance-wise?
You'd think this would be a rather simple question to answer, but I haven't found a decent one... | Python vs. Java performance (runtime speed) |
Possible Duplicate:
is python slower than java/C#?
Ignoring all the characteristics of each languages and focusing SOLELY on speed, which language is better performance-wise?
You'd think this would be a rather simple question to answer, but I haven't found a decent one.
I'm aware that some types of operations may be... | [
"Java is faster than Python. Easily.\nPython is favorable for many things; speed isn't necessarily one of them.\nReferences\n\npython.org/Language Comparisons\n\nC++ vs Java vs Python vs Ruby : a first impression\nA subjective analysis of two high-level, object-oriented languages: Comparing Python to Java\n\n\n",
... | [
82,
34,
13,
8
] | [] | [] | [
"java",
"performance",
"python"
] | stackoverflow_0003044620_java_performance_python.txt |
Q:
On thread safety in python using D-Bus asynchronous method calls
I write a python class which makes asynchronous method calls using D-Bus. When my reply_handler is called, it stores data in list. This list can be used by another class methods at the same time. Is it safe or I can use only synchronized data structu... | On thread safety in python using D-Bus asynchronous method calls | I write a python class which makes asynchronous method calls using D-Bus. When my reply_handler is called, it stores data in list. This list can be used by another class methods at the same time. Is it safe or I can use only synchronized data structures like Queue class?
| [
"If you do not modify the list outside of the callback context, then you do not necessarily need synchronization - you will just need to be aware that the list object's state is volatile. \nIf the list must be modified both in the callback handler as well as, say, the main execution context (or other threads, etc.)... | [
0
] | [] | [] | [
"dbus",
"python",
"thread_safety"
] | stackoverflow_0003044596_dbus_python_thread_safety.txt |
Q:
How can I make an alt+number global hotkey in Python?
I want to make a global hotkey, with alt+1, 2, ..., that paste some string in the clipboard.
How can I do that?
A:
As an alternative, I would recommend using each tool for what it was designed to do. That is, use AutoHotkey for setting the hot-keys and for ot... | How can I make an alt+number global hotkey in Python? | I want to make a global hotkey, with alt+1, 2, ..., that paste some string in the clipboard.
How can I do that?
| [
"As an alternative, I would recommend using each tool for what it was designed to do. That is, use AutoHotkey for setting the hot-keys and for other types of Windows automation. AutoHotkey (AHK) connects with Python very well in several ways (many are discussed in the AHK forums). One interesting way is using autoh... | [
3,
3,
2
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003042201_python_windows.txt |
Q:
How to convert string "0671" or "0x45" into integer form with 0 and 0x in the beginning
I wanted to make my own encryption algorithm and decryption algorithm , encryption algorithm works fine and converts ascii value of the characters into alternate hexadecimal and octal representations. But when I tried decryptio... | How to convert string "0671" or "0x45" into integer form with 0 and 0x in the beginning | I wanted to make my own encryption algorithm and decryption algorithm , encryption algorithm works fine and converts ascii value of the characters into alternate hexadecimal and octal representations. But when I tried decryption, problem occured as it return int('0671') = 671, as 0671 is string type in the following co... | [
"there you go (s is the string)\nint(s,0)\n\n"
] | [
2
] | [] | [] | [
"octal",
"python"
] | stackoverflow_0003045202_octal_python.txt |
Q:
Should I use a class in this: Reading a XML file using lxml
This question is in continuation to my previous question, in which I asked about passing around an ElementTree.
I need to read the XML files only and to solve this, I decided to create a global ElementTree and then parse it wherever required.
My question ... | Should I use a class in this: Reading a XML file using lxml | This question is in continuation to my previous question, in which I asked about passing around an ElementTree.
I need to read the XML files only and to solve this, I decided to create a global ElementTree and then parse it wherever required.
My question is:
Is this an acceptable practice? I heard global variables are ... | [
"Pragmatically, is your code expected to grow? Even though people herald OOP as the right way, I found that sometimes it's better to weigh cost:benefit(s) whenever you refactor a piece of code. If you are looking to grow this, then OOP is a better option in that you can extend and customise any future use case, whi... | [
0,
0,
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003045038_design_patterns_python.txt |
Q:
Using Pycairo to generate images dynamically and serve in Django
I want to generate a dynamically created png image with Pycairo and serve it usign Django. I read this: Serve a dynamically generated image with Django.
Is there a way to transport data from Pycairo surface directly into HTTP response? I'm doing this... | Using Pycairo to generate images dynamically and serve in Django | I want to generate a dynamically created png image with Pycairo and serve it usign Django. I read this: Serve a dynamically generated image with Django.
Is there a way to transport data from Pycairo surface directly into HTTP response? I'm doing this for now:
data = surface.to_rgba()
im = Image.frombuffer ("RGBA", (wid... | [
"def someView(request):\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)\n context = cairo.Context(surface)\n # Draw something ...\n\n response = HttpResponse(mimetype=\"image/png\")\n surface.write_to_png(response)\n return response\n\n",
"You can try this:\nhttp://www.stuartaxon.com/2010/02/0... | [
7,
0
] | [] | [] | [
"django",
"image",
"pycairo",
"python",
"python_imaging_library"
] | stackoverflow_0003004854_django_image_pycairo_python_python_imaging_library.txt |
Q:
Python and object/class attrs - what's going on?
Can someone explain why Python does the following?
>>> class Foo(object):
... bar = []
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]
>>> a.bar = 1
>>> a.bar
1
>>> b.bar
[1]
>>> a.bar = []
>>> a.bar
[]
>>> b.bar
[1]
>>> del a.bar
>>> a.bar
[1]
... | Python and object/class attrs - what's going on? | Can someone explain why Python does the following?
>>> class Foo(object):
... bar = []
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]
>>> a.bar = 1
>>> a.bar
1
>>> b.bar
[1]
>>> a.bar = []
>>> a.bar
[]
>>> b.bar
[1]
>>> del a.bar
>>> a.bar
[1]
It's rather confusing!
| [
"This is because the way you have written it, bar is a class variable rather than an instance variable.\nTo define an instance variable, bind it in the constructor:\nclass Foo(object):\n def __init__(self):\n self.bar = []\n\nNote that it now belongs to a single instance of Foo (self) rather than the Foo class,... | [
7,
0,
0,
0,
0,
0
] | [] | [] | [
"class_attributes",
"python"
] | stackoverflow_0003045246_class_attributes_python.txt |
Q:
Python - How to find a correlation between two vectors?
Given two vectors X and Y, I have to find their correlation, i.e. their linear dependence/independence. Both vectors have equal dimension. The result should be a floating point number from [-1.0 .. 1.0].
Example:
X=[-1, 2, 0]
Y=[ 4, 2, -0.3]
Find y = co... | Python - How to find a correlation between two vectors? | Given two vectors X and Y, I have to find their correlation, i.e. their linear dependence/independence. Both vectors have equal dimension. The result should be a floating point number from [-1.0 .. 1.0].
Example:
X=[-1, 2, 0]
Y=[ 4, 2, -0.3]
Find y = cor(X,Y) such that y belongs to [-1.0 .. 1.0].
It should be a s... | [
"Sounds like a dot product to me.\nSolve the equation for the cosine of the angle between the two vectors, which is always in the range [-1, 1], and you'll have what you want.\nIt's equal to the dot product divided by the magnitudes of two vectors.\n",
"Since range is supposed to be [-1, 1] I think that the Pears... | [
4,
4,
2
] | [] | [] | [
"algorithm",
"list_comprehension",
"math",
"python"
] | stackoverflow_0003045040_algorithm_list_comprehension_math_python.txt |
Q:
python: iif or (x ? a : b)
Possible Duplicate:
Python Ternary Operator
If Python would support the (x ? a : b) syntax from C/C++, I would write:
print paid ? ("paid: " + str(paid) + " €") : "not paid"
I really don't want to have an if-check and two independent prints here (because that is only an example above,... | python: iif or (x ? a : b) |
Possible Duplicate:
Python Ternary Operator
If Python would support the (x ? a : b) syntax from C/C++, I would write:
print paid ? ("paid: " + str(paid) + " €") : "not paid"
I really don't want to have an if-check and two independent prints here (because that is only an example above, in my code, it looks much more... | [
"Try\n print (\"paid: \" + str(paid) + \" €\") if paid else \"not paid\"\n\n"
] | [
22
] | [] | [] | [
"iif_function",
"python",
"ternary_operator"
] | stackoverflow_0003045675_iif_function_python_ternary_operator.txt |
Q:
Simulate Browser Resources Expansion Behavior With Python
I'm looking for a way to simulate browser resources expansion behavior.
The flow I'm trying to address is the following:
Access an initial URL (e.g. http://example.dmn/index.htm)
Parse the html response received (e.g. index.htm)
Find the resources tha... | Simulate Browser Resources Expansion Behavior With Python | I'm looking for a way to simulate browser resources expansion behavior.
The flow I'm trying to address is the following:
Access an initial URL (e.g. http://example.dmn/index.htm)
Parse the html response received (e.g. index.htm)
Find the resources that a browser will fetch as a result of the index parsing, e.g.: ... | [
"You may wish to look at the Windmill Testing Framework which allows you to write tests in Python for web apps.\n",
"You might want to look at spider.py, and robotparser. Barring those doing what you want automatically, you can dig into the HTML soup yourself with BeautifulSoup.\n",
"You may want to take a loo... | [
1,
1,
1
] | [] | [] | [
"html",
"http",
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0003044005_html_http_python_scrapy_web_scraping.txt |
Q:
Join a list of lists together into one list in Python
I have a list which consists of many lists. Here is an example,
[
[Obj, Obj, Obj, Obj],
[Obj],
[Obj],
[
[Obj,Obj],
[Obj,Obj,Obj]
]
]
Is there a way to join all these items together as one list, so the output will be somethin... | Join a list of lists together into one list in Python | I have a list which consists of many lists. Here is an example,
[
[Obj, Obj, Obj, Obj],
[Obj],
[Obj],
[
[Obj,Obj],
[Obj,Obj,Obj]
]
]
Is there a way to join all these items together as one list, so the output will be something like
[Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]
| [
"Yes, here's one way to do it:\ndef flatten(lst):\n for elem in lst:\n if type(elem) in (tuple, list):\n for i in flatten(elem):\n yield i\n else:\n yield elem\n\nPlease note, this creates a generator, so if you need a list, wrap it in list():\nflattenedList = l... | [
7,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003046217_list_python.txt |
Q:
Convert a GTK python script to C
The following script will take a screenshot on a Gnome desktop.
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1])
pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1])
if (pb... | Convert a GTK python script to C | The following script will take a screenshot on a Gnome desktop.
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1])
pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1])
if (pb != None):
pb.save("screenshot.png... | [
"I tested this and it does work, but there might be a simpler way to go from GdkPixbuf to a png this was just the first one I found. (There's no gdk_pixbuf_save())\n#include <unistd.h>\n#include <stdio.h>\n#include <gdk/gdk.h>\n#include <cairo.h>\n\nint main(int argc, char **argv)\n{\n gdk_init(&argc, &argv);\n\... | [
3
] | [] | [] | [
"c",
"gtk",
"linux",
"python",
"screenshot"
] | stackoverflow_0003045850_c_gtk_linux_python_screenshot.txt |
Q:
Dragon NaturallySpeaking Programmers
Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can no... | Dragon NaturallySpeaking Programmers | Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the... | [
"Solution: download Natlink - http://qh.antenna.nl/unimacro/installation/installation.html\nIt's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work prope... | [
8
] | [] | [] | [
"naturallyspeaking",
"python",
"speech",
"speech_recognition"
] | stackoverflow_0002952899_naturallyspeaking_python_speech_speech_recognition.txt |
Q:
Django model class and custom property
today a weird problem occurred to me:
I have a model class in Django and added a custom property to it that shall not be saved into the database and therefore is not representative in the model's structure:
class Category(models.Model):
groups = models.ManyToManyField(Gro... | Django model class and custom property | today a weird problem occurred to me:
I have a model class in Django and added a custom property to it that shall not be saved into the database and therefore is not representative in the model's structure:
class Category(models.Model):
groups = models.ManyToManyField(Group)
title = defaultdict()
Now, when I'm... | [
"Don't do it that way. Your title attribute is completely \"global\". It's part of the class, not part of each instance.\nDo something like this.\nclass Category(models.Model):\n groups = models.ManyToManyField(Group)\n @property\n def title(self):\n return self._title\n def save( self, *args, ... | [
9
] | [] | [] | [
"class",
"django",
"django_models",
"python"
] | stackoverflow_0003046398_class_django_django_models_python.txt |
Q:
How does Qt work (exactly)?
When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application?
How exactly does this work? Does ... | How does Qt work (exactly)? | When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application?
How exactly does this work? Does Qt compile to the desired platfor... | [
"Qt (ideally) provides source compatibility, not binary compatibility. You still have to compile the application separately for each platform, and use the appropriate dynamic Qt libraries (which also need to be compiled separately, and have some platform-specific code). \nFor your final question, the user would n... | [
15,
13,
5
] | [] | [] | [
"python",
"qt"
] | stackoverflow_0003045745_python_qt.txt |
Q:
Can this code be further optimized?
i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code.
But this is part of the code which is causing so much of delay in my project and want to optimize this.
i want to know which code part is faulty ... | Can this code be further optimized? | i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code.
But this is part of the code which is causing so much of delay in my project and want to optimize this.
i want to know which code part is faulty and how could this be replaced.
i guess,f... | [
"def get_list(file, cmp, fout):\n ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp))\n return fout[ind].rstrip('\\n').split(' ')\n\nroot = r'c:\\begpython\\wavnk'\nheader = 6\nfor lst in lists:\n save = database_index[lst]\n index, base, _, abs2, abs1, *_ = save\n using_data[index] = save\n... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003046145_python.txt |
Q:
Finding out event that called a CGI script
What I want is to be able to make my CGI script do different things depending on what action initiated the calling of the script.
For example, if one button is pressed, a database is cleared. If another button is pressed, a form is submitted and that data is added to the ... | Finding out event that called a CGI script | What I want is to be able to make my CGI script do different things depending on what action initiated the calling of the script.
For example, if one button is pressed, a database is cleared. If another button is pressed, a form is submitted and that data is added to the database.
Should I be doing something like addin... | [
"POST request includes all the elements of the form you submit. So, if you have a form with several submit buttons:\n <form id=\"mytestform\" target=\"/cgi-bin/script.py\" method=\"POST\">\n <input type=\"submit\" name=\"ClearDB\" value=\"Clear DB\"/>\n <input type=\"submit\" name=\"TestDB\" value=\"Test ... | [
1
] | [] | [] | [
"cgi",
"jquery",
"python"
] | stackoverflow_0002864877_cgi_jquery_python.txt |
Q:
How can I have multiple navigation paths with Django, like a simplifies wizard path and a full path?
Lets say I have an application with a structure such as:
System
set date
set name
set something
Other
set death ray target
calibrate
and I want to have "back" and "next" buttons on a page. The catch is, ... | How can I have multiple navigation paths with Django, like a simplifies wizard path and a full path? | Lets say I have an application with a structure such as:
System
set date
set name
set something
Other
set death ray target
calibrate
and I want to have "back" and "next" buttons on a page. The catch is, if you're going in via the "wizard", I want the nav path to be something like "set name" -> "set death ray... | [
"Have a look at the django form wizard. \n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"path",
"python",
"redirect"
] | stackoverflow_0003047196_django_django_templates_path_python_redirect.txt |
Q:
Is this a valid quine?
def start(fileName):
fileReader = open(fileName)
for row in fileReader:
print row,
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1:
print "usage quine /path/to/file"
sys.exit(-1)
fileName = sys.argv[0]
start(fileName)
python quine.py foo
A:
No, a quine... | Is this a valid quine? | def start(fileName):
fileReader = open(fileName)
for row in fileReader:
print row,
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1:
print "usage quine /path/to/file"
sys.exit(-1)
fileName = sys.argv[0]
start(fileName)
python quine.py foo
| [
"No, a quine shouldn't take in any input:\n\nA quine takes no input. Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms.\n\nFrom Quine (computing).\nUPDATE\nYou need to encode the source into the quine itself. A quine... | [
9,
2
] | [] | [] | [
"python",
"quine"
] | stackoverflow_0003047583_python_quine.txt |
Q:
Where is Python language used?
I am a web developer and usually use PHP, JavaScript or MySQL.
I have heard lot about Python. But I have no idea where it is used and why it is used.
Just like PHP, ASP, ColdFusion, .NET are used to build websites, and
C, C++, Java are used to build software or desktop apps.
Where ... | Where is Python language used? | I am a web developer and usually use PHP, JavaScript or MySQL.
I have heard lot about Python. But I have no idea where it is used and why it is used.
Just like PHP, ASP, ColdFusion, .NET are used to build websites, and
C, C++, Java are used to build software or desktop apps.
Where does Python fit in this?
What can Py... | [
"Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web ap... | [
23,
17,
14,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003043085_python.txt |
Q:
Django QuerySet filter + order_by + limit
So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work:
e = Exam.objects.all()
total = e.count()
median = int(round(total / 2))
median_exam = Exam.objects.filter(assessment=as... | Django QuerySet filter + order_by + limit | So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work:
e = Exam.objects.all()
total = e.count()
median = int(round(total / 2))
median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1]
median... | [
"Your slice syntax is wrong. The value after the colon is not the count of elements to get, but the index of the end of the slice. Using 'median' on its own without a colon, as you do in your second example, would work.\n"
] | [
5
] | [] | [] | [
"django",
"django_orm",
"django_queryset",
"python"
] | stackoverflow_0003047549_django_django_orm_django_queryset_python.txt |
Q:
How can I update only certain fields in a Django model form?
I have a model form that I use to update a model.
class Turtle(models.Model):
name = models.CharField(max_length=50, blank=False)
description = models.TextField(blank=True)
class TurtleForm(forms.ModelForm):
class Meta:
model = Turtl... | How can I update only certain fields in a Django model form? | I have a model form that I use to update a model.
class Turtle(models.Model):
name = models.CharField(max_length=50, blank=False)
description = models.TextField(blank=True)
class TurtleForm(forms.ModelForm):
class Meta:
model = Turtle
Sometimes I don't need to update the entire model, but only wan... | [
"Only use specified fields:\nclass FirstModelForm(forms.ModelForm):\n class Meta:\n model = TheModel\n fields = ('title',)\n def clean_title(self....\n\nSee http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude\nIt is common to us... | [
9,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003047700_django_python.txt |
Q:
Using end of word mark with unicode in regular expressions in Python
The following matches in Idle, but does not match when run in a method in a module file:
import re
re.search('\\bשלום\\b','שלום עולם',re.UNICODE)
while the following matches in both cases:
import re
re.search('שלום','שלום עולם',re.UNICODE)
(Not... | Using end of word mark with unicode in regular expressions in Python | The following matches in Idle, but does not match when run in a method in a module file:
import re
re.search('\\bשלום\\b','שלום עולם',re.UNICODE)
while the following matches in both cases:
import re
re.search('שלום','שלום עולם',re.UNICODE)
(Notice that stackoverflow erroneously switches the first and second items in ... | [
"Seems to work for me when I'm using unicode strings:\n# -*- coding: utf-8 -*-\n\nimport re\nmatch = re.search(u'\\\\bשלום\\\\b', u'שלום עולם', re.U)\n\nSee it in action: http://codepad.org/xWz5cZj5\n"
] | [
2
] | [] | [] | [
"python",
"regex",
"right_to_left",
"unicode"
] | stackoverflow_0003046528_python_regex_right_to_left_unicode.txt |
Q:
How do I check if two html-strings are equivalent with python?
I need to compare two strings, containing HTML text. The test should return true if the html strings are equivalent, i.e. differ only in whitespace and comments.
Is there any module that can be used for this task?
A:
There's this wrapper around HTMLT... | How do I check if two html-strings are equivalent with python? | I need to compare two strings, containing HTML text. The test should return true if the html strings are equivalent, i.e. differ only in whitespace and comments.
Is there any module that can be used for this task?
| [
"There's this wrapper around HTMLTidy. HTMLTidy allows you to suppress comments and normalize formatting, etc., so that should do the trick.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003048297_python.txt |
Q:
Ubuntu One Folder Sync Filter
I am trying to modify the Ubuntu One File syncing python scripts to not including things like .iso's.
I have got as far as finding this file: /usr/share/pyshared/ubuntuone/u1sync/constants.py
Inside is this piece of code:
import re
# the name of the directory u1sync uses to keep meta... | Ubuntu One Folder Sync Filter | I am trying to modify the Ubuntu One File syncing python scripts to not including things like .iso's.
I have got as far as finding this file: /usr/share/pyshared/ubuntuone/u1sync/constants.py
Inside is this piece of code:
import re
# the name of the directory u1sync uses to keep metadata about a mirror
METADATA_DIR_NA... | [
"The regex documentation for python would be the place to look that up.\nFor isos you could probably just add a \"|.*\\.iso$\" to the last line.\n",
"UbuntuOne should really have a .ignore file or equally.... I want to ignore lots of stuff... .pyc, .blend1 just for start.\nUPDATE: it has - take a look at:\nhttps:... | [
3,
2,
1,
0
] | [] | [] | [
"cloud_platform",
"python",
"ubuntu",
"ubuntu_10.04"
] | stackoverflow_0003005602_cloud_platform_python_ubuntu_ubuntu_10.04.txt |
Q:
Modify Django Forms
I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html.
Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fi... | Modify Django Forms | I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html.
Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fields for day, month and y... | [
"Yes, you can.\nYou just have to override the default widget that gets rendered for the field.\nLook in the docs for all the necessary information.\nYou can also define custom widgets if the necessity arises, e.g. a date field rendered with dropdowns instead of a single text field. \nGoogle for them, there are alr... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003048357_django_django_forms_python.txt |
Q:
How to force GTK window to stay at a certain width, even when widgets try to expand?
How do I force a GTK window object to stay the same size, even when a table inside of it tries to expand?
I've tried using gtk.SHRINK when attaching children to the table, but the TextViews within the table still keep expanding ... | How to force GTK window to stay at a certain width, even when widgets try to expand? | How do I force a GTK window object to stay the same size, even when a table inside of it tries to expand?
I've tried using gtk.SHRINK when attaching children to the table, but the TextViews within the table still keep expanding to way beyond an acceptable width and expanding the window along with it.
| [
"You can set the size manually\npyGtk window docs:\nhttp://www.pygtk.org/docs/pygtk/class-gtkwindow.html\n",
"Text views won't expand if you pack them into a gtk.ScrolledWindow. This is not what you directly asked, but I believe should solve your problem in a better way.\n"
] | [
5,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003047582_pygtk_python.txt |
Q:
Python TCP Server, writing to clients?
I have a tcp server which uses the select call to multiplex reading from clients.
I have a client class (MClient) which manages the decoding of incoming data packets
while(1)
rlist, wlist, xlist = select( input_sockets, output_sockets, [] , 1)
for insock in rlist: #... | Python TCP Server, writing to clients? | I have a tcp server which uses the select call to multiplex reading from clients.
I have a client class (MClient) which manages the decoding of incoming data packets
while(1)
rlist, wlist, xlist = select( input_sockets, output_sockets, [] , 1)
for insock in rlist: #any clients????
if insock is server... | [
"Here's something I wrote a while back to learn about processing multiple connections with a single thread. It is by no means perfect but illustrates what you want to do. The client object manages the read and write streams of the connection, and makes sure the server has the client socket in the right select() l... | [
1,
0
] | [] | [] | [
"python",
"select",
"sockets"
] | stackoverflow_0003043394_python_select_sockets.txt |
Q:
Python 2.6 + JCC + Pylucene issue
Greetings,
I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.
First of all, I build JCC (windows, using cygwin)
python setup.py build
running build
running build_py
[...]
building 'jcc' extension
error: None
python s... | Python 2.6 + JCC + Pylucene issue | Greetings,
I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.
First of all, I build JCC (windows, using cygwin)
python setup.py build
running build
running build_py
[...]
building 'jcc' extension
error: None
python setup.py install
running install
[...]
c... | [
"try:\n\n/cygdrive/f/Python26//python.exe setup.py build\n\nand\n\n/cygdrive/f/Python26//python.exe setup.py build setup.py install\n\nI believe you are using python from cygwin for instaling jcc and python from windows for running...\n",
"Few checkpoints\n\nerror: None mean there is an error on building, it was ... | [
1,
1,
0
] | [] | [] | [
"jcc",
"pylucene",
"python"
] | stackoverflow_0000312444_jcc_pylucene_python.txt |
Q:
Understanding CGI and SQL security from the ground up
This question is for learning purposes. Suppose I am writing a simple SQL admin console using CGI and Python. At http://something.com/admin, this admin console should allow me to modify a SQL database (i.e., create and modify tables, and create and modify recor... | Understanding CGI and SQL security from the ground up | This question is for learning purposes. Suppose I am writing a simple SQL admin console using CGI and Python. At http://something.com/admin, this admin console should allow me to modify a SQL database (i.e., create and modify tables, and create and modify records) using an ordinary form.
In the least secure case, anyb... | [
"Security is not a patch job, it's a holistic approach.\nIncrementally adding security is not a good idea. You should integrate security in your application from the ground up.\nThe best advice I can give you is to try to think like an attacker. Think to yourself: \"If I wanted to do something I'm not supposed to b... | [
3,
2,
2
] | [] | [] | [
"cgi",
"python",
"security",
"sql"
] | stackoverflow_0003048542_cgi_python_security_sql.txt |
Q:
Another floating point question
I have read most of the posts on here regarding floating point, and I understand the basic underlying issue that using IEEE 754 (and just by the nature of storing numbers in binary) certain fractions cannot be represented. I am trying to figure out the following: If both Python and ... | Another floating point question | I have read most of the posts on here regarding floating point, and I understand the basic underlying issue that using IEEE 754 (and just by the nature of storing numbers in binary) certain fractions cannot be represented. I am trying to figure out the following: If both Python and JavaScript use the IEEE 754 standard,... | [
"\ndoing a = 0.3 in Python results in\n 0.29999999999999999\n\nNot quite -- watch:\n>>> a = 0.3\n>>> print a\n0.3\n>>> a\n0.29999999999999999\n\nAs you see, printing a does show 0.3 -- because by default print rounds to 6 or 7 decimal digits, while typing an expression (here a is a single-variable expression) at t... | [
6,
3,
0
] | [] | [] | [
"floating_point",
"javascript",
"python"
] | stackoverflow_0003048865_floating_point_javascript_python.txt |
Q:
How do I override file.write() in Python 3?
The code below works on Python 2.6 but not on Python 3.x:
old_file_write = file.write
class file():
def write(self, d):
if isinstance(d, types.bytes):
self.buffer.write(d)
else:
old_file_write(d)
# ... some code I cannot cha... | How do I override file.write() in Python 3? | The code below works on Python 2.6 but not on Python 3.x:
old_file_write = file.write
class file():
def write(self, d):
if isinstance(d, types.bytes):
self.buffer.write(d)
else:
old_file_write(d)
# ... some code I cannot change or do not want to change
f = open("x")
f.writ... | [
"I see two problems.\n1: Your file class isn't inheriting from any specific class. If I've interpreted the situation correctly, it should be a subclass of io.TextIOWrapper.\n2: In both Python 2.6 and 3.x, the types module (which would need to be imported in the first place) has no element bytes. The recommended met... | [
3,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003046066_python_python_3.x.txt |
Q:
Is there an open source cross-platform push server?
I'm currently in need of a (preferably open-source) free push server, that supports both linux and windows. I need something similar to the Ajax Push Engine, but that project unfortunatelly does not work on windows (I could use a virtual machine, but that's not w... | Is there an open source cross-platform push server? | I'm currently in need of a (preferably open-source) free push server, that supports both linux and windows. I need something similar to the Ajax Push Engine, but that project unfortunatelly does not work on windows (I could use a virtual machine, but that's not what I'm looking for).
I need to be able to push informati... | [
"I like ActiveMQ very much, especially together with Camel. \nFor push web technology, cometd comes first to mind.\n"
] | [
2
] | [] | [] | [
"comet",
"php",
"push",
"python",
"server_push"
] | stackoverflow_0003048941_comet_php_push_python_server_push.txt |
Q:
SQLAlchemy: How to group by two fields and filter by date
So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month.
table.id
table.datestamp
table.field1
table.field2
There should be no duplicate record with the same field1 + 2 compound value in the last mo... | SQLAlchemy: How to group by two fields and filter by date | So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month.
table.id
table.datestamp
table.field1
table.field2
There should be no duplicate record with the same field1 + 2 compound value in the last month.
The steps in my head are:
Group by the two fields
Look ba... | [
"Following should point you in the right direction, also see inline comments:\nqry = (session.query(\n table.c.field1,\n table.c.field2, \n\n # #strftime* for year-month works on sqlite; \n \n # @todo: find proper function for mysql (as in the question)\n # Also it... | [
26
] | [] | [] | [
"group_by",
"mysql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003044455_group_by_mysql_python_sql_sqlalchemy.txt |
Q:
Specifics of List Membership
How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does:
def main():
obj = fancy_obj(arg='C:\\')
needle = (50, obj)
haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle]
print (1, fancy_obj(arg='C:\\'),... | Specifics of List Membership | How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does:
def main():
obj = fancy_obj(arg='C:\\')
needle = (50, obj)
haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle]
print (1, fancy_obj(arg='C:\\'),) in haystack
print needle in ... | [
"From (An Unofficial) Python Reference Wiki:\nFor the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.\nSo in your example, if the fancy_obj class stored the value of arg in an instance variable and were to implement an __eq__ method that returned True if the ... | [
4,
4,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003049651_list_python.txt |
Q:
Convert between python array and .NET Array
I have a python method that returns a Python byte array.array('c').
Now, I want to copy this array using System.Runtime.InteropServices.Marshal.Copy. This method however expects a .NET array.
import array
from System.Runtime.InteropServices import Marshal
bytes = array.... | Convert between python array and .NET Array | I have a python method that returns a Python byte array.array('c').
Now, I want to copy this array using System.Runtime.InteropServices.Marshal.Copy. This method however expects a .NET array.
import array
from System.Runtime.InteropServices import Marshal
bytes = array.array('c')
bytes.append('a')
bytes.append('b')
by... | [
"To convert a python array to a .NET Array:\nimport array\nfrom System import Array, Char\n\nx = array.array('c', 'abc')\n\ny = Array[Char](x)\n\nHere is some information on creating typed Arrays in IronPython:\nhttp://www.ironpython.info/index.php?title=Typed_Arrays_in_IronPython\n"
] | [
7
] | [] | [] | [
".net",
"arrays",
"ironpython",
"marshalling",
"python"
] | stackoverflow_0003020654_.net_arrays_ironpython_marshalling_python.txt |
Q:
How can I prevent a mod_wsgi django application from repeated reloads?
My mod_wsgi django application seems to keep getting reloaded for the first several requests that the client makes. This is killing my performance
After enough requests it seems to settle down, and the application no longer seems to be getting ... | How can I prevent a mod_wsgi django application from repeated reloads? | My mod_wsgi django application seems to keep getting reloaded for the first several requests that the client makes. This is killing my performance
After enough requests it seems to settle down, and the application no longer seems to be getting reloaded. Any thoughts on why this is happening and how I can prevent it?
(I... | [
"This is likely because you are using embedded mode of mod_wsgi and Apache on a UNIX system, possibly even with Apache prefork MPM which makes it all worse. In short, in that configuration Apache it is a multi process web server. Combine that with fact that default is to lazily load application on first request, yo... | [
5
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0003049646_apache_django_mod_wsgi_python.txt |
Q:
Django ORM and PostgreSQL connection limits
I'm running a Django project on Postgresql 8.1.21 (using Django 1.1.1, Python2.5, psycopg2, Apache2 with mod_wsgi 3.2). We've recently encountered this lovely error:
OperationalError: FATAL: connection limit exceeded for non-superusers
I'm not the first person to run up... | Django ORM and PostgreSQL connection limits | I'm running a Django project on Postgresql 8.1.21 (using Django 1.1.1, Python2.5, psycopg2, Apache2 with mod_wsgi 3.2). We've recently encountered this lovely error:
OperationalError: FATAL: connection limit exceeded for non-superusers
I'm not the first person to run up against this. There's a lot of discussion about ... | [
"This could be caused by other things. For example, configuring Apache/mod_wsgi in a way that theoretically it could accept more concurrent requests than what the database itself may be able to accept at the same time. Have you reviewed your Apache/mod_wsgi configuration and compared limit on maximum clients to tha... | [
1
] | [] | [] | [
"database",
"django",
"django_orm",
"postgresql",
"python"
] | stackoverflow_0003049625_database_django_django_orm_postgresql_python.txt |
Q:
Which is faster?
is opening a large file once reading it completely once to list faster (or) opening smaller files whose total sum of size is equal to large file and loading smaller file into list manupalating one by one faster?
which is faster?? is the difference is time large enough to impact my program??
total... | Which is faster? | is opening a large file once reading it completely once to list faster (or) opening smaller files whose total sum of size is equal to large file and loading smaller file into list manupalating one by one faster?
which is faster?? is the difference is time large enough to impact my program??
total time difference of le... | [
"It depends if your data fit in your available memory. If you need to resort to paging, or virtual memory, then opening a single giant file might become slower than opening more smaller files. This will be even more true if the computation you need to make creates intermediate variables that won't fit in the physic... | [
6,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003047799_python.txt |
Q:
Access Denied when using popen - Python
I'm using popen in order to send a few commands within a Django app.
Problem is that I'm getting [Error 5] Access Denied, apparently I have no access to cmd.exe, which popen seems to use.
WindowsError at /test/cmd/
[Error 5] Access is denied: 'C:\WINDOWS\system32\cmd.exe /c... | Access Denied when using popen - Python | I'm using popen in order to send a few commands within a Django app.
Problem is that I'm getting [Error 5] Access Denied, apparently I have no access to cmd.exe, which popen seems to use.
WindowsError at /test/cmd/
[Error 5] Access is denied: 'C:\WINDOWS\system32\cmd.exe /c dir'
I reckon this is because the app sits ... | [
"Why you have the problem:\nWhat you forgot to mention in your question is that you are trying to run it under IIS with ISAPI > ISAPI_WSGI (or FastCGI on IIS 7/6 with flup as FastCGI wrapper for WSGI). \nIt's truly an execute permission issue on c:\\windows\\system32\\cmd.exe \nI had exactly same problem on IIS 6. ... | [
4
] | [] | [] | [
"cmd",
"django",
"popen",
"python",
"windows"
] | stackoverflow_0003049199_cmd_django_popen_python_windows.txt |
Q:
Hot python input loop
I'd like to have something similar to the following pseudo code:
while input is not None and timer < 5:
input = getChar()
timer = time.time() - start
if timer >= 5:
print "took too long"
else:
print input
Anyway to do this without threading? I would like an input method that... | Hot python input loop | I'd like to have something similar to the following pseudo code:
while input is not None and timer < 5:
input = getChar()
timer = time.time() - start
if timer >= 5:
print "took too long"
else:
print input
Anyway to do this without threading? I would like an input method that returns whatever has been ... | [
"On *nix you want select with sys.stdin. On Windows you want msvcrt.kbhit() and msvcrt.getch().\n"
] | [
4
] | [] | [] | [
"input",
"loops",
"python",
"timer"
] | stackoverflow_0003050133_input_loops_python_timer.txt |
Q:
Restarting IIS6 - Python
I'm serving a Django app behind IIS 6. I'm wondering if I can restart IIS 6 within Python/Django and what one of the best ways to do would be.
Help would be great!
A:
Besides what's already suggested, you can also use WMI via either the Win32_Service or the IIsWebService class, which in... | Restarting IIS6 - Python | I'm serving a Django app behind IIS 6. I'm wondering if I can restart IIS 6 within Python/Django and what one of the best ways to do would be.
Help would be great!
| [
"Besides what's already suggested, you can also use WMI via either the Win32_Service or the IIsWebService class, which inherits from it. There is a Python WMI wrapper available, which is based on pywin32.\nUPDATE: A quick test of the following worked for me.\nimport wmi\n\nc = wmi.WMI()\n\nfor service in c.Win32_S... | [
2,
1,
1
] | [] | [] | [
"django",
"iis",
"iis_6",
"python",
"windows"
] | stackoverflow_0003036157_django_iis_iis_6_python_windows.txt |
Q:
Updating a module level shared dictionary
A module level dictionary 'd' and is accessed by different threads/requests in a django web application. I need to update 'd' every minute with a new data and the process takes about 5 seconds.
What could be best solution where I want the users to get either the old value... | Updating a module level shared dictionary | A module level dictionary 'd' and is accessed by different threads/requests in a django web application. I need to update 'd' every minute with a new data and the process takes about 5 seconds.
What could be best solution where I want the users to get either the old value or the new value of d and nothing in between. ... | [
"Probably best -- at module level:\nimport threading\ndlock = threading.Lock()\nd = {}\n\nand every access to d (not just modifications!) is within a with block:\nwith dlock:\n found = k in d\n\nand the like (if you're on Python 2.5, you'll also need to have from __future__ import with_statement at the top of yo... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003050109_python.txt |
Q:
Google finance quotes search box
Trying to implement a web service which should have exactly the same function as http://www.google.com/finance the search quotes box
when user type the stock name or company name, the right stock name is suggested while typing.
my service will using historical information from goo... | Google finance quotes search box | Trying to implement a web service which should have exactly the same function as http://www.google.com/finance the search quotes box
when user type the stock name or company name, the right stock name is suggested while typing.
my service will using historical information from google finance, so get proper quote name ... | [
"The Google Finance API is documented here.\nTo access it from Python, use the gdata python client.\n"
] | [
0
] | [] | [] | [
"google_finance_api",
"python"
] | stackoverflow_0003049819_google_finance_api_python.txt |
Q:
Parsing email with Python
I'm writing a Python script to process emails returned from Procmail. As suggested in this question, I'm using the following Procmail config:
:0:
|$HOME/process_mail.py
My process_mail.py script is receiving an email via stdin like this:
From hostname Tue Jun 15 21:43:30 2010
Received: (... | Parsing email with Python | I'm writing a Python script to process emails returned from Procmail. As suggested in this question, I'm using the following Procmail config:
:0:
|$HOME/process_mail.py
My process_mail.py script is receiving an email via stdin like this:
From hostname Tue Jun 15 21:43:30 2010
Received: (qmail 8580 invoked from network... | [
"You must ensure that the lines are not accidentally broken (as they are above, though it's hard to say if that was a copy-paste problem) -- with an intact message such as:\nReceived: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400\nReceived: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-3... | [
10,
4,
2
] | [] | [] | [
"email",
"mime",
"parsing",
"python"
] | stackoverflow_0003050298_email_mime_parsing_python.txt |
Q:
Help with pyHook error
I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed.
here is the source:
import pyHook
import pythoncom
hm = pyHook.HookManager()
def OnKeyboardEvent(event):
if event.Alt == 32 and event.KeyID == 49:
print 'HERE WILL B... | Help with pyHook error | I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed.
here is the source:
import pyHook
import pythoncom
hm = pyHook.HookManager()
def OnKeyboardEvent(event):
if event.Alt == 32 and event.KeyID == 49:
print 'HERE WILL BE THE CODE'
hm.KeyDown = On... | [
"Note from the tutorial that you need a return value at the end of your handler:\ndef OnKeyboardEvent(event):\n if event.Alt == 32 and event.KeyID == 49:\n print 'HERE WILL BE THE CODE'\n\n # return True to pass the event to other handlers\n return True\n\nI agree it's ambiguous from the docs whethe... | [
9
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003049068_python_windows.txt |
Q:
Running pdb from within pdb
I'm debugging an script that I'm writing and the result of
executing a statement from pdb does not make sense so my
natural reaction is to try to trace it with pdb.
To paraphrase:
Yo dawg, I like python, so can you put my pdb in my pdb so I can debug while I debug?
A:
It sounds lik... | Running pdb from within pdb | I'm debugging an script that I'm writing and the result of
executing a statement from pdb does not make sense so my
natural reaction is to try to trace it with pdb.
To paraphrase:
Yo dawg, I like python, so can you put my pdb in my pdb so I can debug while I debug?
| [
"It sounds like you're looking for something listed fairly prominently in the docs, which is the set of methods that let you programmatically invoke the debugger on expressions, code in strings, or functions:\n\nhttp://docs.python.org/library/pdb.html#pdb.run\nhttp://docs.python.org/library/pdb.html#pdb.runeval\nht... | [
0
] | [] | [] | [
"nested",
"pdb",
"python"
] | stackoverflow_0003048754_nested_pdb_python.txt |
Q:
How to write lazy functions which are chainable, in python?
I want to write functions which are lazy as well as chainable. What would be the best way.
I know that one way would be to do yield instead of return.
I want these functions to be lazy in the way similar to how sqlalchemy functions are lazy when asked to ... | How to write lazy functions which are chainable, in python? | I want to write functions which are lazy as well as chainable. What would be the best way.
I know that one way would be to do yield instead of return.
I want these functions to be lazy in the way similar to how sqlalchemy functions are lazy when asked to fetch the data from DB.
| [
"Generators (functions with yield instead of return) can indeed be seen as \"lazy\" (and itertools.chain can chain them just as well as any other iterator, if that's what you mean by \"chainable\").\nBut if by \"chainable\" (and lazy) you mean you want to call fee().fie().fo().fum() and have all the \"hard work\" h... | [
7
] | [] | [] | [
"lazy_evaluation",
"python"
] | stackoverflow_0003050411_lazy_evaluation_python.txt |
Q:
Parse (extract) DTMF in Python
If I have a recorded audio file (MP3), is there any way to get the figure out the DTMF tones that were recorded in pure Python?
(If pure python is not available, then Java is okay too. The point being that it should be able to run in Google Appengine)
A:
First you will need to deco... | Parse (extract) DTMF in Python | If I have a recorded audio file (MP3), is there any way to get the figure out the DTMF tones that were recorded in pure Python?
(If pure python is not available, then Java is okay too. The point being that it should be able to run in Google Appengine)
| [
"First you will need to decode the MP3 into an uncompressed format of raw samples at a given bit depth and sampling rate. Then you look for the frequencies that make up each DTMF tone. Though FFT can be used for this, the cannonical algorithm is The Goertzel Algorithm, which makes use of the fact that you know what... | [
6,
1
] | [] | [] | [
"dtmf",
"python"
] | stackoverflow_0003050528_dtmf_python.txt |
Q:
accessing files after setup.py install
I'm developing a python application and have a question regarding coding it so that it still works after an user has installed it on his or her machine via setup.py install or similar.
In one of my files, I use the following:
file = "TestParser/View/MainWindow.ui"
cwd = os.ge... | accessing files after setup.py install | I'm developing a python application and have a question regarding coding it so that it still works after an user has installed it on his or her machine via setup.py install or similar.
In one of my files, I use the following:
file = "TestParser/View/MainWindow.ui"
cwd = os.getcwd()
argv_path = os.path.dirname(sys.argv[... | [
"With setup.py there is never a simple answer that works for all scenarios. Setup.py is a huge PITA to get working with different installation procedures (e.g., \"setup.py install\", py2exe, py2app).\nFor example, in my app, I have this code to find files needed by the app:\ndef getHome():\n if hasattr(sys, \"fro... | [
1
] | [] | [] | [
"file",
"py2exe",
"python",
"setup.py"
] | stackoverflow_0002985755_file_py2exe_python_setup.py.txt |
Q:
Bundle a Python app as a single file to support add-ons or extensions?
There are several utilities — all with different procedures, limitations, and target operating systems — for getting a Python package and all of its dependencies and turning them into a single binary program that is easy to ship to customers:
... | Bundle a Python app as a single file to support add-ons or extensions? | There are several utilities — all with different procedures, limitations, and target operating systems — for getting a Python package and all of its dependencies and turning them into a single binary program that is easy to ship to customers:
http://wiki.python.org/moin/Freeze
http://www.pyinstaller.org/
http://www.py... | [
"You should be able to have a plugins directory that your application scans at runtime (or later) to import the code in question. Here's an example that should work with regular .py or .pyc code that even works with plugins stored inside zip files (so users could just drop someplugin.zip in the 'plugins' directory... | [
7,
0
] | [] | [] | [
"py2app",
"py2exe",
"pyinstaller",
"python",
"software_distribution"
] | stackoverflow_0002876967_py2app_py2exe_pyinstaller_python_software_distribution.txt |
Q:
SQLAlchemy session management in long-running process
Scenario:
A .NET-based application server (Wonderware IAS/System Platform) hosts automation objects that communicate with various equipment on the factory floor.
CPython is hosted inside this application server (using Python for .NET).
The automation objects h... | SQLAlchemy session management in long-running process | Scenario:
A .NET-based application server (Wonderware IAS/System Platform) hosts automation objects that communicate with various equipment on the factory floor.
CPython is hosted inside this application server (using Python for .NET).
The automation objects have scripting functionality built-in (using a custom, .NET-... | [
"The described decorator is suitable for long running applications, but you can run into trouble if you accidentally share objects between requests. To make the errors appear earlier and not corrupt anything it is better to discard the session with session.remove().\ntry:\n try:\n retval = func(*args, **k... | [
4,
1
] | [] | [] | [
"python",
"sqlalchemy",
"wonderware"
] | stackoverflow_0001421502_python_sqlalchemy_wonderware.txt |
Q:
How do you efficiently bulk index lookups?
I have these entity kinds:
Molecule
Atom
MoleculeAtom
Given a list(molecule_ids) whose lengths is in the hundreds, I need to get a dict of the form {molecule_id: list(atom_ids)}. Likewise, given a list(atom_ids) whose length is in the hunreds, I need to get a dict of th... | How do you efficiently bulk index lookups? | I have these entity kinds:
Molecule
Atom
MoleculeAtom
Given a list(molecule_ids) whose lengths is in the hundreds, I need to get a dict of the form {molecule_id: list(atom_ids)}. Likewise, given a list(atom_ids) whose length is in the hunreds, I need to get a dict of the form {atom_id: list(molecule_ids)}.
Both of th... | [
"Your third approach (denormalizing the data) is, generally speaking, the right one. In particular, db.get by keys is indeed about as fast as the datastore gets.\nOf course, you'll need to denormalize the other way around too (entity with key name atom ID, value a list of molecule IDs) and will need to update ever... | [
3
] | [] | [] | [
"google_app_engine",
"indexing",
"python",
"scalability"
] | stackoverflow_0003050304_google_app_engine_indexing_python_scalability.txt |
Q:
A simple Python extension in C
I am trying to create a simple python extension module. I compiled the following code into a transit.so dynamic module
#include <python2.6/Python.h>
static PyObject*
_print(PyObject* self, PyObject* args)
{
return Py_BuildValue("i", 10);
}
static PyMethodDef TransitMethods[] =... | A simple Python extension in C | I am trying to create a simple python extension module. I compiled the following code into a transit.so dynamic module
#include <python2.6/Python.h>
static PyObject*
_print(PyObject* self, PyObject* args)
{
return Py_BuildValue("i", 10);
}
static PyMethodDef TransitMethods[] = {
{"print", _print, METH_VARARG... | [
"I'm guessing that it has to do with using a keyword as a function name. I tried defining a function print() in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.\n"
] | [
4
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003050940_c_python.txt |
Q:
Python __subclasses__() not listing subclasses
I cant seem to list all derived classes using the __subclasses__() method. Here's my directory layout:
import.py
backends
__init__.py
--digger
__init__.py
base.py
test.py
--plugins
plugina_plugin.py
From i... | Python __subclasses__() not listing subclasses | I cant seem to list all derived classes using the __subclasses__() method. Here's my directory layout:
import.py
backends
__init__.py
--digger
__init__.py
base.py
test.py
--plugins
plugina_plugin.py
From import.py i'm calling test.py. test.py in turn iterat... | [
"There were no other base.py files. I'm on a WinXP (SP2) with Python 2.6. I added another class to my test.py file called PluginB which used BasePlugin as the base class. When i did \n print PluginA.__mro__\n print PluginB.__mro__\n\nI got:\n(<class 'plugina_plugin.PluginA'>, <class 'base.BasePlugin'>, <type ... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0003048337_python.txt |
Q:
How can I paste some string to the active window in Python?
Possible Duplicate:
How do I copy a string to the clipboard on Windows using Python?
Can someone make me an example or explain to me how can I paste something to the active window with Python?
A:
It is easiest if you use the SendKeys package. You can... | How can I paste some string to the active window in Python? |
Possible Duplicate:
How do I copy a string to the clipboard on Windows using Python?
Can someone make me an example or explain to me how can I paste something to the active window with Python?
| [
"It is easiest if you use the SendKeys package. You can find a Windows installer for various Python versions here.\nThe simplest use case, sending plain text, is very simple:\nimport SendKeys\nSendKeys.SendKeys(\"Hello world\")\n\nYou can do all sorts of nifty things using key-codes to represent for unprintable ch... | [
2
] | [] | [] | [
"python",
"sendkeys",
"windows"
] | stackoverflow_0003051030_python_sendkeys_windows.txt |
Q:
How do I use python to hit this command and return the result?
$whois abc.com
I want to use python to hit this command, and then give the result as a String of text. How can I do that?
A:
You can use subprocess, for example:
from subprocess import Popen, PIPE
output = Popen(["/usr/bin/whois", "abc.com"], stdout... | How do I use python to hit this command and return the result? | $whois abc.com
I want to use python to hit this command, and then give the result as a String of text. How can I do that?
| [
"You can use subprocess, for example:\nfrom subprocess import Popen, PIPE\noutput = Popen([\"/usr/bin/whois\", \"abc.com\"], stdout = PIPE).communicate()[0]\n\nThe stdout = PIPE parameter forces stdout to be written to a temporary pipe instead of the console (if you don't want that, remove the stdout parameter).\n"... | [
4,
1,
0
] | [] | [] | [
"linux",
"python",
"unix",
"whois"
] | stackoverflow_0003040886_linux_python_unix_whois.txt |
Q:
redirection follow by post
just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected?
Is the technique used is to open up new... | redirection follow by post | just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected?
Is the technique used is to open up new browser window and do a ajax PO... | [
"It can work like this:\non air ticket booking system you have a html form pointing on certain airline booking website (by action parameter). If user submits data then data lands on airline booking website and this website proceed the request.\nUsuallly people want to get back to the first site. This can be done by... | [
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0003050477_javascript_python.txt |
Q:
Image Gurus: Optimize my Python PNG transparency function
I need to replace all the white(ish) pixels in a PNG image with alpha transparency.
I'm using Python in AppEngine and so do not have access to libraries like PIL, imagemagick etc. AppEngine does have an image library, but is pitched mainly at image resizing... | Image Gurus: Optimize my Python PNG transparency function | I need to replace all the white(ish) pixels in a PNG image with alpha transparency.
I'm using Python in AppEngine and so do not have access to libraries like PIL, imagemagick etc. AppEngine does have an image library, but is pitched mainly at image resizing.
I found the excellent little pyPNG module and managed to knoc... | [
"Honestly, the only heuristic I could conceive is picking a few arbitrary, random points on your image and using a flood fill.\nThis only works well if your image as large contiguous white portions (if your image is an object with no or little holes in front of a background, then you're in luck -- you actually have... | [
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"google_app_engine",
"image",
"png",
"python"
] | stackoverflow_0003045377_algorithm_google_app_engine_image_png_python.txt |
Q:
Operating on rows and then on columns of a matrix produces code duplication
I have the following (Python) code to check if there are any rows or columns that contain the same value:
# Test rows ->
# Check each row for a win
for i in range(self.height): # For each row ...
... | Operating on rows and then on columns of a matrix produces code duplication | I have the following (Python) code to check if there are any rows or columns that contain the same value:
# Test rows ->
# Check each row for a win
for i in range(self.height): # For each row ...
firstValue = None # Initialize first value ... | [
"To check whether all elements in a row are equal, I'd suggest building a python set of the row and then check whether it has only one element. Similarly for the columns.\nE.g. like this\ndef testRowWin(b):\n for row in b:\n if len(set(row)) == 1:\n return True\n return False\n\ndef testColW... | [
2,
2,
1
] | [] | [] | [
"code_duplication",
"python",
"refactoring"
] | stackoverflow_0003051570_code_duplication_python_refactoring.txt |
Q:
can the python wave module accept StringIO object
i'm trying to use the wave module to read wav files in python.
whats not typical of my applications is that I'm NOT using a file or a filename to read the wav file, but instead i have the wav file in a buffer.
And here's what i'm doing
import StringIO
buffer = S... | can the python wave module accept StringIO object | i'm trying to use the wave module to read wav files in python.
whats not typical of my applications is that I'm NOT using a file or a filename to read the wav file, but instead i have the wav file in a buffer.
And here's what i'm doing
import StringIO
buffer = StringIO.StringIO()
buffer.output(wav_buffer)
file = wa... | [
"try this:\nimport StringIO\n\nbuffer = StringIO.StringIO(wav_buffer)\nfile = wave.open(buffer, 'r')\n\n",
"buffer = StringIO.StringIO()\nbuffer.output(wav_buffer)\n\nA StringIO doesn't work like that. It's not a pipe that's connected to itself: when you read(), you don't receive data that you previously passed t... | [
2,
2
] | [] | [] | [
"audio",
"python",
"wave"
] | stackoverflow_0003051747_audio_python_wave.txt |
Q:
Generating very large XML files in Python?
Does anyone know of a memory efficient way to generate very large xml files (e.g. 100-500 MiB) in Python?
I've been utilizing lxml, but memory usage is through the roof.
A:
Perhaps you could use a templating engine instead of generating/building the xml yourself?
Gens... | Generating very large XML files in Python? | Does anyone know of a memory efficient way to generate very large xml files (e.g. 100-500 MiB) in Python?
I've been utilizing lxml, but memory usage is through the roof.
| [
"Perhaps you could use a templating engine instead of generating/building the xml yourself? \nGenshi for example is xml-based and supports streaming output. A very basic example:\nfrom genshi.template import MarkupTemplate\n\ntpl_xml = '''\n<doc xmlns:py=\"http://genshi.edgewall.org/\">\n<p py:for=\"i in data\">${i... | [
11,
2,
2,
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003049188_lxml_python_xml.txt |
Q:
exeuting command in background
Trying to execute shell command in background using pythons commands module
>>>import commands
>>>output = commands.getstatusoutput("find / > tmp.txt &")
sh: Syntax error: ";" unexpected
Can anyone explain what is wrong with the syntax ? How should it be executed then ?
Tazim.
A... | exeuting command in background | Trying to execute shell command in background using pythons commands module
>>>import commands
>>>output = commands.getstatusoutput("find / > tmp.txt &")
sh: Syntax error: ";" unexpected
Can anyone explain what is wrong with the syntax ? How should it be executed then ?
Tazim.
| [
"According to the getstatusoutput documentation, commands.getstatusoutput(cmd) is executed as\n{ cmd ; } 2>&1\n\nso your command is run as if it was\n{ find / > tmp.txt & ; } 2 >& 1\n\nand the ; is not valid after the & in such a command.\nYou should use the subprocess module to simulate the old-style os.spawn com... | [
7,
1,
1
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0003052466_python_shell.txt |
Q:
Django: Get remote IP address inside settings.py
I want to enable debug (DEBUG = True) For my Django project only if it runs on localhost. How can I get user IP address inside settings.py? I would like something like this to work:
#Debugging only on localhost
if user_ip = '127.0.0.1':
DEBUG = True
else:
DE... | Django: Get remote IP address inside settings.py | I want to enable debug (DEBUG = True) For my Django project only if it runs on localhost. How can I get user IP address inside settings.py? I would like something like this to work:
#Debugging only on localhost
if user_ip = '127.0.0.1':
DEBUG = True
else:
DEBUG = False
How do I put user IP address in user_ip ... | [
"Maybe it is enough for you to specify some INTERNAL_IPS:\nhttps://docs.djangoproject.com/en/dev/ref/settings/#internal-ips\n",
"use this.\nimport socket\n\nprint socket.gethostbyname_ex(socket.gethostname())[2]\n\nedit: ah, i had misunderstood the topic.\n",
"Try this in you settings.py\nclass LazyDebugSetting... | [
5,
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003051365_django_python.txt |
Q:
Server-side rendering using blender and twisted (python)
The project I am working on at the moment basically takes in an image and then renders a video using blender from the command line. At the moment I am using Twisted to deal with the requests but there is certainly something that I am doing wrong as it is not... | Server-side rendering using blender and twisted (python) | The project I am working on at the moment basically takes in an image and then renders a video using blender from the command line. At the moment I am using Twisted to deal with the requests but there is certainly something that I am doing wrong as it is not working how I would like it to. You can see the jist of the p... | [
"Is Twisted the right choice for this? - Perhaps.\nAre there other options? - Yes.\nIf not, is my implementation of the system flawed? - Yes. It looks to me that your subprocess call is blocking: p.wait()\nIt is possible to do what it sounds like you're trying to do in Twisted, but you are a very long way from it.\... | [
3
] | [] | [] | [
"blender",
"python",
"rendering",
"twisted"
] | stackoverflow_0003052230_blender_python_rendering_twisted.txt |
Q:
Django templates tag error
def _table_(request,id,has_permissions):
dict = {}
dict.update(get_newdata(request,rid))
return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)}))
In templates the code is a... | Django templates tag error | def _table_(request,id,has_permissions):
dict = {}
dict.update(get_newdata(request,rid))
return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)}))
In templates the code is as,
{% if has_permissions == "1" ... | [
"Versions of Django before 1.2 do not support relational operators in {% if %}. Use {% ifequal %} or a bare {% if %} instead.\n"
] | [
2
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003052549_django_django_templates_django_views_python.txt |
Q:
os.environ() giving errors while setting for Hudson
I want a small python script to set the HUDSON_HOME environment variable.
When using the shell, I can easily do this using >>set HUDSON_HOME=http://localhost:8080
But how can I do the same directly through python?? I don't want to do it by passing the command lin... | os.environ() giving errors while setting for Hudson | I want a small python script to set the HUDSON_HOME environment variable.
When using the shell, I can easily do this using >>set HUDSON_HOME=http://localhost:8080
But how can I do the same directly through python?? I don't want to do it by passing the command line to os.system().. can os.environ() be of any help??
I ha... | [
"os.environ is a dictionary represenation of the environment. You'd use it like this:\n>>> import os\n>>> os.environ['HUDSON_HOME'] = 'http://localhost:8080'\n\nHowever, it cannot modify the environment of the parent process AFAIK.\n",
"I am unaware of any way to do this as you've requested, as modifying the envi... | [
3,
0
] | [] | [] | [
"environment_variables",
"hudson",
"python"
] | stackoverflow_0003052534_environment_variables_hudson_python.txt |
Q:
Multi-part template issue with Jinja2
When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single string to the web-server (CherryPy in this case).
My first approach is as follows...
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=Fil... | Multi-part template issue with Jinja2 | When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single string to the web-server (CherryPy in this case).
My first approach is as follows...
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(''))
tmpl = env.get_template... | [
"If you don't want to do template inheritance, have you considered include?\n{% include 'header.html' %}\n Body\n{% include 'footer.html' %}\n\n"
] | [
11
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0003052702_jinja2_python_templates.txt |
Q:
AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime?
If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example:
class MyEntity(db.Expando):
x = db.IntegerProperty()
my_entity = MyEntity(x=1)... | AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime? | If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example:
class MyEntity(db.Expando):
x = db.IntegerProperty()
my_entity = MyEntity(x=1)
my_entity.y = 2
But suppose I have the name of the dynamic property in a variable... ... | [
"Yes, you can. You simply have to set the attribute on the entity:\nsome_name = 'wee'\nsetattr(my_entity, some_name, 'value')\nprint getattr(my_entity, some_name)\nmy_entity.put()\n\nsetattr and getattr are built-in functions of Python used to set/get attributes with arbitrary names on an object.\n"
] | [
6
] | [] | [] | [
"entity",
"google_app_engine",
"google_cloud_datastore",
"properties",
"python"
] | stackoverflow_0003052821_entity_google_app_engine_google_cloud_datastore_properties_python.txt |
Q:
store/load numpy array from binary files
I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix.
def saveArrayToFile(data, fileName):
with open(fileName, 'w') as file:
a = ar... | store/load numpy array from binary files | I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix.
def saveArrayToFile(data, fileName):
with open(fileName, 'w') as file:
a = array.array('f')
nSamples, ndim = data.s... | [
"Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.\n"
] | [
2
] | [] | [] | [
"binaryfiles",
"file",
"python"
] | stackoverflow_0003052669_binaryfiles_file_python.txt |
Q:
Fully customized login system in Django?
I am currently writing an application which I plan to sell as SaaS. Without giving away "secrets," I can say that it is basically a "document editing system" in which many users will be submitting documents.
The basic heirarchy is this:
Institution
Individual
Document
Sub-... | Fully customized login system in Django? | I am currently writing an application which I plan to sell as SaaS. Without giving away "secrets," I can say that it is basically a "document editing system" in which many users will be submitting documents.
The basic heirarchy is this:
Institution
Individual
Document
Sub-document
So each Individual should be able to... | [
"What you're looking for is authorization, not authentication. Django's built-in authorization system is fairly crude, as you've discovered. You'll need something like django-authority if you want a more complete solution.\n",
"The auth module is typically used to cover authentication cases.\nGives you groups (In... | [
3,
1,
0
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0003050063_authentication_django_python.txt |
Q:
Python Attributes and Inheritance
Say I have the folowing code:
class Class1(object):
def __init__(self):
self.my_attr = 1
self.my_other_attr = 2
class Class2(Class1):
def __init__(self):
super(Class1,self).__init__()
Why does Class2 not inherit the attributes of Class1?
A:
Yo... | Python Attributes and Inheritance | Say I have the folowing code:
class Class1(object):
def __init__(self):
self.my_attr = 1
self.my_other_attr = 2
class Class2(Class1):
def __init__(self):
super(Class1,self).__init__()
Why does Class2 not inherit the attributes of Class1?
| [
"You used super wrong, change it to\nsuper(Class2, self).__init__()\n\nBasically you tell super to look above the given class, so if you give Class1 then that __init__ method is never called.\n",
"Because you're giving super the wrong class. It should be:\nclass Class2(Class1):\n\n def __init__(self):\n ... | [
10,
4
] | [] | [] | [
"attributes",
"inheritance",
"python"
] | stackoverflow_0003053256_attributes_inheritance_python.txt |
Q:
How to read watermarks with Python?
Is there any way to read metadata - watermarks from image files with Python?
A:
If by watermark you mean some "signature" image content added to an image in order to mark it, then no. Such a watermark is merged with the original image and thus an integral part of it. If you me... | How to read watermarks with Python? | Is there any way to read metadata - watermarks from image files with Python?
| [
"If by watermark you mean some \"signature\" image content added to an image in order to mark it, then no. Such a watermark is merged with the original image and thus an integral part of it. If you mean meta-data info then yes, this can be read: but you don't specify whether you mean programmatically, or what langu... | [
3
] | [] | [] | [
"python",
"watermark"
] | stackoverflow_0003053480_python_watermark.txt |
Q:
multiple custom app in django
I want to have two custom made app dealing with two different tasks.
i have a page(template) where the data from the both app come together.
how to deploy url for that, in the common urls.py so that the two app work together. how to integrate the views from both app to return data to ... | multiple custom app in django | I want to have two custom made app dealing with two different tasks.
i have a page(template) where the data from the both app come together.
how to deploy url for that, in the common urls.py so that the two app work together. how to integrate the views from both app to return data to same template simultaneously. is th... | [
"You'll need to be a bit more specific. There's nothing magical about an app in Django - it's just a collection of models and views. If you need access to some of the models from one app in another app, just import them and use them as normal.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003053442_django_python.txt |
Q:
Beginner questions regarding Python classes
I am new to Python so please don't flame me if I ask something too noobish :)
1.
Consider I have a class:
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def wow():
print 5 * 5
Now I try to create an object of the class:
x = T... | Beginner questions regarding Python classes | I am new to Python so please don't flame me if I ask something too noobish :)
1.
Consider I have a class:
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def wow():
print 5 * 5
Now I try to create an object of the class:
x = Test(3, 4)
This works as expected. However, when ... | [
"If you do that :\ndef __init__(self):\n self.x = x\n self.y = y\n\nyou assign the gobal vars x and y (it they exists ) to your instance\nwith :\ndef __init__(self, x, y):\n self.x = x\n self.y = y\n\nyou assign what you give as parameter to the constructor\nand that is a lot more flexible :-)\n",
"Th... | [
4,
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003053680_python.txt |
Q:
adding space in an output file with out having to read the entire thing first
Question: How do you write data to an already existing file at the beginning of the file with out writing over what's already there and with out reading the entire file into memory? (e.g. prepend)
Info:
I'm working on a project right no... | adding space in an output file with out having to read the entire thing first | Question: How do you write data to an already existing file at the beginning of the file with out writing over what's already there and with out reading the entire file into memory? (e.g. prepend)
Info:
I'm working on a project right now where the program frequently dumps data into a file. this file will very quickly ... | [
"See the answers to this question:\nHow do I modify a text file in Python?\nSummary: you can't do it without reading the file in (this is due to how the operating system works, rather than a Python limitation)\n",
"It's not addressing your original question, but here are some possible workarounds:\n\nUse SQLite (... | [
2,
1,
0
] | [] | [] | [
"append",
"file",
"prepend",
"python"
] | stackoverflow_0003053875_append_file_prepend_python.txt |
Q:
Using Python: How can I telnet into a server and then from that connection telnet into a second server?
I am able to establish the initial telnet session. But from this session I need to create a second. Basically I can not telnet directly to the device I need to access. Interactively this is not an issue but I am... | Using Python: How can I telnet into a server and then from that connection telnet into a second server? | I am able to establish the initial telnet session. But from this session I need to create a second. Basically I can not telnet directly to the device I need to access. Interactively this is not an issue but I am attempting to setup an automated test using python.
Does anyone know who to accomplish this?
| [
"After establishing the first connection, just write the same telnet command you use manually to that connection.\n",
"If you log in from A to B to C, do you need the console input from A to go to C ?\nIf not, it is fairly straightforward, as you can execute commands on the second server to connect to the third.\... | [
1,
0
] | [] | [] | [
"python",
"telnet",
"telnetlib"
] | stackoverflow_0003054086_python_telnet_telnetlib.txt |
Q:
Python execution order using C module
I'm trying to learn python and have encountered some strange behaviour. I am experimenting with ctypes and a self-made (very simple) DLL.
This is Python script I'm trying to run:
from ctypes import *
myLib = CDLL("libDlltest")
myLib.hello()
myLib.goodbye()
print 'I am a line'... | Python execution order using C module | I'm trying to learn python and have encountered some strange behaviour. I am experimenting with ctypes and a self-made (very simple) DLL.
This is Python script I'm trying to run:
from ctypes import *
myLib = CDLL("libDlltest")
myLib.hello()
myLib.goodbye()
print 'I am a line'
myLib.goodbye()
I've configured eclipse ... | [
"It looks like Python's stdout is buffered independently from C's stdout. You should try calling flush() on them to force them to write their data.\n"
] | [
2
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003054077_ctypes_python.txt |
Q:
defining precision in python(2.6) division
from future import division
To perform a division in which I need some percision. However, it gives a long number, like:
1.876543820098765
I only need the the first two numbers after "." => 1.87
How can I do that?
A:
"%0.2f" % yournumber
As you said you don't want a ... | defining precision in python(2.6) division | from future import division
To perform a division in which I need some percision. However, it gives a long number, like:
1.876543820098765
I only need the the first two numbers after "." => 1.87
How can I do that?
| [
"\"%0.2f\" % yournumber\n\nAs you said you don't want a rounded number, you might want to try\ndef twoDigits(x):\n return int(100*x)/100.0\n\n",
"The number are stored as binary floating point. If you need to show just two digits, you can turn the float into a string and control the number of digits displayed... | [
4,
2,
1
] | [] | [] | [
"floating_point",
"python",
"string_formatting"
] | stackoverflow_0003054030_floating_point_python_string_formatting.txt |
Q:
Repoze.bfg or Grok
I am about to take the head long plunge into Zope land and am wondering which framework would fit my needs better. I have some experience toying around with django and the primary reason I am switching to a zope-based framework is ZPT and also needing to occasionally do things with Plone. Both s... | Repoze.bfg or Grok | I am about to take the head long plunge into Zope land and am wondering which framework would fit my needs better. I have some experience toying around with django and the primary reason I am switching to a zope-based framework is ZPT and also needing to occasionally do things with Plone. Both seem to be well run proje... | [
"BFG doesn't have very much to do with Zope, except:\n\nit uses some Zope libraries internally.\nit uses a variant of ZPT as its built-in templating language.\nit uses some concepts, such as traversal, that will be familiar to Zope people.\n\nIf you know Zope 3 very well, and you like it, you'll like Grok. If you ... | [
3,
0
] | [] | [] | [
"plone",
"python",
"zope"
] | stackoverflow_0003049431_plone_python_zope.txt |
Q:
Add string to another string
I currently encountered a problem:
I want to handle adding strings to other strings very efficiently, so I looked up many methods and techniques, and I figured the "fastest" method.
But I quite can not understand how it actually works:
def method6():
return ''.join([`num` for num i... | Add string to another string | I currently encountered a problem:
I want to handle adding strings to other strings very efficiently, so I looked up many methods and techniques, and I figured the "fastest" method.
But I quite can not understand how it actually works:
def method6():
return ''.join([`num` for num in xrange(loop_count)])
From sourc... | [
"it's a list comprehension, that uses backticks for repr conversion. Don't do this. Backticks are deprecated and removed in py3k and more efficient and pythonic way is not to build intermediate list at all, but to use generator expression:\n''.join(str(num) for num in xrange(loop_count)) # use range in py3k\... | [
6,
2,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003054215_python_string.txt |
Q:
Best strategy for dealing with incomplete lines of data from a file
I use the following block of code to read lines out of a file 'f' into a nested list:
for data in f:
clean_data = data.rstrip()
data = clean_data.split('\t')
t += [data[0]]
strmat += [data[1:]]
Sometimes, however, the data is... | Best strategy for dealing with incomplete lines of data from a file | I use the following block of code to read lines out of a file 'f' into a nested list:
for data in f:
clean_data = data.rstrip()
data = clean_data.split('\t')
t += [data[0]]
strmat += [data[1:]]
Sometimes, however, the data is incomplete and a row may look like this:
['955.159', '62.8168', '', ''... | [
"The way how you should deal with incomplete values depends on the context of your application (which you haven't mentioned yet).\nFor example, you can simply ignore missing values\n>>> l = ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0']\n>>> filter(bool, l) # remove... | [
1
] | [] | [] | [
"arrays",
"file",
"list",
"nested",
"python"
] | stackoverflow_0003054013_arrays_file_list_nested_python.txt |
Q:
Django : In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response?
In case of views that contain login or logout,
this sessionid is different from the one submitted in request's Coockie header.
I need to retrieve it before returning response for some purpose.
How ca... | Django : In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response? | In case of views that contain login or logout,
this sessionid is different from the one submitted in request's Coockie header.
I need to retrieve it before returning response for some purpose.
How can I do this ?
| [
"I think you should be able to access this via request.session.session_key\n"
] | [
1
] | [] | [] | [
"cookies",
"django",
"django_authentication",
"python"
] | stackoverflow_0003053923_cookies_django_django_authentication_python.txt |
Q:
How do I implement a dictionary "with a Python tuple" as key in C++?
I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on ear... | How do I implement a dictionary "with a Python tuple" as key in C++? | I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on earth do I write something similar in C++? Maybe my algorithm is horrendous a... | [
"map<pair<..., string>, ...> if you're hellbent on using C++ for this.\n",
"for once, you're calling separate_words(post.text) for every search_word in search_words. You should call separate_words only once for each post in posts.\nThat is, rather than:\nfor search_word in search_words:\n for post in posts:\n ... | [
3,
2
] | [] | [] | [
"c++",
"dictionary",
"python"
] | stackoverflow_0003053956_c++_dictionary_python.txt |
Q:
Tkinter using a non-saved picture as an image
I'm trying to grab a screenshot every 30 seconds and display it on my GUI, heres what I've got so far.
Code:
from Tkinter import *
from PIL import ImageGrab
window = Tk()
box = (100,100,400,400)
MyImage = ImageGrab.grab(box)
MyPhotoImage = PhotoImage(file=MyImage) #... | Tkinter using a non-saved picture as an image | I'm trying to grab a screenshot every 30 seconds and display it on my GUI, heres what I've got so far.
Code:
from Tkinter import *
from PIL import ImageGrab
window = Tk()
box = (100,100,400,400)
MyImage = ImageGrab.grab(box)
MyPhotoImage = PhotoImage(file=MyImage) #I know this is where its going wrong, just not sure... | [
"You should be able to use StringIO for this:\nimport cStringIO\nfp = cStringIO.StringIO()\nMyImage.save(fp,'GIF')\nMyPhotoImage = PhotoImage(data=fp.getvalue())\n\nEDITS\nLooks like I should read the docs a little closer. The PhotoImage data must be encoded to base64\nfrom Tkinter import *\nfrom PIL import ImageG... | [
0,
0
] | [] | [] | [
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0003052236_python_python_imaging_library_tkinter.txt |
Q:
Improving Python readability?
I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't r... | Improving Python readability? | I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more ... | [
"Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments a... | [
24,
15,
8,
7,
3,
0
] | [
"I would look in to understanding more details about Python syntax. Often times if a piece of code looks odd, there usually is a better way to write it. For example, in the above example:\nbar = foo if baz else None\nwhile bar not biz:\n bar = i_am_going_to_find_you_biz_i_swear_on_my_life()\n\ndid_i_not_warn_you... | [
-1
] | [
"python",
"readability"
] | stackoverflow_0000051502_python_readability.txt |
Q:
Load globally accessible singleton on app start in Google App Engine using Python
Using Google app engine, is it possible to initialize a globally accessible singleton on app startup? I have a large static tree structure that I need to use on every request and want to initialize it beforehand. The tree structure... | Load globally accessible singleton on app start in Google App Engine using Python | Using Google app engine, is it possible to initialize a globally accessible singleton on app startup? I have a large static tree structure that I need to use on every request and want to initialize it beforehand. The tree structure is too large (20+MB) to be put into Memcache and I am trying to figure out what other ... | [
"Each request might be served from a completely different process, on a different server, which might even be on a separate datacenter (hey, maybe in a different continent). There is nothing that's guaranteed to be \"globally accessible\" to the handlers of different requests to the same app except the datastore (... | [
4,
3,
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003050463_google_app_engine_python.txt |
Q:
Django access data passed to form
I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code:
class GroupAdd(forms.Form):
... | Django access data passed to form | I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code:
class GroupAdd(forms.Form):
def __init__(self, *args, **kwargs):... | [
"OK a couple of minor points here before I answer your question. \nFirstly, your field should probably be a ModelChoiceField - this takes a queryset parameter, rather than a list of choices, which avoids the need for the list comprehension to get id and value.\nSecondly, your query to get the Objtree objects is muc... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"forms",
"python"
] | stackoverflow_0003054683_django_django_forms_django_models_forms_python.txt |
Q:
PythonMagickWand Shepards Distortion (ctypes LP_c_double problem)
I am trying to use PythonMagickWand to use a Shepards distortion on an image. You can also see the source of distort.c that is used by ImageMagick.
PythonMagickWand does not by default support Shepards distortion. To fix this, I added in:
ShepardsDi... | PythonMagickWand Shepards Distortion (ctypes LP_c_double problem) | I am trying to use PythonMagickWand to use a Shepards distortion on an image. You can also see the source of distort.c that is used by ImageMagick.
PythonMagickWand does not by default support Shepards distortion. To fix this, I added in:
ShepardsDistortion = DistortImageMethod(15)
to line 544 of PythonMagickWand (See ... | [
"From NeedMoreBeer on Reddit.com:\nfrom PythonMagickWand import *\nfrom ctypes import *\n\narrayType = c_double * 8 \npointsNew = arrayType()\npointsNew[0] = c_double(121.523809524)\npointsNew[1] = c_double(317.79638009)\npointsNew[2] = c_double(141)\npointsNew[3] = c_double(275) \npointsNew[4] = c_double(346.1587... | [
2,
0,
0
] | [] | [] | [
"ctypes",
"imagemagick",
"magickwand",
"python"
] | stackoverflow_0002989543_ctypes_imagemagick_magickwand_python.txt |
Q:
Graphing a line and scatter points using Matplotlib?
I'm using matplotlib at the moment to try and visualise some data I am working on. I'm trying to plot around 6500 points and the line y = x on the same graph but am having some trouble in doing so. I can only seem to get the points to render and not the line its... | Graphing a line and scatter points using Matplotlib? | I'm using matplotlib at the moment to try and visualise some data I am working on. I'm trying to plot around 6500 points and the line y = x on the same graph but am having some trouble in doing so. I can only seem to get the points to render and not the line itself. I know matplotlib doesn't plot equations as such rath... | [
"Correct me if I'm wrong (I'm not a pro at matplotlib), but 't' will simply get the value [0.].\nt = numpy.arange(0.,0.03,1)\n\nThat means start at 0 and go to 0.03 (not inclusive) with a step size of 1. Resulting in an array containing just 0.\nIn that case you are simply plotting one point. It takes two to make a... | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003055085_matplotlib_python.txt |
Q:
Trimming lists using a loop
I have few lists like:
a = [1, 2, 3, 4, 5]
b = [4, 6, 5, 9, 2]
c = [4, 7, 9, 1, 2]
I want to trim all of them using a loop, instead of doing as below:
a[-2:]
b[-2:]
c[-2:]
I tried but got confused with pass by value or pass by reference fundamentals, looked into other questions as wel... | Trimming lists using a loop | I have few lists like:
a = [1, 2, 3, 4, 5]
b = [4, 6, 5, 9, 2]
c = [4, 7, 9, 1, 2]
I want to trim all of them using a loop, instead of doing as below:
a[-2:]
b[-2:]
c[-2:]
I tried but got confused with pass by value or pass by reference fundamentals, looked into other questions as well but no help.
Thanks
| [
"for l in [a, b, c]:\n del l[-2:]\n\nThis removes the last two elements from each list. If you want to remove all but the last two elements only, do this:\nfor l in [a, b, c]:\n del l[:-2]\n\nThere's no need to worry about references here; the list over which the for loop iterates contains references to a, b ... | [
4,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003055330_list_python.txt |
Q:
Plotting and Animating 2D points with 'headings'
I will have a set of data (x, y, heading), and I need to animate it in real-time. I am currently using matplotlib to animate (x, y) and it works fine, but I would really like to have some way to indicate heading, ie what direction the object is facing. What would be... | Plotting and Animating 2D points with 'headings' | I will have a set of data (x, y, heading), and I need to animate it in real-time. I am currently using matplotlib to animate (x, y) and it works fine, but I would really like to have some way to indicate heading, ie what direction the object is facing. What would be the best library for this? It seems like PyGame might... | [
"How about quiver? The examples all use a mesh grid, but of course you can simply give the coordinates of arbitrary points:\nquiver([1,2,3],[3,1,4],[.5,.4,-.6],[.5,-.7,.3])\nxlim(0,4)\nylim(0,5)\nshow()\n\nThe xlim and ylim calls are because quiver doesn't do a very good job of setting the limits automatically.\n"
... | [
1
] | [] | [] | [
"animation",
"matplotlib",
"python"
] | stackoverflow_0003055199_animation_matplotlib_python.txt |
Q:
Getting a string from Python list?
I have a List object like this ['tag1', 'tag2', 'tag3 tag3', ...]
How I can skip [, ], ' characters and get a string "tag1, tag2, tag3 tag3, ..."?
A:
if you have a list of strings you could do:
>>> lst = ['tag1', 'tag2', 'tag3 tag3']
>>> ', '.join(lst)
'tag1, tag2, tag3 tag3'
... | Getting a string from Python list? | I have a List object like this ['tag1', 'tag2', 'tag3 tag3', ...]
How I can skip [, ], ' characters and get a string "tag1, tag2, tag3 tag3, ..."?
| [
"if you have a list of strings you could do:\n>>> lst = ['tag1', 'tag2', 'tag3 tag3']\n>>> ', '.join(lst)\n'tag1, tag2, tag3 tag3'\n\nNote: you do not remove characters [, ], '. You're concatenating elements of a list into a string. Original list will remain untouched. These characters serve for representing releva... | [
5,
3,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003055644_list_python.txt |
Q:
Installing Python 3.1.2 from source, how do you resolve the sqlite3-dev dependency?
Running ubuntu 9.04 "jaunty".
When I run make I get the following error:
Python build finished, but the necessary bits to build these modules were not found:
_sqlite3
So the easy solution is to just install the missing depende... | Installing Python 3.1.2 from source, how do you resolve the sqlite3-dev dependency? | Running ubuntu 9.04 "jaunty".
When I run make I get the following error:
Python build finished, but the necessary bits to build these modules were not found:
_sqlite3
So the easy solution is to just install the missing dependency using apt-get, "sudo apt-get -f install libsqlite3-dev" but I get the following error... | [
"The dependency mismatch in that error message doesn't agree with the official ubuntu repository. (The official version of libsqlite3-dev in Jaunty depends on libsqlite3-0 (= 3.6.10-1ubuntu0.2).) Perhaps your last apt-get update was done while the repo was still being updated and only some of the latest packages... | [
1
] | [] | [] | [
"gnu",
"makefile",
"python",
"sqlite",
"ubuntu_9.04"
] | stackoverflow_0003055675_gnu_makefile_python_sqlite_ubuntu_9.04.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.