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: Postgres - Sql - PgSql Cheatsheets I am developing some python queries using psycopg and I was looking for some good cheat sheet. Which Postgres - Sql - PgSql Cheatsheets do you use regularly during DB development? A: I just use the manual, it's well written and comprehensive. A: The guys from Postgresonline.c...
Postgres - Sql - PgSql Cheatsheets
I am developing some python queries using psycopg and I was looking for some good cheat sheet. Which Postgres - Sql - PgSql Cheatsheets do you use regularly during DB development?
[ "I just use the manual, it's well written and comprehensive.\n", "The guys from Postgresonline.com made a couple of cheatcheats.\nBut nothing can beat the fine manual :-)\n" ]
[ 7, 4 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0005359528_postgresql_psycopg2_python_sql.txt
Q: how to implement timeline (real-time - like twitter's) using tornado? guys, I want to implement a website, which need the function of timeline (just like twitter's). Now I'm using Tornado as the web framework. How can I get it? Thank you! A: The real time element of the twitter "timeline" is almost certainly a l...
how to implement timeline (real-time - like twitter's) using tornado?
guys, I want to implement a website, which need the function of timeline (just like twitter's). Now I'm using Tornado as the web framework. How can I get it? Thank you!
[ "The real time element of the twitter \"timeline\" is almost certainly a load of AJAX which periodically goes back to the server, requests any new posts and then updates the page with the results.\nGoogle has many suggestions on how to update a page using AJAX. Get reading :-)\n" ]
[ 1 ]
[]
[]
[ "python", "timeline", "tornado" ]
stackoverflow_0005360817_python_timeline_tornado.txt
Q: How to display and change an icon inside a python Tk Frame I have a python Tkinter Frame that displays several fields. I want to also add an red/yellow/green icon that will display the status of an external device. The icon is loaded from a file called ICON_LED_RED.ico. How do I display the icon in my frame? H...
How to display and change an icon inside a python Tk Frame
I have a python Tkinter Frame that displays several fields. I want to also add an red/yellow/green icon that will display the status of an external device. The icon is loaded from a file called ICON_LED_RED.ico. How do I display the icon in my frame? How do I change the icon at runtime? For example replace BitmapI...
[ "The problem is that you are mixing grid and pack in the same container. This is quite often the cause of a GUI freezing. The problem is, the grid manager resizes everything to fit, then the pack manager sees a change and resizes things to fit. The grid manager sees a change and resizes things to fit, and ...\nYou ...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005360052_python_tkinter.txt
Q: how to connect to a printer and print a png image using python and PIL library in Ubuntu how to connect to a printer and print a png image using python and PIL library in Ubuntu A: subprocess.call(['lp', 'foo.png'])
how to connect to a printer and print a png image using python and PIL library in Ubuntu
how to connect to a printer and print a png image using python and PIL library in Ubuntu
[ "subprocess.call(['lp', 'foo.png'])\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005360862_python.txt
Q: Best practices when accessing the attributes and methods of other classes this is a best practices type of question. I want to access the attributes and methods of one class from another(maybe this is a bad practice in itself) and what i'm doing to achieve this is class table(): def __init__(self): sel...
Best practices when accessing the attributes and methods of other classes
this is a best practices type of question. I want to access the attributes and methods of one class from another(maybe this is a bad practice in itself) and what i'm doing to achieve this is class table(): def __init__(self): self.color = 'green' colora = 'red' def showColor(self): print('...
[ "more explixitly, if you want to access table.color from pencil, you don't need to wrap it in a method, but you need to call the table constructor first:\nclass table():\n\n colora = 'red'\n def __init__(self):\n self.color = 'green'\n print 'table: table.color', self.color\n print 'table...
[ 3, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0005360636_inheritance_python.txt
Q: How do I embed an open-source project in a django project for GAE? I am a python newbie. Can anybody tell me how I will be embed an open-source project in my django project for GAE? Let's say I would like to embed Python markdown. Can anybody show me a direction? Can I just copy and paste my source into my django ...
How do I embed an open-source project in a django project for GAE?
I am a python newbie. Can anybody tell me how I will be embed an open-source project in my django project for GAE? Let's say I would like to embed Python markdown. Can anybody show me a direction? Can I just copy and paste my source into my django folder and modify something in the settings.py to get it done? The reaso...
[ "Simply unzip the contents of the folder inside the .egg archive which is not named EGG-INFO to your application folder.\n", "Obviously you are inteding to use the python version of appengine, for every external library that you want to deploy with your application, except from importing in my own experience when...
[ 3, 2, 1, 1 ]
[]
[]
[ "django", "google_app_engine", "inclusion", "open_source", "python" ]
stackoverflow_0005348913_django_google_app_engine_inclusion_open_source_python.txt
Q: Python String memory usage on FreeBSD I'm observing a strange memory usage pattern with python strings on Freebsd. Consider the following session. Idea is to create a list which holds some strings so that cumulative characters in the list is 100MB. l = [] for i in xrange(100000): l.append(str(i) * (1000/len(st...
Python String memory usage on FreeBSD
I'm observing a strange memory usage pattern with python strings on Freebsd. Consider the following session. Idea is to create a list which holds some strings so that cumulative characters in the list is 100MB. l = [] for i in xrange(100000): l.append(str(i) * (1000/len(str(i)))) This uses around 100MB of memory a...
[ "In my opinion, that would probably be fragments in memory. First of all, memory chunks which are bigger than 255 bytes will be allocated with malloc in CPython. You can reference to\nImproving Python's Memory Allocator\nFor performance reason, most of memory allocation, like malloc, will return a aligned address. ...
[ 1, 0, 0 ]
[]
[]
[ "freebsd", "malloc", "python" ]
stackoverflow_0005342600_freebsd_malloc_python.txt
Q: Memory issues with as.dist function in R/rpy2 I'm trying to perform a hierarchical clustering using a custom distance measure. I perform all the calculations in Python and then pass the data structures to R to do the clustering import rpy2.robjects as robjects r=robjects.r from rpy2.robjects.packages import import...
Memory issues with as.dist function in R/rpy2
I'm trying to perform a hierarchical clustering using a custom distance measure. I perform all the calculations in Python and then pass the data structures to R to do the clustering import rpy2.robjects as robjects r=robjects.r from rpy2.robjects.packages import importr stats = importr('stats') m = r.matrix(robjects.F...
[ "Calling Python's del() does not guarantee that the memory is becoming immediately available for use. Calling the garbage collector explicitly helps. The answer to an other question here (Clearing memory used by rpy2) points to the relevant section in the rpy2 documentation.\nRegarding clustering algorithms hierach...
[ 2 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0005354840_python_r_rpy2.txt
Q: how to get the two '111 = ' using python Regular Expressions this is mu\y code: a = '111 = dw11qdwq\n111 = aaaaa' print re.search(r'111 = (\S*)',a).group(1) it show : dw11qdwq but i want get dw11qdwq and aaaaa so what can i do , thanks updated a = '111 = dw11qdwq\n111 = aaaaa' b=re.findall(r'111 = (\S*)',a) d ...
how to get the two '111 = ' using python Regular Expressions
this is mu\y code: a = '111 = dw11qdwq\n111 = aaaaa' print re.search(r'111 = (\S*)',a).group(1) it show : dw11qdwq but i want get dw11qdwq and aaaaa so what can i do , thanks updated a = '111 = dw11qdwq\n111 = aaaaa' b=re.findall(r'111 = (\S*)',a) d = ['qqqqqq','wwwwwww'] a= re.sub(r'111 = (\S*)',lambda x: d[],a) ...
[ "a = '111 = dw11qdwq\\n111 = aaaaa'\n\nprint re.findall(r'111 = (\\S+)',a)\n\nThis matches any word with 1 or more non-space characters. (I'm fairly sure you don't want to match 0 or more characters(which is what '*' provide))\nEdit:\nCode for your update:\nreplacements = {\"dw11qdwq\":\"qqqqqq\" , \"aaaaa\" : \"ww...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005359751_python_regex.txt
Q: What does __setattr__ do in this python code? this is my code: class fun: def __getattr__(self,key): return self[key] def __setattr__(self,key,value): self[key] = value+1 a = fun() a['x']=1 print a['x'] and the error is : AttributeError: fun instance has no attribute '__getitem__' when ...
What does __setattr__ do in this python code?
this is my code: class fun: def __getattr__(self,key): return self[key] def __setattr__(self,key,value): self[key] = value+1 a = fun() a['x']=1 print a['x'] and the error is : AttributeError: fun instance has no attribute '__getitem__' when i change it to : class fun: def __getattr__(se...
[ "The problem is that self.key = ... invokes __setattr__, so you end up in an infinite recursion. To use __setattr__, you have to access the object's field some other way. There are two common solutions:\ndef __setattr__(self,key,value):\n # Access the object's fields through the special __dict__ field\n self....
[ 7, 3, 1 ]
[]
[]
[ "get", "python", "set" ]
stackoverflow_0005361291_get_python_set.txt
Q: How to check is first character is ñ - Django I get a word from a form, and to slugify it I want to differentiate it. Using django's slugify if I get the word 'Ñandu', the slug becomes 'nandu'. And if I get the word 'Nandu' the slug also becomes 'nandu'. So I decided that if the word starts with 'Ñ' the slug will ...
How to check is first character is ñ - Django
I get a word from a form, and to slugify it I want to differentiate it. Using django's slugify if I get the word 'Ñandu', the slug becomes 'nandu'. And if I get the word 'Nandu' the slug also becomes 'nandu'. So I decided that if the word starts with 'Ñ' the slug will become 'word_ene'. The problem is I can't find a wa...
[ "This works for me:\n>>> str = u\"Ñandu\"\n>>> str[0] == u\"\\xd1\"\nTrue\n>>> if str[0] == u\"\\xd1\": print \"Begins with \\xd1!\"\nBegins with Ñ!\n\nWatch out for case; lower case ñ is encoded as u\"\\xf1\".\n", "If you type things like u\"ñ\" directly in the code, then you have to remember about putting sth l...
[ 4, 0 ]
[]
[]
[ "django", "non_ascii_characters", "python", "unicode" ]
stackoverflow_0005358984_django_non_ascii_characters_python_unicode.txt
Q: Why does (()) equal ()? >>> (()) == () True >>> (()) () A: () is a 0-tuple. (foo) results in the value of foo. Hence, (()) results in a 0-tuple. From the tutorial: ; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). A: ...
Why does (()) equal ()?
>>> (()) == () True >>> (()) ()
[ "() is a 0-tuple. (foo) results in the value of foo. Hence, (()) results in a 0-tuple.\nFrom the tutorial:\n\n; a tuple with one item is constructed\n by following a value with a comma (it\n is not sufficient to enclose a single\n value in parentheses).\n\n", "For the same reason that (4) == 4: adding parenthe...
[ 12, 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005361416_python.txt
Q: emacs 23 python.el auto-indent style -- can this be configured? I have been using emacs 23 (python.el) for just over a month now and I'm unhappy with the default auto-indentation settings. Currently, my Python files are auto-indented as follows: x = a_function_with_dict_parameter({ ...
emacs 23 python.el auto-indent style -- can this be configured?
I have been using emacs 23 (python.el) for just over a month now and I'm unhappy with the default auto-indentation settings. Currently, my Python files are auto-indented as follows: x = a_function_with_dict_parameter({ 'test' : 'Here is a value', 'se...
[ "You can try this peace of code :\n(require 'python)\n\n; indentation\n(defadvice python-calculate-indentation (around outdent-closing-brackets)\n \"Handle lines beginning with a closing bracket and indent them so that\n they line up with the line containing the corresponding opening bracket.\"\n(save-excursion\n...
[ 3, 1 ]
[ "M-x customize-group RET\npython RET\n" ]
[ -1 ]
[ "coding_style", "emacs", "indentation", "python" ]
stackoverflow_0005094649_coding_style_emacs_indentation_python.txt
Q: Services dependency and interaction in Twisted Python while working on Twisted, I was wondering if there is: a way to explicitly define services dependencies (e.g. in order to start service B, before I need to fire service A) a "pythonic" way to make two services communicate (e.g. B shares information with A, A c...
Services dependency and interaction in Twisted Python
while working on Twisted, I was wondering if there is: a way to explicitly define services dependencies (e.g. in order to start service B, before I need to fire service A) a "pythonic" way to make two services communicate (e.g. B shares information with A, A can control B execution) Thanks
[ "Take a look at Twisted Application Documentation. It sounds like you want to create a MultiService each with its own sub-Service implementation. What you do is define a number of services, implementing a startService and stopService and arrange your services in a tree hierarchy (via setServiceParent) to determine ...
[ 3 ]
[]
[]
[ "python", "service", "twisted" ]
stackoverflow_0005287142_python_service_twisted.txt
Q: When is {!s} meaningful in format()? >>> import math >>> print "{} {!s} {!r}".format(math.pi, math.pi, math.pi) 3.14159265359 3.14159265359 3.141592653589793 When is the !s inside {} meaningful? Or in other words, when is calling str() on a format() argument meaningful? A: Whenever the type to be printed implem...
When is {!s} meaningful in format()?
>>> import math >>> print "{} {!s} {!r}".format(math.pi, math.pi, math.pi) 3.14159265359 3.14159265359 3.141592653589793 When is the !s inside {} meaningful? Or in other words, when is calling str() on a format() argument meaningful?
[ "Whenever the type to be printed implements __format__ in an an unsuitable way for your purpose. In this case, you can use !s or !r (and I think there is even !a) to specify an alternate formatter.\nYou certainly won't need it for printing floating-point numbers, but probably for custom types.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005361951_python.txt
Q: webcam using phone am tryin to create an app that should make my cellphone work as a webcam ... there are softwres like smart cam for that... also there is an app like mycam that lets you use a gif and create a vistual cam ... i want to know how an app like that works... i want to know which directory to put the ...
webcam using phone
am tryin to create an app that should make my cellphone work as a webcam ... there are softwres like smart cam for that... also there is an app like mycam that lets you use a gif and create a vistual cam ... i want to know how an app like that works... i want to know which directory to put the temp images for the vide...
[ "It depends more on the operating system of your phone, not your computer.\nFor Android, check out IP Webcam. For iPhone, check out iWebcamera.\nFor Symbian, SmartCam is open source.\n" ]
[ 1 ]
[]
[]
[ "python", "ubuntu_10.04", "webcam" ]
stackoverflow_0005362227_python_ubuntu_10.04_webcam.txt
Q: How do I optimize retrieval of related records in self referencing model in django? I am creating a form from a model. This form contains a category. The category model is a self referencing model. I want to display the categories in a dropdown on the form so they show their parent categories too. ie, parentcat3 >...
How do I optimize retrieval of related records in self referencing model in django?
I am creating a form from a model. This form contains a category. The category model is a self referencing model. I want to display the categories in a dropdown on the form so they show their parent categories too. ie, parentcat3 > parentcat2 > parentcat1 > leafcategory the last category is denoted by leafCategory=True...
[ "This code is incredibly inefficient. It will do a new series of database queries for every single category, and for each category's ancestor.\nYou need to look into the algorithms that are optimised for storing and retrieving this sort of hierarchical data in a database. django-mptt is my favourite of these.\nAs a...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_queryset", "python" ]
stackoverflow_0005362174_django_django_forms_django_queryset_python.txt
Q: swig undefined symbol on templates with static members in python The need is to export to python with swig a portion of a templated class with some static members. All compiles well and the module is correctly created with the name _pipeit.so; the problem comes when from python i execute import pipeit as it gives ...
swig undefined symbol on templates with static members in python
The need is to export to python with swig a portion of a templated class with some static members. All compiles well and the module is correctly created with the name _pipeit.so; the problem comes when from python i execute import pipeit as it gives the following error: ImportError: ./_pipeit.so: undefined symbol: _ZN...
[ "Where is the destructor ~FactoriesPool() defined? The runtime linker is looking for it.\n" ]
[ 1 ]
[]
[]
[ "c++", "python", "static_members", "swig", "templates" ]
stackoverflow_0005362097_c++_python_static_members_swig_templates.txt
Q: Chained Python class invocations I am trying to build a set of classes to define hierarchical properties for protocols in the OSI stack... in an abstract sense, I just need to inherit properties from parent python classes, but I need to be able to invoke the entire class chain at once... so, I'm looking for someth...
Chained Python class invocations
I am trying to build a set of classes to define hierarchical properties for protocols in the OSI stack... in an abstract sense, I just need to inherit properties from parent python classes, but I need to be able to invoke the entire class chain at once... so, I'm looking for something like this... #!/usr/bin/env python...
[ "Take a look how it is done in scapy:\n$ sudo scapy\nWelcome to Scapy (2.1.0) \n>>> sr(IP(dst=\"8.8.8.8\") / UDP() / DNS(rd=1,qd=DNSQR(qname=\"stackoverflow.com\")))\nBegin emission:\n..............................Finished to send 1 packets.\n.............*\nReceived 44 packets, got 1 answers, remaining 0 packets\n...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005362247_python.txt
Q: When is "raise Class, instance" useful? If you have an exception instance, why would you need to specify its class? What's the advantage over simply raise instance? A: There's no reason ever to use it really. It's archaic usage from back before exceptions had to be class instances, and it's gone in Python 3. A:...
When is "raise Class, instance" useful?
If you have an exception instance, why would you need to specify its class? What's the advantage over simply raise instance?
[ "There's no reason ever to use it really. It's archaic usage from back before exceptions had to be class instances, and it's gone in Python 3.\n", "There is no advantage. raise Class, instance is a legacy expression and is completely equivalent to raise instance. Especially, the first notation is removed in Pytho...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005362425_python.txt
Q: How can I paste some string to the active window in Python? Possible Duplicate: How do I copy a string to the clipboard on Windows using Python? Can someone make me an example or explain to me how can I paste something to the active window with Python? I've edited because I didn't know that paste to the clipboar...
How can I paste some string to the active window in Python?
Possible Duplicate: How do I copy a string to the clipboard on Windows using Python? Can someone make me an example or explain to me how can I paste something to the active window with Python? I've edited because I didn't know that paste to the clipboard doesnt paste to the active window...
[ "since you haven't accepted the duplicate as an answer may i suggest:\nimport win32com.client\nshell = win32com.client.Dispatch(\"WScript.Shell\")\nshell.SendKeys('keys to send to active window...')\n\nfrom:\nhere\nand if you need to find out about keys like Backspace go to\nhere\n" ]
[ 3 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003048307_python_windows.txt
Q: In the Inline "open and write file" is the close() implicit? In Python (>2.7) does the code : open('tick.001', 'w').write('test') has the same result as : ftest = open('tick.001', 'w') ftest.write('test') ftest.close() and where to find documentation about the 'close' for this inline functionnality ? A: The...
In the Inline "open and write file" is the close() implicit?
In Python (>2.7) does the code : open('tick.001', 'w').write('test') has the same result as : ftest = open('tick.001', 'w') ftest.write('test') ftest.close() and where to find documentation about the 'close' for this inline functionnality ?
[ "The close() here happens when the file object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to open() like this without a close(). Th...
[ 25 ]
[]
[]
[ "file", "python" ]
stackoverflow_0005362901_file_python.txt
Q: why my Multi-threading code spend More time than Single-threading code this is my code : import re,threading class key_value: def __init__(self,filename='a.txt'): self.filename = filename def __getitem__(self,key): file = open(self.filename,'r') data = file.read() value =...
why my Multi-threading code spend More time than Single-threading code
this is my code : import re,threading class key_value: def __init__(self,filename='a.txt'): self.filename = filename def __getitem__(self,key): file = open(self.filename,'r') data = file.read() value = re.findall(r''+str(key)+' - (\S+)',data) return value def __set...
[ "CPython (the main Python implementation) doesn't multi-thread. The GIL gets in the way. So you just have two threads running on one core (i.e. they don't run in parallel) but with all the context switching and other overhead a thread necesarily has. Note though:\n\nEven if you do multi-thread, you're still limited...
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005362732_multithreading_python.txt
Q: Python: Substracting between list of dictionaries I have 2 list containing dictionaries as follows: listone = [{'unit1': {'test1': 10}}, {'unit1': {'test2': 45'}, {'unit2': {'test1': 78'}, {'unit2': {'test2': 2'}}] listtwo = [{'unit1': {'test1': 56}}, {'unit1': {'te...
Python: Substracting between list of dictionaries
I have 2 list containing dictionaries as follows: listone = [{'unit1': {'test1': 10}}, {'unit1': {'test2': 45'}, {'unit2': {'test1': 78'}, {'unit2': {'test2': 2'}}] listtwo = [{'unit1': {'test1': 56}}, {'unit1': {'test2': 34'}, {'unit2': {'test1': 23'}, ...
[ "Perhaps convert your data to a different, more convenient data structure.\nFor example, instead of listone, it would be easier to work with a single dict like this:\n{('unit1', 'test1'): 10,\n ('unit2', 'test1'): 78,\n ('unit2', 'test2'): 2,\n ('unit1', 'test2'): 45}\n\nSo given,\nimport itertools\nunits = ['unit1...
[ 2, 1, 1, 1 ]
[]
[]
[ "delta", "dictionary", "list_comprehension", "python" ]
stackoverflow_0005362644_delta_dictionary_list_comprehension_python.txt
Q: Video output within Tkinter? I posted a similar question a while ago but haven't received any answers so i thought i might ask a more generic question: Does anyone know how to, through any means, output true video, not a rapidly changing sequence of images, in a Tkinter window with python? A: You probably need a...
Video output within Tkinter?
I posted a similar question a while ago but haven't received any answers so i thought i might ask a more generic question: Does anyone know how to, through any means, output true video, not a rapidly changing sequence of images, in a Tkinter window with python?
[ "You probably need an extension like TkVideo or Quicktime to do that, not sure there is a python style wrapper for it available yet.\nhttps://github.com/patthoyts/tkvideo\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter", "video" ]
stackoverflow_0005362613_python_tkinter_video.txt
Q: Is it possible to create a Tkinter Window with no frame, and no background? I've looked through the documentation, and searched quite a bit now, and couldn't find an answer for this problem. Before I give up, I'll ask here. I want to create a window that has no frame (as in, no titlebar, no border around the windo...
Is it possible to create a Tkinter Window with no frame, and no background?
I've looked through the documentation, and searched quite a bit now, and couldn't find an answer for this problem. Before I give up, I'll ask here. I want to create a window that has no frame (as in, no titlebar, no border around the window), and maybe a transparent background. I've found how to set the background to a...
[ "No border is possible. Try something like wm transient or wm overrideredirect.\nTransparent depends, have a look at the documentation for wm attributes:\nhttp://www.tcl.tk/man/tcl/TkCmd/wm.htm#M8 On windows you can set a transparentcolor.\nOtherwise you might need a platform specific extension to create oddly shap...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005363432_python_tkinter.txt
Q: Get around raising IndexError My code is as follows : for p in qs: set = None try: set = p.property.property_locations.all() except IndexError: pass if set: Problem is that when set is none it still throws IndexError from this part of django.db.models.query: try: qs = self._cl...
Get around raising IndexError
My code is as follows : for p in qs: set = None try: set = p.property.property_locations.all() except IndexError: pass if set: Problem is that when set is none it still throws IndexError from this part of django.db.models.query: try: qs = self._clone() qs.query.set_limits(k, k ...
[ "In any case, there are two mistakes in your code:\n\nset is a builtin (as you can see from SO's syntax highlighting), so by giving your variable that name you're shadowing the builtin for no purpose, which is at least bad practice, and likely to cause issues later in the code.\nThe canonical way to check if set is...
[ 13 ]
[]
[]
[ "django", "exception", "list", "python" ]
stackoverflow_0005166887_django_exception_list_python.txt
Q: Django: Invalid block tag 'form.username' I'm new to Django and I'm trying to create a login page. Here's (part of) my urls.py file: urlpatterns = patterns('', (r'^$', main_page), (r'^login/$', 'django.contrib.auth.views.login'), ) And here's the template for my login page (registration/login.html): <html...
Django: Invalid block tag 'form.username'
I'm new to Django and I'm trying to create a login page. Here's (part of) my urls.py file: urlpatterns = patterns('', (r'^$', main_page), (r'^login/$', 'django.contrib.auth.views.login'), ) And here's the template for my login page (registration/login.html): <html> <head> <title>User Login</title> </head> <bo...
[ "form is a context variable, not a template tag. So access it via {{ form }} or {{ form.username }}!\n", "Problem solved.\nThere was a confusion between {% ... %} and {{ ... }}.\n{{ variable name }}\n{% command %}\nIt's supposed to be {{ form.username }} and {{ form.password }} \ninstead of {% form.username %} an...
[ 7, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005363679_django_python.txt
Q: Could python have suffix-based number notation for engineering purposes? As an electrical engineer I (we?) use python for helping out with calculation/automation/etc. When dealing with calculations using some real-world numbers it is VERY common to think in -nano, -pico, -tera, etc. way. For example: I know what a...
Could python have suffix-based number notation for engineering purposes?
As an electrical engineer I (we?) use python for helping out with calculation/automation/etc. When dealing with calculations using some real-world numbers it is VERY common to think in -nano, -pico, -tera, etc. way. For example: I know what a 1pF capacitor is, but 1e-12 F capacitor is somewhow less friendly. Also, it i...
[ "Sure. Just write your own parser and generate your own AST with Python's language services.\n", "You could create a module with all the necessary units as symbols, say units.py, containing something like\npico = 1*e-12\nnano = 1*e-9\nmicro = 1*e-6\nmili = 1*e-3 \n\nFarad = 1\n\npF = pico*Farad\nnF = nano*Farad\n...
[ 3, 3, 1, 1 ]
[]
[]
[ "notation", "numbers", "python" ]
stackoverflow_0005361079_notation_numbers_python.txt
Q: Virtualenv and pip on a mac, does it pickup the environment automatically? Does python's pip with virutalenv automatically detect the virtualenv based on the folder you are on (similar to how ruby and rvm does)? i.e. I may have many virtual environments, and as I just through projects it will automatically change ...
Virtualenv and pip on a mac, does it pickup the environment automatically?
Does python's pip with virutalenv automatically detect the virtualenv based on the folder you are on (similar to how ruby and rvm does)? i.e. I may have many virtual environments, and as I just through projects it will automatically change the environment?
[ "No, virtualenv's are not activated based on your current working directory. To activate a virtualenv, run the source ../bin/activate command from the folder of the specific virtualenv you wish to activate.\n", "As far as I know, no, it won't. I've recently started using virtualenvwrapper, which provides you wit...
[ 1, 0 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0005363633_pip_python_virtualenv.txt
Q: Rope / Ropemacs - Auto Import feature I'm using Rope and Ropemacs to transform my emacs as a IDE for Python. I have a problem with the rope-auto-import feature. I read in the doc that I must add modules that I want to autoimport like this: (setq ropemacs-autoimport-modules '("os" "shutil")) But I want to autoimpo...
Rope / Ropemacs - Auto Import feature
I'm using Rope and Ropemacs to transform my emacs as a IDE for Python. I have a problem with the rope-auto-import feature. I read in the doc that I must add modules that I want to autoimport like this: (setq ropemacs-autoimport-modules '("os" "shutil")) But I want to autoimport all modules installed on my computer. Ho...
[ "I miss the same feature but unfortunately it is not possible to tell rope/ropemacs to enable autoimport for all modules. You have to manually add the modules to the ropemacs-autoimport-modules variable.\nSee the last messages of this thread:\nhttp://groups.google.com/group/rope-dev/browse_thread/thread/6d4778e7bed...
[ 3 ]
[]
[]
[ "emacs", "python", "rope", "ropemacs" ]
stackoverflow_0004530776_emacs_python_rope_ropemacs.txt
Q: simple archery game in python I'm just starting out with python and I'm trying to make a little archery game. However, it creates an error at this point: d = math.sqrt(x*x + y*y) (i.e. the distance between the new point and the original center of the cirlce) Any ideas on why this doesn't work? def archery(): ...
simple archery game in python
I'm just starting out with python and I'm trying to make a little archery game. However, it creates an error at this point: d = math.sqrt(x*x + y*y) (i.e. the distance between the new point and the original center of the cirlce) Any ideas on why this doesn't work? def archery(): win = GraphWin("Archery Game", 5...
[ " x = p.getX\n y = p.getY\n\nwill return the function getX and getY instead of executing it. As Mike Steder said, try getX(), that should return a value.\n", "First, you probably need to do:\nx = p.getX()\ny = p.getY()\n\ni.e. call the functions and use the return value, instead of using the functions thems...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005108434_python.txt
Q: Python PySide (Internal c++ Object Already Deleted) I recently decided to write my first app with Python and PySide. But I have a problem and hope you guys can help. Python keeps raising exceptions that the "Internal C++ Object" is deleted. From my limited experience with Python I figure that my object is going ou...
Python PySide (Internal c++ Object Already Deleted)
I recently decided to write my first app with Python and PySide. But I have a problem and hope you guys can help. Python keeps raising exceptions that the "Internal C++ Object" is deleted. From my limited experience with Python I figure that my object is going out of scope and being deleted by Python's Garbage Collecto...
[ "After some searching and hair pulling, I found the solution. I was showing all the pages by setting them as the central widget, and when reading the QMainWindow documentation I found that my widget basically gets deleted by qt as stated:\n\nNote: QMainWindow takes ownership of\n the widget pointer and deletes it ...
[ 20, 16 ]
[]
[]
[ "pyside", "python" ]
stackoverflow_0005339062_pyside_python.txt
Q: creating multiple audio streams of an icecast2 server using python-shout I am trying to create a web radio server to stream 3 sources at once. I am using python to create a source client for icecast2 using the python-shout library. I am not too familiar with the language (python). however, i got a sample program w...
creating multiple audio streams of an icecast2 server using python-shout
I am trying to create a web radio server to stream 3 sources at once. I am using python to create a source client for icecast2 using the python-shout library. I am not too familiar with the language (python). however, i got a sample program which does what i need to and more and i have tweaked it for my need. However, ...
[ "So, it turns out that my code is correct. The problem was in the configuration for Icecast. By default, only two streams can be created. after editing that in the icecast config file, It all worked perfectly. Thanks.\n" ]
[ 4 ]
[]
[]
[ "audio", "audio_streaming", "icecast", "python" ]
stackoverflow_0005303445_audio_audio_streaming_icecast_python.txt
Q: PYQT files paths to tree I'm working on a project in which I need to display some folders in a Tree view. I have a list of full file paths like: C:\folder1\file1 C:\folder1\folder11\file2 C:\folder2\file3 etc Well the file paths are actually stored in a sql server which I aquire by running a query. I'm looking f...
PYQT files paths to tree
I'm working on a project in which I need to display some folders in a Tree view. I have a list of full file paths like: C:\folder1\file1 C:\folder1\folder11\file2 C:\folder2\file3 etc Well the file paths are actually stored in a sql server which I aquire by running a query. I'm looking for a way to put this into a QT...
[ "Pls, see if an example below would work for you:\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass TestSortFilterProxyModel(QtGui.QSortFilterProxyModel):\n def __init__(self, parent=None):\n super(TestSortFilterProxyModel, self).__init__(parent)\n self.filter = ['folder0/file0', 'folder1/file1...
[ 2 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005359377_pyqt_python.txt
Q: how to pass arguments to a function using a predefined SIGNAL in PyQT lets suppose you have 3 QRadioButtons instances inside a class self.Option1 = QRadioButton() self.Option2 = QRadioButton() self.Option2 = QRadioButton() (for brevity i didn't wrote the entire script) and you want to use them to execute a partic...
how to pass arguments to a function using a predefined SIGNAL in PyQT
lets suppose you have 3 QRadioButtons instances inside a class self.Option1 = QRadioButton() self.Option2 = QRadioButton() self.Option2 = QRadioButton() (for brevity i didn't wrote the entire script) and you want to use them to execute a particular function when the user clicks it, so you do self.connect(self.Option1...
[ "The Qt solution of this problem is QSignalMapper I think. But I had the same problem before, and I figured out using \"partial\" function is simplier. Use it like that:\nfrom functools import partial\n\nself.connect(self.Option1,SIGNAL(\"clicked()\"), partial(self.myFunction, 1))\nself.connect(self.Option2,SIGNAL(...
[ 5 ]
[]
[]
[ "pyqt4", "python", "signals_slots" ]
stackoverflow_0005364291_pyqt4_python_signals_slots.txt
Q: python wnck not returning any data until after a pdb.set_trace() On Ubuntu Linux / Gnome, I am trying to use python's wnck binding to get a list of all the open windows. My code looks like this: #! /usr/bin/python from pprint import pprint import wnck screen = wnck.screen_get_default() pprint(screen.get_windows...
python wnck not returning any data until after a pdb.set_trace()
On Ubuntu Linux / Gnome, I am trying to use python's wnck binding to get a list of all the open windows. My code looks like this: #! /usr/bin/python from pprint import pprint import wnck screen = wnck.screen_get_default() pprint(screen.get_windows()) import pdb ; pdb.set_trace() pprint(screen.get_windows()) The o...
[ "File so-wnck.py (from How might I grab all windows with a certain word in their titles?)\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport wnck\n\nscreen = wnck.screen_get_default()\nwhile gtk.events_pending():\n gtk.main_iteration()\n\nwindows = screen.get_windows()\nprint (windows)\n\n\npython so-wnck.p...
[ 1, 0 ]
[]
[]
[ "gnome", "python", "window_managers", "wnck" ]
stackoverflow_0005352027_gnome_python_window_managers_wnck.txt
Q: How do I package a python application to make it pip-installable? I'm writing a django application in my spare time for a footy-tipping competition we're running at work. I figured I'd use this time wisely, and get up to speed on virtualenv, pip, packaging, django 1.3, and how to write an easily redistributable ap...
How do I package a python application to make it pip-installable?
I'm writing a django application in my spare time for a footy-tipping competition we're running at work. I figured I'd use this time wisely, and get up to speed on virtualenv, pip, packaging, django 1.3, and how to write an easily redistributable application. So far, so good. I'm up to the packaging part. A lot of the ...
[ "Yes, MANIFEST.in and setup.py should be sufficient.\nThis blog post really has some good information on this topic: \nPackaging a Django reusable app\nAnd here's another good, detailed overview that helped me a lot: \nPython Packaging User Guide\nEspecially the tips to get your static files (templates) included ar...
[ 89 ]
[]
[]
[ "dependencies", "django", "pip", "python" ]
stackoverflow_0005360873_dependencies_django_pip_python.txt
Q: searching & comparing valuse in csv files with python I have two csv files - a master & an update file. I want take specific columns from the update file, & check the values against the master. Both files will have the same columns & should look roughly like this: Listed Company's English Name,Listed Company's Ch...
searching & comparing valuse in csv files with python
I have two csv files - a master & an update file. I want take specific columns from the update file, & check the values against the master. Both files will have the same columns & should look roughly like this: Listed Company's English Name,Listed Company's Chinese Name,Stock Code,Listing Status,Director's English Nam...
[ "Do this help you ? :\nfile master.csv\nListed Company's English Name,Listed Company's Chinese Name,Stock Code,Listing Status,Director's English Name,Director's Chinese Name,Capacity,Position,Appointment Date (yyyy-mm-dd),Resignation Date (yyyy-mm-dd) \nC.P. Lotus Corporation,________,00122,Current,CHEARAVANONT Dh...
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005350477_csv_python.txt
Q: how do I use the facebook api to modify a video title or description? How can I update the title/description of a previously updated video? I am using python and pyfacebook... but any starting point would be fine and I can write it in python. A: I don't think it's possible to edit a Video object at all with the...
how do I use the facebook api to modify a video title or description?
How can I update the title/description of a previously updated video? I am using python and pyfacebook... but any starting point would be fine and I can write it in python.
[ "I don't think it's possible to edit a Video object at all with the Graph API at the moment. You can't create objects through the API, therefore I don't think you can edit or modify existing ones either.\n" ]
[ 0 ]
[]
[]
[ "facebook", "facebook_fql", "facebook_graph_api", "python" ]
stackoverflow_0005172735_facebook_facebook_fql_facebook_graph_api_python.txt
Q: How can I check if a particular value exists in a particular column in google app engine datastore?(python) Suppose I have a table with the Column A and B. I want to find out whether a particular field exists in Column A. I also want to know how many of them are there A: Suppose you have a Model that looks like ...
How can I check if a particular value exists in a particular column in google app engine datastore?(python)
Suppose I have a table with the Column A and B. I want to find out whether a particular field exists in Column A. I also want to know how many of them are there
[ "Suppose you have a Model that looks like this:\nclass Employee(db.Model):\n name = db.StringProperty()\n\nYou can query the existence of a particular value and/or the total number of entities which have that value in a property, you can query like so:\ndef jack_chan_in_employee():\n query = Employee.all()\n ...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005364938_google_app_engine_python.txt
Q: Python JSON decoding I'm having some trouble decoding this json in python. From basehttpserver I'm getting back [ { "changed_aspect": "media", "object": "geography", "object_id": "1306", "subscription_id": 1326, "time": 1300570688 } ] which I'm putting into simplejsondecoder with data = ...
Python JSON decoding
I'm having some trouble decoding this json in python. From basehttpserver I'm getting back [ { "changed_aspect": "media", "object": "geography", "object_id": "1306", "subscription_id": 1326, "time": 1300570688 } ] which I'm putting into simplejsondecoder with data = simplejson.loads(s) but w...
[ "When you decode the JSON you get exactly what it looks like, a list containing a single item.\ndata[0] should be the dictionary you expected to see.\n" ]
[ 8 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0005365132_json_python_simplejson.txt
Q: Are there any benchmarks showing good performance of `collections.deque`? I was always intrigued by Python's collections.deque object. It seems to be like a list, except that adding/deleting items in the beginning is faster than in a list. This makes me want to replace list with deque in various places in my code ...
Are there any benchmarks showing good performance of `collections.deque`?
I was always intrigued by Python's collections.deque object. It seems to be like a list, except that adding/deleting items in the beginning is faster than in a list. This makes me want to replace list with deque in various places in my code where I have a list that I do left pops on. So my question: Did anyone ever ben...
[ "I just did a quick google search, and found two sources with code and numbers:\nA mailing-list post:\nhttp://coding.derkeiler.com/Archive/Python/comp.lang.python/2010-01/msg02138.html\nA blog post:\nhttp://txzone.net/2010/04/python-is-x-is-better-than-y-round-1-deque-vs-list/\nIt looks like a list is slightly fast...
[ 3 ]
[]
[]
[ "collections", "complexity_theory", "data_structures", "deque", "python" ]
stackoverflow_0005364640_collections_complexity_theory_data_structures_deque_python.txt
Q: Finding out an average in python I'm reading from a .txt file and have four scores for each person, i need to find out how to take the scores from each line and find the average for each person. s={} results= open("surf.txt") for line in results: (s['Name'], s['scoreOne'], s['scoreTwo'], s['scoreThree'], s['scor...
Finding out an average in python
I'm reading from a .txt file and have four scores for each person, i need to find out how to take the scores from each line and find the average for each person. s={} results= open("surf.txt") for line in results: (s['Name'], s['scoreOne'], s['scoreTwo'], s['scoreThree'], s['scoreFour']) =line.split(";") That seems ...
[ "Solution:\nseparator = \";\"\ninputFile = \"input.txt\"\n\nwith open(inputFile) as f:\n for line in f:\n values = line.split(separator)\n name = values[0]\n scores = map(float, values[1:])\n avg = sum(scores) / len(scores)\n print name, avg\n\nInput:\nMaciej;5;10;15;50\nJohn;1...
[ 2, 1, 1, 0 ]
[]
[]
[ "equation", "python" ]
stackoverflow_0005365194_equation_python.txt
Q: Why does this fail? (google appengine datastore, python) 1 from google.appengine.ext import webapp 2 from google.appengine.ext.webapp.util import run_wsgi_app 3 from google.appengine.ext import db 4 5 a = db.GqlQuery('SELECT * FROM Store WHERE count = True').count 6 7 print 'Content-Type: text/plai...
Why does this fail? (google appengine datastore, python)
1 from google.appengine.ext import webapp 2 from google.appengine.ext.webapp.util import run_wsgi_app 3 from google.appengine.ext import db 4 5 a = db.GqlQuery('SELECT * FROM Store WHERE count = True').count 6 7 print 'Content-Type: text/plain' 8 print '' 9 print str(a)+'blah blah' The table 'Store...
[ "You need to define a model for \"Store\". Even if you've managed to get data into the datastore as Store rows, this fails when the model class doesn't exist.\nI verified this by renaming one of my model classes in a working application that had data stored for that type of object. It throws the same exception, so ...
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005365454_google_app_engine_python.txt
Q: White background to transparent background using PIL python How can i transform all white background and white elements of a png or jpg image in a transparent backgroun using PIL? A: Using numpy, the following makes white-ish areas transparent. You can change threshold and dist to control the definition of "whi...
White background to transparent background using PIL python
How can i transform all white background and white elements of a png or jpg image in a transparent backgroun using PIL?
[ "Using numpy, the following makes white-ish areas transparent. You can change threshold and dist to control the definition of \"white-ish\". \nimport Image\nimport numpy as np\n\nthreshold=100\ndist=5\nimg=Image.open(FNAME).convert('RGBA')\n# np.asarray(img) is read only. Wrap it in np.array to make it modifiable.\...
[ 9 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0005365589_python_python_imaging_library.txt
Q: Tkinter window in bottom right corner Is it possible to display a Python Tkinter window in the bottom right hand corner of the screen? If so, how? A: Yes, it is possible. You use the wm_geometry method of the window to specify the geometry (width, height, x and y location) of the window.
Tkinter window in bottom right corner
Is it possible to display a Python Tkinter window in the bottom right hand corner of the screen? If so, how?
[ "Yes, it is possible. You use the wm_geometry method of the window to specify the geometry (width, height, x and y location) of the window.\n" ]
[ 2 ]
[]
[]
[ "python", "screen", "tkinter" ]
stackoverflow_0005365172_python_screen_tkinter.txt
Q: Why is the value of __name__ changing after assignment to sys.modules[__name__]? While trying to do something similar to what's in the ActiveState recipe titled Constants in Python by Alex Martelli, I ran into the unexpected side-effect (in Python 2.7) that assigning a class instance to an entry in sys.modules has...
Why is the value of __name__ changing after assignment to sys.modules[__name__]?
While trying to do something similar to what's in the ActiveState recipe titled Constants in Python by Alex Martelli, I ran into the unexpected side-effect (in Python 2.7) that assigning a class instance to an entry in sys.modules has -- namely that doing so apparently changes the value of __name__ to None as illustrat...
[ "This happens because you have overwrite your module when you did sys.modules[__name__] = _test() so your module was deleted (because the module didn't have any references to it anymore and the reference counter went to zero so it's deleted) but in the mean time the interpreter still have the byte code so it will s...
[ 34 ]
[ "If I assign anything to sys.modules['__main__'] I get a severely broken environment. Not this exact behaviour, but all my globals and builtins disappear.\nsys.modules isn't documented to behave in any particular way when written to, only vaguely that you can use it for “reloading tricks” (and there are some signif...
[ -2 ]
[ "module", "python" ]
stackoverflow_0005365562_module_python.txt
Q: what's the specification of python's heapq._siftdown() functionality? I couldn't find a documentation about this function... I specifically want to know what the parameters are and what do the parameters exactly represent... using python 3 A: The convention in Python is to use a single leading _ for non-public m...
what's the specification of python's heapq._siftdown() functionality?
I couldn't find a documentation about this function... I specifically want to know what the parameters are and what do the parameters exactly represent... using python 3
[ "The convention in Python is to use a single leading _ for non-public methods and instance variables. So, _siftdown is not intended to be called externally and, thus, is not documented in the standard library documentation. If you want to examine how it works, look at the code. Note that the latest Python 3.2 do...
[ 3 ]
[]
[]
[ "data_structures", "heap", "parameters", "python" ]
stackoverflow_0005365658_data_structures_heap_parameters_python.txt
Q: Resources for pylons development Are there any good resources for pylons development? I want to build a pylons app and run it on nginx (for speed) I am looking to use mongo for the db. Given this stack are there any resources that would point me in the right direction? Any tips / suggestions welcome. A: Yes and...
Resources for pylons development
Are there any good resources for pylons development? I want to build a pylons app and run it on nginx (for speed) I am looking to use mongo for the db. Given this stack are there any resources that would point me in the right direction? Any tips / suggestions welcome.
[ "Yes and they are free:\nthe pylons book: http://pylonsbook.com/\nAnd the Pylonshq, where you can find more updated info, for example im not using the authkit that the book use, its kinda unsuported, I use the repoze.what and repoze pluggins for authentication and authorization\nhttp://wiki.pylonshq.com/dashboard.a...
[ 5 ]
[]
[]
[ "mongodb", "nginx", "pylons", "python" ]
stackoverflow_0005364927_mongodb_nginx_pylons_python.txt
Q: Optimizing NumPy with Cython I am currently trying to optimize the code that I had written in pure Python. This code uses NumPy very heavily as I am working with NumPy arrays. Below you can see the simplest of my classes that I converted to Cython. Which only does a multiplication of two Numpy arrays. Here: bendin...
Optimizing NumPy with Cython
I am currently trying to optimize the code that I had written in pure Python. This code uses NumPy very heavily as I am working with NumPy arrays. Below you can see the simplest of my classes that I converted to Cython. Which only does a multiplication of two Numpy arrays. Here: bendingForces = self.matrixPrefactor * m...
[ "For simple matrix multiplications, the NumPy code is already doing only the looping and multiplying natively, so it would be hard to beat that in Cython. Cython is great for situations where you are replacing loops in Python with those in Cython. One of the reasons your code is slower than NumPy is because every t...
[ 9, 0 ]
[]
[]
[ "cython", "matrix_multiplication", "numpy", "optimization", "python" ]
stackoverflow_0005331275_cython_matrix_multiplication_numpy_optimization_python.txt
Q: Python: Floating Point images / alternative to matlab's im2double? I'm trying to convert some matlab code to python and the im2double function is giving me trouble. It takes an image and returns a matrix with the pixels using doubles instead of ints. Currently I'm manipulating my images with PIL. It has a convert ...
Python: Floating Point images / alternative to matlab's im2double?
I'm trying to convert some matlab code to python and the im2double function is giving me trouble. It takes an image and returns a matrix with the pixels using doubles instead of ints. Currently I'm manipulating my images with PIL. It has a convert method that can take 'F' as parameter, but all it does is convert the in...
[ "The way to do this properly in Python will to use Numpy. You can read images via PIL into numpy arrays. At this point a wide range of Matlab like matrix operations become available to you via numpy/scipy. Changing the precision of the array is simply a matter of switching the arrays datatype via numpy. Recent rele...
[ 1 ]
[]
[]
[ "image", "image_processing", "matlab", "python", "python_imaging_library" ]
stackoverflow_0005365865_image_image_processing_matlab_python_python_imaging_library.txt
Q: Python - Parsing a string for URLs and extracting them I know that with urllib you can parse a string and check if it's a valid URL. But how would one go about checking if a sentence contains a URL within it, and then extract that URL. I've seen some huge regular expressions out there, but i would rather not use s...
Python - Parsing a string for URLs and extracting them
I know that with urllib you can parse a string and check if it's a valid URL. But how would one go about checking if a sentence contains a URL within it, and then extract that URL. I've seen some huge regular expressions out there, but i would rather not use something that I really can't comprehend. So basically I have...
[ "You can search for \"words\" containing : and then pass them to urlparse (renamed to urllib.parse in Python 3.0 and newer) to check if they are valid URLs.\nExample:\npossible_urls = re.findall(r'\\S+:\\S+', text)\n\nIf you want to restrict yourself only to URLs starting with http:// or https:// (or anything else ...
[ 2, 1 ]
[]
[]
[ "python", "regex", "url", "urlparse" ]
stackoverflow_0005364357_python_regex_url_urlparse.txt
Q: I am creating a python program that counts the number of characters input by user in a file that is not case-sensitive I am having problem with my code and a TypeError: string indices must be integers, not str. Any help or suggestion? my code is: f= open("studentname.txt", 'r') finChar = raw_input("please enter a ...
I am creating a python program that counts the number of characters input by user in a file that is not case-sensitive
I am having problem with my code and a TypeError: string indices must be integers, not str. Any help or suggestion? my code is: f= open("studentname.txt", 'r') finChar = raw_input("please enter a character to count ") a=finChar.lower() b=finChar.upper() c=a+b str = '' for line in f.readlines(): str = str + line co...
[ "for i in str iterates over the characters in a string, not their indices. Therefore you can write\nfor i in str:\n if i in c:\n\n", "for i in str gives you the characters in str, not the indices to index into str by.\nTry if i == c instead of if str[i] == c.\n" ]
[ 3, 2 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0005366076_programming_languages_python.txt
Q: Pythonic representation of a list of values with optional flags What first pops into my head is a dictionary with keys acting as list values and dictionary values defaulting to None, but this feels sub-optimal to me. Can anyone propose a single-structure (i.e. no separate 'options' dict) alternative where dict[key...
Pythonic representation of a list of values with optional flags
What first pops into my head is a dictionary with keys acting as list values and dictionary values defaulting to None, but this feels sub-optimal to me. Can anyone propose a single-structure (i.e. no separate 'options' dict) alternative where dict[key] on an item with no flags set returns None and otherwise returns a l...
[ "Maybe a defaultdict will do:\nfrom collections import defaultdict\n\nflags = defaultdict(lambda : None)\nflags.update({'F1':True,'F3':True,'F8':True})\n\nfor f in 'F1 F2 F3 F4 F5 F6 F7 F8'.split():\n print f, '->', flags[f]\n\nPrints:\nF1 -> True\nF2 -> None\nF3 -> True\nF4 -> None\nF5 -> None\nF6 -> None\nF7 -...
[ 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005365981_python.txt
Q: Deleting using google IMAP (python, imaplib) When I use google IMAP and try to delete message the message removes from folder but not going to trash folder. Did i must to copy this message before delete it? A: With the new Gmail advanced IMAP controls you can now set messeges that are deleted over imap to be mov...
Deleting using google IMAP (python, imaplib)
When I use google IMAP and try to delete message the message removes from folder but not going to trash folder. Did i must to copy this message before delete it?
[ "With the new Gmail advanced IMAP controls you can now set messeges that are deleted over imap to be moved to the bin.\nJust enable \"Advanced IMAP Controls\" in Gmail Labs, and then set the settings IMAP settings like this:\n\nThen when you mark a message as deleted and expunge as per this answer it will be moved ...
[ 2, 1 ]
[]
[]
[ "gmail", "gmail_imap", "imap", "imaplib", "python" ]
stackoverflow_0004067499_gmail_gmail_imap_imap_imaplib_python.txt
Q: How to make a filtering annotation with ManyToMany relation in Django? I have a model with articles, events and people: class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) class Event(models.Model): id = models.IntegerField(primary_key=True) title ...
How to make a filtering annotation with ManyToMany relation in Django?
I have a model with articles, events and people: class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=30) class Event(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) class Article(models.Model): id = mode...
[ "To simplify your example:\nclass Event(models.Model):\n title = models.CharField(max_length=200)\n\nclass Person(models.Model):\n name = models.CharField(max_length=30)\n\nclass Article(models.Model):\n title = models.CharField(max_length=200)\n publishDate = models.DateTimeField(blank=True, null=True)...
[ 5, 0 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0005363856_django_django_models_many_to_many_python.txt
Q: splitting merged words in python I am working with a text where all "\n"s have been deleted (which merges two words into one, like "I like bananasAnd this is a new line.And another one.") What I would like to do now is tell Python to look for combinations of a small letter followed by capital letter/punctuation fo...
splitting merged words in python
I am working with a text where all "\n"s have been deleted (which merges two words into one, like "I like bananasAnd this is a new line.And another one.") What I would like to do now is tell Python to look for combinations of a small letter followed by capital letter/punctuation followed by capital letter and insert a ...
[ "Try the following:\nre.sub(r\"([a-z\\.!?])([A-Z])\", r\"\\1 \\2\", your_string)\n\nFor example:\nimport re\nlines = \"I like bananasAnd this is a new line.And another one.\"\nprint re.sub(r\"([a-z\\.!?])([A-Z])\", r\"\\1 \\2\", lines)\n# I like bananas And this is a new line. And another one.\n\nIf you want to ins...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005366513_python.txt
Q: I am having a problem with my python program that im running From an input file I'm suppose to extract only first name of the student and then save the result in a new file called "student-­‐firstname.txt" The output file should contain a list of first names (not include middle name). I was able to get delete of t...
I am having a problem with my python program that im running
From an input file I'm suppose to extract only first name of the student and then save the result in a new file called "student-­‐firstname.txt" The output file should contain a list of first names (not include middle name). I was able to get delete of the last name but I'm having problem deleting the middle name any h...
[ "Split token[1] with space.\nfname = token[1].split(' ')[0]\n\n", "f=open(\"studentname.txt\", 'r')\nf2=open (\"student-firstname.txt\",'w')\n\nfor line in f.readlines():\n token=line.split()\n f2.write(token[1]+\"\\n\")\nf.close()\nf2.close()\n\n", "with open(\"studentname.txt\") as f, open(\"student-f...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0005366471_programming_languages_python.txt
Q: Hiding field in dhangoforms which are generated from a model and saving it in the database 1] I have the following model: class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty(default='Afghanistan',choices=['Afgh...
Hiding field in dhangoforms which are generated from a model and saving it in the database
1] I have the following model: class UserReportedData(db.Model): #country selected by the user, this will also populate the drop down list on the html page country = db.StringProperty(default='Afghanistan',choices=['Afghanistan']) #city selected by the user city = db.StringProperty() user_reported_boolean = d...
[ "1: Exclude the field from your modelform.\nclass MyModelForm(ModelForm):\n class Meta:\n model = Foo\n exclude = ('myfield',)\n\n2: In the unsaved model instance you have via commit=False\nentity = data.save(commit=False)\nentity.user_reported_boolean = True # False, whatever.\nentity.save()\n\n...
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005366928_django_google_app_engine_python.txt
Q: Python Image Library - Create and paste image How do I create a new image with a black background and paste another image on top of it? What I am looking to do is turn some 128x128 transparent icons into 75x75 black background icons. Doesnt work ... import Image theFile = "/home/xxxxxx/Pictures/xxxxxx_128.png" ...
Python Image Library - Create and paste image
How do I create a new image with a black background and paste another image on top of it? What I am looking to do is turn some 128x128 transparent icons into 75x75 black background icons. Doesnt work ... import Image theFile = "/home/xxxxxx/Pictures/xxxxxx_128.png" img = Image.open(theFile) newImage = Image.new(im...
[ "The resize method returns a new image object, rather than changing the existing one. Also, you should resize the image before pasting it. The following works for me:\nimport Image\n\ntheFile = \"foo.png\"\n\nimg = Image.open(theFile)\nresized = img.resize((75,75))\nr, g, b, alpha = resized.split()\n\nnewImage = ...
[ 10 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0005366936_image_python_python_imaging_library.txt
Q: Pylons Paste running with no output I've hit a snag while running through the hello world pylons example. I see the following in terminal after calling paster serve development.ini with the vanilla development.ini file. Starting server in PID 14457. serving on http://127.0.0.1:5000 However, when I navigate to 127...
Pylons Paste running with no output
I've hit a snag while running through the hello world pylons example. I see the following in terminal after calling paster serve development.ini with the vanilla development.ini file. Starting server in PID 14457. serving on http://127.0.0.1:5000 However, when I navigate to 127.0.0.1:5000 in the browser I see Oops! Co...
[ "If you're using chrome, you might be experiencing this bug:\nhttp://code.google.com/p/chromium/issues/detail?id=42058\n" ]
[ 1 ]
[]
[]
[ "paste", "pylons", "python" ]
stackoverflow_0005365576_paste_pylons_python.txt
Q: How to make Python / Nginx / FastCGI automatically recompile code when it is updated/changed? So I've been working on my first Django / Python project and I got my production server up and running. I was wondering if it's possible to make Python/FastCGI (not really sure which is responsible for the task) to recom...
How to make Python / Nginx / FastCGI automatically recompile code when it is updated/changed?
So I've been working on my first Django / Python project and I got my production server up and running. I was wondering if it's possible to make Python/FastCGI (not really sure which is responsible for the task) to recompile my code. As of right now, when I upload updated code, I need to restart the server for the ch...
[ "for anyone else that was interested in my question.. this is only a partial solution, but I ended up finding my answer here: How to gracefully restart django running fcgi behind nginx?\nYou can just run the script (I'm going to modify it a bit), everytime you edit your code and it will gracefully restart everyth...
[ 2, 1 ]
[]
[]
[ "django", "fastcgi", "nginx", "python" ]
stackoverflow_0005360986_django_fastcgi_nginx_python.txt
Q: Python interface to dynamic binary instrumentaton framework PIN I work in analyzing binary files, using Python. I have been using debuggers to do a dynamic analysis (i.e running the application and using breakpoints to get runtime execution). however, results can be improved if i can use some binary instrumentatio...
Python interface to dynamic binary instrumentaton framework PIN
I work in analyzing binary files, using Python. I have been using debuggers to do a dynamic analysis (i.e running the application and using breakpoints to get runtime execution). however, results can be improved if i can use some binary instrumentation fremework like PIN. The PIN is developed in C++ and provided as clo...
[ "Check out the ProcessTap project. Appears to implement exactly what you are looking for: http://code.google.com/p/processtap/\n", "I was thinking about this recently, while I haven't looked into it, I would approach the problem like this: write a pintool that, upon initialization, starts an embedded python inter...
[ 3, 0 ]
[]
[]
[ "dynamic_analysis", "instrumentation", "python", "python_c_extension" ]
stackoverflow_0004345243_dynamic_analysis_instrumentation_python_python_c_extension.txt
Q: use javascript variable into python Block I want to use JavaScript variable into python Block. <script> $(document).ready(function() { $("#WO_cpp_id").change(function() { id = this.selectedIndex; ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci...
use javascript variable into python Block
I want to use JavaScript variable into python Block. <script> $(document).ready(function() { $("#WO_cpp_id").change(function() { id = this.selectedIndex; ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id'); }) .change(); }); </script> Thanks in A...
[ "Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.\nOne of those ways is \"ajax\". This client-...
[ 3, 0 ]
[]
[]
[ "javascript", "jquery", "python" ]
stackoverflow_0005367414_javascript_jquery_python.txt
Q: Why don't list objects belong to a class? From the classes tutorial: In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. One implication I can find is this gives ...
Why don't list objects belong to a class?
From the classes tutorial: In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. One implication I can find is this gives an error: [].foo = 'bar'. Are there other impli...
[ "lists are implemented as a class:\n>>> [].__class__\n<type 'list'>\n\nIt's just you can't assign to arbitrary attributes on them. The same applies to other types e.g. strings.\n>>> \"foo\".bar = \"something\"\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'str' object...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005362205_python.txt
Q: Using 'get' method of a dictionary to select case. Why does it keep selecting the wrong thing? I'm using a dictionary's get() method to choose a case based on a variable key value. Problem is, it keeps choosing the wrong case for the key. I'm not sure if I'm using the right words to explain it, but the code should...
Using 'get' method of a dictionary to select case. Why does it keep selecting the wrong thing?
I'm using a dictionary's get() method to choose a case based on a variable key value. Problem is, it keeps choosing the wrong case for the key. I'm not sure if I'm using the right words to explain it, but the code should make it clear enough. di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \ "ABC...
[ "I believe the problem is that all the Pred_XXXX(liLn) values -- which appear to be function calls -- in the di_eqns dictionary are being replaced with their return values when you create it...which of course will depending on the value of liLn at the time of construction, not at the time you call get().\nSomething...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005367300_python.txt
Q: DictReader, No quotes, tabbed file I have a csv file that looks like this: Please note, there are no quotes, a tab (\t) is the delimiter, and there is a blank line between the header and the actual content. Facility No Testing No Name Age 252 2351 Jackrabbit, Jazz 15 345 257 Aard...
DictReader, No quotes, tabbed file
I have a csv file that looks like this: Please note, there are no quotes, a tab (\t) is the delimiter, and there is a blank line between the header and the actual content. Facility No Testing No Name Age 252 2351 Jackrabbit, Jazz 15 345 257 Aardvark, Ethel 41 I think I've tried nearl...
[ "What is your csvFile? Is it a string representing your filename starting with 'F'?\ncsv.DictReader needs an opened file object, not a filename.\nTry:\nwith open(csvFile, 'rb') as f:\n reader = csv.DictReader(f, delimiter='\\t', quoting=csv.QUOTE_NONE)\n print reader.fieldnames\n\nEDIT\nIf your csvFile is a s...
[ 42, 2, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005360932_csv_python.txt
Q: How to determine if an HTTP request is asynchronous in Python or Pylons I can't help but think that this is a duplicate, but if it is, I can't seem to find the doppelganger. I'm just starting to learn Python (focusing on Pylons) and I'd like to know if there is a way to determine if a call to a controller is done ...
How to determine if an HTTP request is asynchronous in Python or Pylons
I can't help but think that this is a duplicate, but if it is, I can't seem to find the doppelganger. I'm just starting to learn Python (focusing on Pylons) and I'd like to know if there is a way to determine if a call to a controller is done asynchronously or not. In PHP it would look something like this: function isA...
[ "To directly translate that code to python using pylons you would do something along the lines of:\ndef isAjax(request):\n return request.environ.get('HTTP_X_REQUEST_WITH') == 'XMLHttpRequest'\n\nwhere request is the request object passed to the controller.\n", "Paste supports this method:\nrequest.is_xhr\n\nI...
[ 4, 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0004139201_pylons_python.txt
Q: Is there a Python persitent data store that has the same functionality as dict (or how to coax "Shelve" to get that)? I am using Python 3. shelve is advertised in the documentation as a persistent version of dict. However, in my usage, it turns out that shelve does not allow tuples as keys, while dict does: import...
Is there a Python persitent data store that has the same functionality as dict (or how to coax "Shelve" to get that)?
I am using Python 3. shelve is advertised in the documentation as a persistent version of dict. However, in my usage, it turns out that shelve does not allow tuples as keys, while dict does: import shelve def tryShelve(): db = shelve.open("shelvefile") db["word1"] = 1 db[("word1", "word2")] = 15 tryShelve(...
[ "The first paragraph in the shelve module documentation:\n\nA “shelf” is a persistent,\n dictionary-like object. The difference\n with “dbm” databases is that the\n values (not the keys!) in a shelf can\n be essentially arbitrary Python\n objects — anything that the pickle\n module can handle. This includes m...
[ 4, 2, 1, 1 ]
[]
[]
[ "persistent", "python" ]
stackoverflow_0005367524_persistent_python.txt
Q: Python script drops into pdb without reason I have a python function that I'm calling from inside an iPython session. In a very specific situation, in which a conditional in a certain line comes out as True, the script consistently drops into a pdb debug mode. There is no trace or any other indication of a problem...
Python script drops into pdb without reason
I have a python function that I'm calling from inside an iPython session. In a very specific situation, in which a conditional in a certain line comes out as True, the script consistently drops into a pdb debug mode. There is no trace or any other indication of a problem with the code, and as soon as I type c to contin...
[ "Depending on your ipython config it automatically goes into PDB if an exception is raised.\n", "Seems like there was a import pdb; pdb.set_trace() line in the code after all, which I missed due to source control issues.\n" ]
[ 1, 0 ]
[]
[]
[ "ipython", "pdb", "python" ]
stackoverflow_0005365765_ipython_pdb_python.txt
Q: Loading numpy into IronPython I've recently installed Ironpython + tools and having trouble loading external modules (numpy). this is my test code: import numpy numpy.test() when writing my simple test, intellisense can find numpy, however when it's run from vs2010, I get: ImportException was unhandled by user co...
Loading numpy into IronPython
I've recently installed Ironpython + tools and having trouble loading external modules (numpy). this is my test code: import numpy numpy.test() when writing my simple test, intellisense can find numpy, however when it's run from vs2010, I get: ImportException was unhandled by user code: No module named numpy IronPyth...
[ "I have used the Numpy implementation for IronPython from Enthough. It works so far, but I have not tested it enough.\nI have blogged about it here\nNumpy for .NET is implemented though wrappers to native calls.\nIn my blog post I used this tutorial.\n", "I don't believe Numpy is supported for IronPython: http://...
[ 3, 2, 0 ]
[]
[]
[ "compiler_construction", "ironpython", "python", "visual_studio", "visual_studio_2010" ]
stackoverflow_0003613409_compiler_construction_ironpython_python_visual_studio_visual_studio_2010.txt
Q: import woes in python I'm super new on python and i am just deploying an open source app that was done in python and I'm getting a: ImportError: cannot import name DataSource on from django.contrib.gis.gdal import DataSource However, this is just fine: import django.contrib.gis.gdal My current environment setup i...
import woes in python
I'm super new on python and i am just deploying an open source app that was done in python and I'm getting a: ImportError: cannot import name DataSource on from django.contrib.gis.gdal import DataSource However, this is just fine: import django.contrib.gis.gdal My current environment setup is: Linux Python 2.7 instal...
[ "Do you have python-gdal installed? It seems that django.contrib.gis.gdal only exposes the DataSource class if it is installed. At least on Ubuntu, installing python-django didn't install python-gdal by default.\nEDIT: as noted in the comments below, you did have it installed, but the module responsible for locatin...
[ 3 ]
[]
[]
[ "gdal", "import", "python" ]
stackoverflow_0005367747_gdal_import_python.txt
Q: Can zope.interface define how a class' __init__ method should look? I have several similar classes which will all be initialised by the same code, and thus need to have the same "constructor signature." (Are there really constructors and signatures in the dynamic Python? I digress.) What is the best way to defin...
Can zope.interface define how a class' __init__ method should look?
I have several similar classes which will all be initialised by the same code, and thus need to have the same "constructor signature." (Are there really constructors and signatures in the dynamic Python? I digress.) What is the best way to define a classes __ init __ parameters using zope.interface? I'll paste some c...
[ "First of all: there is a big difference between the concepts of providing and implementing an interface.\nBasically, classes implement an interface, instances of those classes provide that interface. After all, classes are the blueprints for instances, detailing their implementations.\nNow, an interface describes ...
[ 9, 2, 0 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0005365348_python_zope.txt
Q: How to debug django, it spawns a new process to which I'm not attached? I'm trying to debug django using PyCharm, and notice that it spawns a new process to which PyCharm is not attached. My breakpoints aren't hit in this new process. How do I debug it then? (See autoreload.restart_with_reloader()) A: If you are...
How to debug django, it spawns a new process to which I'm not attached?
I'm trying to debug django using PyCharm, and notice that it spawns a new process to which PyCharm is not attached. My breakpoints aren't hit in this new process. How do I debug it then? (See autoreload.restart_with_reloader())
[ "If you are debugging - it is a good idea to have \"--noreload\" option for the dev-server.\nAFAIK PyCharm has a checkbox \"No reload\" in the run options for the project.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005367695_django_python.txt
Q: Is it possible to override Sphinx autodoc for specific functions? I'm using Sphinx's autodoc plugin to automatically document a set of modules. I have a function that accepts *args, and I'd like to override the documentation to show the slightly nicer funcname(arg1[, arg2[, ...]]) style that the Python stdlib doc...
Is it possible to override Sphinx autodoc for specific functions?
I'm using Sphinx's autodoc plugin to automatically document a set of modules. I have a function that accepts *args, and I'd like to override the documentation to show the slightly nicer funcname(arg1[, arg2[, ...]]) style that the Python stdlib docs use. Is it possible to override the autodoc output for a specific fun...
[ "It is possible to override a signature by using autofunction:\n.. automodule:: yourmodule\n :members:\n :exclude-members: funcname\n\n.. autofunction:: funcname(arg1[, arg2[, ...]])\n\nHowever, the function with the overridden signature is not sorted with the other functions pulled in with automodule. Using ex...
[ 20 ]
[]
[]
[ "autodoc", "python", "python_sphinx" ]
stackoverflow_0005365684_autodoc_python_python_sphinx.txt
Q: How does wordpress password hash work? I need to integrate a Django system with a Wordpress site, as in wordpress users should be able to log in the DJnago part and vice versa, For this I need to understand how the password hashing works in Wordpress. I can see the wp_users table which stores the username and pass...
How does wordpress password hash work?
I need to integrate a Django system with a Wordpress site, as in wordpress users should be able to log in the DJnago part and vice versa, For this I need to understand how the password hashing works in Wordpress. I can see the wp_users table which stores the username and password hashes. Looking through the wordpress c...
[ "There is a comment in the implementation saying:\n 28 /**\n 29 * Portable PHP password hashing framework.\n 30 *\n 31 * @package phpass\n 32 * @version 0.1 / genuine\n 33 * @link http://www.openwall.com/phpass/\n 34 * @since 2.5\n 35 */\n\nThe hashing framework used is phpass, and its page l...
[ 7, 2 ]
[]
[]
[ "django", "php", "python", "wordpress" ]
stackoverflow_0002076507_django_php_python_wordpress.txt
Q: How do I override this method on a Django Model Field I'm trying to modify an existing Django Mezzanine setup to allow me to blog in Markdown. Mezzanine has a "Core" model that has content as an HtmlField which is defined like so: from django.db.models import TextField class HtmlField(TextField): """ ...
How do I override this method on a Django Model Field
I'm trying to modify an existing Django Mezzanine setup to allow me to blog in Markdown. Mezzanine has a "Core" model that has content as an HtmlField which is defined like so: from django.db.models import TextField class HtmlField(TextField): """ TextField that stores HTML. """ def formfield(...
[ "You could change the used formfield in the admin's method formfield_for_dbfield:\nclass BlogAdmin(admin.ModelAdmin):\n\n def formfield_for_dbfield(self, db_field, **kwargs):\n field = super(BlogAdmin, self).formfield_for_dbfield(db_field, **kwargs)\n if db_field.name == 'content':\n fie...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0004414767_django_django_admin_django_models_python.txt
Q: Understanding concepts of Python installation on Mac OS for Cocoa development I want to try to develop Cocoa application using Python. I'm new to Mac and I need some help to understand how it works. First of all I found that I need to install py2app and py2objc. I used easy_install as documented here. There were a...
Understanding concepts of Python installation on Mac OS for Cocoa development
I want to try to develop Cocoa application using Python. I'm new to Mac and I need some help to understand how it works. First of all I found that I need to install py2app and py2objc. I used easy_install as documented here. There were a few errors with setup tools but eventually py2app was installed. Then I launch "ea...
[ "\nCannot give a definitive answer to that. See comment.\nYou can install multiple versions of python on your machine (OSX includes a defualt one as you already mentioned). In the applications folder there are some apps to open an interactive interpreter in which you can enter python commands, such as IDLE. These a...
[ 1 ]
[]
[]
[ "cocoa_bindings", "osx_snow_leopard", "py2app", "python" ]
stackoverflow_0005367920_cocoa_bindings_osx_snow_leopard_py2app_python.txt
Q: Django DateTimeField Defined as blank=True, null=True but doesn't allow null I have a DateTimeField in one of my Django models. completed_date = models.DateTimeField('date completed', blank=True, null=True) I've defined it to allow blank and null values. However, when I try to create an instance of the model,...
Django DateTimeField Defined as blank=True, null=True but doesn't allow null
I have a DateTimeField in one of my Django models. completed_date = models.DateTimeField('date completed', blank=True, null=True) I've defined it to allow blank and null values. However, when I try to create an instance of the model, I get the following error: IntegrityError at /admin/tasks/project/add/ tasks_p...
[ "django syncdb and an updated model\nfrom that question/answer:\n\nDjango doesn't support migrations out\n of the box. There is a pluggable app\n for Django that does exactly that\n though, and it works great. It's\n called South.\n\nhttp://south.aeracode.org/\n\nHavent used django in a while, but i\n seem to ...
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005368345_django_python.txt
Q: IRC Python Bot: Best Way I want to build a bot that basically does the following: Listens to the room and interacts with users and encourages them to PM the bot. Once a user has PMed the bot engage with the client using various AI techniques. Should I just use the IRC library or Sockets in python or do I need m...
IRC Python Bot: Best Way
I want to build a bot that basically does the following: Listens to the room and interacts with users and encourages them to PM the bot. Once a user has PMed the bot engage with the client using various AI techniques. Should I just use the IRC library or Sockets in python or do I need more of a bot framework. What w...
[ "Use Twisted or Asynchat if you want to have a sane design. It is possible to just do it with sockets but why bother doing it from scratch?\n", "If you want to have AI techniques involved, then I suggest you look at the AIML package for Python. It is the same technology that ALICE bots are done in.\n", "If what...
[ 12, 7, 5, 4, 2, 2 ]
[]
[]
[ "bots", "irc", "python" ]
stackoverflow_0001100840_bots_irc_python.txt
Q: similar tools in Python? (tools from Ruby) gem: package management. bundler: dependency management rspec: test framework. watchr: autotest tool yard: documentation tool. rdoc Markdown: markdown for writing code's comment. rvm: Ruby version Manager. rake: task tool. I want to find some tools in Python can do the j...
similar tools in Python? (tools from Ruby)
gem: package management. bundler: dependency management rspec: test framework. watchr: autotest tool yard: documentation tool. rdoc Markdown: markdown for writing code's comment. rvm: Ruby version Manager. rake: task tool. I want to find some tools in Python can do the job describe above.
[ "\ngem == easy_install, a part of setuptools\nsetuptools\nfor testing framework see nosetest\nautonose\nepydoc or sphinx\nuse docstrings\nvirtualenv along with virtualenvwrapper.\npaver\n\n", "1) PyPI/setuptools/distribute\n2) done via setuptools (install_requires directive in setup.py)\n3) unittest/unittest/nose...
[ 9, 1 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0005368960_python_ruby.txt
Q: How to sort by a particular attribute of a class? I have a model with an attribute which keeps track of the price. Right now, I have a list of that certain model. Is there anyway to rearrange the list to sort by that particular attribute? Is python smart enough to know that the attribute is a value which can be so...
How to sort by a particular attribute of a class?
I have a model with an attribute which keeps track of the price. Right now, I have a list of that certain model. Is there anyway to rearrange the list to sort by that particular attribute? Is python smart enough to know that the attribute is a value which can be sorted? I am not keeping keeping track of the instances o...
[ "You can use the inbuilt sorted function, together with a custom-made function that returns the price of an object:\nclass Dummy(object) :\n pass\n\ndef getPrice(obj) :\n return obj.price\n\nd0 = Dummy()\nd0.price = 56.\nd1 = Dummy()\nd1.price=16.\n\nd2 = Dummy()\nd2.price=786.\n\nd3 = Dummy()\nd3.price=5.5\n...
[ 4, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005367582_django_python.txt
Q: How to change db in django depending on request.get_host()? I am creating multisites platform. Anybody can make simple site, with my platform. I plan to use django multidb support. One db for one site. And i need to change db settings depending on request.get_host(). I think that i's not good idea. Prompt other d...
How to change db in django depending on request.get_host()?
I am creating multisites platform. Anybody can make simple site, with my platform. I plan to use django multidb support. One db for one site. And i need to change db settings depending on request.get_host(). I think that i's not good idea. Prompt other decisions? How it is realised on various designers of sites?
[ "You might want to reconsider using a separate db for reach site. In reviewing the multi-db source, it looks like you'll run into a few scalability issues, depending on how many sites you want to support:\nCurrently all the databases are set up in settings.py. This could cause a few issues:\n\nEach new site would r...
[ 1, 0 ]
[]
[]
[ "django", "django_middleware", "django_orm", "python" ]
stackoverflow_0002532268_django_django_middleware_django_orm_python.txt
Q: TypeError: 'builtin_function_or_method' object is unsubscriptable I'm getting a strange error from the Python interpreter when I run this code: def make_map(): map = [[Tile(0, 0) for col in range(MAP_WIDTH)] for row in range(MAP_HEIGHT)] for x in range(MAP_WIDTH): for y in range(MAP_HEIGHT): ...
TypeError: 'builtin_function_or_method' object is unsubscriptable
I'm getting a strange error from the Python interpreter when I run this code: def make_map(): map = [[Tile(0, 0) for col in range(MAP_WIDTH)] for row in range(MAP_HEIGHT)] for x in range(MAP_WIDTH): for y in range(MAP_HEIGHT): map[x][y].tileType = round((libtcod.noise_perlin(noise2d,[y...
[ "This error mean that python try to get a variable name \"map\" in tileType = map[x][y].tileType but he don't find it any where so it fetch the build in function map, which is unsubscriptable because it's a built-in function that explain the error message:\nTypeError: 'builtin_function_or_method' object is unsubscr...
[ 7, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005369219_python.txt
Q: What does "children__" mean in Django? Where is it documented? I am trying to parse this Django code (without any familiarity with Django, I might add) Question.objects.filter(children__marked=True) I know the model contains a table called "forum_node" with one of the column named "marked". From what I understand...
What does "children__" mean in Django? Where is it documented?
I am trying to parse this Django code (without any familiarity with Django, I might add) Question.objects.filter(children__marked=True) I know the model contains a table called "forum_node" with one of the column named "marked". From what I understand, this statement fetches all the questions where any of its children...
[ "To understand what happens you should take a closer look at Django's docs explaining the query options and the object-relational mapping.\nchildren refers to a related model (there should be an according m2m or foreign key field named children on your question model, indicating the related model, e.g. node) and ma...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005369225_django_python.txt
Q: Suggestions for improving how I loop through the values of a dictionary? This is what I have been using: for i in iter(SHAPES): SHAPES[i].drawOrder(97) SHAPES[i].alpha(CFG["SHP_alpha"]) . . This is what I thought about doing: for i, v in app.SHAPES.items(): v.drawOrder(97) v.alpha(CFG["SHP...
Suggestions for improving how I loop through the values of a dictionary?
This is what I have been using: for i in iter(SHAPES): SHAPES[i].drawOrder(97) SHAPES[i].alpha(CFG["SHP_alpha"]) . . This is what I thought about doing: for i, v in app.SHAPES.items(): v.drawOrder(97) v.alpha(CFG["SHP_alpha"]) . . Which of the two am I supposed to use? Are there any ot...
[ "If you don't need the key, just ignore it and use .itervalues(). If you need both key and value, .iteritems() is indeed the way to go. Note that in Python 3, those got rid of the iter prefix and Python 2 .values() and .items() (which returned lists) are gone. They have their (rare) uses, but when you just iterate,...
[ 6, 0, 0 ]
[]
[]
[ "dictionary", "loops", "optimization", "python" ]
stackoverflow_0005369346_dictionary_loops_optimization_python.txt
Q: Export functions which returns a reference I want to export into python module (written in c++, with boost.python library) such function: Vec2<Type> &normalize () Type dot(const Vec2<Type> &vector) const These are the members of template class Vec2. Here is my export code: bp::class_< Vec2<int> >("Vec2i", bp::in...
Export functions which returns a reference
I want to export into python module (written in c++, with boost.python library) such function: Vec2<Type> &normalize () Type dot(const Vec2<Type> &vector) const These are the members of template class Vec2. Here is my export code: bp::class_< Vec2<int> >("Vec2i", bp::init<int, int>()) .def("Length", &Vec2<int>::l...
[ "If you look at vec2.h (or the docs you link to), you'll see that dot and normalize are both overloaded, since there also exist static versions of these.\nYou can get around this by using a few function pointers:\nVec2<int> &(Vec2<int>::*norm)() = &Vec2<int>::normalize;\n\nand then using that in the def, as explain...
[ 4, 2 ]
[]
[]
[ "boost", "c++", "export", "python", "reference" ]
stackoverflow_0005369135_boost_c++_export_python_reference.txt
Q: How do I write this join in django? Look at this django code: filtered = Question.objects.filter(children__marked=True).distinct() return Question.objects.exclude(id__in=filtered) It returns the list of all questions, except those that have an accepted (marked) answer. I'm trying to make it return questions with ...
How do I write this join in django?
Look at this django code: filtered = Question.objects.filter(children__marked=True).distinct() return Question.objects.exclude(id__in=filtered) It returns the list of all questions, except those that have an accepted (marked) answer. I'm trying to make it return questions with upvoted answers as well. See this SQL joi...
[ "answered = Question.objects.filter(children__marked=True).distinct()\nunanswered = Question.objects.exclude(id__in=answered) \nupvoted = Question.objects.filter(children__score__gt=0).distinct()\nreturn unanswered | upvoted\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0005369383_django_python_sql.txt
Q: Loading database? my question is how can I do something while I connect to a MySQL database? To make this clearer: Lets say I try to connect to a database: db = MySQLdb.connect(host = "testhost",user ="testuser", passwd ="testpw", db = "testdb") Well, thing is, generally, when the host isn't localhost, it usually...
Loading database?
my question is how can I do something while I connect to a MySQL database? To make this clearer: Lets say I try to connect to a database: db = MySQLdb.connect(host = "testhost",user ="testuser", passwd ="testpw", db = "testdb") Well, thing is, generally, when the host isn't localhost, it usually takes up a bit to load...
[ "Thanks for all your help, I came to an answer, a more concrete one for wxPython. I followed this simple example to make it work:\nimport wx\nimport thread\nfrom time import sleep\n\nclass MainFrame(wx.Frame):\n\n def __init__(self, parent):\n wx.Frame.__init__(self, parent)\n\n self.label = wx.Sta...
[ 2, 1, 1, 1 ]
[]
[]
[ "mysql", "python", "wxpython" ]
stackoverflow_0005366042_mysql_python_wxpython.txt
Q: utf-8 plus question marks I have a site that displays user input by decoding it to unicode using utf-8. However, user input can include binary data, which is obviously not always able to be 'decoded' by utf-8. I'm using Python, and I get an error saying: 'utf8' codec can't decode byte 0xbf in position 0: unexpect...
utf-8 plus question marks
I have a site that displays user input by decoding it to unicode using utf-8. However, user input can include binary data, which is obviously not always able to be 'decoded' by utf-8. I'm using Python, and I get an error saying: 'utf8' codec can't decode byte 0xbf in position 0: unexpected code byte. You passed in '\x...
[ "Try:\ninputstring.decode(\"utf8\", \"replace\")\n\nSee here for reference\n", "I think what you are looking for is:\nstr.decode('utf8','ignore')\n\nwhich should drop invalid bytes rather than raising exception\n" ]
[ 6, 1 ]
[]
[]
[ "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0005370149_encoding_python_unicode_utf_8.txt
Q: Parsing Message-ID header returned by imaplib I'm fetching the messageid from emails in Gmail via IMAP. This code: messageid = m.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])') print messageid returns this: [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}', 'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n')...
Parsing Message-ID header returned by imaplib
I'm fetching the messageid from emails in Gmail via IMAP. This code: messageid = m.fetch(num, '(BODY[HEADER.FIELDS (MESSAGE-ID)])') print messageid returns this: [('1 (BODY[HEADER.FIELDS (MESSAGE-ID)] {78}', 'Message-ID: <actualmessageid@mail.mail.gmail.com>\r\n\r\n'), ')'] How would I parse just the actual message-i...
[ "You can also achieve what you want using the email module's HeaderParser.parsestr() function (same API as Parser but doesn't worry about the email's body) and the parseaddr() function.\n>>> from email.parser import HeaderParser\n>>> from email.utils import parseaddr\n\n>>> hp = HeaderParser()\n\n>>> response = [('...
[ 7, 0 ]
[]
[]
[ "email_headers", "imaplib", "python" ]
stackoverflow_0005205417_email_headers_imaplib_python.txt
Q: What is the best way to install PIL on Mac Snow Leopard with Xcode 4 installed? What is the best way to install PIL on Mac Snow Leopard with Xcode 4 installed? I have seen a lot of information about how difficult it is to install PIL on a Mac but nothing seems too definitive. is there any way to get it installed w...
What is the best way to install PIL on Mac Snow Leopard with Xcode 4 installed?
What is the best way to install PIL on Mac Snow Leopard with Xcode 4 installed? I have seen a lot of information about how difficult it is to install PIL on a Mac but nothing seems too definitive. is there any way to get it installed with the version of Python that comes with Snow Leopard or Xcode 4?
[ "Install dependencies first\nJPG\nDownload http://www.ijg.org/files/jpegsrc.v8c.tar.gz\ntar xzf jpegsrc.v8c.tar.gz \ncd jpeg*\n./configure\nmake\nsudo make install\n\nFreetype\nfrom http://sourceforge.net/projects/freetype/files/\ndownload http://downloads.sourceforge.net/project/freetype/freetype2/2.4.4/freetype-2...
[ 5 ]
[]
[]
[ "macos", "python", "python_imaging_library" ]
stackoverflow_0005345348_macos_python_python_imaging_library.txt
Q: MySQL query to match similar words/sentences I have a table in a MySQL Database which has this structure: CREATE TABLE `papers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(1000) COLLATE utf8_bin DEFAULT NULL, `booktitle` varchar(300) COLLATE utf8_bin DEFAULT NULL, `journal` varchar(300) COLLATE utf8_bi...
MySQL query to match similar words/sentences
I have a table in a MySQL Database which has this structure: CREATE TABLE `papers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(1000) COLLATE utf8_bin DEFAULT NULL, `booktitle` varchar(300) COLLATE utf8_bin DEFAULT NULL, `journal` varchar(300) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`id`), FULLTEXT KEY `...
[ "I see you have added FULLTEXT indexes, I though you already knew about MATCH AGAINST syntax of MySQL.\nYou should try\nSELECT id FROM papers \nWHERE MATCH (title,booktitle,journal) AGAINST ('nFOIL: integrating Naïve Bayes and FOIL' IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION);\n\n", "Change your collate in utf...
[ 2, 0 ]
[]
[]
[ "full_text_search", "mysql", "python", "search" ]
stackoverflow_0005370685_full_text_search_mysql_python_search.txt
Q: Getting the 'real' Google results with Python I'm trying to do something very simple, get the top result URL of a Google search, f.e. for the search LMFAO Yes at Pandora (at is intentional here) I want to receive the link www.pandora.com/music/song/lmfao/yes. All 3 of the major search engines return this result w...
Getting the 'real' Google results with Python
I'm trying to do something very simple, get the top result URL of a Google search, f.e. for the search LMFAO Yes at Pandora (at is intentional here) I want to receive the link www.pandora.com/music/song/lmfao/yes. All 3 of the major search engines return this result without any troubles. The standard response on stack...
[ "This library might be of interest to you: http://www.catonmat.net/blog/python-library-for-google-search/\n>>> from xgoogle.search import GoogleSearch, SearchError\n>>> try:\n... gs = GoogleSearch(\"LMFAO Yes at Pandora\")\n... gs.results_per_page = 50\n... results = gs.get_results()\n... for res in results...
[ 4, 0, 0 ]
[]
[]
[ "python", "search_engine" ]
stackoverflow_0005361735_python_search_engine.txt
Q: Django: name 'csrf_token' is not defined I've a little problem with adding a csrf_token on my form in Django (1.2.5), though I've added all the necessary middleware classes {% csrf_token %} gives the ...name 'csrf_token' is not defined error. What is the problem? Sultan A: You need to check out your MIDDLEWARE_C...
Django: name 'csrf_token' is not defined
I've a little problem with adding a csrf_token on my form in Django (1.2.5), though I've added all the necessary middleware classes {% csrf_token %} gives the ...name 'csrf_token' is not defined error. What is the problem? Sultan
[ "You need to check out your MIDDLEWARE_CLASSES and ensure that the CSRF middleware is in there. As of Django 1.2, this was django.middleware.csrf.CsrfViewMiddleware — ensure that you're using the right class by reading the Django documentation on middleware.\n" ]
[ 2 ]
[]
[]
[ "csrf", "django", "django_csrf", "python", "security" ]
stackoverflow_0005370714_csrf_django_django_csrf_python_security.txt
Q: How to count connected clients in TCPServer? I'm using Pythons SocketServer.ThreadingTCPServer. Now I want to know how many clients are connected at a certain moment. How to solve this? A: SocketServer.ThreadingTCPServer swap a new thread for each client connection so knowing the number of client connected in a ...
How to count connected clients in TCPServer?
I'm using Pythons SocketServer.ThreadingTCPServer. Now I want to know how many clients are connected at a certain moment. How to solve this?
[ "SocketServer.ThreadingTCPServer swap a new thread for each client connection so knowing the number of client connected in a certain moment is the same as knowing how many thread are alive in that moment , so just use threading.activeCount and the number of client will be:\nnum_client = threading.activeCount() - 1 ...
[ 6, 0 ]
[]
[]
[ "network_programming", "python", "tcp" ]
stackoverflow_0005370778_network_programming_python_tcp.txt
Q: Why doesn't mod_wsgi support daemon mode on Windows? On http://code.google.com/p/modwsgi/ one can read this statement Daemon mode of mod_wsgi will however only be available on Apache 2.0 or 2.2 running on UNIX, and only when the Apache runtime library underlying Apache has been compiled with support for...
Why doesn't mod_wsgi support daemon mode on Windows?
On http://code.google.com/p/modwsgi/ one can read this statement Daemon mode of mod_wsgi will however only be available on Apache 2.0 or 2.2 running on UNIX, and only when the Apache runtime library underlying Apache has been compiled with support for threading. What's the reason there's no support for daem...
[ "Windows doesn't provide UNIX style fork() system call and so process spawning where child process inherits parent process memory image isn't possible. Apache/mod_wsgi requires fork().\n", "For all who, after reading Graham's answer, want to know more on fork() on Windows here are questions related to this subjec...
[ 7, 2 ]
[]
[]
[ "apache", "mod_wsgi", "python", "windows" ]
stackoverflow_0005364949_apache_mod_wsgi_python_windows.txt
Q: How do create multiple processes that will pull messages from rabbitmq? Say I have a python script that pulls messages of a queue and process it process_queue_emails.py Now I want to somehow run multiple processes of this file at once, how would I do that? I need it to run in the background, and I'm guessing on ...
How do create multiple processes that will pull messages from rabbitmq?
Say I have a python script that pulls messages of a queue and process it process_queue_emails.py Now I want to somehow run multiple processes of this file at once, how would I do that? I need it to run in the background, and I'm guessing on a seperate port? (this is on ubuntu) So I want to write messages to the queue...
[ "The zdaemon module can be used to write demonized processes. Or you can look into the multiprocessing module of Python. And alternative is using supervisord for starting arbitrary scripts or programs as daemon.\n" ]
[ 1 ]
[]
[]
[ "python", "rabbitmq" ]
stackoverflow_0005371034_python_rabbitmq.txt
Q: Python, Webbrowser and Gmail Hey friends. I want to open Gmail but with a particular account. My python script has a list of gmail accounts and i want the one to open in gmail which has been clicked/selected. I tried using the credentials in the URL but am not happy with that as I don't want to put the users passw...
Python, Webbrowser and Gmail
Hey friends. I want to open Gmail but with a particular account. My python script has a list of gmail accounts and i want the one to open in gmail which has been clicked/selected. I tried using the credentials in the URL but am not happy with that as I don't want to put the users password in the URL + it doesn't work :...
[ "I have no clue if this would work, but it may be worth a shot.\nYou could try to spoof the browser and login via urllib and grab the cookie. Then you could programatically put the cookie in the browsers cookie directory and launch the browser to gmail.\nIt seems like it would work if you can get the browser+google...
[ 0, 0 ]
[]
[]
[ "browser", "gmail", "python" ]
stackoverflow_0003211105_browser_gmail_python.txt