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: Sort a list of Class Instances Python I have a list of class instances - x = [<iteminstance1>,...] among other attributes the class has score attribute. How can I sort the items in ascending order based on this parameter? EDIT: The list in python has something called sort. Could I use this here? How do I direct...
Sort a list of Class Instances Python
I have a list of class instances - x = [<iteminstance1>,...] among other attributes the class has score attribute. How can I sort the items in ascending order based on this parameter? EDIT: The list in python has something called sort. Could I use this here? How do I direct this function to use my score attribute?
[ "In addition to the solution you accepted, you could also implement the special __lt__() (\"less than\") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.\n...
[ 218, 146 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004010322_python_sorting.txt
Q: Django development version vs stable release I am about to start ramping up on Django and develop a web app that I want to deploy on Google App Engine. I learn that Google has Django 0.96 already installed on the APP engine, but the latest "official" version of Django I see is at 1.2.3 and its a bit of an effort t...
Django development version vs stable release
I am about to start ramping up on Django and develop a web app that I want to deploy on Google App Engine. I learn that Google has Django 0.96 already installed on the APP engine, but the latest "official" version of Django I see is at 1.2.3 and its a bit of an effort to install it there. I am curious which version of ...
[ "Most people are currently using Django 1.2. You should not use or learn Django .96 - it's VERY old, and learning to use it won't prepare you for any non-app-engine Django work since things have changed significantly since then.\nDjango on App Engine is something of a pain, since you lose a lot of the ORM, which is...
[ 3, 3, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004010349_django_google_app_engine_python.txt
Q: Qt C++ tcp client with python twisted server I'm trying to connect a very basic twisted "hello world" server with a basic Qt tcp client. The client uses these Signals: connect(&socket, SIGNAL(connected()), this, SLOT(startTransfer())); connect(&socket, SIGNAL(readyRead()), this, SLOT(readServer())); and then read...
Qt C++ tcp client with python twisted server
I'm trying to connect a very basic twisted "hello world" server with a basic Qt tcp client. The client uses these Signals: connect(&socket, SIGNAL(connected()), this, SLOT(startTransfer())); connect(&socket, SIGNAL(readyRead()), this, SLOT(readServer())); and then readServer() looks like this: ui->resultLabel->setText...
[ "The issue turned out to be QDataStream, which is apparently more than just a little particular about the data it's reading.\nThankfully, I discovered QDataStream::readRawData which liked data being sent by python a lot better (further I discovered this had nothing to do with twisted, but the python socket implemen...
[ 2, 1 ]
[]
[]
[ "c++", "python", "qt", "twisted" ]
stackoverflow_0004006854_c++_python_qt_twisted.txt
Q: Having a problem getting my output to look a certain way Thanks for viewing my question and thanks in advance for any help you may provide. I am writing a program that reads lines from a txt file and then prints the output in a certain fashion. Here they both are Here is the txt file I am reading from JOE FRITZ ...
Having a problem getting my output to look a certain way
Thanks for viewing my question and thanks in advance for any help you may provide. I am writing a program that reads lines from a txt file and then prints the output in a certain fashion. Here they both are Here is the txt file I am reading from JOE FRITZ AMERICAN GOVERNMENT B JOE FRITZ C...
[ "i just figure it out one of the bugs in your code in the function readRecord() you are just reading the first line of your file just it ; you should loop over all lines or make readRecord() a generator .\n def readRecord():\n global name, course, grade, eof\n\n studentRecord = gradeFile.readline() # <---...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004010714_python.txt
Q: unable to help(exec) Ok, this is funny. >>> exec("print") >>> help(exec) File "<stdin>", line 1 help(exec) ^ SyntaxError: invalid syntax >>> looks like exec is a statement, not a function, hence you cannot help() it. Is this expected or a bug? if expected, why? can you reproduce it on python3 ...
unable to help(exec)
Ok, this is funny. >>> exec("print") >>> help(exec) File "<stdin>", line 1 help(exec) ^ SyntaxError: invalid syntax >>> looks like exec is a statement, not a function, hence you cannot help() it. Is this expected or a bug? if expected, why? can you reproduce it on python3 ? I have Python 2.6.1 here...
[ "In Python 2.x, exec is a statement (and thus doesn't have a docstring associated with it.)\nIn Python 3.x, exec is now a function: http://docs.python.org/py3k/library/functions.html?highlight=exec#exec\nSo it can (and does) have a docstring.\nYou'd get this same behavior for help(print), which also became a functi...
[ 2, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004010980_python.txt
Q: Registry Startup Entry with runas argument? Is it possible to add a startup entry in the windows registry with a runas argument? So when it launches, it runs with the user specified? A: See this recipe: Reading from and writing to the Windows Registry (Python) It has python code to read from the registry to sh...
Registry Startup Entry with runas argument?
Is it possible to add a startup entry in the windows registry with a runas argument? So when it launches, it runs with the user specified?
[ "See this recipe:\n\nReading from and writing to the Windows Registry (Python)\n\nIt has python code to read from the registry to show which applications run at start as well as to write a new entry to launch a windows explorer at startup\n" ]
[ 1 ]
[]
[]
[ "python", "registry", "runas", "startup", "windows" ]
stackoverflow_0004010875_python_registry_runas_startup_windows.txt
Q: iterating through all items in listA that don't appear in listB How can I fix this statement: for i in LISTA and i not in LISTB: print i A: for i in LISTA: if i not in LISTB: print i A: new_list = set(LISTA) - set(LISTB) # if you don't have duplicate for i in new_list: print i Or : for i in LISTA...
iterating through all items in listA that don't appear in listB
How can I fix this statement: for i in LISTA and i not in LISTB: print i
[ "for i in LISTA:\n if i not in LISTB:\n print i\n\n", "new_list = set(LISTA) - set(LISTB) # if you don't have duplicate\nfor i in new_list:\n print i\n\nOr :\nfor i in LISTA:\n if i in LISTB:\n continue\n print i\n\n", "A more sophisticated solution. This is a simple intersection complement.\na ...
[ 8, 7, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004011217_python.txt
Q: how to iterate from a specific point in a sequence (Python) [Edit] From the feedback/answers I have received, I gather there is some confusion regarding the original question. Consequently, I have reduced the problem to its most rudimentary form Here are the relevant facts of the problem: I have a sorted sequence...
how to iterate from a specific point in a sequence (Python)
[Edit] From the feedback/answers I have received, I gather there is some confusion regarding the original question. Consequently, I have reduced the problem to its most rudimentary form Here are the relevant facts of the problem: I have a sorted sequence: S I have an item (denoted by i) that is GUARANTEED to be contai...
[ "yes , you can do like this:\nimport itertools\nfrom datetime import datetime\n\ndata = {\n \"2008-11-10 17:53:59\":\"data\",\n \"2005-11-10 17:53:59\":\"data\",\n}\n\nlist_ = data.keys()\nnew_list = [datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\") for x in list_]\n\nbegin_date = datetime.strptime(\"2007-11-1...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004006850_python.txt
Q: Python regular expression to remove "problem=None," from "Abc(problem=None, fds=5, sff=(2, 1, 0))" I've got a python string s = "Abc(problem=None, fds=5, sff=(2, 1, 0))" s2 = "Abc(problem=None)" What I want to do is remove the "problem=None, " So it'll looks like s = "Abc(fds=5, sff=(2, 1, 0))" s2 = "Abc()" Ple...
Python regular expression to remove "problem=None," from "Abc(problem=None, fds=5, sff=(2, 1, 0))"
I've got a python string s = "Abc(problem=None, fds=5, sff=(2, 1, 0))" s2 = "Abc(problem=None)" What I want to do is remove the "problem=None, " So it'll looks like s = "Abc(fds=5, sff=(2, 1, 0))" s2 = "Abc()" Please mind the ',' How to achieve this? Thanks very much!!
[ "Removing all syntactically valid whitespace:\n>>> import re\n>>> re.sub(r\"\\s*problem\\s*=\\s*None\\s*,?\\s*\", \"\", \"abc( problem = None , )\")\n'abc()'\n>>> re.sub(r\"\\s*problem\\s*=\\s*None\\s*,?\\s*\", \"\", \"abc( problem = None )\")\n'abc()'\n>>>\n\n", "A regex that will work in both cases is:\n/probl...
[ 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004011237_python_regex.txt
Q: facebook python-sdk post_to_wall attachment Hi I am using the python-sdk (http://github.com/facebook/python-sdk.git) on google appengine. I am runnig the "newsfeed" example. In facebook.py i had to import urllib2 and then change file = urllib.urlopen("https://graph.facebook.com/" + path + "?" + ...
facebook python-sdk post_to_wall attachment
Hi I am using the python-sdk (http://github.com/facebook/python-sdk.git) on google appengine. I am runnig the "newsfeed" example. In facebook.py i had to import urllib2 and then change file = urllib.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data) to ...
[ "Solved the problem by using put_object instead of post_to_wall:\nsee http://developers.facebook.com/docs/reference/api/post for an example on how to post with curl\n self.graph.put_object(\"me\", \"feed\", message=message, \n link=\"http://leona-nachhilfe.appspot.com\", \n ...
[ 2 ]
[]
[]
[ "attachment", "facebook", "python" ]
stackoverflow_0004009441_attachment_facebook_python.txt
Q: Get the width of a TreeViewColumn that would like to be if it were autosized Is there a way to get the width, in pixels, that a gtk.TreeViewColumn would want to be if the sizing mode was set as gtk.TREE_VIEW_COLUMN_AUTOSIZE, even if it's currently gtk.TREE_VIEW_COLUMN_FIXED? A: I think gtk.TreeViewColumn.cell_ge...
Get the width of a TreeViewColumn that would like to be if it were autosized
Is there a way to get the width, in pixels, that a gtk.TreeViewColumn would want to be if the sizing mode was set as gtk.TREE_VIEW_COLUMN_AUTOSIZE, even if it's currently gtk.TREE_VIEW_COLUMN_FIXED?
[ "I think gtk.TreeViewColumn.cell_get_size() will do the job.\nSample code:\ndef show_size(treeview):\n col = treeview.get_column(0)\n cell = col.get_cell_renderers()[0]\n size = col.cell_get_position(cell)\n print 'current size: position=%s, width=%s' % size\n size = col.cell_get_size()\n print 'a...
[ 0 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0004000071_gtk_gtktreeview_pygtk_python.txt
Q: Laplacian smoothing to Biopython I am trying to add Laplacian smoothing support to Biopython's Naive Bayes code 1 for my Bioinformatics project. I have read many documents about Naive Bayes algorithm and Laplacian smoothing and I think I got the basic idea but I just can't integrate this with that code (actually ...
Laplacian smoothing to Biopython
I am trying to add Laplacian smoothing support to Biopython's Naive Bayes code 1 for my Bioinformatics project. I have read many documents about Naive Bayes algorithm and Laplacian smoothing and I think I got the basic idea but I just can't integrate this with that code (actually I cannot see which part I will add 1 -...
[ "Try using this definition of the _contents() method instead:\ndef _contents(items, laplace=False):\n # count occurrences of values\n counts = {}\n for item in items:\n counts[item] = counts.get(item,0) + 1.0\n # normalize\n for k in counts:\n if laplace:\n counts[k] += 1.0\n...
[ 4 ]
[]
[]
[ "bayesian", "biopython", "machine_learning", "python" ]
stackoverflow_0004011115_bayesian_biopython_machine_learning_python.txt
Q: Pylons and Memcached Anyone happen to use this combination in their web application? I'm having a bit of trouble finding some sort of tutorial or guideline for configuring this. Also seeing as how I started using Pylons recently I'm not familiar so please keep the advice very newbie friendly ( I haven't even used ...
Pylons and Memcached
Anyone happen to use this combination in their web application? I'm having a bit of trouble finding some sort of tutorial or guideline for configuring this. Also seeing as how I started using Pylons recently I'm not familiar so please keep the advice very newbie friendly ( I haven't even used modules like Beaker all th...
[ "memcached is nice and framework-agnostic, and you just have to write a bit of code to interact with it. The general idea of memcached is:\nobject = try_memcached()\nif not object:\n object = real_query()\n put_in_memcached(object)\n\nThat will likely be done in your SQLAlchemy abstraction, in your case. Sin...
[ 7, 1 ]
[]
[]
[ "memcached", "pylons", "python" ]
stackoverflow_0001738250_memcached_pylons_python.txt
Q: Installing MySQLdb on Snow Leopard I followed this tutorial to install Django with MySQL on my Snow Lepard : http://programmingzen.com/2007/12/22/how-to-install-django-with-mysql-on-mac-os-x/ When I run this command : python setup.py build I get a lot of errors, the last one is : error: command 'gcc-4.0' failed ...
Installing MySQLdb on Snow Leopard
I followed this tutorial to install Django with MySQL on my Snow Lepard : http://programmingzen.com/2007/12/22/how-to-install-django-with-mysql-on-mac-os-x/ When I run this command : python setup.py build I get a lot of errors, the last one is : error: command 'gcc-4.0' failed with exit status 1 These are the first l...
[ "Looks like you're missing MySQL development headers. Apple's support site has a (possible) solution: http://support.apple.com/kb/TA25017\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0004011500_django_mysql_python.txt
Q: Medical information extraction using Python I am a nurse and I know python but I am not an expert, just used it to process DNA sequences We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. A...
Medical information extraction using Python
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format le...
[ "Here are some possible way you can solve this - \n\nUsing Regular Expressions - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)\nSt...
[ 9, 9, 3, 1 ]
[]
[]
[ "information_extraction", "machine_learning", "nlp", "parsing", "python" ]
stackoverflow_0004011526_information_extraction_machine_learning_nlp_parsing_python.txt
Q: svg image - zoom and borders I have the following small svg file hosted at: http://dl.dropbox.com/u/7393/hmap.svg and I am trying to make it look like this: http://dl.dropbox.com/u/7393/final.png The docs where I got this from mentions that this change can be easily obtained by changing a couple of tags on the svg...
svg image - zoom and borders
I have the following small svg file hosted at: http://dl.dropbox.com/u/7393/hmap.svg and I am trying to make it look like this: http://dl.dropbox.com/u/7393/final.png The docs where I got this from mentions that this change can be easily obtained by changing a couple of tags on the svg file. However I have tried changi...
[ "To zoom change the viewbox setting. The file uses one on the first and only svg tag at the top of the file. The viewbox you are using is for the full image viewBox=\"0 -500 2752.766 2537.631\" and you are placing it into a box with height=\"476.7276\" width=\"634.26801\" pixels. So a line 1 unit wide would be abou...
[ 1 ]
[]
[]
[ "python", "svg" ]
stackoverflow_0003998254_python_svg.txt
Q: How to get the smallest list of duplicate items from list of lists? I'm a Python newbie, I worked with list for 2 months and I have some questions. I have some list and they have duplicate items. I can get duplicate items between 2 lists, now I want the number of lists and the deepness increased like this example:...
How to get the smallest list of duplicate items from list of lists?
I'm a Python newbie, I worked with list for 2 months and I have some questions. I have some list and they have duplicate items. I can get duplicate items between 2 lists, now I want the number of lists and the deepness increased like this example: http://i219.photobucket.com/albums/cc213/DoSvn/example.png. I want to ge...
[ "If you are searching something like this: http://i219.photobucket.com/albums/cc213/DoSvn/example02.png\nThen you can try the Counter (available in Python 2.7+). It should work like this:\nfrom collections import Counter\n\nc = Counter()\nfor s in (listOfLists):\n c.update(s)\n\nfor item, nbItems in c.iteritems(...
[ 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0004011967_algorithm_python.txt
Q: In mako template: call python function within html string How do I do this in mako: <% import cherrypy %> ... <link rel="stylesheet" href="${cherrypy.url('/media/layout.css')}" type="text/css" /> AttributeError: 'Undefined' object has no attribute 'url' A: Answer: Instead of <% import cherrypy %> one needs <%! ...
In mako template: call python function within html string
How do I do this in mako: <% import cherrypy %> ... <link rel="stylesheet" href="${cherrypy.url('/media/layout.css')}" type="text/css" /> AttributeError: 'Undefined' object has no attribute 'url'
[ "Answer: Instead of <% import cherrypy %> one needs <%! import cherrypy %>\n" ]
[ 3 ]
[]
[]
[ "cherrypy", "mako", "python" ]
stackoverflow_0004007898_cherrypy_mako_python.txt
Q: Python2.6 xmpp Jabber Error I am using xmpp with python and I want create a simple client to communicate with a gmail id. #!/usr/bin/python import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login,pwd, 'bot...
Python2.6 xmpp Jabber Error
I am using xmpp with python and I want create a simple client to communicate with a gmail id. #!/usr/bin/python import xmpp login = 'Your.Login' # @gmail.com pwd = 'YourPassword' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login,pwd, 'botty') cnx.send( xmpp.Message( "Yo...
[ "Here is how it did on my PyTalk client.\nDon't forget the @gmail.com in the userID.\nI think you should try to connect talk.google.com on the 5222 port.\nAlso try to specify a ressource for the auth.\nimport xmpp\nimport sys\n\nuserID = 'Your.Login@gmail.com' \npassword = 'YourPassword'\nressource = 'Script'\n\n...
[ 6, 1, 1, 0 ]
[]
[]
[ "python", "xmpp" ]
stackoverflow_0001301303_python_xmpp.txt
Q: A question about lists in Python I'm having some trouble with a couple of hmwk questions and i can't find th answer- How would you write an expression that removes the first or last element of a list? i.e. One of my questions reads "Given a list named 'alist' , write an expression that removes the last element of...
A question about lists in Python
I'm having some trouble with a couple of hmwk questions and i can't find th answer- How would you write an expression that removes the first or last element of a list? i.e. One of my questions reads "Given a list named 'alist' , write an expression that removes the last element of 'alist'"
[ "Have you looked at this? http://docs.python.org/tutorial/datastructures.html\nParticularly at pop([i])? \nYour assignment sounds like a standard question in functional programming. Are you supposed to use lambdas?\n", "I'm pretty sure its as simple as \"alist.pop()\"\n", "Here's how you do it in Python -\nx = ...
[ 2, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004011446_list_python.txt
Q: Python (creating a negative of this black and white image) I am trying to create a negative of this black and white image. The opposite of white (255) is black (0) and vice versa. The opposite of a pixel with a value of 100 is 155. I cannot use convert, invert, point, eval, lambda. Here is my code but it doesnt wo...
Python (creating a negative of this black and white image)
I am trying to create a negative of this black and white image. The opposite of white (255) is black (0) and vice versa. The opposite of a pixel with a value of 100 is 155. I cannot use convert, invert, point, eval, lambda. Here is my code but it doesnt work yet. Could you please let me know which part i am wrong. def ...
[ "Python is an interpreted language, which has the advantage that you can use an interactive interpreter-session to try out things. Try to open the image file in an interactive session and look at the list you get from list(image.getdata()). Once you understand what that list contains, you can think about a way to i...
[ 1 ]
[]
[]
[ "image", "pixel", "python" ]
stackoverflow_0004012841_image_pixel_python.txt
Q: python running multiple instances hi lets assume i have a simple programm in python. This programm is running every five minutes throught cron. but i dont know how to write it so the programm will allow to run multiple processes of its self simultaneously. i want to speed things up ... A: I'd handle the forking ...
python running multiple instances
hi lets assume i have a simple programm in python. This programm is running every five minutes throught cron. but i dont know how to write it so the programm will allow to run multiple processes of its self simultaneously. i want to speed things up ...
[ "I'd handle the forking and process control inside your main python program. Let the cron spawn only a single process and that process be a master for (possible multiple) worker processes.\nAs for how you can create multiple workers, there's the threading module for multi threading and multiprocessing module for mu...
[ 1 ]
[]
[]
[ "fork", "jobs", "process", "python", "subprocess" ]
stackoverflow_0004012934_fork_jobs_process_python_subprocess.txt
Q: How do I forcefully clean a field and redisplay it in Django? How can I clean the data in a form and have the cleaned data redisplayed instead of the submitted data? There are several fields in my form, and every time the user submits it, it should be redisplayed with the values the user entered. However, some of...
How do I forcefully clean a field and redisplay it in Django?
How can I clean the data in a form and have the cleaned data redisplayed instead of the submitted data? There are several fields in my form, and every time the user submits it, it should be redisplayed with the values the user entered. However, some of the fields I would like to clean and update for the user. More spe...
[ "If, after you've cleaned your form with is_valid(), you render that cleaned form with your view, rather than redirect to a new page, you'll see the cleaned data in your page. \n(If you wanted the user to see this cleaned data and then properly submit it, you could use a hidden field to track whether the form data ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004010507_django_python.txt
Q: How to speed up transfer of images from client to server I am solving a problem of transferring images from a camera in a loop from a client (a robot with camera) to a server (PC). I am trying to come up with ideas how to maximize the transfer speed so I can get the best possible FPS (that is because I want to cre...
How to speed up transfer of images from client to server
I am solving a problem of transferring images from a camera in a loop from a client (a robot with camera) to a server (PC). I am trying to come up with ideas how to maximize the transfer speed so I can get the best possible FPS (that is because I want to create a live video stream out of the transferred images). Disreg...
[ "This might be quite a bit of work but if your client can handle the computations in real time you could use the same method that video encoders use. Send a key frame every say 5 frames and in between only send the information that changed not the whole frame. I don't know the details of how this is done, but try G...
[ 4, 2 ]
[]
[]
[ "algorithm", "c#", "c++", "performance", "python" ]
stackoverflow_0004013046_algorithm_c#_c++_performance_python.txt
Q: how to make installer or exe of python code Possible Duplicate: py2exe - generate single executable file Hi, I have a python project and wanted to make a exe for windows. In my project I am using pyqt,python and MiKTeX , xlrd. How to bundle the project so that user in windows can run the exe and every package ge...
how to make installer or exe of python code
Possible Duplicate: py2exe - generate single executable file Hi, I have a python project and wanted to make a exe for windows. In my project I am using pyqt,python and MiKTeX , xlrd. How to bundle the project so that user in windows can run the exe and every package get install. I am not able to find any reading ma...
[ "py2exe, unless you want to hide your logic. I use it to deploy my programs inside the company I work at and it works perfectly well\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004013248_python.txt
Q: How many bytes does a string have Is there some function which will tell me how many bytes does a string occupy in memory? I need to set a size of a socket buffer in order to transfer the whole string at once. A: If it's a Python 2.x str, get its len. If it's a Python 3.x str (or a Python 2.x unicode), first enc...
How many bytes does a string have
Is there some function which will tell me how many bytes does a string occupy in memory? I need to set a size of a socket buffer in order to transfer the whole string at once.
[ "If it's a Python 2.x str, get its len. If it's a Python 3.x str (or a Python 2.x unicode), first encode to bytes (or a str, respectively) using your preferred encoding ('utf-8' is a good choice) and then get the len of the encoded bytes/str object.\n\nFor example, ASCII characters use 1 byte each:\n>>> len(\"hello...
[ 95, 63 ]
[]
[]
[ "python" ]
stackoverflow_0004013230_python.txt
Q: Best way for a total noob to create a simple web application I want to make an interactive, simple web application. Where should I start? Preferably python/django because it sounds easiest? you tell me. tia. A: Easiest is not necessarily the best route for any development work. I would want the most suitable fra...
Best way for a total noob to create a simple web application
I want to make an interactive, simple web application. Where should I start? Preferably python/django because it sounds easiest? you tell me. tia.
[ "Easiest is not necessarily the best route for any development work. I would want the most suitable framework for the job with the best learning support and best available tools. Some of the worst coding I have ever seen was done the easiest way. \nIf you are looking for a powerful framework with good supporting co...
[ 3, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004013163_django_python.txt
Q: Python and Web applications I want to start writing python to support some of my web applications. Mainly i'm trying to fetch pages, send POST data to urls and some string manipulation. I understand that there are some disadvantages with the urllib in the new versions. Can anyone please tell me which release is be...
Python and Web applications
I want to start writing python to support some of my web applications. Mainly i'm trying to fetch pages, send POST data to urls and some string manipulation. I understand that there are some disadvantages with the urllib in the new versions. Can anyone please tell me which release is best for my needs? Thanks
[ "Step 1. Use urllib2 to fetch pages. Save them in flat files\nhttp://docs.python.org/library/urllib2.html\nStep 2. Use a WSGI-based server like werkzeug to serve those pages. \nhttp://docs.python.org/library/wsgiref.html\nhttp://werkzeug.pocoo.org/\nWhen you get that working, plug it into a proper web server (...
[ 2, 1 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0004013512_python_urllib.txt
Q: how do I generate a cartesian product of several variables using python iterators? Dear all, Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables. While this code does the trick, site_range=[0,1,2] states = [(s0,s1,s2) for s0 i...
how do I generate a cartesian product of several variables using python iterators?
Dear all, Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables. While this code does the trick, site_range=[0,1,2] states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range] it's somewhat, uhm, clumsy, and...
[ "import itertools\nsite_range=[0,1,2]\n[x for x in itertools.product(site_range, repeat=len(site_range))]\n\n", "Use itertools.product:\n>>> site_range=[0,1]\n>>> list(product(site_range, repeat=3))\n[000 001 010 011 100 101 110 111]\n\nEdit As @Glenn Maynard points out in a comment, this is not the cartesian pro...
[ 4, 3 ]
[]
[]
[ "cartesian_product", "iterator", "python" ]
stackoverflow_0004013730_cartesian_product_iterator_python.txt
Q: smallest value of hash() function? in python (3), what is the smallest value that hash(x) can return? i want to use hashes to give a quick 'fingerprint' to database values (basically making it easy to see whether two longish, similar texts are actually equal or not), and want to get rid of negative numbers (for s...
smallest value of hash() function?
in python (3), what is the smallest value that hash(x) can return? i want to use hashes to give a quick 'fingerprint' to database values (basically making it easy to see whether two longish, similar texts are actually equal or not), and want to get rid of negative numbers (for simplicity), so i thought i'd just add th...
[ "hash() can return any integer, and as you have seen, the size of the integer can vary with the architecture. This is one of the reasons dictionary ordering is arbitrary: the same set of operations on two different platforms can give different results because the hashes used along the way can differ.\nIf all you a...
[ 5, 4, 1, 1 ]
[]
[]
[ "32bit_64bit", "c", "hash", "python", "python_3.x" ]
stackoverflow_0004010859_32bit_64bit_c_hash_python_python_3.x.txt
Q: Stuck in a while loop, can you please help? I am currently writing a program that reads records from a txt file and prints the data on the screen as such: GRADE REPORT NAME COURSE GRADE ----------------------------------------------------------- JOE...
Stuck in a while loop, can you please help?
I am currently writing a program that reads records from a txt file and prints the data on the screen as such: GRADE REPORT NAME COURSE GRADE ----------------------------------------------------------- JOE FRITZ AMERICAN GOVERNMENT ...
[ "Why don't you do it all in a single function -\ndef processRecords():\n print (\"grade report\\n\").center(60).upper()\n print \"name\".upper(),\"course\".rjust(22).upper(),\"grade\".rjust(32).upper()\n print \"-\" * 60\n\n rec_count = 0\n for line in open(\"grades.txt\",\"r\"):\n name = li...
[ 5, 4, 3, 3, 2, 2, 1 ]
[]
[]
[ "python", "variable_assignment" ]
stackoverflow_0004009899_python_variable_assignment.txt
Q: PyGTK - Adding Rows to gtk.TreeStore After following the official tutorial here: tutorial I'm still having issues adding rows/creating a TreeIter object. Here's what my code looks like: builder = gtk.Builder() self.treeview = builder.get_object("treeview") self.treestore = gtk.TreeStore(str) self....
PyGTK - Adding Rows to gtk.TreeStore
After following the official tutorial here: tutorial I'm still having issues adding rows/creating a TreeIter object. Here's what my code looks like: builder = gtk.Builder() self.treeview = builder.get_object("treeview") self.treestore = gtk.TreeStore(str) self.treeview.set_model(self.treestore) se...
[ "I spot a number of general problems with the code as well:\n\nYou're creating too many CellRenderer's! Use just one for the whole table.\nDon't use the Builder()! It's just stupidly overcomplicating things.\nYou're not adding columns the most efficent way.\n\nLook into the question I've already asked.\n" ]
[ 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0003917228_gtk_gtktreeview_pygtk_python.txt
Q: How to get the EXIF or meta-data from images? I need a really good library or a command-line software that can be used to extract Exif data from images. No specific programming language, except the library or the software has to work really well. I found various libraries for PHP and Python, but most of it hasn't...
How to get the EXIF or meta-data from images?
I need a really good library or a command-line software that can be used to extract Exif data from images. No specific programming language, except the library or the software has to work really well. I found various libraries for PHP and Python, but most of it hasn't been updated or being maintained and don't work fo...
[ "Right this is what you want.\nhttp://www.sno.phy.queensu.ca/~phil/exiftool/\nGets what flickr does!\n", "The Gimp's Exif Viewer plugin uses libexif, which is written in C and seems to have been updated recently. Also, here is the EXIF standard itself, if you feel like rolling your own. \n", "jhead is a great c...
[ 5, 2, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "exif", "image", "java", "php", "python" ]
stackoverflow_0002079013_exif_image_java_php_python.txt
Q: how to wrap file object read and write operation (which are readonly)? i am trying to wrap the read and write operation of an instance of a file object (specifically the readline() and write() methods). normally, i would simply replace those functions by a wrapper, a bit like this: def log(stream): def logwrit...
how to wrap file object read and write operation (which are readonly)?
i am trying to wrap the read and write operation of an instance of a file object (specifically the readline() and write() methods). normally, i would simply replace those functions by a wrapper, a bit like this: def log(stream): def logwrite(write): def inner(data): print 'LOG: > '+data.replace(...
[ "use __getattr__ to wrap your file object. provide modified methods for the ones that you are concerned with.\nclass Wrapped(object):\n def __init__(self, file_):\n self._file = file_\n\n def write(self, data):\n print 'LOG: > '+data.replace('\\r','<cr>').replace('\\n','<lf>')\n return se...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004013843_python.txt
Q: Auto truncation of a Tkinter label I have a label sitting on a frame which is updated periodically to show the status of the application. Periodically, the name of the item being processed will not fit into the window, and with the way I currently have the label configured the window expands to accomidate the lab...
Auto truncation of a Tkinter label
I have a label sitting on a frame which is updated periodically to show the status of the application. Periodically, the name of the item being processed will not fit into the window, and with the way I currently have the label configured the window expands to accomidate the label. Ideally, I'd like way to smartly t...
[ "The answer depends very much on the way you currently have configured the widget.\nFor example, I can get the desired functionality as such:\n>>> import Tkinter as tk\n>>> r=tk.Tk()\n>>> r.title('hello')\n''\n>>> l= tk.Label(r, name='lbl', width=20, text='reduce the window width')\n>>> l.pack(fill=tk.BOTH) # or tk...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004001285_python_tkinter.txt
Q: How to enable SSL with a IIS 6 + FastCGI + Django setup? I have successfully setup FastCGI/Django on a IIS 6 Server. What I don't know how to do, is to enable SSL connections. Any tips or ideas to get me started? I'm not an IIS expert, so this is quite confusing for me. :) A: I'm not an IIS expert either, altho...
How to enable SSL with a IIS 6 + FastCGI + Django setup?
I have successfully setup FastCGI/Django on a IIS 6 Server. What I don't know how to do, is to enable SSL connections. Any tips or ideas to get me started? I'm not an IIS expert, so this is quite confusing for me. :)
[ "I'm not an IIS expert either, although I do have my own web server.\nHave you installed your SSL certificate? If so try reading,\nhttps://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5055536.html\nwhich should assist you in completing the installation.\n" ]
[ 2 ]
[]
[]
[ "django", "fastcgi", "iis", "python", "ssl" ]
stackoverflow_0004013536_django_fastcgi_iis_python_ssl.txt
Q: Extending forms.SelectMultiple Without Losing Values I have a model form that I am writing a custom widget for in order to replace the many-to-many forms.SelectMultiple fields with jQuery FCBKcomplete widgets. While the replacement of the multiselect element works fine, it is no longer pulling the options for the ...
Extending forms.SelectMultiple Without Losing Values
I have a model form that I am writing a custom widget for in order to replace the many-to-many forms.SelectMultiple fields with jQuery FCBKcomplete widgets. While the replacement of the multiselect element works fine, it is no longer pulling the options for the multiselect. Here is my widget: class FCBKcompleteWidget(f...
[ "1 year passed, but answer may be valuable even with current django version. \nReason for such behavior seems to missing CHOICES property for fcbk fields \njust push choices to the Form \nclass EmailSubscriptionFilterForm(forms.ModelForm):\n\n class Meta:\n model = EmailSubscription\n exclude = (...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001668881_django_django_forms_python.txt
Q: Splitting results from chardet output to collect encoding type I am testing chardet in one of my scripts. I wanted to identify the encoding type of a result variable and chardet seems to do fine here. So this is what I am doing: myvar1 <-- gets its value from other functions myvar2 = chardet.detect(myvar1) <-- to...
Splitting results from chardet output to collect encoding type
I am testing chardet in one of my scripts. I wanted to identify the encoding type of a result variable and chardet seems to do fine here. So this is what I am doing: myvar1 <-- gets its value from other functions myvar2 = chardet.detect(myvar1) <-- to detect the encoding type of myvar1 Now when I do a print myvar2, I...
[ "print myvar2['encoding']\n\n\nNow for the added related info: chardet is an attempt of detecting the encoding. It isn't 100% reliable and fails sometimes. However it's the best you've got since reliable encoding detection is impossible. Just provide a way for your users to specify encoding if chardet fails for the...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004014706_python.txt
Q: Viewing the code of a Python function Let's say I'm working in the Python shell and I'm given a function f. How can I access the string containing its source code? (From the shell, not by manually opening the code file.) I want this to work even for lambda functions defined inside other functions. A: inspect.get...
Viewing the code of a Python function
Let's say I'm working in the Python shell and I'm given a function f. How can I access the string containing its source code? (From the shell, not by manually opening the code file.) I want this to work even for lambda functions defined inside other functions.
[ "inspect.getsource\nIt looks getsource can't get lambda's source code.\n", "Not necessarily what you're looking for, but in ipython you can do:\n>>> function_name??\n\nand you will get the code source of the function (only if it's in a file). So this won't work for lambda. But it's definitely useful!\n", "maybe...
[ 9, 8, 3, 0 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0004014722_introspection_python.txt
Q: Send commands between two computers over the internet I wish to control my computer (and usb devices attached to the computer) at home with any computer that is connected to the internet. The computer at home must have a program installed that receives commands from any other computer that is connected to the inte...
Send commands between two computers over the internet
I wish to control my computer (and usb devices attached to the computer) at home with any computer that is connected to the internet. The computer at home must have a program installed that receives commands from any other computer that is connected to the internet. I thought it would be best if I do this with a web in...
[ "VNC\nSSH\nRemote Desktop (Windows)\n", "You can write a WEB APPLICATION. The encryption part is solved by simple HTTPS usage. On the server side (your home computer with USB devices attached to it) you should use Python (since you're quite experienced with it) and a Python Web Framework you want (I.E. Django).\n...
[ 12, 2, 2, 0, 0, 0 ]
[]
[]
[ "java", "javascript", "php", "python" ]
stackoverflow_0004014670_java_javascript_php_python.txt
Q: Python - Neaten this append/extend conditional I have a method which I will accept either a single object or a list of objects. I want to add whatever is passed to another list. Currently, my method looks like this: def appendOrExtend(self, item): if type(item).__name__ == "list": self.list.extend(item) el...
Python - Neaten this append/extend conditional
I have a method which I will accept either a single object or a list of objects. I want to add whatever is passed to another list. Currently, my method looks like this: def appendOrExtend(self, item): if type(item).__name__ == "list": self.list.extend(item) else: self.list.append(item) It seems to me that ...
[ "def append(self, item):\n self.list.append(item)\ndef extend(self, item):\n self.list.extend(item)\n\nBottom line: Don't have a method to do both things. It confuses and makes your method less useful, instead of more useful. It's also harder to test and to maintain. Also the user of your function already kno...
[ 10, 3, 1, 1, 0 ]
[]
[]
[ "append", "extend", "list", "python" ]
stackoverflow_0004014982_append_extend_list_python.txt
Q: Regex matching items following a header in HTML What should be a fairly simple regex extraction is confounding me. Couldn't find a similar question on SO, so happy to be pointed to one if it exists. Given the following HTML: <h1 class="title">Title One</h1><p><a href="#">40.5</a><a href="#">31.3</a></p> <h1 clas...
Regex matching items following a header in HTML
What should be a fairly simple regex extraction is confounding me. Couldn't find a similar question on SO, so happy to be pointed to one if it exists. Given the following HTML: <h1 class="title">Title One</h1><p><a href="#">40.5</a><a href="#">31.3</a></p> <h1 class="title alternate">Title Two</h1><p><a href="#">12.1...
[ "You're right, regex is absolutely the wrong tool for HTML matching.\nYour question, however, sounds exactly like the problem for Beautiful Soup - a HTML parser that can deal with less-than-perfect HTML.\n", "The other obvious answer to solve this problem is BeautifulSoup -- I like that it handles the kind of cra...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "html", "parsing", "python", "regex" ]
stackoverflow_0004014546_html_parsing_python_regex.txt
Q: Using an image URL for link_callback in the pisa html to pdf library Related to: django - pisa : adding images to PDF output I've got a site that uses the Google Chart API to display a bunch of reports to the user, and I'm trying to implement a PDF version. I'm using the link_callback parameter in pisa.pisaDocumen...
Using an image URL for link_callback in the pisa html to pdf library
Related to: django - pisa : adding images to PDF output I've got a site that uses the Google Chart API to display a bunch of reports to the user, and I'm trying to implement a PDF version. I'm using the link_callback parameter in pisa.pisaDocument which works great for local media (css/images), but I'm wondering if it ...
[ "Well this was a whole lot easier than I expected. In your link_callback method, if the uri is a remote image, simply return that value.\ndef link_callback(uri, rel):\n if uri.find('chart.apis.google.com') != -1:\n return uri\n return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, \"...
[ 6 ]
[]
[]
[ "pdf_generation", "pisa", "python" ]
stackoverflow_0004000951_pdf_generation_pisa_python.txt
Q: Create a new variable as named from input in Python? This is something that I've been questioning for some time. How would I create a variable at runtime as named by the value of another variable. So, for example, the code would ask the user to input a string. A variable would then be created named after that stri...
Create a new variable as named from input in Python?
This is something that I've been questioning for some time. How would I create a variable at runtime as named by the value of another variable. So, for example, the code would ask the user to input a string. A variable would then be created named after that string with a default value of "default". Is this even possibl...
[ "It is possible, but it's certainly not advised. You can access the global namespace as a dict (it's a dict internally) and add entries to it.\nIf you were doing an interactive interpreter, say, for doing maths, or something. You would actually pass a dict to each eval() or exec that you could then re-use as it's l...
[ 4 ]
[]
[]
[ "initialization", "python", "runtime", "variables" ]
stackoverflow_0004015550_initialization_python_runtime_variables.txt
Q: Compression with best ratio in Python? Which compression method in Python has the best compression ratio? Is the commonly used zlib.compress() the best or are there some better options? I need to get the best compression ratio possible. I am compresing strings and sending them over UDP. A typical string I compress...
Compression with best ratio in Python?
Which compression method in Python has the best compression ratio? Is the commonly used zlib.compress() the best or are there some better options? I need to get the best compression ratio possible. I am compresing strings and sending them over UDP. A typical string I compress has about 1,700,000 bytes.
[ "I'm sure that there might be some more obscure formats with better compression, but lzma is the best, of those that are well supported. There are some python bindings here.\nEDIT\nDon't pick a format without testing, some algorithms do better depending on the data set.\n", "If you are willing to trade performan...
[ 9, 5, 3 ]
[]
[]
[ "compression", "python" ]
stackoverflow_0004015425_compression_python.txt
Q: Figure out child type with Django MTI or specify type as field? I'm setting up a data model in django using multiple-table inheritance (MTI) like this: class Metric(models.Model): account = models.ForeignKey(Account) date = models.DateField() value = models.FloatField() calculation_in_progress = mo...
Figure out child type with Django MTI or specify type as field?
I'm setting up a data model in django using multiple-table inheritance (MTI) like this: class Metric(models.Model): account = models.ForeignKey(Account) date = models.DateField() value = models.FloatField() calculation_in_progress = models.BooleanField() type = models.CharField( max_length=20, choic...
[ "While it might offend some people's sensibilities, the only practical way to solve this problem is to put either a field or a method in the base class which says what kind of object each record really is. The problem with the method you describe is that it requires a separate database query for every type of subc...
[ 1 ]
[ "\nBut do I need to do this? \n\nNever. Never. Never.\n\nIs there some way that django handles this automatically?\n\nYes. It's called \"polymorphism\".\nYou never need to know the subclass. Never.\n\"What about my WebMetric.url and my TextMetric.text attributes?\"\nWhat will you do with these attributes? Defi...
[ -1 ]
[ "django", "django_models", "python" ]
stackoverflow_0003990470_django_django_models_python.txt
Q: Does master/worker scale? I have a master/worker model implemented with separate python processes. The master process holds job/result lists which are protected by mutexes. Many workers run on many machines (about 200 worker processes). I have noticed that on each machine the workers tend to do 0-20% more or less ...
Does master/worker scale?
I have a master/worker model implemented with separate python processes. The master process holds job/result lists which are protected by mutexes. Many workers run on many machines (about 200 worker processes). I have noticed that on each machine the workers tend to do 0-20% more or less work than other worker processe...
[ "The simplest explanation for the +/- 20% thing is that you're seeing a load balancing problem; some of the workers are just getting 20% more work than some of their peers. This could represent an implementation problem, or it could just be discreteness; if you have 200 worker processes but 1040 roughly-equal jobs...
[ 3 ]
[]
[]
[ "concurrency", "python" ]
stackoverflow_0004015348_concurrency_python.txt
Q: Can I include sub-config files in my mercurial .hgrc? I want to keep my main .hgrc in revision control, because I have a fair amount of customization it in, but I want to have different author names depending on which machine I'm using (work, home, &c.). The way I'd do this in a bash script is to source a host-loc...
Can I include sub-config files in my mercurial .hgrc?
I want to keep my main .hgrc in revision control, because I have a fair amount of customization it in, but I want to have different author names depending on which machine I'm using (work, home, &c.). The way I'd do this in a bash script is to source a host-local bash script that is ignored by Mercurial, but I'm not su...
[ "You can do this using the not-often-used but been-there-awhile include syntax.\nPut your machine specific stuff in your ~/.hgrc and then include a constant-across-all-systems boilerplate config file. Example:\n[ui]\nusername=You <you@somewhere>\n\n%include .hgrc-boilerplate\n\nTrack the .hgrc-boilerplate file in ...
[ 20 ]
[]
[]
[ "dotfiles", "hgrc", "mercurial", "python" ]
stackoverflow_0004015901_dotfiles_hgrc_mercurial_python.txt
Q: Running a PIL based Python program as a web application I have created a Python Program that converts strings into images at run time , using PIL's Image Draw module. I want to run this program interfaced with a simple web form that should display a text field to input the string and on pressing a button , it sho...
Running a PIL based Python program as a web application
I have created a Python Program that converts strings into images at run time , using PIL's Image Draw module. I want to run this program interfaced with a simple web form that should display a text field to input the string and on pressing a button , it should display the string converted as an image. Would be a grea...
[ "I would suggest using web.py from http://webpy.org/. It is an excellent micro-framework for doing simple or one-off web apps. \nDo your image creator write files or return streams? Anyway, web.py can return both files and stream large files to the browser. See http://webpy.org/images for an example on how to set h...
[ 1, 0 ]
[]
[]
[ "image_manipulation", "python", "web_applications", "webforms" ]
stackoverflow_0004016101_image_manipulation_python_web_applications_webforms.txt
Q: Recursive problem I have a problem when I import classes from one to another. I have those classes in different modules: crm.py from CRMContactInformation import CRMContactInformation class CRM(rdb.Model): """Set up crm table in the database""" rdb.metadata(metadata) rdb.tablename("crms") ...
Recursive problem
I have a problem when I import classes from one to another. I have those classes in different modules: crm.py from CRMContactInformation import CRMContactInformation class CRM(rdb.Model): """Set up crm table in the database""" rdb.metadata(metadata) rdb.tablename("crms") id = Column("i...
[ "Delay the imports:\nclass CRM(rdb.Model):\n \"\"\"Set up crm table in the database\"\"\"\n rdb.metadata(metadata)\n rdb.tablename(\"crms\")\n\n id = Column(\"id\", Integer, ForeignKey(\"screens.id\"), primary_key=True)\n screen_id = Column(\"screen_id\", Integer, )\n\n ......
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004016047_python_sqlalchemy.txt
Q: Prevent OpenSSL from using system certificates? How can I prevent OpenSSL (specifically, Python's ssl module) from using system certificate authorities? In other words, I would like it to trust only the certificate authorities which I specify, and nothing else: ssl_socket = ssl.wrap_socket(newsocket, server_side=T...
Prevent OpenSSL from using system certificates?
How can I prevent OpenSSL (specifically, Python's ssl module) from using system certificate authorities? In other words, I would like it to trust only the certificate authorities which I specify, and nothing else: ssl_socket = ssl.wrap_socket(newsocket, server_side=True, certfile="my_cert.pem", ...
[ "I've just run a few tests, and listing your selection of CAs in the ca_certs parameters is exactly what you need.\nThe system I've tried it on is Linux with Python 2.6. If you don't use ca_certs, it doesn't let you use cert_reqs=ssl.CERT_REQUIRED:\nTraceback (most recent call last):\n File \"sockettest.py\", line...
[ 2 ]
[]
[]
[ "openssl", "python", "ssl" ]
stackoverflow_0004006489_openssl_python_ssl.txt
Q: Django Celery causes an import error on runserver command When I issue a runserver command, an ImportError is raised from djcelery (Django Celery). % python manage.py runserver ~/Workspace/django-projects/no...
Django Celery causes an import error on runserver command
When I issue a runserver command, an ImportError is raised from djcelery (Django Celery). % python manage.py runserver ~/Workspace/django-projects/no-labels/src Validating models... Unhandled exception in thread ...
[ "celery.app was only added on September 14. You'll need to be running a copy of celery released since then.\n" ]
[ 3 ]
[]
[]
[ "celery", "django", "importerror", "python" ]
stackoverflow_0004016704_celery_django_importerror_python.txt
Q: Using the video-card memory (ram) to store objects Is it possible to store objects in the video-card memory instead of the ram? I have been using StringIO to store some objects in the RAM; would it be possible to allocate some of the video-card's memory for this purpose? A: Not without OS support. PyOpenCL might...
Using the video-card memory (ram) to store objects
Is it possible to store objects in the video-card memory instead of the ram? I have been using StringIO to store some objects in the RAM; would it be possible to allocate some of the video-card's memory for this purpose?
[ "Not without OS support. PyOpenCL might have something that you can leverage for that.\n" ]
[ 2 ]
[]
[]
[ "python", "video_card" ]
stackoverflow_0004016861_python_video_card.txt
Q: Python and Postgres on Red Hat I've been having trouble installing psycopg2 on linux. I receive the following error when I try to import psycopg2. Python 2.6.4 (r264:75706, Nov 19 2009, 14:52:22) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information...
Python and Postgres on Red Hat
I've been having trouble installing psycopg2 on linux. I receive the following error when I try to import psycopg2. Python 2.6.4 (r264:75706, Nov 19 2009, 14:52:22) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 Traceback (mos...
[ "Red hat comes with a build of postgres, which can conflict with a custom installation. Python uses pg_config to configure the psycopg2 build. I installed postgres into /usr/local/pgsql/, but calling which pg_config returned /usr/bin/pg_config/.\nIn the psycopg2 build directory, there is a file setup.cfg, which let...
[ 2 ]
[]
[]
[ "django", "linux", "postgresql", "python" ]
stackoverflow_0004016594_django_linux_postgresql_python.txt
Q: Pass Password to runas from Python I need to run a file as another user without it prompting for a password, from my script. How is this done? A: There's an executable program called SANUR.EXE that's made for just this kind of situation: you can use it to pipe in the password on the command-line, like this: runa...
Pass Password to runas from Python
I need to run a file as another user without it prompting for a password, from my script. How is this done?
[ "There's an executable program called SANUR.EXE that's made for just this kind of situation: you can use it to pipe in the password on the command-line, like this: runas /user:domain\\username cmd.exe | sanur mysekritpassword.\n", "Have the user add whatever it is as a scheduled task with a specific name but no s...
[ 2, 0 ]
[]
[]
[ "passwords", "python", "runas", "windows" ]
stackoverflow_0004011245_passwords_python_runas_windows.txt
Q: GAE: ValueError: insecure string pickle I'm having trouble unpickling objects from Google App Engine. I am running Windows 7. Here is the procedure: Create a CSV with one of the fields being pickle.dumps([[('CS', 2110), ('CS', 3300), ('CS', 3140)]]), or some similar argument. The CSV looks something like this: I...
GAE: ValueError: insecure string pickle
I'm having trouble unpickling objects from Google App Engine. I am running Windows 7. Here is the procedure: Create a CSV with one of the fields being pickle.dumps([[('CS', 2110), ('CS', 3300), ('CS', 3140)]]), or some similar argument. The CSV looks something like this: INFO,2210,"CS 2110, 3300, 3140","(lp0 (lp1 (S'...
[ "Pickle is a binary format, and CSV isn't binary-safe. You need to encode your pickle - say, using base64.b64encode - if you want to transport it inside a text format.\n", "Pickle can be a binary format, but by default it is completely ASCII safe(protocol 0). Read the pickle docs for specifics: pickle.dump.\nIt ...
[ 4, 2 ]
[]
[]
[ "google_app_engine", "pickle", "python" ]
stackoverflow_0002963602_google_app_engine_pickle_python.txt
Q: catching a broken socket in python I'm having problems detecting a broken socket when a broken pipe exception occurs. See the below code for an example: The Server: import errno, select, socket, time, SocketServer class MetaServer(object): def __init__(self): self.server = Server(None, Handler, bind_...
catching a broken socket in python
I'm having problems detecting a broken socket when a broken pipe exception occurs. See the below code for an example: The Server: import errno, select, socket, time, SocketServer class MetaServer(object): def __init__(self): self.server = Server(None, Handler, bind_and_activate=False) def run(self, so...
[ "Yes, that's something which is not really in the documentation but old Un*x behavior: You need to abort when you get an empty string.\n" ]
[ 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004016920_python_sockets.txt
Q: Implement a Web based Client that interacts with a TCP Server EDIT:Question Updated. Thanks Slott. I have a TCP Server in Python. It is a server with asynchronous behaviour. . The message format is Binary Data. Currently I have a python client that interacts with the code. What I want to be able to do eventuall...
Implement a Web based Client that interacts with a TCP Server
EDIT:Question Updated. Thanks Slott. I have a TCP Server in Python. It is a server with asynchronous behaviour. . The message format is Binary Data. Currently I have a python client that interacts with the code. What I want to be able to do eventually implement a Web based Front End to this client. I just wanted to...
[ "Start with any WSGI-based web server. werkzeug is a choice.\nThe Asynchronous TCP/IP is a seriously complicated problem. HTTP is synchronous. So using the synchronous web server presenting some asynchronous data is always a problem. Always.\nThe best you can do is to buffer things and have two processes in you...
[ 1, 0, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0004017883_python_web_applications.txt
Q: implementing callback between Python and C I have wrapped some C code using SWIG to use it as a python library. Within this framework, some python code I have written calls a C function, which returns a string. However, for creating the string, the C function requires a ranking, the generation of which I have impl...
implementing callback between Python and C
I have wrapped some C code using SWIG to use it as a python library. Within this framework, some python code I have written calls a C function, which returns a string. However, for creating the string, the C function requires a ranking, the generation of which I have implemented in Python. How would I go about implemen...
[ "The PyObject_Call*() functions can be used to call a Python function or method from C.\n", "It is not specific to your question, but here is an example that I asked: swig-passing-argument-to-python-callback-function\nHope this is helpful.\n" ]
[ 0, 0 ]
[]
[]
[ "c", "callback", "python", "swig" ]
stackoverflow_0004016528_c_callback_python_swig.txt
Q: Passing a list of values to a function Sorry for such a silly question, but sitting in front of the comp for many hours makes my head overheated, in other words — I'm totally confused. My task is to define a function that takes a list of words and returns something. How can I define a function that will take a li...
Passing a list of values to a function
Sorry for such a silly question, but sitting in front of the comp for many hours makes my head overheated, in other words — I'm totally confused. My task is to define a function that takes a list of words and returns something. How can I define a function that will take a list of words? def function(list_of_words): ...
[ "Use code:\ndef function(*list_of_words):\n do something\n\nlist_of_words will be a tuple of arguments passed to a function.\n", "Simply call your function with:\nfunction( ['this', 'is', 'a', 'list', 'of', 'words'] )\n\nThis is passing a list as an argument.\n", "It's simple:\nlist_of_words = ['this', 'is'...
[ 9, 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004018178_python.txt
Q: How can we modify data that is in a shelve? I have opened a shelve using the following code: #!/usr/bin/python import shelve #Module:Shelve is imported to achieve persistence Accounts = 0 Victor = {'Name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Sa...
How can we modify data that is in a shelve?
I have opened a shelve using the following code: #!/usr/bin/python import shelve #Module:Shelve is imported to achieve persistence Accounts = 0 Victor = {'Name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Savings'} Beverly = {'Name':'Beverly Dsilva','Email...
[ "Firstly, don't use a global for Accounts, rather pass it back and forth. Using the global caused your error. Like this:\ndef open_shelf(name='shelfile.shl'):\n Accounts = shelve.open(name) #Accounts = {}\n ...\n return Accounts\n\ndef close_shelf(Accounts):\n Accounts.close()\n\n\ndef Deposi...
[ 4, 3 ]
[]
[]
[ "dictionary", "python", "shelve" ]
stackoverflow_0004017733_dictionary_python_shelve.txt
Q: Is Zpsycopg2 compatible with zope 2? I have zope 2.11 installed. Now i want to use Posgresql 7.4.13 DB with it. So i know i need to install psycopg2 Database Adapter. Can any one tell me Is psycopg2 compatible with zope2?? A: Yes, you can use psycopg2 with Zope2. Just install it in your Python with easy_install...
Is Zpsycopg2 compatible with zope 2?
I have zope 2.11 installed. Now i want to use Posgresql 7.4.13 DB with it. So i know i need to install psycopg2 Database Adapter. Can any one tell me Is psycopg2 compatible with zope2??
[ "Yes, you can use psycopg2 with Zope2. \nJust install it in your Python with easy_install or setup.py. You will also need a matching ZPsycopgDA Product in Zope. You find the ZPsycopgDA folder in the psycopg2 source distribution tarball.\n" ]
[ 1 ]
[]
[]
[ "database", "python", "zope" ]
stackoverflow_0003725699_database_python_zope.txt
Q: Encryption: simulate SSL in javascript and python Because of china Great Firewall has blocked google appengine's https port. So I want to simulate a Secure Socket Layer by javascript and python to protect my users information will not be capture by those ISP and GFW. My plan: Shake hands: Browser request server...
Encryption: simulate SSL in javascript and python
Because of china Great Firewall has blocked google appengine's https port. So I want to simulate a Secure Socket Layer by javascript and python to protect my users information will not be capture by those ISP and GFW. My plan: Shake hands: Browser request server, server generate a encrypt key k1, and decrypt key k2,...
[ "You have a fundamental problem in that a JavaScript implementation of SSL would have no built-in root certificates to establish trust, which makes it impossible to prevent a man-in-the-middle attack. Any certificates you deliver from your site, including a root certificate, could be intercepted and replaced by a s...
[ 2, 1, 1, 0 ]
[]
[]
[ "javascript", "python", "ssl" ]
stackoverflow_0003977274_javascript_python_ssl.txt
Q: convert string to datetime object I'd like to convert this string into a datetime object: Wed Oct 20 16:35:44 +0000 2010 Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth? EDIT: strptime is great. However, with datetime.strptime(date_str, "%a %b %...
convert string to datetime object
I'd like to convert this string into a datetime object: Wed Oct 20 16:35:44 +0000 2010 Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth? EDIT: strptime is great. However, with datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y") I get ValueError: '...
[ "No RE needed. Try this:\nfrom dateutil import parser\n\nyourDate = parser.parse(yourString) \n\nfor \"Wed Oct 20 16:35:44 +0000 2010\" returns datetime.datetime(2010, 10, 20, 16, 35, 44, tzinfo=tzutc())\n", "http://docs.python.org/library/time.html#time.strptime\n", "I'm pretty sure you're able to do that usi...
[ 28, 2, 2, 2, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0004018730_datetime_python.txt
Q: Once I can save this string as image, other time I can' Ok. Long story short. My camera has a method which takes a photo and this is what it returns: [160, 120, 3, 10, 1287848024, 96181, 'super long image string'] I am able to decode the string and save it as image right after I call the method like this: for i i...
Once I can save this string as image, other time I can'
Ok. Long story short. My camera has a method which takes a photo and this is what it returns: [160, 120, 3, 10, 1287848024, 96181, 'super long image string'] I am able to decode the string and save it as image right after I call the method like this: for i in range(0, 10): image = camProxy.getImageRemote(nameId) i...
[ "I got it working by changing the file mode from \"r\" to \"rb\".\nHere's the working code:\nimport time\nimport Image\nimage_data = [160, 120, 3, 10, 1287848024, 96181, 'really long string from http://richardknop.com/log.txt']\nimageWidth = image_data[0]\nimageHeight = image_data[1]\nimageByteArray = image_data[6]...
[ 6, 3, 1 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0004017609_image_processing_python.txt
Q: Python: Is it bad style to give an argument the same name as the function? Consider the following code: def localize(value, localize=None): # do something with the localize argument The localize variable contains information whether the global localization setting should be respected or not. It is called by ...
Python: Is it bad style to give an argument the same name as the function?
Consider the following code: def localize(value, localize=None): # do something with the localize argument The localize variable contains information whether the global localization setting should be respected or not. It is called by the same name through three layers of code. What's the lesser evil, shadow the ...
[ "I'd say that's bad style. Instead of changing the function name you could change the parameter name. Perhaps you could use a name like locale or localization? A noun is probably a better choice than a verb anyway.\n", "What's more likely to happen, the caller is confused by having to pass in a different named ar...
[ 11, 1, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0004018783_coding_style_python.txt
Q: Python urllib2 file upload problems I'm currently trying to initiate a file upload with urllib2 and the urllib2_file library. Here's my code: import sys import urllib2_file import urllib2 URL='http://aquate.us/upload.php' d = [('uploaded', open(sys.argv[1:]))] req = urllib2.Request(URL, d) u = urllib2.urlopen(req...
Python urllib2 file upload problems
I'm currently trying to initiate a file upload with urllib2 and the urllib2_file library. Here's my code: import sys import urllib2_file import urllib2 URL='http://aquate.us/upload.php' d = [('uploaded', open(sys.argv[1:]))] req = urllib2.Request(URL, d) u = urllib2.urlopen(req) print u.read() I've placed this .py fi...
[ "If you're using Python 2.5 or newer, urllib2_file is both unnecessary and unsupported, so check which version you're using (and perhaps upgrade).\nIf you're using Python 2.3 or 2.4 (the only versions supported by urllib2_file), try running the sample code and see if you have the same problem. If so, there is like...
[ 2, 0, 0 ]
[]
[]
[ "post", "python", "upload", "urllib2" ]
stackoverflow_0000407468_post_python_upload_urllib2.txt
Q: Form doesn't accept additional parameters I was trying to pass an additional parameter to my form, which is anObject to ForeignKey relation. But dunno why form returns __init__() got an unexpected keyword argument 'parent' when I'm pretty sure that it is possible to send additional parameters to form's __init__ (i...
Form doesn't accept additional parameters
I was trying to pass an additional parameter to my form, which is anObject to ForeignKey relation. But dunno why form returns __init__() got an unexpected keyword argument 'parent' when I'm pretty sure that it is possible to send additional parameters to form's __init__ (ie here : Simple form not validating). Am I wron...
[ "kwargs.pop['parent'] is throwing TypeError: 'builtin_function_or_method' object is unsubscriptable, because you're trying to do a key lookup on a function method ({}.pop). This error is then being swallowed by your exception handler. \nFor this to work do kwargs.pop('parent', None). In your case:\nclass Video...
[ 6 ]
[]
[]
[ "django", "django_forms", "keyword_argument", "python" ]
stackoverflow_0004019711_django_django_forms_keyword_argument_python.txt
Q: How to filter objects of an object_list of a generic view in Django So I have a view that does a queryset and returns a simple list: def cdr(request): queryset = CdrView.objects.all() return object_list(request, queryset = queryset, template_name = "reports/cdrview_li...
How to filter objects of an object_list of a generic view in Django
So I have a view that does a queryset and returns a simple list: def cdr(request): queryset = CdrView.objects.all() return object_list(request, queryset = queryset, template_name = "reports/cdrview_list.html", paginate_by = 200, pa...
[ "You filter in your views.py. Since it's a search, we'll use request.REQUEST instead of the normal request.POST.\nfrom forms.py import SearchForm\n\ndef cdr(request, form_class=SearchForm):\n queryset = CdrView.objects.all()\n search_form = SearchForm(request.REQUEST)\n if search_form.is_valid():\n search_s...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004019328_django_python.txt
Q: split a 256 bit hash into 32 bit prefix in python In python, how does one split a SHA256 hash into a 32bit prefixes? I'm working with Google's safebrowsing api, which requires that I compare 32bit prefixes between my own collection, and the collection the API sends to me. I understand how to pull the list from Goo...
split a 256 bit hash into 32 bit prefix in python
In python, how does one split a SHA256 hash into a 32bit prefixes? I'm working with Google's safebrowsing api, which requires that I compare 32bit prefixes between my own collection, and the collection the API sends to me. I understand how to pull the list from Google, and I understand how to form a collection of hashe...
[ "32 bits is the first 4 bytes. So you can slice the byte array.\nhash_obj.digest()[:4]\n\nYou can take that and use it as a dictionary key.\nEDIT\nI'm not sure if you need the hex representation, that would be.\nhash_obj.hexdigest()[:8]\n\n" ]
[ 3 ]
[]
[]
[ "hash", "prefix", "python" ]
stackoverflow_0004019730_hash_prefix_python.txt
Q: problematic python function returns I have a function similar to the following: def getCost(list): cost = 0 for item in list: cost += item return cost and I call it as so: cost = getCost([1, 2, 3, 4]) This is GREATLY simplified but it illustrates what is going on. No matter what I do, cost always ends...
problematic python function returns
I have a function similar to the following: def getCost(list): cost = 0 for item in list: cost += item return cost and I call it as so: cost = getCost([1, 2, 3, 4]) This is GREATLY simplified but it illustrates what is going on. No matter what I do, cost always ends up == 0. If I change the value of cost ...
[ "This should solve all of your problems (if summing the list items in cost is indeed what you're trying to do:\ndef getCost(costlist):\n return sum(costlist)\n\nIt accomplishes the exact same things and is guaranteed to work. It's also much more simple than using a loop and an accumulator.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004019527_python.txt
Q: Results being duplicated after 2nd request I am playing around with django and python and have hit a bit of a roadblock here. I query my model and return the objects and then perform some simple operations on the results and return them to the view. After the 2nd request the childs for the forum category are dupli...
Results being duplicated after 2nd request
I am playing around with django and python and have hit a bit of a roadblock here. I query my model and return the objects and then perform some simple operations on the results and return them to the view. After the 2nd request the childs for the forum category are duplicated and I have no idea why this happens. Forum...
[ "Let me guess... You have something like:\nclass Foo(object):\n childs = []\n\nWhen you should have something like:\nclass Foo(object)\n def __init__(self):\n self.childs = []\n\nThe difference is that in the first case, all your Foo instance will share the same childs object (class attribute) and in t...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004020060_django_python.txt
Q: The simplest video streaming? I have a camera that is taking pictures one by one (about 10 pictures per second) and sending them to PC. I need to show this incoming sequence of images as a live video in PC. Is it enough just to use some Python GUI framework, create a control that will hold a single image and just ...
The simplest video streaming?
I have a camera that is taking pictures one by one (about 10 pictures per second) and sending them to PC. I need to show this incoming sequence of images as a live video in PC. Is it enough just to use some Python GUI framework, create a control that will hold a single image and just change the image in the control ver...
[ "\nOr would that be just lame?\n\nNo. It wouldn't work at all.\nThere's a trick to getting video to work. Apple's QuickTime implements that trick. So does a bunch of Microsoft product. Plus some open source video playback tools.\nThere are several closely-related tricks, all of which are a huge pain in the neck...
[ 2 ]
[]
[]
[ "python", "video", "video_streaming" ]
stackoverflow_0004019571_python_video_video_streaming.txt
Q: What is a Class in python, what does it do, why is it needed? Possible Duplicate: Do I correctly understand what a class is? Before you rant and rage and scream at me, understand that I tried searching everywhere, from google to this very site on what exactly a class in python is. I have found definitions of sor...
What is a Class in python, what does it do, why is it needed?
Possible Duplicate: Do I correctly understand what a class is? Before you rant and rage and scream at me, understand that I tried searching everywhere, from google to this very site on what exactly a class in python is. I have found definitions of sorts, but have never been able to understand them fully. So here's t...
[ "Class (in any language) basically help in implementing OOPS. By Following these principles, it becomes easier to maintain code & make changes etc. \nI guess you start off by reading what OOPS is & then come back to Python.\n" ]
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004020290_class_python.txt
Q: Check maxlen of deque in python 2.6 I have had to change from python 2.7 to 2.6. I've been using a deque with the maxlen property and have been checking what the maxlen is. Apparently you can use maxlen in python 2.6, but in 2.6 deques do not have a maxlen attribute. What is the cleanest way to check what the maxl...
Check maxlen of deque in python 2.6
I have had to change from python 2.7 to 2.6. I've been using a deque with the maxlen property and have been checking what the maxlen is. Apparently you can use maxlen in python 2.6, but in 2.6 deques do not have a maxlen attribute. What is the cleanest way to check what the maxlen of a deque is in python 2.6? In 2.7: ...
[ "I would create my own deque by inheriting from collections.deque. It is not difficult. Namely, here it is:\nimport collections\n\nclass deque(collections.deque):\n def __init__(self, iterable=(), maxlen=None):\n super(deque, self).__init__(iterable, maxlen)\n self._maxlen = maxlen\n @property\n...
[ 6, 2, 2, 1 ]
[]
[]
[ "deque", "python", "python_2.6" ]
stackoverflow_0004020264_deque_python_python_2.6.txt
Q: Speed up NumPy loop I'm running a model in Python and I'm trying to speed up the execution time. Through profiling the code I've found that a huge amount of the total processing time is spent in the cell_in_shadow function below. I'm wondering if there is any way to speed it up? The aim of the function is to provi...
Speed up NumPy loop
I'm running a model in Python and I'm trying to speed up the execution time. Through profiling the code I've found that a huge amount of the total processing time is spent in the cell_in_shadow function below. I'm wondering if there is any way to speed it up? The aim of the function is to provide a boolean response sta...
[ "I do agree with Sancho that Cython will probably be the way to go, but here are a couple of small speed-ups:\nA. Store grid[y, orig_x] in some variable before you start the while loop and use that variable instead. This will save a bunch of look-up calls to the grid array.\nB. Since you are basically just starting...
[ 3, 2, 1 ]
[]
[]
[ "numpy", "performance", "python" ]
stackoverflow_0004000674_numpy_performance_python.txt
Q: python, functions combination via names and chain them to invoke in-a-go? All, I have confuse below may need your help suppose I have a row based variable length data matrix 93 77 96 85 50 69 54 16 39 91 59 38 64 30 18 50 43 9 74 94 44 87 95 89 ... I want to generate result data via above sou...
python, functions combination via names and chain them to invoke in-a-go?
All, I have confuse below may need your help suppose I have a row based variable length data matrix 93 77 96 85 50 69 54 16 39 91 59 38 64 30 18 50 43 9 74 94 44 87 95 89 ... I want to generate result data via above source with different generating algorithms while the different range selection al...
[ "For your first question, you can define a function composition operation like this:\ndef compose(f, g):\n return lambda *x: f(g(*x))\n\nThen, you can:\nra = compose(rangeset_001, algo_001)\nra(lsrc)\n\nIf you make lists of functions like this:\nrangesets = [rangeset_001, rangeset_002, rangeset_003]\n\nthen you ...
[ 1 ]
[]
[]
[ "combinations", "function", "python" ]
stackoverflow_0004020671_combinations_function_python.txt
Q: Problems creating tables one to one relation I get errors when I try to create tables one to one relation. Screen contains crm and crm contains more classes. The relation is one to one between crm, so I want to use the screen id as primary key in crm. And the relation is one to one between crm and some classes, I ...
Problems creating tables one to one relation
I get errors when I try to create tables one to one relation. Screen contains crm and crm contains more classes. The relation is one to one between crm, so I want to use the screen id as primary key in crm. And the relation is one to one between crm and some classes, I just added one class as example, so children of cr...
[ "First, why 3 tables all with 1:1 relationships? A 2NF-compliant single table should work considerably better.\nBut if you still want 3 tables, try relating crm_contact_informations to crms, not to screens:\nid = Column(\"id\", Integer, ForeignKey(\"crms.id\"), primary_key=True)\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004017303_python_sqlalchemy.txt
Q: python middleware to capture errors? is there a python middleware that captures errors from web app and emails it? which is the easiest one to use. i am deploying app using nginx proxying to multiple app servers of gunicorn+web.py framework. right now any error is printed out in each app server, which is not very ...
python middleware to capture errors?
is there a python middleware that captures errors from web app and emails it? which is the easiest one to use. i am deploying app using nginx proxying to multiple app servers of gunicorn+web.py framework. right now any error is printed out in each app server, which is not very easy to manage. what is the best way to ha...
[ "Check out Paste. Code to email an exception would look something like:\nfrom paste.exceptions.errormiddleware import ErrorMiddleware\napp = ErrorMiddleware(app,\n global_conf, debug=False,\n error_email='foo@example.com',\n smtp_server='localhost')\n\n...
[ 2 ]
[]
[]
[ "email", "error_handling", "middleware", "python" ]
stackoverflow_0004016749_email_error_handling_middleware_python.txt
Q: Python Object Storage Memory/Dict/DB/Other Options I'm currently writing a python application that will take a directory of text files and parse them into custom python objects based on the the attributes specified in the text file. As part of my application, I compare the current loaded object data set to a previ...
Python Object Storage Memory/Dict/DB/Other Options
I'm currently writing a python application that will take a directory of text files and parse them into custom python objects based on the the attributes specified in the text file. As part of my application, I compare the current loaded object data set to a previous dataset (same format) and scan it for possible dupli...
[ "You can fake what Git does and load the entire set as basically a single file and parse from there. The biggest issue is that dictionaries are not ordered so your comparisons will not always be 1:1. A list of tuples will give you 1:1 comparisons. If a lot has changed this will be difficult.\nHere is a basic flo...
[ 1 ]
[]
[]
[ "object", "python" ]
stackoverflow_0004019557_object_python.txt
Q: Finding the index of a string in a tuple Tup = ('string1','string2','string3') My program returned string2 how do I get it's index within Tup? A: >>> tup.index('string2') 1 Note that the index() method has only just been added for tuples in versions 2.6 and better.
Finding the index of a string in a tuple
Tup = ('string1','string2','string3') My program returned string2 how do I get it's index within Tup?
[ ">>> tup.index('string2')\n1\n\nNote that the index() method has only just been added for tuples in versions 2.6 and better.\n" ]
[ 49 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0004021154_python_tuples.txt
Q: How do I use a variable as table name in Django? I'd like to do the following: for table in table_list: 'table'.samefield = newvalue A: If you know the name of the application that it's in, then you can do model = getattr(application_name.models, 'table') model.somefield = newvalue or just getattr(applicatio...
How do I use a variable as table name in Django?
I'd like to do the following: for table in table_list: 'table'.samefield = newvalue
[ "If you know the name of the application that it's in, then you can do\nmodel = getattr(application_name.models, 'table')\nmodel.somefield = newvalue\n\nor just\ngetattr(application_name.models, 'table').somefield = newvalue\n\nif you only want to access it once (although that doesn't really make any sense).\n" ]
[ 3 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0004021211_django_models_python.txt
Q: Using pip packages in python scripts I've install this script via pip, but how to a reference these files as part of my script, do I need to use import or some other magic? Thanks A: import isn't magic, it's how things get done.
Using pip packages in python scripts
I've install this script via pip, but how to a reference these files as part of my script, do I need to use import or some other magic? Thanks
[ "import isn't magic, it's how things get done.\n" ]
[ 2 ]
[]
[]
[ "package", "python" ]
stackoverflow_0004021333_package_python.txt
Q: How do you decode a binary encoded mail message in Python? I'm writing a Google App engine app that processes incoming mail, and here's the code I'm currently using to process mail messages: for content_type, body in email_bodies: #8bit bug in mail messages - see bug report here #http://code.google.com/p/googleapp...
How do you decode a binary encoded mail message in Python?
I'm writing a Google App engine app that processes incoming mail, and here's the code I'm currently using to process mail messages: for content_type, body in email_bodies: #8bit bug in mail messages - see bug report here #http://code.google.com/p/googleappengine/issues/detail?id=2383 if body.encoding == '8bit': bod...
[ "Rather than reinventing the wheel, you should try Python's built in email parser.\nhttp://docs.python.org/library/email.parser.html\nIt's designed to handle the lifting involved in getting all sorts of different email formats into a good Python object. Use it to do the parsing, and you'll get nicely predictable ob...
[ 1 ]
[]
[]
[ "binary", "email", "encoding", "google_app_engine", "python" ]
stackoverflow_0004021392_binary_email_encoding_google_app_engine_python.txt
Q: Python: How to print text inputed by user? My code is as follows: #!/usr/bin/python #Filename:2_7.py text=raw_input("Enter string:") for ?? in range(??) print For example, if the user enters test text, I want test text to be printed on the screen by this code. What should I write instead of ?? to achieve th...
Python: How to print text inputed by user?
My code is as follows: #!/usr/bin/python #Filename:2_7.py text=raw_input("Enter string:") for ?? in range(??) print For example, if the user enters test text, I want test text to be printed on the screen by this code. What should I write instead of ?? to achieve this purpose?
[ "Maybe you want something like this?\nvar = raw_input(\"Enter something: \")\nprint \"you entered \", var\n\nOr in Python 3.x\nvar = input(\"Enter something: \")\nprint (\"you entered \", var)\n\n", "Do you want to split the string into separate words and print each one?\ne.g.\nfor word in text.split():\n prin...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004021742_python.txt
Q: Execute functions in a list as a chain In Python I defined these functions: def foo_1(p): return p + 1 def foo_2(p): return p + 1 def foo_3(p): return p + 1 def foo_4(p): return p + 1 def foo_5(p): return p + 1 I want to execute these functions in a chain like this: foo_1(foo_2(foo_3(foo_4(foo_5(1))))) I'd like ...
Execute functions in a list as a chain
In Python I defined these functions: def foo_1(p): return p + 1 def foo_2(p): return p + 1 def foo_3(p): return p + 1 def foo_4(p): return p + 1 def foo_5(p): return p + 1 I want to execute these functions in a chain like this: foo_1(foo_2(foo_3(foo_4(foo_5(1))))) I'd like to specify these functions as a list, execut...
[ "You can use reduce for this:\nreduce(lambda x, y: y(x), list_of_functions, initial_value)\n\nLike so:\nreduce(lambda x, y: y(x), reversed([foo_1, foo_2, foo_3, ...]), 1)\n\nNote that If you want to apply the functions in the order of foo_1(foo_2(etc...)), you have to make sure that foo_1 is the last element of the...
[ 8, 5, 3 ]
[]
[]
[ "composition", "function", "python" ]
stackoverflow_0004021731_composition_function_python.txt
Q: How to write this exception in Python 2.6 I need to write an expection that if a string is null, then fire this exception. How to write this? Eg. str = get_str() if get_str() returns None or nothing. It should raise an exception. A: There is no such thing as "nothing" in Python. There is either something, or th...
How to write this exception in Python 2.6
I need to write an expection that if a string is null, then fire this exception. How to write this? Eg. str = get_str() if get_str() returns None or nothing. It should raise an exception.
[ "There is no such thing as \"nothing\" in Python. There is either something, or there is not.\nif str is None:\n raise SomeException()\n\n", "returning None (which is the same as not returning anything explicitly) isn't an exception by itself. If it should be an exception, get_str() should raise this exception, ...
[ 3, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0004021754_exception_python.txt
Q: Implement iteritems function for my custom iterator? The objective of the following program is to learn python generators and iterator implementation in order to understand Python magic methods. I'm stuck implementing the iteritems() function. Also, I want to know whether I'm going on right direction or I'm concep...
Implement iteritems function for my custom iterator?
The objective of the following program is to learn python generators and iterator implementation in order to understand Python magic methods. I'm stuck implementing the iteritems() function. Also, I want to know whether I'm going on right direction or I'm conceptually wrong in understanding of python magic methods. imp...
[ "iteritems is supposed to return a sequence of (key, val) pairs for a dictionary, so I don't think it's appropriate for your class. If you created a descendant of UserDict, then there might be a case to override it.\nIf you do override iteritems, you should do so by yielding key, value pairs.\nPoor programmer's ove...
[ 4 ]
[]
[]
[ "containers", "iterator", "python" ]
stackoverflow_0004020905_containers_iterator_python.txt
Q: Force Update QTableView + QSqlTableModel in PyQt I have a QTableView which displays data from a QSqlTableModel. I want my model to check for changes when a user hits a "refresh" button but I can't find a way to update the data. I tried the reset() and update() methods on the model without any result. Is it possibl...
Force Update QTableView + QSqlTableModel in PyQt
I have a QTableView which displays data from a QSqlTableModel. I want my model to check for changes when a user hits a "refresh" button but I can't find a way to update the data. I tried the reset() and update() methods on the model without any result. Is it possible to "re-read" from the database and update the model?...
[ "As you dont state what you canged in your model, ill assume the simplest form of change (changed data).\nFor me model.select() works to update the data in the model and force the View to update itself.\n" ]
[ 5 ]
[]
[]
[ "pyqt", "python", "qtableview" ]
stackoverflow_0004022049_pyqt_python_qtableview.txt
Q: How to create a self contained Python Qt app on mac I've recently started using a mac, and I'm curious about how to make a mac app that uses PyQt and is self-contained. Can anyone give me any pointers on where to start and what I'll need? A: PyInstaller should be pretty good for that -- it's cross-platform (Mac,...
How to create a self contained Python Qt app on mac
I've recently started using a mac, and I'm curious about how to make a mac app that uses PyQt and is self-contained. Can anyone give me any pointers on where to start and what I'll need?
[ "PyInstaller should be pretty good for that -- it's cross-platform (Mac, Windows, Linux) and offers out-of-the-box support for PyQt (among other useful third-party libraries). Now that a good release (1.4) has finally been recognized as stable, and officially released, after a somewhat long hiatus, PyInstaller is ...
[ 3, 2, 1 ]
[]
[]
[ "macos", "python", "qt" ]
stackoverflow_0003173047_macos_python_qt.txt
Q: pygtk - update a gtk.liststore adds blank line I'm having issue with adding extra lines to gtk.liststore. below is a snipped of the code. The glade definition can be found here. When I add a row the row seperators appear but where text should appear i keeps empty... please help define everything with glade interf...
pygtk - update a gtk.liststore adds blank line
I'm having issue with adding extra lines to gtk.liststore. below is a snipped of the code. The glade definition can be found here. When I add a row the row seperators appear but where text should appear i keeps empty... please help define everything with glade interface designer. class GTKInterface(gobject.GObject): ...
[ "I have found what I have forgot cell renders !!! I read about here\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004022275_pygtk_python.txt
Q: Validating ModelChoiceField in Django forms I'm trying to validate a form containing a ModelChoiceField: forms.py: from django import forms from modelchoicetest.models import SomeObject class SomeObjectAddForm(forms.ModelForm): class Meta: model = SomeObject models.py: from django.db import models ...
Validating ModelChoiceField in Django forms
I'm trying to validate a form containing a ModelChoiceField: forms.py: from django import forms from modelchoicetest.models import SomeObject class SomeObjectAddForm(forms.ModelForm): class Meta: model = SomeObject models.py: from django.db import models class SomeChoice(models.Model): name = models...
[ "It looks to me like the exception is being raised by the clean method of the actual ModelChoiceField object. Because it's a foreign key, Django is expecting an int, which would be representative of the pk for SomeChoice. How exactly are you passing invalid into the form?\nRESPONSE TO COMMENT\nIf you really feel yo...
[ 1, 0 ]
[]
[]
[ "django", "forms", "python", "validation" ]
stackoverflow_0002400548_django_forms_python_validation.txt
Q: efficient and complete input check for command line argument and option with python I am developing cli with python version 2.4.3. i want to have the input exception check. The following is part of the code. With this code, I can type addcd -t 11 and if I type addcd -t str_not_int or addcd -s 3 I will catch th...
efficient and complete input check for command line argument and option with python
I am developing cli with python version 2.4.3. i want to have the input exception check. The following is part of the code. With this code, I can type addcd -t 11 and if I type addcd -t str_not_int or addcd -s 3 I will catch the error of wrong type argument and wrong option. However, it is not sufficient. e.g. add...
[ "First, read this http://docs.python.org/library/optparse.html#terminology.\nYou're not following the optparse rules for options. If you don't follow the rules, you cannot use this library.\nSpecifically.\naddcd s 11\n\nor\naddcd s a \n\nAre not legal options. No \"-\". No \"--\". Why no \"-\"?\n\"then it canno...
[ 2 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0004022485_command_line_arguments_python.txt
Q: Context locals - how do they make local context variables global? I was reading through the Flask doc - and came across this: ... For web applications it’s crucial to react to the data a client sent to the server. In Flask this information is provided by the global request object. If you have some experie...
Context locals - how do they make local context variables global?
I was reading through the Flask doc - and came across this: ... For web applications it’s crucial to react to the data a client sent to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be globa...
[ "They are actually proxy objects to the real objects so that when you reference one you get access to the object for your current thread.\nAn example would be the request object. You can see this being set up in globlals.py and then imported into the __init__.py for flask.\nThe benefit of this is that you can acces...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0004022537_python.txt
Q: Testing call order across mock objects with Mox and Python I'm testing a function that obtains a skeleton object from one helper object, modifies it using a second helper, and passes the modified object back to the first helper. Something along the lines of: class ReadModifyUpdate(object): def __init__(self, s...
Testing call order across mock objects with Mox and Python
I'm testing a function that obtains a skeleton object from one helper object, modifies it using a second helper, and passes the modified object back to the first helper. Something along the lines of: class ReadModifyUpdate(object): def __init__(self, store, modifier): self._store = store self._modif...
[ "Maybe not the best solution but you could try to use one mock that you give twice to your object under test. You then have control over the call order.\nclass ReadModifyUpdateTest(mox.MoxTestBase):\n def test_modify(self):\n mock_record = self.mox.CreateMockAnthing()\n mock_storeModifier = self.mo...
[ 0, 0 ]
[]
[]
[ "mocking", "mox", "python", "testing" ]
stackoverflow_0004016798_mocking_mox_python_testing.txt
Q: Wondering whether I should just bail on using properties in python I have been trying to use properties instead of specific setters and getters in my app. They seem more pythonic and generally make my code more readable. More readable except for one issue: Typos. consider the following simple example (note, my p...
Wondering whether I should just bail on using properties in python
I have been trying to use properties instead of specific setters and getters in my app. They seem more pythonic and generally make my code more readable. More readable except for one issue: Typos. consider the following simple example (note, my properties actually do some processing even though the examples here just...
[ "Have you tried a static analysis tool? Here is a great thread about them.\n", "Depending on how your code works, you could try using slots. You'll get an AttributeError exception thrown when you try to assign something that's not in slots then, which will make such typo's more obvious.\n", "There are times whe...
[ 3, 2, 0 ]
[]
[]
[ "getter", "properties", "python", "setter" ]
stackoverflow_0004021862_getter_properties_python_setter.txt
Q: Transaction collision for sequential insert on Google App Engine. Why? I am inserting a set of records on Google App Engine. I insert them in batch to avoid deadline exceptions. When there is a large number of records (for example 1k) I always receive an unexpected: Transaction collision for entity group with k...
Transaction collision for sequential insert on Google App Engine. Why?
I am inserting a set of records on Google App Engine. I insert them in batch to avoid deadline exceptions. When there is a large number of records (for example 1k) I always receive an unexpected: Transaction collision for entity group with key datastore_types.Key.from_path(u'GroupModel', u'root', _app=u'streamtom...
[ "The collision is on an instance of your 'GroupModel' entity with the key name 'root'. Based on that, I'm guessing you're putting everything inside a single entity group with that as the parent. As documented here, every entity with the same parent is in the same entity group, to which transactions are serialized. ...
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004007650_google_app_engine_google_cloud_datastore_python.txt
Q: Python: Existing environment variables which need to be added again to execute I'm trying to execute a command which runs a program that uses perl and python. Although both of them are already in PATH, I get this error 'perl' is not recognized as an internal or external command,operable program or batch file. 'pyt...
Python: Existing environment variables which need to be added again to execute
I'm trying to execute a command which runs a program that uses perl and python. Although both of them are already in PATH, I get this error 'perl' is not recognized as an internal or external command,operable program or batch file. 'python' is not recognized as an internal or external command,operable program or batch ...
[ "So try\nos.putenv('PATH', dir + \";\" + otherdir)\n\n" ]
[ 0 ]
[]
[]
[ "environment_variables", "python", "windows" ]
stackoverflow_0004022414_environment_variables_python_windows.txt
Q: How does numpy zeros implement the parameter shape? I want to implement a similar function, and want to accept an array or number that I pass to numpy.ones. Specifically, I want to do this: def halfs(shape): shape = numpy.concatenate([2], shape) return 0.5 * numpy.ones(shape) Example input-output pairs: #...
How does numpy zeros implement the parameter shape?
I want to implement a similar function, and want to accept an array or number that I pass to numpy.ones. Specifically, I want to do this: def halfs(shape): shape = numpy.concatenate([2], shape) return 0.5 * numpy.ones(shape) Example input-output pairs: # default In [5]: beta_jeffreys() Out[5]: array([-0.5, -0....
[ "def halfs(shape=()):\n if isinstance(shape, tuple):\n return 0.5 * numpy.ones((2,) + shape)\n else:\n return 0.5 * numpy.ones((2, shape))\n\n\n\na = numpy.arange(5)\n# array([0, 1, 2, 3, 4])\n\n\nhalfs(a.shape)\n#array([[ 0.5, 0.5, 0.5, 0.5, 0.5],\n# [ 0.5, 0.5, 0.5, 0.5, 0.5]])\n...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004023574_numpy_python.txt
Q: XML-RPC for an object broker is there any good reason not to use XML-RPC for an object-broker server/client architecture? Maybe something like "no it's already outfashioned, there is X for that now". To give you more details: I want to build a framework which allows for standardized interaction and the exchange of...
XML-RPC for an object broker
is there any good reason not to use XML-RPC for an object-broker server/client architecture? Maybe something like "no it's already outfashioned, there is X for that now". To give you more details: I want to build a framework which allows for standardized interaction and the exchange of results between many little tools...
[ "XML-RPC has a lot going for it. It's simple to create and to consume, easy to understand and easy to code for.\nI'd say avoid SOAP and CORBA like the plague. They are way too complex, and with SOAP you have endless problems because only implementations from single vendors tend to interact nicely - probably becaus...
[ 5 ]
[]
[]
[ "corba", "python", "rpc", "xml_rpc" ]
stackoverflow_0004022311_corba_python_rpc_xml_rpc.txt