content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I modify a file in a gzipped tar file? I want to write a (preferably python) script to modify the content of one file in a gzipped tar file. The script must run on FreeBSD 6+. Basically, I need to: open the tar file if the tar file has _MY_FILE_ in it: if _MY_FILE_ has a line matching /RE/ in it: insert ...
How can I modify a file in a gzipped tar file?
I want to write a (preferably python) script to modify the content of one file in a gzipped tar file. The script must run on FreeBSD 6+. Basically, I need to: open the tar file if the tar file has _MY_FILE_ in it: if _MY_FILE_ has a line matching /RE/ in it: insert LINE after the matching line rewrite the content in...
[ "Don't think of a tar file as a database that you can read/write -- it's not. A tar file is a concatenation of files. To modify a file in the middle, you need to rewrite the rest of the file. (for files of a certain size, you might be able to exploit the block padding)\nWhat you want to do is process the tarball...
[ 5, 1 ]
[]
[]
[ "automation", "python", "scripting", "tar" ]
stackoverflow_0004610205_automation_python_scripting_tar.txt
Q: Transitive value assignation in Python classes I don't think it can be done easily, but here is the thing: Assume you have a simple class like this: class Demo: a = 'to update' b = a As you can see, I want the variable 'b' to be another name for variable 'a'. So, what I want to do is something like this: ...
Transitive value assignation in Python classes
I don't think it can be done easily, but here is the thing: Assume you have a simple class like this: class Demo: a = 'to update' b = a As you can see, I want the variable 'b' to be another name for variable 'a'. So, what I want to do is something like this: >>> demo = Demo() >>> demo.a 'to update' >>> demo.b ...
[ "You can't hook into assignment to get the effect you're looking for. You're right that you'll need to set both a and b to the same mutable object, and change your assignment to be something that mutates the object.\nclass Demo:\n a = ['to update']\n b = a\n\n>>> demo = Demo()\n>>> demo.a[0]\n'to update'\n>>...
[ 8, 3 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0004610169_python_variables.txt
Q: django join-like expansion of queryset I have a list of Persons each which have multiple fields that I usually filter what's upon, using the object_list generic view. Each person can have multiple Comments attached to them, each with a datetime and a text string. What I ultimately want to do is have the option ...
django join-like expansion of queryset
I have a list of Persons each which have multiple fields that I usually filter what's upon, using the object_list generic view. Each person can have multiple Comments attached to them, each with a datetime and a text string. What I ultimately want to do is have the option to filter comments based on dates. class Per...
[ "The other option you have is to pull all objects out as (Person, Date, Comment) tuples and sort them in Python.\nHowever, I don't know what your reason for not wanting to use Comment.objects.filter(). This is likely going to be fairly fast, especially if your date field is indexed.\n" ]
[ 3 ]
[]
[]
[ "django", "django_queryset", "join", "python" ]
stackoverflow_0004610010_django_django_queryset_join_python.txt
Q: Twisted server for multiple clients I want to write a server that can accept multiple clients in python (twisted). I am already quite familiar with socket programming with the standard python socket module but here comes the trouble.. I think twisted is really hard to get into and i have read some tutorials about ...
Twisted server for multiple clients
I want to write a server that can accept multiple clients in python (twisted). I am already quite familiar with socket programming with the standard python socket module but here comes the trouble.. I think twisted is really hard to get into and i have read some tutorials about it. But a thing that i can't really find...
[ "Say, you want to run a server accepting client connections on port 9000:\nfrom twisted.internet import reactor, protocol\n\nPORT = 9000\n\nclass MyServer(protocol.Protocol):\n pass\n\nclass MyServerFactory(protocol.Factory):\n protocol = MyServer\n\nfactory = MyServerFactory()\nreactor.listenTCP(PORT, factor...
[ 12, 7, 2, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0004604580_python_twisted.txt
Q: Why does this valid Tkinter code crash when mixed with a bit of PyWin32? So I'm making a very small program for personal use in tkinter, and I've run into a really strange wall. I'm mixing tkinter with the pywin32 bindings because I really hate everything to do with the syntax and naming conventions of pywin32, an...
Why does this valid Tkinter code crash when mixed with a bit of PyWin32?
So I'm making a very small program for personal use in tkinter, and I've run into a really strange wall. I'm mixing tkinter with the pywin32 bindings because I really hate everything to do with the syntax and naming conventions of pywin32, and it feels like tkinter gets more done with far less code. The strangeness is ...
[ "Not sure if it could help, but i assume it breaks down as you invoke the update from inside an win32 event handler and tkinter might not like that.\nUsual trick to work around it is to defer the update via an after_idle() callback.\nSo try to replace:\n def OnDrawClipboard (self, msg, wParam, lParam):\n if se...
[ 2 ]
[]
[]
[ "clipboard", "crash", "python", "pywin32", "tkinter" ]
stackoverflow_0004555568_clipboard_crash_python_pywin32_tkinter.txt
Q: Login to AJAX form with Python BTW... This website only works with Internet Explorer.... I am attempting to scrap a website for a client so that I can automate a task for them. Basically it will scrape for different reports and look for the turn around times and email them to the client. My scrapping program works...
Login to AJAX form with Python
BTW... This website only works with Internet Explorer.... I am attempting to scrap a website for a client so that I can automate a task for them. Basically it will scrape for different reports and look for the turn around times and email them to the client. My scrapping program works fine, the problem I am having is lo...
[ "Mechanize doesn't, as far as I know, process Javascript. So your options are, in rough order of what I'd try:\n\nTurn Javascript off in your browser, and see if you can still log into the site. If so, attempt to use mechanize with that process.\nTry to work out what the effect of the AJAX form is (both server side...
[ 1 ]
[]
[]
[ "ajax", "mechanize", "python", "web_scraping" ]
stackoverflow_0004610502_ajax_mechanize_python_web_scraping.txt
Q: Django - determining if geographic coordinates are inside of an circle Does django have anything that will look at a geographic coordinate (decimal lat/long) and determine if is inside a circle with a certain radius (let's say 100 Km)? I have certain type of data, each has a lat/long and I would like to make a se...
Django - determining if geographic coordinates are inside of an circle
Does django have anything that will look at a geographic coordinate (decimal lat/long) and determine if is inside a circle with a certain radius (let's say 100 Km)? I have certain type of data, each has a lat/long and I would like to make a search in the database to see if that data is located inside of a circle with ...
[ "This problem can be solved in pure SQL if you dont mind about very good precision.\nYou can find points around a GPS position with this specific SQL query :\n# find point around :\nlatitude = 46.2037010192871\nlongitude = 5.20353984832764\nquery= \"SELECT ID, NOM, LAT, LON, 3956 * 2 * ASIN(SQRT(POWER(SIN((%s - LAT...
[ 12 ]
[]
[]
[ "django", "geodjango", "geopy", "gis", "python" ]
stackoverflow_0004610717_django_geodjango_geopy_gis_python.txt
Q: Python: Get items that follow a specified element of a list I have a list of strings similar to ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN']. Given a string that I know is in the list, is there a simple way to return an iterable of all of the elements that follow that string (and None if nothing follows it)? ...
Python: Get items that follow a specified element of a list
I have a list of strings similar to ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN']. Given a string that I know is in the list, is there a simple way to return an iterable of all of the elements that follow that string (and None if nothing follows it)? So, inputing 'ONE' would return ['TWO', 'SEVEN'] and inputing 'S...
[ "How about something like:\n>>> a = ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN']\n>>> [a[x+1] if x+1 < len(a) else None for x in range(len(a)) if a[x] == 'ONE']\n['TWO', 'SEVEN']\n\n", "l = ['ONE', 'TWO', 'SEVEN', 'TWELVE', 'ONE', 'SEVEN']\nk = 'ONE'\n[l[i+1] if i<len(l)-1 else None for i,e in enumerate(l) i...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004610114_list_python.txt
Q: can I put my sqlite connection and cursor in a function? I was thinking I'd try to make my sqlite db connection a function instead of copy/pasting the ~6 lines needed to connect and execute a query all over the place. I'd like to make it versatile so I can use the same function for create/select/insert/etc... Belo...
can I put my sqlite connection and cursor in a function?
I was thinking I'd try to make my sqlite db connection a function instead of copy/pasting the ~6 lines needed to connect and execute a query all over the place. I'd like to make it versatile so I can use the same function for create/select/insert/etc... Below is what I have tried. The 'INSERT' and 'CREATE TABLE' querie...
[ "I think the problem is a little more difficult than it looks at first.\nYou're seeing the error because you've closed your connection to the database in your \"connection\" function.\nYour probably better off creating a DatabaseManagement Class, to manage a single connection.\nSomething like:\nimport sqlite3\n\ncl...
[ 21, 0 ]
[]
[]
[ "oop", "python", "sqlite" ]
stackoverflow_0004610791_oop_python_sqlite.txt
Q: How to structure a Python web service with an API and a web interface? It's good practice to separate your API and your user-facing website, so I am seeking some advice on how to structure the module/sub-module layout for a Python project that has simultaneous API and front-end development. When currently deployin...
How to structure a Python web service with an API and a web interface?
It's good practice to separate your API and your user-facing website, so I am seeking some advice on how to structure the module/sub-module layout for a Python project that has simultaneous API and front-end development. When currently deploying, we have two different machines: one is the web service, which uses the AP...
[ "I would definitely keep them as different repositories. The super-module is up to you. Not having them as submodules doesn't prevent you from doing tags in both repositories so that you can keep things in sync for different releases. Your point about submodules being overcomplicated is correct and if you do so ...
[ 1 ]
[]
[]
[ "api", "deployment", "git_submodules", "python", "web_services" ]
stackoverflow_0004610818_api_deployment_git_submodules_python_web_services.txt
Q: Calculate next scheduled time based on cron spec What's an efficient way to calculate the next run time of an event given the current time and a cron spec? I'm looking for something other than "loop through every minute checking if it matches spec". Examples of specs might be: Every month, on the 1st and 15 at 15...
Calculate next scheduled time based on cron spec
What's an efficient way to calculate the next run time of an event given the current time and a cron spec? I'm looking for something other than "loop through every minute checking if it matches spec". Examples of specs might be: Every month, on the 1st and 15 at 15:01 At 10,20,30,40,50 mins past the hour every hour P...
[ "Just looking at it, I think you need to:\n\nparse the chron spec to five arrays containing acceptable values for each field;\nparse 'now' to a value for each field;\nin order of minute, hour, {day-of-month OR day-of-week}, month-of year: find the lowest array value that matches or exceeds the current value, correc...
[ 30 ]
[]
[]
[ "algorithm", "cron", "python", "scheduler" ]
stackoverflow_0004610904_algorithm_cron_python_scheduler.txt
Q: Python search: how to do it efficiently I have one class have 2 variable members: class A: fullname = "" email = "" There is a list of A stored in memory, now I need to search against fullname or email, the search needs to support fuzzy search(assemble the SQL 'like' clause), eg) search "abc", for "dabcd"...
Python search: how to do it efficiently
I have one class have 2 variable members: class A: fullname = "" email = "" There is a list of A stored in memory, now I need to search against fullname or email, the search needs to support fuzzy search(assemble the SQL 'like' clause), eg) search "abc", for "dabcd" it should match(if it can show the exact mat...
[ "Look at the sqlite3 module. You can put your data into an in-memory database, index it, and query it with standard SQL.\n", "\nIf I only need exact match, will two dictionaries with 'fullname' and 'email' to be the key is the best choice? \n\nIf by \"Best\" you mean \"best speed\", then yes. \n\nI see some arti...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004611164_python.txt
Q: Visible lines in Tkinter text widget Is there any way to get what lines are currently visible in a Tkinter text widget? I'm trying to make a scrollbar. Currently I'm trying to coordinate my scroll bar with the other methods of scrolling (ie, the arrow keys and scroll wheel). So that when I scroll with the arrow k...
Visible lines in Tkinter text widget
Is there any way to get what lines are currently visible in a Tkinter text widget? I'm trying to make a scrollbar. Currently I'm trying to coordinate my scroll bar with the other methods of scrolling (ie, the arrow keys and scroll wheel). So that when I scroll with the arrow keys or mouse, my bar scrolls too.
[ "You can get the character (and thus, the line number) at a pixel position using an index of @x,y (eg: @0,0 for the top-left-most visible character). Since you know the width and height of the widget (using the winfo_width and winfo height methods) you can calculate what lines are at the bottom of the widget too.\n...
[ 5, 1, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004610074_python_tkinter.txt
Q: Interpretation of range(n) and boolean list, one-to-one map, simpler? #!/usr/bin/python # # Description: bitwise factorization and then trying to find # an elegant way to print numbers # Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422 # bug with large numbers such as 99, but main point in simpl...
Interpretation of range(n) and boolean list, one-to-one map, simpler?
#!/usr/bin/python # # Description: bitwise factorization and then trying to find # an elegant way to print numbers # Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422 # bug with large numbers such as 99, but main point in simplifying it # def primes(n): # all even numbers greater than 2 are not pr...
[ "For python2.7+, you can use itertools.compress\nitertools.compress(b,a)\n\neg\n>>> from itertools import compress\n>>> a=[True, False, True]\n>>> b=[1,2,3]\n>>> list(compress(b,a))\n[1, 3]\n\notherwise you can use a list comprehension\n>>> [j for i,j in zip(a,b) if i]\n[1, 3]\n\nIf you want to do this on your list...
[ 2, 0, 0 ]
[]
[]
[ "python", "variable_assignment" ]
stackoverflow_0004611160_python_variable_assignment.txt
Q: If Python's exec and eval were compiled? Can the equivalent of eval and exec exist in a compiled language? If so, how would they be compiled (roughly speaking)? A: Certainly, various Lisp environments have had this capability for decades. A Lisp compiler typically works on a per-function basis, and the compiler ...
If Python's exec and eval were compiled?
Can the equivalent of eval and exec exist in a compiled language? If so, how would they be compiled (roughly speaking)?
[ "Certainly, various Lisp environments have had this capability for decades. A Lisp compiler typically works on a per-function basis, and the compiler and runtime system work hand in hand.\nWhen asked to eval something, the Lisp runtime environment will pass the list (a data structure) to the compiler for compiling....
[ 5, 5 ]
[]
[]
[ "compilation", "eval", "exec", "python" ]
stackoverflow_0004611369_compilation_eval_exec_python.txt
Q: Sorted Doubly Linked List Python I'm having trouble understanding and implementing a Doubly Linked List. I can grasp most of the concepts of a Linked List. Here is my code so far (in Python) *This is a purely academic exercise. I would normally use list and dict. class DoublyNode(object): """A node of the Sort...
Sorted Doubly Linked List Python
I'm having trouble understanding and implementing a Doubly Linked List. I can grasp most of the concepts of a Linked List. Here is my code so far (in Python) *This is a purely academic exercise. I would normally use list and dict. class DoublyNode(object): """A node of the SortedDoublyLL object. DoublyNode(ite...
[ "Change your loop to\nfor element in sequence:\n prev_node = cur_node\n cur_node = DoublyNode(element, None, prev_node)\n prev_node.next = cur_node\n\nBecause the line prev_node = cur_node precedes the call DoublyNode(element, cur_node, prev_node), you end up setting both the previous and next elements to ...
[ 2 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0004611254_linked_list_python.txt
Q: Is there a "children" method in App Engine? When entities with a parent are created, they can always reference this parent by calling the parent() method in Python. Does the parent have a corresponding children() method? I didn't see one in the docs. If not, is there an equivalent query? A: Yes, you can query ...
Is there a "children" method in App Engine?
When entities with a parent are created, they can always reference this parent by calling the parent() method in Python. Does the parent have a corresponding children() method? I didn't see one in the docs. If not, is there an equivalent query?
[ "Yes, you can query for objects with a given ancestor. Check out the ancestor() method on the query object, or ANCESTOR IS if you prefer GQL.\n" ]
[ 2 ]
[]
[]
[ "data_modeling", "google_app_engine", "parent", "parent_child", "python" ]
stackoverflow_0004611329_data_modeling_google_app_engine_parent_parent_child_python.txt
Q: How to extract certain value from collection of text files Say, I have a collection of text files I need to process (e.g. search for a certain label and extract the value). What would be the general way to tackle the problem? I also read this: "Retrieve Variable Values from Python" but it seems not applicable to s...
How to extract certain value from collection of text files
Say, I have a collection of text files I need to process (e.g. search for a certain label and extract the value). What would be the general way to tackle the problem? I also read this: "Retrieve Variable Values from Python" but it seems not applicable to some of the cases I face (like tab is used instead of :) I just w...
[ "I always shove Python into people's faces ;)\nI recommend looking at Regex: http://docs.python.org/howto/regex.html, as it might fit your needs. I won't do it for you (because I can't), but I know this will work if your files are colon-delimited key/value pairs separated by newline characters. Here's a quick start...
[ 1 ]
[]
[]
[ "java", "pyparsing", "python", "text", "text_parsing" ]
stackoverflow_0004611522_java_pyparsing_python_text_text_parsing.txt
Q: Error 403 uploading a file to Google Docs with Python I'm having a 403 error when trying to upload a file to Google Docs with Python / gdata-2.0.13: import gdata.docs.data import gdata.docs.client client = gdata.docs.client.DocsClient(source="MyUpdater") client.ClientLogin("mymail@gmail.com", "mykey", client.sour...
Error 403 uploading a file to Google Docs with Python
I'm having a 403 error when trying to upload a file to Google Docs with Python / gdata-2.0.13: import gdata.docs.data import gdata.docs.client client = gdata.docs.client.DocsClient(source="MyUpdater") client.ClientLogin("mymail@gmail.com", "mykey", client.source); client.http_client_debug = True ms = gdata.data.Media...
[ "import gdata.docs.service\nimport gdata.docs.data\n\nclient = gdata.docs.service.DocsService()\nclient.ClientLogin(\"me@gmail.com\", 'pass', 'test')\n\nms = gdata.data.MediaSource(file_path=\"/home/jake/Desktop/test.txt\",\n content_type=gdata.docs.service.SUPPORTED_FILETYPES['TXT'])\nen...
[ 1 ]
[]
[]
[ "gdata", "google_docs", "google_docs_api", "python" ]
stackoverflow_0004433324_gdata_google_docs_google_docs_api_python.txt
Q: How can I write a python function to accept *arguments and a keyword argument? I feel like there must be something simple I'm missing here. Here's what I want to do: >>> def x(*args, a=False): ... print args, a >>> x(1,2) (1,2) False >>> x(1,2,3, a=True) (1,2,3) True But you can't define a function like that....
How can I write a python function to accept *arguments and a keyword argument?
I feel like there must be something simple I'm missing here. Here's what I want to do: >>> def x(*args, a=False): ... print args, a >>> x(1,2) (1,2) False >>> x(1,2,3, a=True) (1,2,3) True But you can't define a function like that. I know this would work, but it doesn't seem as nice: >>> def x(*args, **kwargs): .....
[ "I think what you have is the only way. But you can write it nicer:\ndef x(*args, **kwargs):\n a = kwargs.get('a', False)\n print args, a\n\nx(1,2,3,a=42)\n\n", "Just found this http://www.python.org/dev/peps/pep-3102/\n\nThe first change is to allow regular\n arguments to appear after a varargs\n argumen...
[ 5, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004611593_python.txt
Q: Does db.run_in_transaction return anything? I'm mimicking a transaction example I found in the Taggable Mixin, but it's not behaving in the same manner. def txn(): // statements omitted for brevity blog_index.put() new_post = Post(key_name=new_post_key_name, parent=blog_index, ...
Does db.run_in_transaction return anything?
I'm mimicking a transaction example I found in the Taggable Mixin, but it's not behaving in the same manner. def txn(): // statements omitted for brevity blog_index.put() new_post = Post(key_name=new_post_key_name, parent=blog_index, index = new_index, title = new_title, ...
[ "run_in_transaction returns whatever the called function returned. You need to include the compelte stacktrace and the original code for us to help.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "transactions" ]
stackoverflow_0004611528_google_app_engine_google_cloud_datastore_python_transactions.txt
Q: In python, is there anyway to have a variable be a different random number everytime? Basically I have this: import random variable1 = random.randint(13, 19) And basically what that does is assign variable1 a random number between 13 and 19. Great. But, what I want it to do is assign a different random number bet...
In python, is there anyway to have a variable be a different random number everytime?
Basically I have this: import random variable1 = random.randint(13, 19) And basically what that does is assign variable1 a random number between 13 and 19. Great. But, what I want it to do is assign a different random number between 13 and 19 to that variable every time it is called. Is there anyway I can do this? If ...
[ "Perhaps a silly question, but why not just use a function instead of a variable?\nOr perhaps more inline with your variable paradigm, why not use a method on an object. The object can then be passed as a variable, and the method returns the new random number.\n", "In that specific example, there's a rather asini...
[ 4, 3, 3, 2, 1, 0 ]
[ "Why not skip the variable altogether? You can use the function inline too: print(random.randint(13, 19) + 1).\nTry this, and see if it fits your needs ;)\nprint(random.randint(13, 19))\nprint(random.randint(13, 19))\nprint(random.randint(13, 19))\nprint(random.randint(13, 19))\nprint(random.randint(13, 19))\n\nI c...
[ -1, -1 ]
[ "python", "python_3.x", "random", "variables" ]
stackoverflow_0004611589_python_python_3.x_random_variables.txt
Q: What do I need to distribute (keys, certs) for Python w/ SSL-socket connection? I'm trying to write a generic server-client application that will be able to exchange data amongst servers. I've read over quite a few OpenSSL documents, and I have successfully setup my own CA and created a cert (and private key) for...
What do I need to distribute (keys, certs) for Python w/ SSL-socket connection?
I'm trying to write a generic server-client application that will be able to exchange data amongst servers. I've read over quite a few OpenSSL documents, and I have successfully setup my own CA and created a cert (and private key) for testing purposes. I'm stuck with Python 2.3, so I can't use the standard "ssl" libra...
[ "In an SSL transaction, each side can present a certificate to verify its identity to the other side. To do this, it needs to have the private key corresponding to that certificate. These are intended to be two different certificates, so each side will have two different private keys.\nThis certificate/private key...
[ 4 ]
[]
[]
[ "openssl", "pyopenssl", "python", "ssl" ]
stackoverflow_0004609859_openssl_pyopenssl_python_ssl.txt
Q: Google Search API - Only returning 4 results After much experimenting and googling, the following Python code successfully calls Google's Search APi - but only returns 4 results: after reading the Google Search API docs, I thought the 'start=' would return additional results: but this not happen. Can anyone give p...
Google Search API - Only returning 4 results
After much experimenting and googling, the following Python code successfully calls Google's Search APi - but only returns 4 results: after reading the Google Search API docs, I thought the 'start=' would return additional results: but this not happen. Can anyone give pointers? Thanks. Python code: /usr/bin/python impo...
[ "The start option doesn't give you more results, it just moves you forward that many results. Think of the results as a queue. Starting at 50 will give you results 50, 51, 52, and 53. \nWith this you can get more results by starting every 4th result:\nimport urllib\nimport simplejson\n\nnum_queries = 50*4 \nquery =...
[ 2 ]
[]
[]
[ "google_search", "google_search_api", "python" ]
stackoverflow_0004506173_google_search_google_search_api_python.txt
Q: Wrapping a C++ class in Python using SWIG example.h: #ifndef EXAMPLE_H #define EXAMPLE_H class Math { public: int pi() const; void pi(int pi); private: int _pi; }; #endif example.cpp: #include "example.h" int Math::pi() const { return this->_pi; } void Math::pi(int pi) { this->_pi = pi;...
Wrapping a C++ class in Python using SWIG
example.h: #ifndef EXAMPLE_H #define EXAMPLE_H class Math { public: int pi() const; void pi(int pi); private: int _pi; }; #endif example.cpp: #include "example.h" int Math::pi() const { return this->_pi; } void Math::pi(int pi) { this->_pi = pi; } example.swig: %module example %{ #defi...
[ "I think the swig command should be \"swig -c++ -python example.swig\"\n", "There's not enough information here to be sure what's wrong, but I have two ideas for things you can try.\n\nYour g++ invocation is compiling a C source file as if it were C++. This is not guaranteed to work. Try instead\ngcc -I/usr/loc...
[ 13, 5, 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0004596484_c++_python_swig.txt
Q: python: html writer? With jquery it's very easy to insert some element inside another element using the selector technology, I am wondering if there is any python library that can do things similar with jquery, the reason is I want server side python program to produce the static pages, which needs to parse the ht...
python: html writer?
With jquery it's very easy to insert some element inside another element using the selector technology, I am wondering if there is any python library that can do things similar with jquery, the reason is I want server side python program to produce the static pages, which needs to parse the html and insert something in...
[ "It sounds like pyquery works very similarly to what you're looking for.\n", "BeautifulSoup can modify the parse tree see http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree\n", "lxml\n\nlxml is a Pythonic binding for the\n libxml2 and libxslt libraries. It is\n uniq...
[ 3, 3, 2 ]
[]
[]
[ "jquery", "python" ]
stackoverflow_0004612069_jquery_python.txt
Q: Django Find Out if User is Authenticated in Custom Tag I'm trying to create a custom tag. Inside this custom tag, I want to be able to have some logic that checks if the user is logged in, and then have the tag rendered accordingly. This is what I have: def user_actions(context): request = template.Variable('r...
Django Find Out if User is Authenticated in Custom Tag
I'm trying to create a custom tag. Inside this custom tag, I want to be able to have some logic that checks if the user is logged in, and then have the tag rendered accordingly. This is what I have: def user_actions(context): request = template.Variable('request').resolve(context) return { 'auth': request['user...
[ "By default, an instance of django.template.Context is used in rendering templates, but you can override this in your view, either by passing a subclass of django.template.Context as the context_instance keyword argument to render_to_response, or by instantiating the subclass, and passing it directly to Template.re...
[ 3, 1, 1, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004576824_django_django_templates_python.txt
Q: creating a database-neutral app in python I have a project coming up that involves a desktop application (tournament scoring for an amateur competition) that probably 99+% of the time will be a single-user on a single machine, no network connectivity, etc. For that, sqlite will likely work beautifully. For those...
creating a database-neutral app in python
I have a project coming up that involves a desktop application (tournament scoring for an amateur competition) that probably 99+% of the time will be a single-user on a single machine, no network connectivity, etc. For that, sqlite will likely work beautifully. For those other few times when there are more than one p...
[ "Yes, SQLAlchemy will help you to be independent on what SQL database you use, and you get a nice ORM as well. Highly recommended.\n" ]
[ 1 ]
[ "I don't see how those 2 use cases would use the same methods. Just create a wrapper module that conditionally imports either the sqlite or sqlalchemy modules or whatever else you need.\n" ]
[ -1 ]
[ "database", "orm", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0004610698_database_orm_python_sqlalchemy_sqlite.txt
Q: Help needed with db structure I'm developing a web app that uses stock data. The stock data can be stored in: Files DB The structure of the data is simple: there's a daily set and a weekly set. If files are used, then I can store a file per symbol/set, such as GOOGLE_DAILY and GOOGLE_WEEKLY. Each set includes a...
Help needed with db structure
I'm developing a web app that uses stock data. The stock data can be stored in: Files DB The structure of the data is simple: there's a daily set and a weekly set. If files are used, then I can store a file per symbol/set, such as GOOGLE_DAILY and GOOGLE_WEEKLY. Each set includes a simple list of (Date, open/hight/l...
[ "You don't need a table per stock symbol, you just need one of the fields in the table to be the stock symbol. The table might be called StockPrices and its fields might be\n\nticker_symbol - the stock ticker symbol\ntime - the time of the stock quote\nprice - the price of the stock at that time\n\nAs long as ticke...
[ 3, 0 ]
[]
[]
[ "data_structures", "django", "python" ]
stackoverflow_0004613251_data_structures_django_python.txt
Q: pygame code organization I've started to learn making games with python/pygame and as though it is easy to make a working game quickly in pygame, there's no real tutorial on how to organize the code in a sensible way. On the pygame tutorials page, I've found 3 ways to do it. 1- No use of classes, for small project...
pygame code organization
I've started to learn making games with python/pygame and as though it is easy to make a working game quickly in pygame, there's no real tutorial on how to organize the code in a sensible way. On the pygame tutorials page, I've found 3 ways to do it. 1- No use of classes, for small projects 2- MVC ruby-on-rails kind of...
[ "I'd also suggest maybe using comments (as dreary as it seems as first) for dividing your work. As an example:\nimport pygame, random, math\n\n## CLASSES ----------------------------------------------\n\nclass Ball():\n def __init__(self, (x,y), size):\n \"\"\"Setting up the new instance\"\"\"\n se...
[ 4, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0004612064_pygame_python.txt
Q: Python- Bouncing Balls? How to pass separately as one parameter? How do I pass ball_boundary_2 and ball_boundary_3 separately as one parameter to ball_collisions function? Here is the code below: ## Import PyGame system import sys, pygame ## Initialise PyGame system pygame.init() ## Function to handle ball c...
Python- Bouncing Balls? How to pass separately as one parameter?
How do I pass ball_boundary_2 and ball_boundary_3 separately as one parameter to ball_collisions function? Here is the code below: ## Import PyGame system import sys, pygame ## Initialise PyGame system pygame.init() ## Function to handle ball colissions ### NOTE: Should alos include sound but we could not get it...
[ "I'd consider passing a list of ball boundaries rather than individual ball boundaries. (Is that your question?)\nIf this doesn't answer your question, then shorten the answer, it's far too long and wordy. (My eyes glazeth over!)\n", "You could just wrap the x-boundary and the y-boundary in a tuple, and pass that...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0003956251_pygame_python.txt
Q: How can I simplify "for x in a for y in b for z in c ..." with the unordered? #!/usr/bin/python # # Description: I try to simplify the implementation of the thing below. # Sets, such as (a,b,c), with irrelavant order are given. The goal is to # simplify the messy "assignment", not sure of the term, below. # # # QU...
How can I simplify "for x in a for y in b for z in c ..." with the unordered?
#!/usr/bin/python # # Description: I try to simplify the implementation of the thing below. # Sets, such as (a,b,c), with irrelavant order are given. The goal is to # simplify the messy "assignment", not sure of the term, below. # # # QUESTION: How can you simplify it? # # >>> a=['1','2','3'] # >>> b=['bc','b'] # >>> ...
[ "Try this\n>>> import itertools\n>>> a=['1','2','3']\n>>> b=['bc','b']\n>>> c=['#'] \n>>> print [ \"\".join(res) for res in itertools.product(a,b,c) ]\n['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']\n\n", ">>> from itertools import product\n>>> a=['1','2','3']\n>>> b=['bc','b']\n>>> c=['#']\n>>> map(\"\".join, pro...
[ 12, 8 ]
[]
[]
[ "cartesian_product", "list_comprehension", "python", "unordered" ]
stackoverflow_0004613481_cartesian_product_list_comprehension_python_unordered.txt
Q: Script from stdin use case Taking e.g. Python as a good example of a modern scripting language, it has the option of reading a program (as opposed to input data for the program) from stdin. The REPL is the obvious use case where stdin is a terminal, but it's also designed to handle the scenario where it's not a te...
Script from stdin use case
Taking e.g. Python as a good example of a modern scripting language, it has the option of reading a program (as opposed to input data for the program) from stdin. The REPL is the obvious use case where stdin is a terminal, but it's also designed to handle the scenario where it's not a terminal. What use cases are there...
[ "If you want to execute code generated by some tool it could be useful to be able to pipe the generated into your interpreter/compiler..\nSimply support it ;) Checking if stdin is a tty or not is not hard anyway.\n" ]
[ 3 ]
[]
[]
[ "programming_languages", "python", "scripting" ]
stackoverflow_0004613888_programming_languages_python_scripting.txt
Q: How do I set a session to expire within 4 minutes? Suppose I do this: request.session['x'] = 33 How do I make this session variable expire in 4 minutes? This variable only!! I don't want all the sessions to expire. If this cannot be done, is there a function that can keep track of it? (a function that uses sessio...
How do I set a session to expire within 4 minutes?
Suppose I do this: request.session['x'] = 33 How do I make this session variable expire in 4 minutes? This variable only!! I don't want all the sessions to expire. If this cannot be done, is there a function that can keep track of it? (a function that uses sessions itself to count?)
[ "You'll have to track the age of session variable yourself. In actual Python code it could look something like this:\nfrom datetime import datetime, timedelta\n\nrequest.session['x'] = dict(dt=datetime.now(), value='something')\n\nMAX_AGE = timedelta(seconds=240)\n\nif ('x' in request.session and datetime.now() - r...
[ 3, 1, 0 ]
[]
[]
[ "count", "django", "http", "python", "session" ]
stackoverflow_0004612449_count_django_http_python_session.txt
Q: create a new subprocess in python gtk I am creating a python gtk program which uploads videos to youtube in ubuntu 10.10. It works using the Googlecl package. You can google it for more info. I've implemented calling the program through the following syntax. os.system('google youtube post --category %s --title \'%...
create a new subprocess in python gtk
I am creating a python gtk program which uploads videos to youtube in ubuntu 10.10. It works using the Googlecl package. You can google it for more info. I've implemented calling the program through the following syntax. os.system('google youtube post --category %s --title \'%s\' --summary \'%s\' --tags %s %s' % ("Educ...
[ "You could do time-consuming operation in a separate thread. PyGTK FAQ has example how to couple threading and UI updates (mind that all UI updates should be done in Gtk+ thread).\n", "Using os.system in this case won't work: when running os.system it'll wait till the process you started finished before continuin...
[ 1, 1 ]
[]
[]
[ "pygtk", "python", "subprocess" ]
stackoverflow_0004613501_pygtk_python_subprocess.txt
Q: CSV reading issues in python I'm totaly new to Python (and programming), so I'm stuck with some csv readings. I have a csv file in the rows I have measurement data in the same order (in the line the first entry is the id for example 1-4). I want to get the data from the lines from line to line, I found the reader....
CSV reading issues in python
I'm totaly new to Python (and programming), so I'm stuck with some csv readings. I have a csv file in the rows I have measurement data in the same order (in the line the first entry is the id for example 1-4). I want to get the data from the lines from line to line, I found the reader.next() function but it works a bit...
[ "You don't need to call reader.next(), just do this:\nfor line in reader:\n print line\n\nThis will loop through every line in your CSV file and print it as a list:\nFrom the documentation on next:\n\nReturn the next row of the reader’s iterable object as a list, parsed according to the current dialect.\n\nWhat yo...
[ 8, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0004614258_csv_python.txt
Q: Resize an image with python 2.4: The _imaging C module is not installed How to resize an image with python 2.4 version.I am trying t make it a thumbnail I have downloaded thePIL librrary but am facing the same problem as https://stackoverflow.com/questions/4134966/problem-in-the-installed-pil. Is there any other w...
Resize an image with python 2.4: The _imaging C module is not installed
How to resize an image with python 2.4 version.I am trying t make it a thumbnail I have downloaded thePIL librrary but am facing the same problem as https://stackoverflow.com/questions/4134966/problem-in-the-installed-pil. Is there any other way to resize the image from PIL import Image import glob, os size = 40, 40 ...
[ "I think that is the same question : PIL error: The _imaging C module is not installed\nI hope that it will fix your problem !\n" ]
[ 1 ]
[]
[]
[ "python", "python_2.4", "python_imaging_library" ]
stackoverflow_0004614373_python_python_2.4_python_imaging_library.txt
Q: How to select a row by primary key in sqlite3? I'm trying to find a way to select a row in sqlite from Python. Say I have a table soft drinks with columns drink and price, with the primary key being drink name. I want to select coke out of drink name. How would I do this without looping through every single entry?...
How to select a row by primary key in sqlite3?
I'm trying to find a way to select a row in sqlite from Python. Say I have a table soft drinks with columns drink and price, with the primary key being drink name. I want to select coke out of drink name. How would I do this without looping through every single entry? Here's my code: conn = sqlite3.Connection("database...
[ "SQLite uses quotation marks as column identifiers, so you'd need to put quotation marks around the column and table name: SELECT * FROM \"soft drinks\" WHERE \"drink name\" = 'Coke';\n" ]
[ 2 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0004614337_python_sql_sqlite.txt
Q: form.has_errors tag not working Im using Django 1.2.3. I have login functionality in my site using django.contrib.auth.views.login. The user is able to login after entering correct username and password. But, form.has_errors is not working i.e. if the login credentials entered are incorrect i dont see the error me...
form.has_errors tag not working
Im using Django 1.2.3. I have login functionality in my site using django.contrib.auth.views.login. The user is able to login after entering correct username and password. But, form.has_errors is not working i.e. if the login credentials entered are incorrect i dont see the error message. My login.html in templates/reg...
[ "A Form object does have an errors attribute, read the docs for more information:\n{% if form.errors %}\n <p>Your username and password didn't match. Please try again.</p>\n{% endif %}\n\nApparently has_errors was valid in Django 0.95 but not from at least 1.0 upwards (as it was replaced with errors). [reference...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004614769_django_python.txt
Q: Running Python from a virtualenv with Apache/mod_wsgi, on Windows I'm trying to set up WAMP server. I've got Apache working correctly, and I've installed mod_wsgi without a hitch. Problem is, I'm using virtual environments (using virtualenv) for my projects. So obviously, mod_wsgi is having problems locating my in...
Running Python from a virtualenv with Apache/mod_wsgi, on Windows
I'm trying to set up WAMP server. I've got Apache working correctly, and I've installed mod_wsgi without a hitch. Problem is, I'm using virtual environments (using virtualenv) for my projects. So obviously, mod_wsgi is having problems locating my installation of Django. I'm trying to understand how I can get mod_wsgi t...
[ "You can activate the environment programmatically from Python adding this to your .wsgi file before importing anything else.\nFrom virtualenv's docs:\n\nSometimes you can't or don't want to\n use the Python interpreter created by\n the virtualenv. For instance, in a\n mod_python or mod_wsgi environment,\n ther...
[ 13 ]
[]
[]
[ "apache", "python", "virtualenv", "wamp", "wampserver" ]
stackoverflow_0004614121_apache_python_virtualenv_wamp_wampserver.txt
Q: Select one distinct column, others can be non distinct. - MySQL Ok I have a temporary table with 135000 rows, I'm trying to insert some of the values from this temporary table into other tables. This is the schema I'm using tvtemptable +-------------+-------------+------+-----+---------+-------+ | Field | Ty...
Select one distinct column, others can be non distinct. - MySQL
Ok I have a temporary table with 135000 rows, I'm trying to insert some of the values from this temporary table into other tables. This is the schema I'm using tvtemptable +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-----------...
[ "That doesn't make sense. How can a row be partially distinct and partially non-distinct? Think of the selected result as a table - how would you represent the data, if there is one value for PROGTITLE that has multiple values for the rest of the columns?\n", "This doesn't answer your question, but probably will ...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "distinct", "distinct_values", "mysql", "python", "sql" ]
stackoverflow_0004613999_distinct_distinct_values_mysql_python_sql.txt
Q: Has anyone gotten distribute to work correctly with github, specifically private repositories? I built a small micro framework for our web service / web app and have it hosted it in a private repository on github. I've added the private github repo in the dependency_links and have verified that it exists in depen...
Has anyone gotten distribute to work correctly with github, specifically private repositories?
I built a small micro framework for our web service / web app and have it hosted it in a private repository on github. I've added the private github repo in the dependency_links and have verified that it exists in dependency_links.txt When I execute python setup.py install, I get unknown url type: git+ssh, so I looked...
[ "If you know, that \"pip\" works, why don't you just use \"pip\"? \"pip\" can not only install from a package index, but also from a local source directory. Just use pip install . instead of python setup.py install.\nConcerning your impression, it is indeed wrong. \"pip\" and \"distribute\" are altogether differ...
[ 3 ]
[]
[]
[ "distribution", "distutils", "easy_install", "github", "python" ]
stackoverflow_0004614552_distribution_distutils_easy_install_github_python.txt
Q: what is the difference between easy_install and apt-get I have just started using Ubuntu as my first Linux, have a couple of question. What is the difference between easy_install and apt-get? How do I update my packages with packages installed in both these ways? They are under pythonpath right? A: You are con...
what is the difference between easy_install and apt-get
I have just started using Ubuntu as my first Linux, have a couple of question. What is the difference between easy_install and apt-get? How do I update my packages with packages installed in both these ways? They are under pythonpath right?
[ "You are confusing two completely separate things.\nAptitude, of which apt_get is one part, is the Ubuntu system-wide package manager. It has packages for absolutely everything - applications, libraries, system utils, whatever. They may not be the latest versions, as packages are usually only updated for each separ...
[ 8 ]
[]
[]
[ "linux", "package", "python", "ubuntu" ]
stackoverflow_0004615299_linux_package_python_ubuntu.txt
Q: Convert relative date string to absolute date As input, I have a date string that can take three general formats: a) January 6, 2011 b) 4 days ago c) 12 hours ago I want the script to be able to recognize the format and call the appropriate function with the parameters. So if a then convert_full_string("January...
Convert relative date string to absolute date
As input, I have a date string that can take three general formats: a) January 6, 2011 b) 4 days ago c) 12 hours ago I want the script to be able to recognize the format and call the appropriate function with the parameters. So if a then convert_full_string("January 6, 2011") if b then convert_days(4) if c then conv...
[ "Using parsedatetime, you could parse all three date formats into datetime.datetime objects without having to code the logic yourself:\nimport parsedatetime.parsedatetime as pdt\nimport parsedatetime.parsedatetime_consts as pdc\nimport datetime\nc = pdc.Constants()\np = pdt.Calendar(c)\nfor text in ('january 6, 201...
[ 12, 0, 0 ]
[]
[]
[ "date", "datetime", "python", "string" ]
stackoverflow_0004615250_date_datetime_python_string.txt
Q: How do I pass in the 'id' portion of the URL to a view_callable? I've been playing around with Pyramid lately and, coming from a Pylons background, I've been focusing in URL routing rather than traversal. I've also been looking at using handlers to group together 'controller' specific functions into the one class....
How do I pass in the 'id' portion of the URL to a view_callable?
I've been playing around with Pyramid lately and, coming from a Pylons background, I've been focusing in URL routing rather than traversal. I've also been looking at using handlers to group together 'controller' specific functions into the one class. Rather than having view.py polluted with a bunch of functions. Config...
[ "You can access «id» through request.matchdict:\nfrom pyramid.response import Response\nfrom pyramid.view import action\n\nclass Page(object):\n\n def __init__(self, request):\n self.request = request\n\n def view_page(self):\n matchdict = request.matchdict\n id = matchdict.get('id', None...
[ 10 ]
[]
[]
[ "pylons", "pyramid", "python" ]
stackoverflow_0004614260_pylons_pyramid_python.txt
Q: Populating a table with a large amount of data from a temporary table - MySQL Ok I have a temporary MySQL table with 135,000 rows, from this temporary table I want to populate several other tables. First of all this is the structure of the temporary table CREATE TEMPORARY TABLE TVTEMPTABLE ( PROGTITLE TEXT, SUBTI...
Populating a table with a large amount of data from a temporary table - MySQL
Ok I have a temporary MySQL table with 135,000 rows, from this temporary table I want to populate several other tables. First of all this is the structure of the temporary table CREATE TEMPORARY TABLE TVTEMPTABLE ( PROGTITLE TEXT, SUBTITLE TEXT, EPISODE TEXT, YR YEAR, DIRECTOR TEXT, PERFORMERS TEXT, PREMIERE BOOL, FIL...
[ "How about this:\nINSERT INTO PROGRAMME ( GENREID, PROGTITLE, YR, DIRECTOR, PERFORMERS, FILM, WIDESCREEN, BNW, CERTIFICATE, DESCRIPTION)\nSELECT G.GENREID, T.PROGTITLE, T.YR, T.DIRECTOR, T.PERFORMERS, T.FILM, T.WIDESCREEN, T.BNW, T.CERTIFICATE, T.DESCRIPTION\nFROM TVTEMPTABLE T,GENRE G\nWHERE G.GENRENAME = T.GENRE\...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "insert", "mysql", "python", "sql", "temp_tables" ]
stackoverflow_0004605054_insert_mysql_python_sql_temp_tables.txt
Q: django how to work with templates I'm practising Django now, and I'm stuck. When I run: >>> from django import template >>> t = template.Template('hi') Gives me: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Any idea what causes this? What should I d...
django how to work with templates
I'm practising Django now, and I'm stuck. When I run: >>> from django import template >>> t = template.Template('hi') Gives me: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Any idea what causes this? What should I do?
[ "Django is designed to work within a project, which contains a file named settings.py. Rather than just importing it on the command line, you should work through the tutorial, which shows you how to create a project and its apps.\nIf you just want a quick start, you need to execute this on the command line:\ndjang...
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004615530_django_python.txt
Q: invalid SUDS envelope When I try to execute this code: mmurl = 'http://server/_mmwebext/mmwebext.dll?WSDL?server=localhost' mmclient = Client(mmurl, plugins=[EnvelopeFixer()]) loginResult = mmclient.service[1].Login(u'localhost', u'user', u'pass') the following envelope is created: <SOAP-ENV:Envelope xmlns:ns0="h...
invalid SUDS envelope
When I try to execute this code: mmurl = 'http://server/_mmwebext/mmwebext.dll?WSDL?server=localhost' mmclient = Client(mmurl, plugins=[EnvelopeFixer()]) loginResult = mmclient.service[1].Login(u'localhost', u'user', u'pass') the following envelope is created: <SOAP-ENV:Envelope xmlns:ns0="http://menandmice.com/webser...
[ "It's unfortunate that the RPC endpoint does not parse XML correctly. One way to fix would be to add a plugin to your Client() that edits the envelope before sending. A MessagePlugin gives you the chance to modify the suds.sax.document.Document or the message text before sending.\nfrom suds.plugin import MessagePlu...
[ 3 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0004605687_python_soap_suds.txt
Q: What would happen if I abruptly close my script while it's still doing file I/O operations? here's my question: I'm writing a script to check if my website running all right, the basic idea is to get the server response time and similar stuff every 5 minutes or so, and the script will log the info each time after ...
What would happen if I abruptly close my script while it's still doing file I/O operations?
here's my question: I'm writing a script to check if my website running all right, the basic idea is to get the server response time and similar stuff every 5 minutes or so, and the script will log the info each time after checking the server status. I know it's no good to close the script while it's in the middle of c...
[ "According to the python io documentation, buffering is handled according to the buffering parameter to the open function.\nThe default behavior in this case would be either the device's block size or io.DEFAULT_BUFFER_SIZE if the block size can't be determined. This is probably something like 4096 bytes.\nIn short...
[ 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004615905_file_io_python.txt
Q: Calculate page generation time - Django I'm just wondering if there is a way to do this out of the box. I need the time it takes to generate a web page within the site templates. Any ideas? A: It's not out of the box, but the Django debug toolbar displays stats on how long various elements of the page rendering ...
Calculate page generation time - Django
I'm just wondering if there is a way to do this out of the box. I need the time it takes to generate a web page within the site templates. Any ideas?
[ "It's not out of the box, but the Django debug toolbar displays stats on how long various elements of the page rendering process took.\n", "I don't think there is one built in, but this middleware promises to do what you want: http://djangosnippets.org/snippets/358/\n" ]
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004615721_django_python.txt
Q: Meta programming in Django get_foo_display, foo_set and others, how does it work? I have a user model with a profile UserProfile. Somehow my user can have several type of books: TA, TB, TC, TD. Those choices are defined in a choices tuple in my model (standard way). From my template I would like to be able to call...
Meta programming in Django get_foo_display, foo_set and others, how does it work?
I have a user model with a profile UserProfile. Somehow my user can have several type of books: TA, TB, TC, TD. Those choices are defined in a choices tuple in my model (standard way). From my template I would like to be able to call {{ user.get_profile.has_book_type_TA }} and returns True/False. TA is the dynamic p...
[ "In the __init__ method for your model, walk through the different types of books and create properties:\nfor book_type in BOOK_TYPES:\n setattr(self, 'has_book_type_%s' % book_type, self.has_book_type_(book_type))\n\nThen in your templates, checking user.get_profile.has_book_type_TA should work.\n" ]
[ 2 ]
[]
[]
[ "django", "metaprogramming", "python" ]
stackoverflow_0004616272_django_metaprogramming_python.txt
Q: Handling Signals in Python Threads I have a threaded application written in Python, and whenever an interrupt is received via Ctrl+C or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with...
Handling Signals in Python Threads
I have a threaded application written in Python, and whenever an interrupt is received via Ctrl+C or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with Ctrl+Z then attempt to kill it. What is...
[ "If you set newthread.daemon = True before starting each thread, the threads will automatically be killed when the main thread exits. That's not precisely what you were asking, but from what you've described, it sounds like it could be worth knowing.\n", "The way I worked around this issue was to make a module th...
[ 16, 5, 5, 1 ]
[]
[]
[ "multithreading", "python", "signals" ]
stackoverflow_0004616361_multithreading_python_signals.txt
Q: How can I view error messages with pycurl? I have the following pycurl code: curl = pycurl.Curl() foo = StringIO() curl.setopt(pycurl.WRITEFUNCTION, foo.write) curl.setopt(pycurl.POST, 1) curl.setopt(pycurl.URL, finalURL) curl.setopt(pycurl.POSTFIELDS, encodedArgs) curl.perform() responseCode = curl.getinfo(pycur...
How can I view error messages with pycurl?
I have the following pycurl code: curl = pycurl.Curl() foo = StringIO() curl.setopt(pycurl.WRITEFUNCTION, foo.write) curl.setopt(pycurl.POST, 1) curl.setopt(pycurl.URL, finalURL) curl.setopt(pycurl.POSTFIELDS, encodedArgs) curl.perform() responseCode = curl.getinfo(pycurl.RESPONSE_CODE) effectiveURL = curl.getinfo(pyc...
[ "The response from the server is written using the curl option pycurl.WRITEFUNCTION.\nIn your case, since you are passing it a StringIO object, the response data should be in the foo variable: foo.getvalue()\nReference: http://pycurl.sourceforge.net/doc/curlobject.html\n" ]
[ 1 ]
[]
[]
[ "curl", "pycurl", "python" ]
stackoverflow_0004617121_curl_pycurl_python.txt
Q: 2 Lists, a loop and a login I have two lists, one of User IDs and one of passwords. I alread have a script that logs into a website and scrapes out the data i need... #!/usr/bin/env python from mechanize import Browser from BeautifulSoup import BeautifulSoup import easygui br = Browser() hid = easygui.enterbox (m...
2 Lists, a loop and a login
I have two lists, one of User IDs and one of passwords. I alread have a script that logs into a website and scrapes out the data i need... #!/usr/bin/env python from mechanize import Browser from BeautifulSoup import BeautifulSoup import easygui br = Browser() hid = easygui.enterbox (msg="Enter Hotel ID", title="HID",...
[ "If you want to check that the password a user enters is correct, you would be better off storing them in a dictionary like below. You'll need to populate the rest of the dictionary where I've put ....\npasswords = { '254376xml': 'mbhg934uh', '254371xml': 'hj2r93kh8s', ... }\ndef check_password(username, password):...
[ 2, 1, 0 ]
[]
[]
[ "authentication", "list", "loops", "python" ]
stackoverflow_0004616073_authentication_list_loops_python.txt
Q: PyQt4 Need to move DLLs to package root I've used the new installers from http://www.riverbankcomputing.co.uk/software/pyqt/download for Python 2.6 x86_64 and I've a small problem importing PyQt4 in one particular application. Here's the traceback: # ERROR : Traceback (most recent call last): # File "<Script Bl...
PyQt4 Need to move DLLs to package root
I've used the new installers from http://www.riverbankcomputing.co.uk/software/pyqt/download for Python 2.6 x86_64 and I've a small problem importing PyQt4 in one particular application. Here's the traceback: # ERROR : Traceback (most recent call last): # File "<Script Block >", line 2, in <module> # from PyQt4 ...
[ "The problem could be that the PyQt4 installers add the PyQt4\\bin directory to the Windows DLL search path. If you have both the 32 bit and the 64 bit versions installed, only one will find the correct set of DLLs.\nThe solution is to add the following code to each Lib\\site-packages\\PyQt4_init_.py file:\nimport ...
[ 5, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0004616834_pyqt4_python.txt
Q: Learning Python I am going to need to learn advanced Python and must be good at it in about a year, Are there any books, recommendations. I am already very familiar with PHP, MySQL, JS + HTML, and know a bit of java and C (arduino programming). Thanks, RayQuang A: Since you sound like a competent programmer, the...
Learning Python
I am going to need to learn advanced Python and must be good at it in about a year, Are there any books, recommendations. I am already very familiar with PHP, MySQL, JS + HTML, and know a bit of java and C (arduino programming). Thanks, RayQuang
[ "Since you sound like a competent programmer, the best place to start may be the official Python 2.7 Tutorial. It's very thorough, certainly.\nAfter that, I advise looking up through the language reference and standard library reference (the stdlib for Python is pretty massive) to get everything else.\n", "It's n...
[ 5, 3, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004617251_python.txt
Q: Best way to run remote commands thru ssh in Twisted? I have a twisted application which now needs to monitor processes running on several boxes. The way I manually do is 'ssh and ps', now I'd like my twisted application to do. I have 2 options. Use paramiko or leverage the power of twisted.conch I really want to ...
Best way to run remote commands thru ssh in Twisted?
I have a twisted application which now needs to monitor processes running on several boxes. The way I manually do is 'ssh and ps', now I'd like my twisted application to do. I have 2 options. Use paramiko or leverage the power of twisted.conch I really want to use twisted.conch but my research led me to believe that i...
[ "Followup - Happily, the ticket I referenced below is now resolved. The simpler API will be included in the next release of Twisted. The original answer is still a valid way to use Conch and may reveal some interesting details about what's going on, but from Twisted 13.1 and on, if you just want to run a command ...
[ 17 ]
[]
[]
[ "python", "ssh", "twisted" ]
stackoverflow_0004617507_python_ssh_twisted.txt
Q: Extending module I'm getting really sick of having to add_type a bunch of 'missing' mimetypes when using the mimetypes module, is there someway I can do the following? # This file is named mimetypes.py from mimetypes import * add_type('application/x-rar-compressed', 'rar', False) add_type('video/mp4', 'mp4', False...
Extending module
I'm getting really sick of having to add_type a bunch of 'missing' mimetypes when using the mimetypes module, is there someway I can do the following? # This file is named mimetypes.py from mimetypes import * add_type('application/x-rar-compressed', 'rar', False) add_type('video/mp4', 'mp4', False) add_type('video/x-ms...
[ "Don't call your module mimetypes.\nThat's it. Call it something else, and it works. Maybe extra_mimetypes or something. Then just import extra_mimetypes from your software and your father got a brother called Bob.\nThe only unpythonic thing with it is the from mimetypes import *. Change that to from mimetypes impo...
[ 5 ]
[]
[]
[ "mime_types", "python" ]
stackoverflow_0004618108_mime_types_python.txt
Q: Problems in Packaging files for installation in my project I am trying to make a project in Python and was using Pydev to make it.For better structuring I divided all of them into mini packages for better handling of where each code lies.... I have run into problems with actually packaging all of them into a singl...
Problems in Packaging files for installation in my project
I am trying to make a project in Python and was using Pydev to make it.For better structuring I divided all of them into mini packages for better handling of where each code lies.... I have run into problems with actually packaging all of them into a single file for installation..... In eclipse I had made packages and ...
[ "\nIn development you can set PYTHONPATH environment variable to define where modules will sit.\nFor something like this, I think what you want is to use distutils to setup an installation process. One part of the process will install files to the default location for each machine. There should also be a way to i...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004618224_python.txt
Q: specific searching in python? Is there any way to search and replace certain strings, but also watch out for similar strings, and not replace those? for example, if i have self.a self.b self.c self.d self.e self.f self.g and i wanted self.a self.__b self.c self.__d self.__e self.f self.g and i want to add __ to...
specific searching in python?
Is there any way to search and replace certain strings, but also watch out for similar strings, and not replace those? for example, if i have self.a self.b self.c self.d self.e self.f self.g and i wanted self.a self.__b self.c self.__d self.__e self.f self.g and i want to add __ to some of the variables to make them...
[ "Regular expressions?\nPython's re module has a function called re.sub which will replace everything matching a pattern with something else.\nYou can also use regular expressions from Perl, awk, sed, etc. depending on your preferences. Just search and replace based on whatever patterns you might want to match and c...
[ 3, 1, 1, 1 ]
[]
[]
[ "python", "replace", "string" ]
stackoverflow_0004618418_python_replace_string.txt
Q: celery does not start on centos 5.4 I install celery using "pip install celery" and setup the celeryconfig.py to talk to the rabbitmq server running on another server running in the same network. The python version i have is 2.7 When i try to run start celeryd i get the following error: # celeryd -l info -I tasks ...
celery does not start on centos 5.4
I install celery using "pip install celery" and setup the celeryconfig.py to talk to the rabbitmq server running on another server running in the same network. The python version i have is 2.7 When i try to run start celeryd i get the following error: # celeryd -l info -I tasks Traceback (most recent call last): File "...
[ "You need to install the latest version of pyparsing\nYou can do so by doing:\npip install -U pyparsing\n\n" ]
[ 2 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0004593921_celery_python.txt
Q: Working with python off of a FAT32 filesystem I pulled a django project repository (git) to a FAT32 drive and made some changes but when I went to commit, every file is out of date because of it's mode (i.e. - was 100644 is 100755) that's because of FAT32 right? I haven't ever really thought about this, do I just ...
Working with python off of a FAT32 filesystem
I pulled a django project repository (git) to a FAT32 drive and made some changes but when I went to commit, every file is out of date because of it's mode (i.e. - was 100644 is 100755) that's because of FAT32 right? I haven't ever really thought about this, do I just need to work off of a different filesystem or is th...
[ "I think you want to tell Git to ignore the file permissions. See this question: How do I make Git ignore file mode (chmod) changes?\n", "You should not use FAT32 unless you really have to. There are several reasons for this ranging from memory, CPU, speed, lack of security, lack of journaling and even that FAT3...
[ 3, 0 ]
[]
[]
[ "django", "fat32", "filesystems", "git", "python" ]
stackoverflow_0004617316_django_fat32_filesystems_git_python.txt
Q: Making windows appear on Bottom How can I make a window appear at the bottom of the window stack? Preferably with Tkinter (However, WXPython works too). I'd like it to appear below every other window. This is in Windows 7, btw. A: The pywin32 package can give you access to Windows Scripting functions. For exam...
Making windows appear on Bottom
How can I make a window appear at the bottom of the window stack? Preferably with Tkinter (However, WXPython works too). I'd like it to appear below every other window. This is in Windows 7, btw.
[ "The pywin32 package can give you access to Windows Scripting functions. For example, select a window by title and move it to the bottom of the Z order:\nimport win32ui, win32con as w\n\ndef MoveToBack(window_name):\n flags = w.SWP_NOSIZE | w.SWP_NOMOVE | w.SWP_NOACTIVATE | w.SWP_SHOWWINDOW | w.SWP_ASYNCWINDOWP...
[ 3 ]
[]
[]
[ "python", "tkinter", "windows_7", "wxpython" ]
stackoverflow_0004573244_python_tkinter_windows_7_wxpython.txt
Q: numpy arange and where I am trying to find values in an array created by "arange" by means of "where", but it seems it does not work fine. Here is one example: from numpy import arange, where myarr = arange(6.6,10.25,0.05) for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]: print where(myarr...
numpy arange and where
I am trying to find values in an array created by "arange" by means of "where", but it seems it does not work fine. Here is one example: from numpy import arange, where myarr = arange(6.6,10.25,0.05) for item in [6.6,6.65,6.7,6.8,6.9,6.95,7.95,8.0,8.1,8.15,6.2,6.25,6.35]: print where(myarr == item) (array([0]),) (ar...
[ "Note:\nIn [32]: repr(myarr[1])\nOut[32]: '6.6499999999999995'\n\nIn [33]: repr(6.65)\nOut[33]: '6.6500000000000004'\n\nSo the float64 value that np.arange assigns to myarr[1] is not exactly the same float that Python uses to represent 6.65. \nSo, unless you really know what you are doing, never test floats for equ...
[ 6 ]
[]
[]
[ "numpy", "python", "where" ]
stackoverflow_0004618395_numpy_python_where.txt
Q: Webkit context-menu I have a little program with a webkit window inside (realy cutted code attached), I would disable the context-menu, but I don't know how.. I found this 'enable-default-context-menu': http://webkitgtk.org/reference/webkitgtk-WebKitWebSettings.html, but I can't make it work.. Can you help me? TNK...
Webkit context-menu
I have a little program with a webkit window inside (realy cutted code attached), I would disable the context-menu, but I don't know how.. I found this 'enable-default-context-menu': http://webkitgtk.org/reference/webkitgtk-WebKitWebSettings.html, but I can't make it work.. Can you help me? TNK #!/usr/bin/env python ...
[ "Going by the seat of my pants here, but try:\n#!/usr/bin/env python\nimport gtk\nimport webkit\n\nbrowser = webkit.WebView()\nsettings = browser.get_settings()\nsettings.set_property('enable-default-context-menu', False)\nbrowser.set_settings(settings) # Push the changed settings back!\n\nscroller = gtk.Scrolle...
[ 3, 0 ]
[]
[]
[ "contextmenu", "python", "webkit" ]
stackoverflow_0004540584_contextmenu_python_webkit.txt
Q: Tkinter Canvas Access from a separate Class I've run into problems while trying to create a program for my frequent biking. I want the program to draw a red line across the designated course when the start button of the stopwatch is pressed. However, I can't seem to access the canvas from the class stopwatch and I...
Tkinter Canvas Access from a separate Class
I've run into problems while trying to create a program for my frequent biking. I want the program to draw a red line across the designated course when the start button of the stopwatch is pressed. However, I can't seem to access the canvas from the class stopwatch and I need help doing that. The code is below. from Tk...
[ "Just pass a reference to the canvas to the constructor of the StopWatch class. Or, create a controller class that knows about the canvas and the stopwatch, then the stopwatch will ask the controller to ask the canvas to draw the line.\n[edit] How would you do that? First, make the canvas, then make the stopwatch:\...
[ 3, 3 ]
[]
[]
[ "canvas", "python", "stopwatch", "tkinter", "variables" ]
stackoverflow_0004618435_canvas_python_stopwatch_tkinter_variables.txt
Q: Asynchronous Python Classes I'm a real coding n00b so apologies if this is a simple or basic question. I'm coding on Python, Webapp, Appengine. My question, is it possible to carry on working after I've written out the page? And is that the best way to do something? Basically, when someone creates a list on my sit...
Asynchronous Python Classes
I'm a real coding n00b so apologies if this is a simple or basic question. I'm coding on Python, Webapp, Appengine. My question, is it possible to carry on working after I've written out the page? And is that the best way to do something? Basically, when someone creates a list on my site (www.7bks.com) I want to carry ...
[ "Check out the Task Queue API. \nTask or message queues tend to be the way to go about doing some sort of work that is initiated by a user request, but not necessarily completed within the time frame of that request's execution.\n" ]
[ 5 ]
[]
[]
[ "asynchronous", "google_app_engine", "python", "web_applications" ]
stackoverflow_0004619201_asynchronous_google_app_engine_python_web_applications.txt
Q: Migrating to Linux from Windows I have a python gui that access files on windows as C:\data and C:\MyDIR all outside my doc's. On, a linux sys i created /data and /MyDIR. My gui cant access. I foresee always using C:\data and C:\MyDIR on both systems. How do I fix code or Linux permissions to have access to both...
Migrating to Linux from Windows
I have a python gui that access files on windows as C:\data and C:\MyDIR all outside my doc's. On, a linux sys i created /data and /MyDIR. My gui cant access. I foresee always using C:\data and C:\MyDIR on both systems. How do I fix code or Linux permissions to have access to both dir and sub directories.
[ "Chmod is your friend.\nHowever I question your design. Why do you want to have priviledges at such high levels of file systems. You know every user has a home dir and ther is always dir for configuration on both Windows and Linux.\nWhat you do is a bad practice.\n", "Place the data in the directory Python consid...
[ 5, 5, 1, 1, 1, 0 ]
[]
[]
[ "linux", "python", "windows" ]
stackoverflow_0004619168_linux_python_windows.txt
Q: python convert string to datetime i have a loop where i try to process set of data where one action is to convert ordinary string to datetime. everything works fine except sometimes happend a weird thing ... here is what i know there are exactly the same parameters entering the function always those parameters ar...
python convert string to datetime
i have a loop where i try to process set of data where one action is to convert ordinary string to datetime. everything works fine except sometimes happend a weird thing ... here is what i know there are exactly the same parameters entering the function always those parameters are the same type always first time i run...
[ "You probably have a different locale set up. %B is March in locales that use English, but in other locales it will fail.\nFor example:\n>>> import locale\n>>> locale.setlocale(locale.LC_ALL, 'sv_SE.utf8')\n'sv_SE.utf8'\n>>> import datetime\n>>> \n>>> data = ['January 20 1999', 'March 4 2010', 'June 11 1819']\n>>> ...
[ 7, 0 ]
[]
[]
[ "date", "datetime", "python" ]
stackoverflow_0004617267_date_datetime_python.txt
Q: Avoid object aliasing in python? I am trying to write a function to check whether a list is sorted (returning True or False). How can I avoid multiple variables pointing to the same thing? def is_sorted(t): a = t a.sort() When I do that, it sorts both a and t. How can I avoid this? A: Here is the O(n)...
Avoid object aliasing in python?
I am trying to write a function to check whether a list is sorted (returning True or False). How can I avoid multiple variables pointing to the same thing? def is_sorted(t): a = t a.sort() When I do that, it sorts both a and t. How can I avoid this?
[ "Here is the O(n) way to do it\n>>> from itertools import islice, izip\n>>> def is_sorted(L):\n... return all(i<=j for i,j in izip(L, islice(L,1,None)))\n... \n>>> is_sorted(range(50))\nTrue\n>>> is_sorted(range(50)+[20])\nFalse\n\nIt shortcircuits, so if the list is unsorted right near the beginning it will be...
[ 9, 6, 3, 3, 2, 0 ]
[]
[]
[ "alias", "python" ]
stackoverflow_0004619367_alias_python.txt
Q: How do I distribute precompiled extension modules for Windows on pypi for multiple versions of Python? I would like to distribute a precompiled C extension module for Python 2.6 and Python 2.7 for 32- and 64-bit versions of Python. How should I build and distribute that on pypi? Should I just use bdist_egg? Can I ...
How do I distribute precompiled extension modules for Windows on pypi for multiple versions of Python?
I would like to distribute a precompiled C extension module for Python 2.6 and Python 2.7 for 32- and 64-bit versions of Python. How should I build and distribute that on pypi? Should I just use bdist_egg? Can I retain compatibility with pip? I notice ordinary bdist just creates a .zip that does not include the Python ...
[ "You generally need to run bdist_something with each version of Python you need to support. bdist_egg does indeed work with PIP afaik (you can easily test it).\nThe Zope Toolkit has several binary distributions for Windows, and it's using binary eggs: http://pypi.python.org/pypi/zope.interface\n" ]
[ 2 ]
[]
[]
[ "distutils", "pip", "python", "windows" ]
stackoverflow_0004618918_distutils_pip_python_windows.txt
Q: How do I get my hudson project build to fail on second set of nosetests? I'm relatively new to Hudson, so please forgive me if this is a "duh" question. I have a project written in python (employing pylons and nosetests) that includes both a server component and a client component. I have function tests set up in...
How do I get my hudson project build to fail on second set of nosetests?
I'm relatively new to Hudson, so please forgive me if this is a "duh" question. I have a project written in python (employing pylons and nosetests) that includes both a server component and a client component. I have function tests set up in both the server hierarchy, and the client hierarchy, to exercise both compone...
[ "Just looking at your exit command makes me wonder why your build breaks when the server test fail. It might be connected with the fact that your server doesn't start when your build fails. In fact you are checking the exit status of echo and not of the exit status of your test suite. Capture your exit status first...
[ 2 ]
[]
[]
[ "bash", "functional_testing", "hudson", "nosetests", "python" ]
stackoverflow_0004616949_bash_functional_testing_hudson_nosetests_python.txt
Q: No cipher can be selected I am having problems making ssl connections with IDEA-CBC-SHA on python 2.7 / Win XP. This is the code: ciphers = "IDEA-CBC-SHA" ssl_sock = ssl.wrap_socket(self.sock, keyfile = keyfile, certfile = certfile, ...
No cipher can be selected
I am having problems making ssl connections with IDEA-CBC-SHA on python 2.7 / Win XP. This is the code: ciphers = "IDEA-CBC-SHA" ssl_sock = ssl.wrap_socket(self.sock, keyfile = keyfile, certfile = certfile, ciphers = ciphers) ssl_sock....
[ "\nAny idea why my ssl connection might be failing for this specific cipher?\n\nPerhaps the server you are connecting to does not support IDEA. A packet capture would confirm this.\nEDIT: In an ssl connection, the client suggests a list of cipher options it is willing to use. The server selects one of the options...
[ 2 ]
[]
[]
[ "openssl", "python", "ssl" ]
stackoverflow_0004617113_openssl_python_ssl.txt
Q: python gnuplot.plot command fails on string input command in the gnuplot command line you can, for instance, do gnuplot> plot "fileA.dat" using 1:2 title 'data A', \ "fileB.dat" using 1:3 title 'data B' using python gnuplot.py, the following function works fine: def create_plot(): ... ...
python gnuplot.plot command fails on string input command
in the gnuplot command line you can, for instance, do gnuplot> plot "fileA.dat" using 1:2 title 'data A', \ "fileB.dat" using 1:3 title 'data B' using python gnuplot.py, the following function works fine: def create_plot(): ... for target in TARGET_LIST: for protocol in PROTOCOL_LI...
[ "got it:\nneither function does a file.close (bad! bad!), which is OK within the scope of a single function- the file descriptor is still valid.\nwhen\nwrite_plot_file.close()\nread_plot_file.close()\nping_plot_file.close()\n\nis included in read_data() everything is better. \n" ]
[ 0 ]
[]
[]
[ "gnuplot", "python" ]
stackoverflow_0004608795_gnuplot_python.txt
Q: python list - storing the most popular color okay say I want to know what the most popular color is can I do it using a list popular.append("red") popular.append("blue") popular.append("green") popular.append("red") popular.append("yellow") popular.append("red") popular.append("blue") popular.append("red") popular...
python list - storing the most popular color
okay say I want to know what the most popular color is can I do it using a list popular.append("red") popular.append("blue") popular.append("green") popular.append("red") popular.append("yellow") popular.append("red") popular.append("blue") popular.append("red") popular.append("yellow") what I want is red,blue,yellow,...
[ "You can use the Counter class to get information about the number of occurrences in a list.\nIf you are building the list yourself, instead of already having the list containing the data, you can just use a Dictionary and increment the value with each color being the key.\nMore detail based on your edit:\nThe appr...
[ 4, 4, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004619982_list_python.txt
Q: Writing CSV values to file results in values being separated in single characters (Python) Kinda knew to Python: I have the following code: def printCSV(output, values, header): 63 """ 64 prints the output data as comma-separated values 65 """ 66 67 try: 68 with open(output, 'w')...
Writing CSV values to file results in values being separated in single characters (Python)
Kinda knew to Python: I have the following code: def printCSV(output, values, header): 63 """ 64 prints the output data as comma-separated values 65 """ 66 67 try: 68 with open(output, 'w') as csvFile: 69 #print headers 70 csvFile.write(header) 71 72 ...
[ "The problem you're encountering is that you're doing \",\".join(value) with value being a string. Strings act like a collection of characters, so the command translates to \"Join each character with a comma.\"\nWhat you could do instead is use a tuple instead of a string for your row values you pass to printCSV, ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004620128_python.txt
Q: Python 64 bit DLL COM Server Registration Problem on 64 bit Windows 7 I am trying to create a simple COM server using Python 2.7 on 64 bit Windows 7, but I can't get the DLL registered successfully. I am able to do this successfully using Python 2.6 on 32 bit Windows XP. I am also able to register my class directl...
Python 64 bit DLL COM Server Registration Problem on 64 bit Windows 7
I am trying to create a simple COM server using Python 2.7 on 64 bit Windows 7, but I can't get the DLL registered successfully. I am able to do this successfully using Python 2.6 on 32 bit Windows XP. I am also able to register my class directly from Python. This is my module, heikki.py, based on the pywin32 COM tutor...
[ "This looks like a duplicate of Com server build using Python on 64-bit Windows 7 machine.\nAdd \"import win32traceutil\" to the top of heikki.py and run C:\\Python27\\Lib\\site-packages\\win32\\lib\\win32traceutil.py in a second Python process to see the traceback from heikki.dll:\nTraceback (most recent call last...
[ 2 ]
[]
[]
[ "com", "dllregistration", "py2exe", "python", "pywin32" ]
stackoverflow_0004619701_com_dllregistration_py2exe_python_pywin32.txt
Q: Python xmpppy client not sending message to appengine xmpp client Hey Guys, I seem to be having trouble using the xmpppy client when sending messages to the app engine's xmpp client. I am not getting any errors. The messages just aren't arriving there. Sending messages from app engine's client to the sl4a client...
Python xmpppy client not sending message to appengine xmpp client
Hey Guys, I seem to be having trouble using the xmpppy client when sending messages to the app engine's xmpp client. I am not getting any errors. The messages just aren't arriving there. Sending messages from app engine's client to the sl4a client works. Sending messages to and from google talk's client to and from ...
[ "1) Check that garrowsbot@gmail.com is on the roster for cellbotmote@appspot.com. GTalk won't deliver messages from unknown users.\n2) Send a message of type chat: \nxmppClient.send(xmpp.Message(operator, msg, typ='chat'))\n\nSome clients do not react well to receiving \"normal\" messages, which don't have a type ...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "xmpp", "xmpppy" ]
stackoverflow_0004611702_google_app_engine_python_xmpp_xmpppy.txt
Q: How can I create a numpy .npy file in place on disk? Is it possible to create an .npy file without allocating the corresponding array in memory first? I need to create and work with a large numpy array, too big to create in memory. Numpy supports memory mapping, but as far as I can see my options are either: Crea...
How can I create a numpy .npy file in place on disk?
Is it possible to create an .npy file without allocating the corresponding array in memory first? I need to create and work with a large numpy array, too big to create in memory. Numpy supports memory mapping, but as far as I can see my options are either: Create a memmapped file using numpy.memmap. This creates the f...
[ "I had the same question and was disappointed when I read Sven's reply. Seems as though numpy would be missing out on some key functionality if you couldn't have a huge array on file and work on little pieces of it at a time. Your case seems to be close to one of the use cases in the origional rational for making...
[ 13, 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004335289_numpy_python.txt
Q: Python's sqlite3.register_converter() does not convert double to Decimal In sqlite3 there is this table: create table t(d double) In python, the code is: sqlite3.register_converter('double', Decimal) ... for d, in connection.execute('select d from t limit 1'): print type(d) The printed result is: <type...
Python's sqlite3.register_converter() does not convert double to Decimal
In sqlite3 there is this table: create table t(d double) In python, the code is: sqlite3.register_converter('double', Decimal) ... for d, in connection.execute('select d from t limit 1'): print type(d) The printed result is: <type 'float'> Any idea why?
[ "connect to the database using the optional argument:\ndetect_types=sqlite3.PARSE_DECLTYPES\n\nie:\nconn = sqlite3.connect('database.db', detect_types=sqlite3.PARSE_DECLTYPES)\n\nthen continue as you have. It should work.\nsee:\nhttp://www.gossamer-threads.com/lists/python/python/627047\n" ]
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003821388_python_sqlite.txt
Q: combining values for a large number of overlapping intervals of dictionary keys I have a dictionary of dictionaries that has items like this all={ 1:{ ('a',123,145):20, ('a',155,170):12, ('b',234,345): 34}, 2:{ ('a',121,135):10, ('a',155,175):28, ('b',230,345): 16}, 3:{ ('a',130,140):20, ('a',150,170)...
combining values for a large number of overlapping intervals of dictionary keys
I have a dictionary of dictionaries that has items like this all={ 1:{ ('a',123,145):20, ('a',155,170):12, ('b',234,345): 34}, 2:{ ('a',121,135):10, ('a',155,175):28, ('b',230,345): 16}, 3:{ ('a',130,140):20, ('a',150,170):10, ('b',234,345): 30}, ... n: {...} } edit: The dictionary names are arbi...
[ "Ok, now i think i get it: Basically you have a bunch of overlapping intervals, represented by bars at a certain position with a given thickness. You would draw these bars below each other and see how thick they are together at any given point.\nI think it's easiest/fastest to abuse the fact that you have integer p...
[ 1, 0 ]
[]
[]
[ "data_structures", "dictionary", "python" ]
stackoverflow_0004620273_data_structures_dictionary_python.txt
Q: Can I add extra header information to a numpy .npy file by using seek? I want to store an array to file with some extra information in a header. I want to use the numpy binary '.npy' format. Can I read an array form a .npy file with an extra header by first seeking to the beginning of the array part? I want to d...
Can I add extra header information to a numpy .npy file by using seek?
I want to store an array to file with some extra information in a header. I want to use the numpy binary '.npy' format. Can I read an array form a .npy file with an extra header by first seeking to the beginning of the array part? I want to do something like this. If a have a header that is 'n' bytes: from tempfile ...
[ "Sure you can put metadata into a file header. But it is a bit complex, and unless the file format has a header for metadata already (which seems to be the case here, unless you can stick it into the description field .npy seems to have), it means you aren't actually using the .npy format, but your own format only ...
[ 1 ]
[]
[]
[ "numpy", "python", "serialization" ]
stackoverflow_0004620712_numpy_python_serialization.txt
Q: Google App Engine Python Simple Question In Google App Engine the datastore creates a new entry every time you assign it a value. What I Am trying to do is store a simple variable x. When a function is called 1 is added to x and it is stored again (and some other simple stuff that i have the code written already)....
Google App Engine Python Simple Question
In Google App Engine the datastore creates a new entry every time you assign it a value. What I Am trying to do is store a simple variable x. When a function is called 1 is added to x and it is stored again (and some other simple stuff that i have the code written already). How would i achieve this is python?
[ "Sounds like you're trying to keep a counter. This tutorial is good for using \"sharded counters\", that is, a counter that not only works like you expect, but also is much more efficient to update, since you won't have as much contention for the counter object.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004620542_google_app_engine_python.txt
Q: Com server build using Python on 64-bit Windows 7 machine Original post is here: http://mail.python.org/pipermail/python-win32/2010-December/011011.html I am using: OS: 64 bit Windows 7 Professional Python: python-2.7.1.amd64 Python win32 extensions: pywin32-214.win-amd64-py2.7 Py2exe: py2exe-0.6.9.win64-py2.7....
Com server build using Python on 64-bit Windows 7 machine
Original post is here: http://mail.python.org/pipermail/python-win32/2010-December/011011.html I am using: OS: 64 bit Windows 7 Professional Python: python-2.7.1.amd64 Python win32 extensions: pywin32-214.win-amd64-py2.7 Py2exe: py2exe-0.6.9.win64-py2.7.amd64 I am trying to build icon overlay for Windows. It has ...
[ "There's a bug in py2exe on 64 bit Python. The sys.frozendllhandle, initialized by py2exe, is invalid such that win32api.GetModuleFileName(sys.frozendllhandle) fails.\nYou might want to try the patched py2exe installers at http://www.lfd.uci.edu/~gohlke/pythonlibs/#py2exe\n" ]
[ 5 ]
[]
[]
[ "64_bit", "py2exe", "python", "pywin32" ]
stackoverflow_0004582819_64_bit_py2exe_python_pywin32.txt
Q: How to Sync MySQL with python? Im setting a VM. Both host and VM machine have Mysql. How do keep the VM Mysql sync'd to to the host Mysql. Host is using MYsql 5.5 on XP. VM is Mysql 5.1 on Fedora 14. 1) I could DUMP to "shared," Restore. Not sure if this will work. 2) I could network Mysql Host to Mysql VM. No...
How to Sync MySQL with python?
Im setting a VM. Both host and VM machine have Mysql. How do keep the VM Mysql sync'd to to the host Mysql. Host is using MYsql 5.5 on XP. VM is Mysql 5.1 on Fedora 14. 1) I could DUMP to "shared," Restore. Not sure if this will work. 2) I could network Mysql Host to Mysql VM. Not how to do this How would I do thi...
[ "You can use mysqldump to make snapshots of the database, and to restore it to known states after tests. \nBut instead or going into the complication of synchronizing different database instances, it would be best to open the host machine's instance to local network access, and have the applications in the virtual ...
[ 1, 0, 0 ]
[]
[]
[ "mysql", "python", "virtual_machine" ]
stackoverflow_0004619392_mysql_python_virtual_machine.txt
Q: From backslash to slash (to create folders named with number) I had a bad problem with these two: "\" and "/" in Windows, obviously :\ I need to replace all \ occurrence in /, so I can use replace() because doesn't work with this "\6" for example. What I have to do? I want "only" use mkdir() to replicate a struct...
From backslash to slash (to create folders named with number)
I had a bad problem with these two: "\" and "/" in Windows, obviously :\ I need to replace all \ occurrence in /, so I can use replace() because doesn't work with this "\6" for example. What I have to do? I want "only" use mkdir() to replicate a structure of folders (without files) from one location to another. So I u...
[ "construct your paths with os.path, then it's platform agnostic and you'll avoid these issues.\nFor example, mkdir(os.path.join(r\"C:\\\", \"6\"))\nor os.path.join(r\"D:\\\", \"main\", \"folder\", \"red\", \"34\")\n", "The backslash is an escape character in Python string literals. To actually use a literal back...
[ 3, 1, 1 ]
[]
[]
[ "mkdir", "python", "string" ]
stackoverflow_0004621447_mkdir_python_string.txt
Q: Library to create videos from pictures and text? Is there some library to generate a video from pictures and text? Something like animoto.com does but much simplier. I basically want to set one picture, and fade in and out text over that picture and make a video out of that. I am looking for something to run from ...
Library to create videos from pictures and text?
Is there some library to generate a video from pictures and text? Something like animoto.com does but much simplier. I basically want to set one picture, and fade in and out text over that picture and make a video out of that. I am looking for something to run from php or python, video format is not so important.
[ "Would you consider an animated GIF to be a video? If so use imagemagick!\n", "There is a pyffmpeg module at http://code.google.com/p/pyffmpeg/ which ought to be able to do this; I'll see if I can bash together an example.\nEdit: ok, I take it back. It doesn't look like pyffmpeg is being actively maintained, and...
[ 0, 0 ]
[]
[]
[ "php", "python", "video", "video_processing" ]
stackoverflow_0004620479_php_python_video_video_processing.txt
Q: Python: How to unshadow the keyword 'property'? I am supporting a legacy python application which has a class written as such (still running in python 2.4): class MyClass(object): def property(self, property_code, default): ... Now I am adding some new code to it: def _check_ok(self): ......
Python: How to unshadow the keyword 'property'?
I am supporting a legacy python application which has a class written as such (still running in python 2.4): class MyClass(object): def property(self, property_code, default): ... Now I am adding some new code to it: def _check_ok(self): ... ok = property(lamdba self:self._check_ok()) Ba...
[ "Python 2:\nimport __builtin__\n__builtin__.property\n\nPython 3:\nimport builtins\nbuiltins.property\n\n", "How about this:\n__builtins__.property(lamdba self:self._check_ok())\n\n" ]
[ 10, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004621718_python.txt
Q: Google App Engine Python adding class Config(db.Model): Latest = db.IntegerProperty() class New(webapp.RequestHandler): def get(self): config = Config() Last = Config.Latest t = Last + 1 returns t = LastUUID + ADDNUM TypeError: unsupported operand type(s) f...
Google App Engine Python adding
class Config(db.Model): Latest = db.IntegerProperty() class New(webapp.RequestHandler): def get(self): config = Config() Last = Config.Latest t = Last + 1 returns t = LastUUID + ADDNUM TypeError: unsupported operand type(s) for +: 'IntegerProperty' and 'Int' Wh...
[ "The changes you need are more than tweaking a single line.\nYou need some sort of initialisation function which will create a Config() instance, assign Latest an initial value (like 1 or 0) and store it in the datastore.\nThen your RequestHandler needs to execute a query to retrieve the relevant Config instance. F...
[ 3, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004610369_google_app_engine_python.txt
Q: How to crop image to a specified height and width in app engine - python? How can I crop image to a specified height and width? As I see this method takes the parameters between 0.0 and 1.0. crop(image_data, left_x, top_y, right_x, bottom_y), output_encoding=images.PNG) A: Divide the width you want to crop to by...
How to crop image to a specified height and width in app engine - python?
How can I crop image to a specified height and width? As I see this method takes the parameters between 0.0 and 1.0. crop(image_data, left_x, top_y, right_x, bottom_y), output_encoding=images.PNG)
[ "Divide the width you want to crop to by the width of the image; likewise for height. This will give you the percentages (values between 0 and 1) you need to pass to the Images API.\nIf you don't know the size of your image ahead of time, you can use the composite function - pass your image in as the sole input ima...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004619878_google_app_engine_python.txt
Q: Intricacies in Python's parser In what order are the contents of the expression"word" in [] == False parsed? It seems to defy all logic: >>> "word" in [] == False False >>> ("word" in []) == False True >>> "word" in ([] == False) TypeError How does Python actually interpret this expression, and why does it interp...
Intricacies in Python's parser
In what order are the contents of the expression"word" in [] == False parsed? It seems to defy all logic: >>> "word" in [] == False False >>> ("word" in []) == False True >>> "word" in ([] == False) TypeError How does Python actually interpret this expression, and why does it interpret it so? Edit: the most general ca...
[ "Normally you can find out operator precedence with this table.. \nBut this is actually a tricky example:\n\nComparisons can be chained\n arbitrarily, e.g., x < y <= z is\n equivalent to x < y and y <= z, except\n that y is evaluated only once (but in\n both cases z is not evaluated at all\n when x < y is foun...
[ 10, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004621938_python.txt
Q: What would happen if there's a power failure while the OS is in the middle of doing file I/O operations? OK, this question is actually a follow-up question from my previous one: What would happen if I abruptly close my script while it's still doing file I/O operations? So it's not possible to see an incomplete lin...
What would happen if there's a power failure while the OS is in the middle of doing file I/O operations?
OK, this question is actually a follow-up question from my previous one: What would happen if I abruptly close my script while it's still doing file I/O operations? So it's not possible to see an incomplete line written into a file whenever you force your script/program to quit, as the OS will do their job. But what if...
[ "Rule 1. There's no magic. No guarantee. No assurance. Power failure means the circuitry passes through states that are outside their design tolerances. Anything could happen. No guarantees.\n\nwhat if there's a power failure, and the OS is just in the middle of appending ... into a file, do I get an incomple...
[ 2, 1 ]
[]
[]
[ "file_io", "operating_system", "python" ]
stackoverflow_0004622284_file_io_operating_system_python.txt
Q: How to loop through a html-table-dataset in Python I'm first time poster here trying to pick up some Python skills; please be kind to me :-) While I'm not a complete stranger to programming concepts (I've been messing around with PHP before), the transition to Python has turned out to be somewhat difficult for me....
How to loop through a html-table-dataset in Python
I'm first time poster here trying to pick up some Python skills; please be kind to me :-) While I'm not a complete stranger to programming concepts (I've been messing around with PHP before), the transition to Python has turned out to be somewhat difficult for me. I guess this mostly has to do with the fact that I lack...
[ "The basic problem is that this table is marked up for looks, not for semantic structure. Properly done, each date and its related items should share a parent. Unfortunately, they don't, so we'll have to make do.\nThe basic strategy is to iterate through each row in the table\n\nif the first tabledata has class 'da...
[ 6, 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0004622117_beautifulsoup_python.txt
Q: Which editor/IDE is the best for editing Python scripts for Google App Engine? Which editor or IDE do you use when you edit Python scripts? Especially when you are working on Google App Engine. Do you know any editor/IDE which support Syntax highlighting and auto-completion for Google App Engine modules? Thanks in...
Which editor/IDE is the best for editing Python scripts for Google App Engine?
Which editor or IDE do you use when you edit Python scripts? Especially when you are working on Google App Engine. Do you know any editor/IDE which support Syntax highlighting and auto-completion for Google App Engine modules? Thanks in advance for any suggestion.
[ "PyDev on Eclipse will support partial code completion with GAE.\nhttp://pydev.org/\nhttp://www.eclipse.org/\n", "I've not only successfully got code completion (and 'go to definition') working on WingIDE, but also was able to run the local SDK through its debugger. See http://wingware.com/doc/howtos/google-app-e...
[ 3, 3, 3, 1, 1 ]
[]
[]
[ "editor", "google_app_engine", "ide", "python" ]
stackoverflow_0004622111_editor_google_app_engine_ide_python.txt
Q: What are the popular video formats I want to write a program to get the list of films in a computer. I thought there are 2 steps to this: Get the list of all the video files in the computer. Find out which of these are films. For the time being, I am interested in how to get the first step done. Where can I fin...
What are the popular video formats
I want to write a program to get the list of films in a computer. I thought there are 2 steps to this: Get the list of all the video files in the computer. Find out which of these are films. For the time being, I am interested in how to get the first step done. Where can I find a list of popular video file extensio...
[ "You will get the list of video file extensions from many places by doing a simple google search. Maintain a list of extensions and walk the directory path and see if the file ends with any of the them.\nlist_of_extensions = ['flv','mp4','avi'] # Supplement it with what you find.\nlist_of_files = []\n\n\nimport os\...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004622513_python.txt
Q: Google App Engine Python Datastore Basically what Im trying to make is a data structure where it has the users name, id, and datejoined. Then i want a "sub-structure" where it has the users "text" and the date it was modified. and the user will have multiple instances of this text. class User(db.Model): ID = d...
Google App Engine Python Datastore
Basically what Im trying to make is a data structure where it has the users name, id, and datejoined. Then i want a "sub-structure" where it has the users "text" and the date it was modified. and the user will have multiple instances of this text. class User(db.Model): ID = db.IntegerProperty() name = ...
[ "One problem you will have is that making User.ID unique will be non-trivial. The problem is that two writes to the database could occur on different shards, both check at about the same time for existing entries that match the uniqueness constraint and find none, then both create identical entries (with regard to...
[ 4, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004622071_google_app_engine_python.txt
Q: Python finding substring between certain characters using regex and replace() Suppose I have a string with lots of random stuff in it like the following: strJunk ="asdf2adsf29Value=five&lakl23ljk43asdldl" And I'm interested in obtaining the substring sitting between 'Value=' and '&', which in this example would b...
Python finding substring between certain characters using regex and replace()
Suppose I have a string with lots of random stuff in it like the following: strJunk ="asdf2adsf29Value=five&lakl23ljk43asdldl" And I'm interested in obtaining the substring sitting between 'Value=' and '&', which in this example would be 'five'. I can use a regex like the following: match = re.search(r'Value=?([^&>]+...
[ "Named groups make it easier to get the group contents afterwards. Compiling your regex once, and then reusing the compiled object, will be much more efficient than recompiling it for each use (which is what happens when you call re.search repeatedly). You can use positive lookbehind and lookahead assertions to m...
[ 9, 2, 0 ]
[]
[]
[ "python", "regex", "replace", "string" ]
stackoverflow_0004622472_python_regex_replace_string.txt
Q: Append JSON elements to a list, then remove duplicates efficiently in Python I have a json file that's like for e.g. [{"fu": "thejimjams", "su": 232104580}, {"fu": "thejimjams", "su": 216575430}, {"fu": "thejimjams", "su": 184695850}] I need to put all the values for a bunch of json files in the "su" categ...
Append JSON elements to a list, then remove duplicates efficiently in Python
I have a json file that's like for e.g. [{"fu": "thejimjams", "su": 232104580}, {"fu": "thejimjams", "su": 216575430}, {"fu": "thejimjams", "su": 184695850}] I need to put all the values for a bunch of json files in the "su" category in a list. So each file (about 200) will have their own list, then I'm going t...
[ "Do you care about order? If not you can add the numbers to a set() which will automatically remove duplicates. For example, if you have 200 \"su\" lists:\nlists = [\n [...su's for file 1...],\n [...su's for file 2...],\n etc.\n]\n\nThen you can combine them into one big set with:\nset(su for sus in lists ...
[ 4, 1, 1 ]
[]
[]
[ "arrays", "dictionary", "duplicates", "list", "python" ]
stackoverflow_0004622485_arrays_dictionary_duplicates_list_python.txt
Q: Real time output of subprocess.popen() and not line by line I'm currently rewriting a little wrapper program in python that I once wrote in C++. It extracts files from a file and boxes them in another format. In C++ the output from the system commands I need to run was "real time" i.e the status bar and the percen...
Real time output of subprocess.popen() and not line by line
I'm currently rewriting a little wrapper program in python that I once wrote in C++. It extracts files from a file and boxes them in another format. In C++ the output from the system commands I need to run was "real time" i.e the status bar and the percentage indicator of some commands where shown in real time. With py...
[ "Could be two things...\nIt's likely that readline is changing some things from the output of your\nprogram. I believe \\r is carriage return and tells the terminal\nto return to the beginning of the\nline and then the program can output overtop the text it just output.\nReadline is most likely removing this.\nFir...
[ 7, 1, 0 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0004620547_popen_python_subprocess.txt
Q: Running install mod_dav_svn and can't decipher thread error I am relatively new to Python, and at the same time, am attempting to install mod_dav_svn into my Apache web server. I am looking to get some idea of the scope of the error I'm receiving. At the command line, I type in 'sudo yum install mod_dav_svn' and r...
Running install mod_dav_svn and can't decipher thread error
I am relatively new to Python, and at the same time, am attempting to install mod_dav_svn into my Apache web server. I am looking to get some idea of the scope of the error I'm receiving. At the command line, I type in 'sudo yum install mod_dav_svn' and receive this output: Loaded plugins: fastestmirror Determining fas...
[ "Disable yum-fastermirror and you should be able to complete the install.\nyum --disableplugin=fastestmirror update\nAre you on a virtual machine?\n" ]
[ 0 ]
[]
[]
[ "apache", "linux", "module", "python", "trace" ]
stackoverflow_0004622562_apache_linux_module_python_trace.txt