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: Role of C,C++,python,perl in Web development Please bear with me experts i'm a newbie in web dev. With html,css can take care of webpages.. javascript,ajax for some dynamic content.. php for server side scripting,accessing databases,sending emails,doing all other stuf... What role do these programming languages pl...
Role of C,C++,python,perl in Web development
Please bear with me experts i'm a newbie in web dev. With html,css can take care of webpages.. javascript,ajax for some dynamic content.. php for server side scripting,accessing databases,sending emails,doing all other stuf... What role do these programming languages play? Can they do any other important task which can...
[ "All languages can all do basically any task any other one of them can do, as they are all Turing complete.\nPHP works as a server-side scripting language, but you can also use Perl, Python, Ruby, Haskell, Lisp, Java, C, C++, assembly, or pretty much any other language that can access standard input and standard ou...
[ 10, 5, 4, 3 ]
[]
[]
[ "c", "c++", "perl", "python" ]
stackoverflow_0001991065_c_c++_perl_python.txt
Q: In Python, what does dict.pop(a,b) mean? class a(object): data={'a':'aaa','b':'bbb','c':'ccc'} def pop(self, key, *args): return self.data.pop(key, *args)#what is this mean. b=a() print b.pop('a',{'b':'bbb'}) print b.data self.data.pop(key, *args) ←------ why is there a second argument? A: ...
In Python, what does dict.pop(a,b) mean?
class a(object): data={'a':'aaa','b':'bbb','c':'ccc'} def pop(self, key, *args): return self.data.pop(key, *args)#what is this mean. b=a() print b.pop('a',{'b':'bbb'}) print b.data self.data.pop(key, *args) ←------ why is there a second argument?
[ "The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs\nThe second argument, default, is what pop returns if the first argument, key, is absent.\n(If you call pop with just one argument, key, it raises an exception if that key's absent).\nIn your ex...
[ 127, 28, 7, 7 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001990802_dictionary_python.txt
Q: A Python script I've written for correcting table names of the SQL dumps from Windows. Any comments? as a newbie in Python I've thought about writing a quick and dirty script for correcting the table anme caps of a MySQL dump file (by phpMyAdmin). The idea is since the correct capitalization of the table names are...
A Python script I've written for correcting table names of the SQL dumps from Windows. Any comments?
as a newbie in Python I've thought about writing a quick and dirty script for correcting the table anme caps of a MySQL dump file (by phpMyAdmin). The idea is since the correct capitalization of the table names are in the comments, I'm going to use it. e.g.: -- -------------------------------------------------------- ...
[ "Looks fairly good, so the following are relatively minor:\n\nget_text_blocks basically splits the entire text by the separator, correct? If so, I think this can be done with a single regex with a re.MULTILINE flag. Something like r'(.*?)\\n-- -+' (warning: untested).\nIf you don't want to use a single regex but pr...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001991117_python.txt
Q: Remove html formatting ">" from text file using Python csv.reader I have a text file with ; used as the delimiter. The problem is that it has some html text formatting in it such as > Obviously the ; in this causes problems. The text file is large and I don't have a list of these html strings, that is there ar...
Remove html formatting ">" from text file using Python csv.reader
I have a text file with ; used as the delimiter. The problem is that it has some html text formatting in it such as > Obviously the ; in this causes problems. The text file is large and I don't have a list of these html strings, that is there are many different examples such as $amp;. How can I remove all of them u...
[ "The quickest way is probably to use the undocumented but so far stable unescape method in HTMLParser:\nimport HTMLParser\ns= HTMLParser.HTMLParser().unescape(s)\n\nNote this will necessarily output a Unicode string, so if you have any non-ASCII bytes in there you will need to s.decode(encoding) first.\n", "Take ...
[ 6, 3, 1 ]
[]
[]
[ "csv", "file", "html", "python", "regex" ]
stackoverflow_0001637253_csv_file_html_python_regex.txt
Q: How does Django + mod_wsgi affect the python path? I have a simple setup with my python libraries in /domains/somedomain.com/libs/ and all my tests run fine. I start WSGI with DJANGO_SETTINGS_MODULE to "somedomain.settings" where somedomain is a package in libs/ Suddenly, when adding pywapi.py into libs/ I can't i...
How does Django + mod_wsgi affect the python path?
I have a simple setup with my python libraries in /domains/somedomain.com/libs/ and all my tests run fine. I start WSGI with DJANGO_SETTINGS_MODULE to "somedomain.settings" where somedomain is a package in libs/ Suddenly, when adding pywapi.py into libs/ I can't import it when hitting the site. But, if I add 'import py...
[ "I think the problem is related with the permissions of that file. Check that the user running wsgi (apache user, usually) is capable of reading and writing the everything in the libs folder and specially capable of reading the file pywapi.py.\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0001991743_apache_django_mod_wsgi_python.txt
Q: Parse xml file while a tag is missing I try to parse an xml file. The text which is in tags is parsed successfully (or it seems so) but I want to output as the text which is not contained in some tags and the following program just ignores it. from xml.etree.ElementTree import XMLTreeBuilder class HtmlLatex: ...
Parse xml file while a tag is missing
I try to parse an xml file. The text which is in tags is parsed successfully (or it seems so) but I want to output as the text which is not contained in some tags and the following program just ignores it. from xml.etree.ElementTree import XMLTreeBuilder class HtmlLatex: # The target object of the ...
[ "Have a look at BeautifulSoup, a python library for parsing, navigating and manipulating html and xml. It has a handy interface and might solve your problem ...\n", "Here's a pyparsing version - I hope the comments are sufficiently explanatory.\nsrc = \"\"\"<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</...
[ 3, 2 ]
[]
[]
[ "html", "parsing", "python", "xml" ]
stackoverflow_0001991840_html_parsing_python_xml.txt
Q: File writing does not happen when it is supposed to happen in the program flow This is not a new problem for me. From C to PERL to Python on Windows Mobile, Windows XP and other Windows versions this problem persists and f**ks my nerves. Now in my latest script it again happens. To be more concrete: I have coded ...
File writing does not happen when it is supposed to happen in the program flow
This is not a new problem for me. From C to PERL to Python on Windows Mobile, Windows XP and other Windows versions this problem persists and f**ks my nerves. Now in my latest script it again happens. To be more concrete: I have coded in Python a trivial script. Now the script writes correctly to the file when run fro...
[ "Remember what your mom taught you:\nalways flush()\n(in python, file_object.flush() followed by os.fsync(file_object.fileno()))\n", "Regarding the code:\nIt looks like the actual problem is one relating to threads, not to files:\nWhilst you are executing this code:\n for t in list:\n fileo.write(t + \"...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001991815_python.txt
Q: python import module to work globally I've got a problem trying to get python to accept an import 'globally' In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example: def start(): ...
python import module to work globally
I've got a problem trying to get python to accept an import 'globally' In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example: def start(): selected = "web" exec("from gui impor...
[ "import gui\nui = None\n\ndef start():\n selected = \"web\"\n log(\"going to start gui \" + selected)\n global ui\n __import__(\"gui.%s\" % selected) # if you're importing a submodule that\n # may not have been imported yet\n ui = getattr(gui, selected)\n ui.start()\n\n", "W...
[ 8, 2, 0, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0001991784_import_module_python.txt
Q: Sorting problem with the Google App Engine I am using the following class to store some data: class NewsArticle(db.Model): score = db.FloatProperty(default=0.0) date_scored = db.DateTimeProperty() ... What I need to do is to get those NewsArticle entities that have the top score in some time frame (e....
Sorting problem with the Google App Engine
I am using the following class to store some data: class NewsArticle(db.Model): score = db.FloatProperty(default=0.0) date_scored = db.DateTimeProperty() ... What I need to do is to get those NewsArticle entities that have the top score in some time frame (e.g. get the top scored data entities of today or ...
[ "You could either:\n\nfilter only by the timeframe and sort by score in memory or, \nif you can limit the timeframes to whole days and weeks, include additional properties in your model to save the the week as a integer and the day as a DateProperty and do a simple equality check on that.\n\nEDIT: To learn more, ha...
[ 5, 1, 0 ]
[ "I think ordering by multiple properties might work. Simply use the first inequality property as the first ordering property.\nquery = db.GqlQuery('SELECT * FROM NewsArticle WHERE date_created > DATETIME(:year, :month, :day, 0, 0, 0) ORDER BY date_created, score DESC', year=date.selected_year, month=date.selected_m...
[ -1 ]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001991022_google_app_engine_google_cloud_datastore_python.txt
Q: python appengine form-posted utf8 file issue i am trying to form-post a sql file that consists on many INSERTS, eg. INSERT INTO `TABLE` VALUES ('abcdé', 2759); then i use re.search to parse it and extract the fields to put into my own datastore. The problem is that, although the file contains accented characters ...
python appengine form-posted utf8 file issue
i am trying to form-post a sql file that consists on many INSERTS, eg. INSERT INTO `TABLE` VALUES ('abcdé', 2759); then i use re.search to parse it and extract the fields to put into my own datastore. The problem is that, although the file contains accented characters (see the e is a é), once uploaded it loses it and ...
[ "You mention utf8 in the Q's title but then never again: what are you doing (in terms of setting headers and checking them) to verify what encoding is in use? There should be headers of the form\nContent-Type: text/plain; charset=utf-8\n\nand the charset= part is where the encoding is specified. So what are the v...
[ 1 ]
[]
[]
[ "forms", "google_app_engine", "python", "utf_8" ]
stackoverflow_0001991658_forms_google_app_engine_python_utf_8.txt
Q: How to install mysqlDb for MySQL and Python on Windows I am a .NET developer trying to install mysqldb for python I keep having this error message raise improperlyconfigured("error loading mysqldb module: %s" % e) django.core.exceptions.improperlyconfigured: error loading mysqldb module: no module named mysql...
How to install mysqlDb for MySQL and Python on Windows
I am a .NET developer trying to install mysqldb for python I keep having this error message raise improperlyconfigured("error loading mysqldb module: %s" % e) django.core.exceptions.improperlyconfigured: error loading mysqldb module: no module named mysqldb> I am following this instruction from this site I do not...
[ "I have downloaded and installed MySQL from here and it solved my problem.\n" ]
[ 19 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001992103_mysql_python.txt
Q: Why does my Python class claim that I have 2 arguments instead of 1? #! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_rea...
Why does my Python class claim that I have 2 arguments instead of 1?
#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by user ...
[ "The first argument for a python class method is the self variable. If you call classInstance.method(parameter), the method is invoked as method(self, parameter).\nSo, when you're defining your class, do something like this: \nclass MyClass(Object): \n def my_method(self, parameter): \n print parameter\n\...
[ 16, 4, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "class_method", "python" ]
stackoverflow_0001868685_class_method_python.txt
Q: Python Hierarchical QcomboBox: clean-up list I have a hierarchical two combo-box. The first combo-box displays a list of customerNames, i.e. different companies from a MySQL db. Each customer has branches in different cities. Then, when a customer name is chosen from combo-box1 option list, e.g. {Aldi, Meyer, Carr...
Python Hierarchical QcomboBox: clean-up list
I have a hierarchical two combo-box. The first combo-box displays a list of customerNames, i.e. different companies from a MySQL db. Each customer has branches in different cities. Then, when a customer name is chosen from combo-box1 option list, e.g. {Aldi, Meyer, Carrefour, WalMart}, for that particular customer, a l...
[ "I think you are missing a QComboBox.clear() call , before the 'for loop'. Try the following code (Notice the new line just before id=0)\ndef loadComboCity(self,customerName):\n \"\"\"query results cityList into self.mydb.matrix\"\"\"\n queryName=\"citylist_thisCustomer\"\n self.mysqlAPI(queryName,customer...
[ 1 ]
[]
[]
[ "combobox", "hierarchical_data", "python", "qt" ]
stackoverflow_0001990782_combobox_hierarchical_data_python_qt.txt
Q: Self-contained egg installs: turbogears and pythonpath I have a TG 1.0 application (not 1.1 -- I'm not sure I can convince the admin to upgrade) running. I have my own checkout of the project from cvs that I'm developing with, and it's come time to integrate xlwt (http://www.python-excel.org/) into the web app. H...
Self-contained egg installs: turbogears and pythonpath
I have a TG 1.0 application (not 1.1 -- I'm not sure I can convince the admin to upgrade) running. I have my own checkout of the project from cvs that I'm developing with, and it's come time to integrate xlwt (http://www.python-excel.org/) into the web app. However, I don't have administrator access and it's not easy ...
[ "Why don't you use just Virtualenv, create a Python installation which you (as a user own) and install the TG egg inside that? This would make it convenient for you to install non-standard packages as well. I did this since I couldn't get my admin to install the stuff I needed. \n", "So, if anyone wants an easy a...
[ 1, 0 ]
[]
[]
[ "easy_install", "egg", "path", "python", "pythonpath" ]
stackoverflow_0001959286_easy_install_egg_path_python_pythonpath.txt
Q: Help needed--Is class necessary in Python scripting? I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables. Is cla...
Help needed--Is class necessary in Python scripting?
I am creating an interface for Python scripting. Later I will be dong Python scripting also for automated testing. Is it necessary the at i must use class in my code.Now I have created the code with dictionaries,lists,functions,global and local variables. Is class necessary? Help me in this.
[ "No, of course class is not a must. As Python is a scripting language, you can simply code your scripts without defining your own classes.\nClasses are useful if you implement a more complex program which needs a structured approach and OOP benfits (encapsulation, polimorphism) help you in doing it.\n", "It's not...
[ 10, 1, 1, 0 ]
[]
[]
[ "class", "python", "scripting" ]
stackoverflow_0000438149_class_python_scripting.txt
Q: SQL to calculate the Tanimoto Coefficient of several vectors I think it's easier to explain my problem with an example. I have one table with ingredients for recipes and I have implemented a function to calculate the Tanimoto coefficient between ingredients. It's fast enough to calculate the coefficient between tw...
SQL to calculate the Tanimoto Coefficient of several vectors
I think it's easier to explain my problem with an example. I have one table with ingredients for recipes and I have implemented a function to calculate the Tanimoto coefficient between ingredients. It's fast enough to calculate the coefficient between two ingredients (3 sql queries needed), but it does not scale well. ...
[ "Why aren't you simply fetching all recipes into memory and then computing Tanimoto coefficients in memory? \nIt's simpler and it's much, much faster.\n", "If anybody is interested, this is the code that I came up with after Alex's and S.Lotts's suggestions. Thank you guys.\ndef __init__(self):\n self._connec...
[ 4, 3, 1, 0 ]
[]
[]
[ "collaborative_filtering", "python", "sql" ]
stackoverflow_0001992158_collaborative_filtering_python_sql.txt
Q: python: Should I use ValueError or create my own subclass to handle invalid strings? Possible Duplicate: Which exception should I raise on bad/illegal argument combinations in Python? I've looked through python's built in exceptions and the only thing that seems close is ValueError. from python documentation: e...
python: Should I use ValueError or create my own subclass to handle invalid strings?
Possible Duplicate: Which exception should I raise on bad/illegal argument combinations in Python? I've looked through python's built in exceptions and the only thing that seems close is ValueError. from python documentation: exception ValueError: Raised when a built-in operation or function receives an argument ...
[ "ValueError is a good match for the case you have. Just go with that and remember that you can specify a useful message as an argument, letting you distinguish this from other types of ValueError.\nI would not make the code more complicated by defining a subclass, however, unless I had a good reason to want to cat...
[ 11, 4, 4, 3 ]
[ "Yes. ;-) ValueError does sound like the most applicable of the built-in ones, and with a subclass of that you seem to be doing the best possible. It's also what f.i. '%q' % 1 would raise.\n", "I also support ValueError for this case. My 2 cents.\n" ]
[ -1, -1 ]
[ "exception", "python" ]
stackoverflow_0001992006_exception_python.txt
Q: Recompile Vim for pythoncomplete#Complete on modules *other* than standard library? I like using pythoncomplete#Complete for Vim omnicompletion, but it doesn't work for Python modules other than the standard library. Is there a way to re-compile Vim so that this will work on non-standard library modules? I have t...
Recompile Vim for pythoncomplete#Complete on modules *other* than standard library?
I like using pythoncomplete#Complete for Vim omnicompletion, but it doesn't work for Python modules other than the standard library. Is there a way to re-compile Vim so that this will work on non-standard library modules? I have tried pysmell, et. al., but they just don't work as well as pythoncomplete#Complete. This...
[ "Have you tried setting PYTHONPATH prior to starting Vim?\nYou can also modify the path from inside Vim, by doing:\n:python import sys\n:python print sys.path\n:python sys.path.append(...)\n... etc\n\n" ]
[ 1 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0001991865_python_vim.txt
Q: python qt raise syntax error I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings. #!/usr/bin/python # simple....
python qt raise syntax error
I have a top level widget that is producing a syntax error in python. raise() on line 15. This is using the python Qt bindings. I know that raise is a python reserved word. I am looking for how to call the Qt "raise()" function with the python bindings. #!/usr/bin/python # simple.py import sys from PyQt4 import ...
[ "\"raise\" is a keyword (reserved word) in Python. So, you can't use it. And PyQt4 certainly doesn't use it as you think, because, well, it's a keyword, so no extension can. It's like you can't use \"from\" for a variable name (pet peeve: Python doesn't have variables, but I digress...)\nAs a hint, it's also hi...
[ 15 ]
[]
[]
[ "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0001992739_pyqt4_python_qt_qt4.txt
Q: Python Working with lists based on indexes I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE colu...
Python Working with lists based on indexes
I have data in a CSV file. One of the column lists a persons name and all the rows that follow in that column provide some descriptive attributes about that person until the next persons name shows up. I can tell when the row has a name or an attribute by the LTYPE column, N in that column indicates that in that row ...
[ "I suggest a different, index-free approach based on itertools.groupby:\nimport itertools, operator\n\ndata = [\n{'LTYPE': 'N', 'RID': '1', 'NAME': 'Jason Smith'},\n{'LTYPE': 'A', 'RID': '2', 'NAME': 'DA'},\n{'LTYPE': 'A', 'RID': '3', 'NAME': 'B'},\n{'LTYPE': 'N', 'RID': '4', 'NAME': 'John Smith'},\n{'LTYPE': 'A', ...
[ 2, 1 ]
[]
[]
[ "list", "python", "variable_assignment" ]
stackoverflow_0001992659_list_python_variable_assignment.txt
Q: how can i escape '\xff\xfe' to a readable string i see a string in this code: data[:2] == '\xff\xfe' i don't know what '\xff\xfe' is, so i want to escape it ,but not successful import cgi print cgi.escape('\xff\xfe')#print \xff\xfe how can i get it. thanks A: '\xFF' means the byte with the hex value FF. '\xff...
how can i escape '\xff\xfe' to a readable string
i see a string in this code: data[:2] == '\xff\xfe' i don't know what '\xff\xfe' is, so i want to escape it ,but not successful import cgi print cgi.escape('\xff\xfe')#print \xff\xfe how can i get it. thanks
[ "'\\xFF' means the byte with the hex value FF. '\\xff\\xfe' is a byte-order mark: http://en.wikipedia.org/wiki/Byte_order_mark\nYou could also represent it as two separate characters but that probably won't tell you anything useful.\n", ">>> print '\\xff\\xfe'.encode('string-escape')\n\\xff\\xfe\n\n", "What is ...
[ 11, 2, 2, -1 ]
[]
[]
[ "encoding", "escaping", "python", "unicode" ]
stackoverflow_0001979171_encoding_escaping_python_unicode.txt
Q: Upload file to a website via Python script I want to upload a file from my computer to a file hoster like hotfile.com via a Python script. Because Hotfile is only offering a web-based upload service (no ftp). I need Python first to login with my username and password and after that to upload the file. When the fil...
Upload file to a website via Python script
I want to upload a file from my computer to a file hoster like hotfile.com via a Python script. Because Hotfile is only offering a web-based upload service (no ftp). I need Python first to login with my username and password and after that to upload the file. When the file transfer is over, I need the Download and Dele...
[ "For a similar task, I've previously used mechanize, with some quite success.\nNote: although I was not uploading files, its documentation says that it is capable to handle also file uploads.\n", "Okay, you want to use Python to upload a file using HTTP \"put\". You will need to use a Python library that lets yo...
[ 1, 1, 0 ]
[]
[]
[ "authentication", "automation", "file_upload", "python" ]
stackoverflow_0001993060_authentication_automation_file_upload_python.txt
Q: How do I open all files of a certain type in Python and process them? I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values. In this example, I'm iterating through a CSV with lots of different types of ...
How do I open all files of a certain type in Python and process them?
I'm trying to figure out how to make python go through a directory full of csv files, process each of the files and spit out a text file with a trimmed list of values. In this example, I'm iterating through a CSV with lots of different types of columns but all I really want are the first name, last name, and keyword. I...
[ "The best way is probably to use the shell's globbing ability, or alternatively the glob module of Python.\nShell (Linux, Unix)\nShell:\n\npython myapp.py folder/*.csv\n\nmyapp.py:\nimport sys\nfor filename in sys.argv[1:]:\n with open(filename) as f:\n # do something with f\n\nWindows (Or no shell availa...
[ 8, 4, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001992657_python.txt
Q: A programming strategy to bypass the os thread limit? The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. My solution is: A global variable...
A programming strategy to bypass the os thread limit?
The scenario: We have a python script that checks thousands of proxys simultaneously. The program uses threads, 1 per proxy, to speed the process. When it reaches the 1007 thread, the script crashes because of the thread limit. My solution is: A global variable that gets incremented when a thread spawns and decrements ...
[ "You want to do non-blocking I/O with the select module.\nThere are a couple of different specific techniques. select.select should work for every major platform. There are other variations that are more efficient (and could matter if you are checking tens of thousands of connections simultaneously) but you will ...
[ 5, 4, 3, 2, 2, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001993079_multithreading_python.txt
Q: SocketServer client side socket error during third send() on winXP I'm struggling with following error: "socket.error: [10053] 'Software caused connection abort'" Traceback (most recent call last): ... self.send(json.dumps([0x02, subItems])+"\n") ... sent = self.handler.send(data) socket.error: [Er...
SocketServer client side socket error during third send() on winXP
I'm struggling with following error: "socket.error: [10053] 'Software caused connection abort'" Traceback (most recent call last): ... self.send(json.dumps([0x02, subItems])+"\n") ... sent = self.handler.send(data) socket.error: [Errno 10053] I established server properely, I can connect to it, send "h...
[ "If this, as you report, is really how your main server code ends...:\nserver_thread.setDaemon(True)\nserver_thread.start()\n\nthen your code is saying: let server_thread just die when the main thread dies, let server_thread start, and now let the main thread die -- i.e., are you really \"falling off the end\" righ...
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001993243_python_sockets.txt
Q: Python web framework with low barrier to entry I am looking for a LAMPish/WAMPish experience. Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction. SQLAlchemy and (maybe) some simple templating engine will be used. I need simple access to the environment - simil...
Python web framework with low barrier to entry
I am looking for a LAMPish/WAMPish experience. Something very transparent. Write the script, hit F5 and see the results. Very little, if any abstraction. SQLAlchemy and (maybe) some simple templating engine will be used. I need simple access to the environment - similar to the PHP way. Something like the COOKIE, SESSIO...
[ "CherryPy might be what you need. It transparently maps URLs onto Python functions, and handles all the cookie and session stuff (and of course the POST / GET parameters for you).\nIt's not a full-stack solution like Django or Rails. On the other hand, that means that it doesn't lump you with a template engine or...
[ 7, 5, 5, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000948815_python.txt
Q: Possible to send variables to the index page in CherryPy? For instance I want to visit http://localhost:8080/?var=val or similar with POST, but I get a 500 server error: 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. Traceback (most recent...
Possible to send variables to the index page in CherryPy?
For instance I want to visit http://localhost:8080/?var=val or similar with POST, but I get a 500 server error: 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. Traceback (most recent call last): File "c:\python26\lib\site-packages\cherrypy\_cpr...
[ "It is definitely possible.\nHere is an example (adapted from the CherryPy tutorial):\n<form action=\"indexPostHandler\" method=\"post\">\n <p>Enter a value:</p>\n <input type=\"text\" name=\"val\" value=\"\"/>\n <p><input type=\"submit\" value=\"Login\"/></p>\n</form>\n\nAnd, in your index, you can use so...
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001993565_cherrypy_python.txt
Q: Pass XML fragments as stylesheet paramters with lxml? I'm starting to use lxml in Python for processing XML/XSL documents, and in general it seems very straight forward. However, I'm not able to find a way to pass an XML fragment as a stylesheet parameter when doing a translation. For example, in PHP it is possibl...
Pass XML fragments as stylesheet paramters with lxml?
I'm starting to use lxml in Python for processing XML/XSL documents, and in general it seems very straight forward. However, I'm not able to find a way to pass an XML fragment as a stylesheet parameter when doing a translation. For example, in PHP it is possible to pass DOMDocument XML fragments as stylesheet parameter...
[ "As far as I know, you can only use xpath expressions (or result of the etree.XSLT.strparam() method for strings with quotes) in lxml (at the moment anyway).\nHowever, because you can use xpath expressions, that means you could \"work around\" by using a custom xpath extension function that returns the Element in q...
[ 1, 1, 0 ]
[]
[]
[ "lxml", "python", "xml", "xslt" ]
stackoverflow_0001756559_lxml_python_xml_xslt.txt
Q: if my condition false how to do a statement one time only in python is there any way to make this logic: I need to make a statement one time only if the condition is false as below: while 1: statement1 statement2 if condition: --condition is true here statement3 else ...
if my condition false how to do a statement one time only in python
is there any way to make this logic: I need to make a statement one time only if the condition is false as below: while 1: statement1 statement2 if condition: --condition is true here statement3 else --condition is false here statement3 ...
[ "add a boolean variable:\nneverdone = True\nwhile 1:\n statement1\n statement2\n if condition:\n statement3\n elif neverdone:\n neverdone = False\n statement3\n if anothercondition:\n break\n\n", "Couldn't you just put a break statement after statement3? That wou...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001993637_python.txt
Q: translate this block of C physics code to python I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advanc...
translate this block of C physics code to python
I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance! for(i=0; i<n; i++) { /* Foreach particle "i" ... */...
[ "Treat this as an ideal opportunity to learn some C, the syntax is not so unlike Python.\nIt will serve you well\n", "Here's a literal translation\n(Edit: was a literal translation but there are some anomalies in the original C code which @hughdbrown pointed out in comments -- looks like you're trying to study th...
[ 7, 2, 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001993580_c_python.txt
Q: How do I trust the order of a Python dictionary? I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this? A: A standard Dictionary does not impose an ordering, it's simply a lookup. You want an Ordered Dictionary or Ordered ...
How do I trust the order of a Python dictionary?
I'm trying to make a dictionary in Python that I can sort through but it seems to change order when I add new things. Is there a way around this?
[ "A standard Dictionary does not impose an ordering, it's simply a lookup.\nYou want an Ordered Dictionary or Ordered Dictionary.\n", "Python dicts are built as hash tables -- great performance, but ordering is essentially arbitrary and unpredictable. If your need for predictably-ordered walks are occasional, and...
[ 9, 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001993747_dictionary_python.txt
Q: Unit testing for D-Bus and HAL? How does one test a method that does some interactions with the local D-Bus (accessing a HAL object)? Results of tests will differ depending on the system that the test is run on, so I don't know how to provide the method reliable input. I'm working in Python, by the way. A: If ...
Unit testing for D-Bus and HAL?
How does one test a method that does some interactions with the local D-Bus (accessing a HAL object)? Results of tests will differ depending on the system that the test is run on, so I don't know how to provide the method reliable input. I'm working in Python, by the way.
[ "If you can not mock the environment then it's probably impossible for you to write the test.\nIf your access to HAL/D-Bus is via an object and you provide a mock instance to your test then it should be possible to emulate the necessary inputs to your test from the mock implementation.\n", "It's also possible to ...
[ 2, 0 ]
[]
[]
[ "dbus", "hal", "python", "unit_testing" ]
stackoverflow_0000827295_dbus_hal_python_unit_testing.txt
Q: How can I force cherrypy to accept a variable number of GET parameters? for instance, say I have my cherrypy index module set up like this >>> import cherrypy >>> class test: def index(self, var = None): if var: print var else: print "nothing" ...
How can I force cherrypy to accept a variable number of GET parameters?
for instance, say I have my cherrypy index module set up like this >>> import cherrypy >>> class test: def index(self, var = None): if var: print var else: print "nothing" index.exposed = True >>> cherrypy.quickstart(test()) If I send more than o...
[ "def index(self, var=None, **params):\n\nor\ndef index(self, **params):\n\n'var2' will be a key in the params dict. In the second example, so will 'var'.\nNote the other answers which reference the *args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positional argum...
[ 36, 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001993604_cherrypy_python.txt
Q: Where is os.environ initialized? Using this code, many keys are output, but I expected no output: import os for i in os.environ: print i This is the code from os.py: try: environ except NameError: environ = {} Where does os.environ get its values from? Where is it initialized? A: The os module st...
Where is os.environ initialized?
Using this code, many keys are output, but I expected no output: import os for i in os.environ: print i This is the code from os.py: try: environ except NameError: environ = {} Where does os.environ get its values from? Where is it initialized?
[ "The os module starts by importing all names from a platform-specific submodule (such as _nt or _posix) then does a little normalization. Clearly the environ name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so the except clause in os.py...
[ 7, 3 ]
[]
[]
[ "initialization", "python", "std" ]
stackoverflow_0001993643_initialization_python_std.txt
Q: My own OCR-program in Python I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling. from PIL import Image import numpy as np im = I...
My own OCR-program in Python
I am still a beginner but I want to write a character-recognition-program. This program isn't ready yet. And I edited a lot, therefor the comments may not match exactly. I will use the 8-connectivity for the connected component labeling. from PIL import Image import numpy as np im = Image.open("D:\\Python26\\PYTHON-PR...
[ "OCR is not an easy task indeed. That's why text CAPTCHAs still work :)\nTo talk only about the letter extraction and not the pattern recognition, the technique you are using to separate the letters is called Connected Component Labeling. Since you are asking for a more efficient way to do this, try to implement th...
[ 34, 7, 5, 4 ]
[]
[]
[ "arrays", "artificial_intelligence", "ocr", "python" ]
stackoverflow_0001989987_arrays_artificial_intelligence_ocr_python.txt
Q: how change int to binary. on python 2.5 print 077777#how can i get binary i use python2.5 A: Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers): def bin(value): binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'} return ''....
how change int to binary. on python 2.5
print 077777#how can i get binary i use python2.5
[ "Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers):\ndef bin(value):\n binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'}\n return ''.join(binmap[x] for x in ('%x' % (value,))).lstrip('0') or '0'\n\n", "Here are some recipes ...
[ 6, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001993834_python.txt
Q: insert tags in ElementTree text I am using the Python ElementTree module to manipulate HTML. I want to emphasize certain words, and my current solution is: for e in tree.getiterator(): for attr in 'text', 'tail': words = (getattr(e, attr) or '').split() change = False for i, word in enu...
insert tags in ElementTree text
I am using the Python ElementTree module to manipulate HTML. I want to emphasize certain words, and my current solution is: for e in tree.getiterator(): for attr in 'text', 'tail': words = (getattr(e, attr) or '').split() change = False for i, word in enumerate(words): word = cle...
[ "You can also use xslt and a custom xpath function to do this. \nShown below is an example. It still needs some work, for example cleaning up extra whitespace at the end of elements and handling mixed-text, but it's another idea.\ngiven this input:\n\n<html>\n<head>\n</head>\n<body>\n<p>here is some text to bold</p...
[ 4, 1 ]
[]
[]
[ "elementtree", "html", "lxml", "python" ]
stackoverflow_0001973026_elementtree_html_lxml_python.txt
Q: What is python's 'restricted execution mode'? When __builtins__ is set and I try to access function globals, I get this error >>> def f(): pass ... >>> f.func_globals {'f': <function f at 0x00B83270>, '__builtins__': <module '__builtin__' (built-in)>} >>> __builtins__ = {} >>> f.func_globals Traceback (most recen...
What is python's 'restricted execution mode'?
When __builtins__ is set and I try to access function globals, I get this error >>> def f(): pass ... >>> f.func_globals {'f': <function f at 0x00B83270>, '__builtins__': <module '__builtin__' (built-in)>} >>> __builtins__ = {} >>> f.func_globals Traceback (most recent call last): File "<string>", line 1, in <string...
[ "Alas, a long-obsolete concept, see the docs -- the original idea was to provide a safe / sandboxed mode, but it just didn't pan out and was abandoned and deprecated since 2.3.\n" ]
[ 3 ]
[]
[]
[ "python", "security" ]
stackoverflow_0001994117_python_security.txt
Q: Learning Python and using dictionaries I'm working through exercises in Building Skills in Python, which to my knowledge don't have any published solutions. In any case, I'm attempting to have a dictionary count the number of occurrences of a certain number in the original list, before duplicates are removed. For...
Learning Python and using dictionaries
I'm working through exercises in Building Skills in Python, which to my knowledge don't have any published solutions. In any case, I'm attempting to have a dictionary count the number of occurrences of a certain number in the original list, before duplicates are removed. For some reason, despite a number of variations...
[ "defaultdict makes this easy:\n>>> from collections import defaultdict\n\n>>> seq = [2,4,5,2,4,6,3,8,9,3,7,2,47,2]\n\n>>> seqDic = defaultdict(int)\n\n>>> for v in seq:\n... seqDic[v] += 1\n\n>>> print seqDic\ndefaultdict(<type 'int'>, {2: 4, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 47: 1})\n\n", "I'm not re...
[ 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001993689_python.txt
Q: Use raw SQL to create tables in SQLAlchemy, after which use ORM Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used ...
Use raw SQL to create tables in SQLAlchemy, after which use ORM
Is it possible to use raw SQL rather than the TABLE construct for creating tables in SQL Alchemy? I would still like to use the rest of SQLAlchemy though, such as the object mapper and session module. I'm just not fond of the SQLAlchemy syntax used to create tables (I've spent too long mired in SAS and SQL to learn a...
[ "Yes.\nconnection.execute(\"\"\"\nCREATE TABLE ...\n\"\"\")\n\nYou can then reflect all tables: MetaData(dsn, reflect=True) or metadata_instance.reflect().\n", "You can use the autoload paramater to the Table constructor to have it automatically load up the table definitions. There are some examples here.\n" ]
[ 3, 1 ]
[]
[]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0001992815_database_design_python_sqlalchemy.txt
Q: PyWin32: Windows Classic theme In the PyWin32 demos folder, the win32gui_dialog.py sample uses the classic windows controls. Can the Windows Vista themed buttons also be displayed using PyWin32, and if so, how? I'm using ActivePython 3.1, if that makes any difference. Sample: PyWin32 http://imagespark.net/files/o...
PyWin32: Windows Classic theme
In the PyWin32 demos folder, the win32gui_dialog.py sample uses the classic windows controls. Can the Windows Vista themed buttons also be displayed using PyWin32, and if so, how? I'm using ActivePython 3.1, if that makes any difference. Sample: PyWin32 http://imagespark.net/files/old.png
[ "Short answer: a resounding YES.\nI know that this is possible because I have seen it being done before. but I am not entirely certain as to how it is done.\nAt the very least, you can use IronPython and use Windows' builtin .NET framework by wielding clr.\nIf you are not interested in IronPython, then might you co...
[ 2, 2, 0 ]
[]
[]
[ "python", "python_3.x", "pywin32", "windows", "windows_vista" ]
stackoverflow_0001969041_python_python_3.x_pywin32_windows_windows_vista.txt
Q: assistance troubleshooting a python/cherrypy error import cherrypy import os PORT = 8080 class intelServ: def index(self, botkey = None, userkey = None, network = None, user = None, channel = None, msg = None, step = None, **args): # If any necessary parameters are missing, the bot should fail silen...
assistance troubleshooting a python/cherrypy error
import cherrypy import os PORT = 8080 class intelServ: def index(self, botkey = None, userkey = None, network = None, user = None, channel = None, msg = None, step = None, **args): # If any necessary parameters are missing, the bot should fail silently. #if not botkey or not userkey or not networ...
[ "It looks like the parameter botkey as supplied to intelServ.index() is None (hence the 'NoneType'). You should uncomment your input validation code.\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001994107_cherrypy_python.txt
Q: Why can't I find '__path__' in django.db.__init__.py? backend_dir = os.path.join(__path__[0], 'backends') Why can't I find it? A: Set settings.DATABASE_ENGINE in settings.py. The execution reaches the line you mentioned only if the back-end is not standard.
Why can't I find '__path__' in django.db.__init__.py?
backend_dir = os.path.join(__path__[0], 'backends') Why can't I find it?
[ "Set settings.DATABASE_ENGINE in settings.py.\nThe execution reaches the line you mentioned only if the back-end is not standard.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001994294_django_python.txt
Q: Is Google App Engine right for me? I am thinking about using Google App Engine.It is going to be a huge website. In that case, what is your piece of advice using Google App Engine. I heard GAE has restrictions like we cannot store images or files more than 1MB limit(they are going to change this from what I read i...
Is Google App Engine right for me?
I am thinking about using Google App Engine.It is going to be a huge website. In that case, what is your piece of advice using Google App Engine. I heard GAE has restrictions like we cannot store images or files more than 1MB limit(they are going to change this from what I read in the GAE roadmap),query is limited to 1...
[ "Having developed a smallish site with GAE, I have some thoughts\n\nIf you mean \"huge\" like \"the next YouTube\", then GAE might be a great fit, because of the previously mentioned scaling.\nIf you mean \"huge\" like \"massively complex, with a whole slew of screens, models, and features\", then GAE might not be ...
[ 8, 5, 3, 2, 1, 0 ]
[ "If you are planning on a 'huge' website, then don't use App Engine. Simple as that. The App Engine is not built to deliver the next top 1000th website. \nAllow me to also ask what do you mean by 'huge', how many simultaneous users? Queries per second? DB load?\n" ]
[ -11 ]
[ "google_app_engine", "python", "web2py" ]
stackoverflow_0001903065_google_app_engine_python_web2py.txt
Q: How to get (and use) extended permissions in Facebook with Python/Django I'm trying to write a simple app that lets a user grant my code permission to write to her page's Facebook stream. As I understand it, it should be as easy as: Have the user click on a button that launches a popup containing the a page in m...
How to get (and use) extended permissions in Facebook with Python/Django
I'm trying to write a simple app that lets a user grant my code permission to write to her page's Facebook stream. As I understand it, it should be as easy as: Have the user click on a button that launches a popup containing the a page in my Facebook app. In that page, they click on something that grants stream_publi...
[ "Have you looked at minifb? Their examples page shows basically everything you need to know to request authorization and receive a session key. (Also, the github page for pyfacebook shows that the library is still alive)\nSo, for your scenario you'd need:\n\nRequest the \"stream_publish\" permission. There are som...
[ 3, 1 ]
[]
[]
[ "django", "facebook", "pyfacebook", "python" ]
stackoverflow_0001967438_django_facebook_pyfacebook_python.txt
Q: How can I open '_mysql.pyd' in 'D:\Python25\Lib\site-packages'? My IDE is 'ulipad', and when I open the file, it can't be shown. How can I get it? A: .pyd files are DLLs. You can't usefully open them in text editors.
How can I open '_mysql.pyd' in 'D:\Python25\Lib\site-packages'?
My IDE is 'ulipad', and when I open the file, it can't be shown. How can I get it?
[ ".pyd files are DLLs. You can't usefully open them in text editors.\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001994403_mysql_python.txt
Q: Problem with for loop iterations over data from a queue I'm having a problem reading and processing data from my server. I've spent hours debugging this and it seems as though the problem has nothing to do with the server but is really just an issue with one of my for loops. Its difficult to explain this without a...
Problem with for loop iterations over data from a queue
I'm having a problem reading and processing data from my server. I've spent hours debugging this and it seems as though the problem has nothing to do with the server but is really just an issue with one of my for loops. Its difficult to explain this without actually seeing the data from the server, but I'll do my best ...
[ "\"As TCP is a stream, I usually don't receive each string separately \"\nYou can't reliably and predictably receive them separately. TCP makes things into a single stream of data. That's what TCP/IP must do. It must buffer to create a \"stream\" of data, not matter what you try to do at each end to send or rec...
[ 3, 1, 1 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0001994904_for_loop_loops_python.txt
Q: Creating an FTP client with Python I've always thought about creating my own ftp client ever since I've started using the Internet. And now that I'm studying Python, I'm thinking about creating one as an exercises/personal project. I'm wondering, What libraries do you guys suggest? Will ftplib suffice? Or would ...
Creating an FTP client with Python
I've always thought about creating my own ftp client ever since I've started using the Internet. And now that I'm studying Python, I'm thinking about creating one as an exercises/personal project. I'm wondering, What libraries do you guys suggest? Will ftplib suffice? Or would you suggest another library(preferably o...
[ "It sounds like you want to make a program that has a GUI. May I recommend using PyQt for that part of your application? ftplib should be fine for your FTP support, and you can find documentation right here.\nAlternatively for FTP support, you can use the QFtp class from the QtNetwork module from PyQt framework. Th...
[ 10, 4 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0001995046_ftp_python.txt
Q: Why am I getting an error using 'set' in Python? s = set('ABC') s.add('z') s.update('BCD') s.remove('DEF') # error here s -= set('DEFG') A: As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as "Raises KeyError if elem is not c...
Why am I getting an error using 'set' in Python?
s = set('ABC') s.add('z') s.update('BCD') s.remove('DEF') # error here s -= set('DEFG')
[ "As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as \"Raises KeyError if elem is not contained in the set.\".\nIf you want \"missing element\" to mean a silent no=op instead, just use discard instead of remove: that's the cruci...
[ 16, 2, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0001994163_python_set.txt
Q: Removing specific items from Django's cache? I'm using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes. If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but su...
Removing specific items from Django's cache?
I'm using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes. If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs. If just the page content ch...
[ "I haven't done a lot of caching with Django, but I think what you want here are signals.\nYou can set up a post_save signal on the underlying object, and have the callback function invalidate that page in the cache.\nfrom django.core.signals import post_save\nfrom django.core.cache import cache\n\ndef invalidate_c...
[ 6, 4 ]
[]
[]
[ "caching", "django", "memcached", "python" ]
stackoverflow_0000720800_caching_django_memcached_python.txt
Q: i *must* store third party credentials in my database. best way? My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing t...
i *must* store third party credentials in my database. best way?
My app must read an SSL url from a third party. How do I best store the third party credentials in my own database, which protects the third party credentials from being compromised? Consider both absolute security and practicality. One-way hashing the credentials is not useful as I must restore credentials to plaintex...
[ "How are the credentials being used? If their use is only triggered by the original owner (eg. you're storing a bank card number and they're making their 2nd purchase) then they can provide a password at that point which is used as your encryption key. You would then never need to store that key locally and the dat...
[ 3, 2, 2, 2 ]
[]
[]
[ "authentication", "google_app_engine", "passwords", "python", "security" ]
stackoverflow_0001994112_authentication_google_app_engine_passwords_python_security.txt
Q: Python vs. Java -- Which would you pick to do concurrent programming and why? Also, if not python or java, then would you more generally pick a statically-typed language or a dynamic-type language? A: I would choose the JVM over python, primarily because multi-threading in Python is impeded by the Global Interpr...
Python vs. Java -- Which would you pick to do concurrent programming and why?
Also, if not python or java, then would you more generally pick a statically-typed language or a dynamic-type language?
[ "I would choose the JVM over python, primarily because multi-threading in Python is impeded by the Global Interpreter Lock. However, Java is unlikely to be your best when running on the JVM. Clojure or Scala (using actors) are both likely to be better suited to multi-threaded problems.\nIf you do choose Java you sh...
[ 31, 12, 11, 6, 5, 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "concurrency", "java", "python", "python_stackless" ]
stackoverflow_0001861457_concurrency_java_python_python_stackless.txt
Q: How can I turn 000000000001 into 1? I need to turn a formatted integer into a regular integer: 000000000001 needs to be turned into 1 000000000053 needs to be turned into 53 000000965948 needs to be turned into 965948 And so on. It seems that a simple int(000000000015) results in the number 13. I understand the...
How can I turn 000000000001 into 1?
I need to turn a formatted integer into a regular integer: 000000000001 needs to be turned into 1 000000000053 needs to be turned into 53 000000965948 needs to be turned into 965948 And so on. It seems that a simple int(000000000015) results in the number 13. I understand there is some weird stuff behind the scenes....
[ "Numbers starting with 0 are considered octal.\n>>> 07\n7\n>>> 08\n File \"<stdin>\", line 1\n 08\n ^\nSyntaxError: invalid token\n\nYou can wrap your zero-padded number into a string, then it should work.\n>>> int(\"08\")\n8\n\nint() takes an optional argument, which is the base, so the above would be the e...
[ 11, 8, 3 ]
[ "if x = \"0000000000000001\":\n x = 1\n\n" ]
[ -8 ]
[ "integer", "parsing", "python" ]
stackoverflow_0001995602_integer_parsing_python.txt
Q: Django/Python: How can I make the following number increment (not in database) I would like to create a number like: 000000000001 to save to the database. I obviously cannot increment in this fashion (I don't think) in a database, so I'm looking for the most efficient method for pulling the previous number from t...
Django/Python: How can I make the following number increment (not in database)
I would like to create a number like: 000000000001 to save to the database. I obviously cannot increment in this fashion (I don't think) in a database, so I'm looking for the most efficient method for pulling the previous number from the database and incrementing it by 1 to create the next record: 000000000002 and so...
[ "All the leading zeroes are just formatting.\n>>> \"%012d\" % ( 1, )\n'000000000001'\n>>> \"%012d\" % ( 2, )\n'000000000002'\n\nUse an ordinary integer and format it to have lots of leading zeroes.\n", "There's actually a super tricky way to do this using the itertools library and a generator function.\nfrom iter...
[ 7, 1 ]
[]
[]
[ "auto_increment", "django", "python" ]
stackoverflow_0001995561_auto_increment_django_python.txt
Q: Optimization of Google App Engine Code Google app engine tells me to optimize this code. Anybody any ideas what I could do? def index(request): user = users.get_current_user() return base.views.render('XXX.html', dict(profiles=Profile.gql("").fetch(limit=100), user=user)) And later in th...
Optimization of Google App Engine Code
Google app engine tells me to optimize this code. Anybody any ideas what I could do? def index(request): user = users.get_current_user() return base.views.render('XXX.html', dict(profiles=Profile.gql("").fetch(limit=100), user=user)) And later in the template I do: {% for profile in profiles ...
[ "The high CPU usage will be due to fetching 100 entities per request. You have several options here:\n\nUsing Profile.all().fetch(100) will be ever so slightly faster, and easier to read besides.\nRemove any extraneous properties from the Profile model. There's significant per-property overhead deserializing entiti...
[ 6, 3, 1, 0 ]
[]
[]
[ "google_app_engine", "optimization", "python" ]
stackoverflow_0000298185_google_app_engine_optimization_python.txt
Q: Polymorphism in Django I have the following models. How do I get access to the unicode of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete. class Entity(models.Model): entity_type...
Polymorphism in Django
I have the following models. How do I get access to the unicode of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete. class Entity(models.Model): entity_type_list = (('T', 'Team'), ('A'...
[ "This answer from Carl Meyer to the question mentioned earlier by Paul McMillan might be what your looking for. A subtlety to this problem not captured in some of the answers is how to get at derived class instances from a QuerySet on Entity.\nThe Problem\nfor entity in Entity.objects.all()\n print unicode(entity)...
[ 6, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "inheritance", "python" ]
stackoverflow_0001397537_django_inheritance_python.txt
Q: How to reset Python interpreter to a 'safe' state? I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything...
How to reset Python interpreter to a 'safe' state?
I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything except I have a bunch of PyObject * references that I n...
[ "Er, trying to \"recover\" from a segfault or access violation is quite dangerous. There is a reason you get these in the first place, and it's that your program has tried to do something which it shouldn't have tried to do; therefore it has hit a bug or an unforeseen condition.\nThere is no provision in the Python...
[ 2 ]
[]
[]
[ "function", "python", "recover" ]
stackoverflow_0001993238_function_python_recover.txt
Q: How do I implement 'Parameter Object' refactor in Python? Right now I use the parameter object's class to be inherited like so class A(): def __init__(self,p1,p2): self.p1, self.p2 = p1, p2 class B(A): def __init__(self,b): self.p1, self.p2 = b.p1, b.p2 This trims up the absurdity of usin...
How do I implement 'Parameter Object' refactor in Python?
Right now I use the parameter object's class to be inherited like so class A(): def __init__(self,p1,p2): self.p1, self.p2 = p1, p2 class B(A): def __init__(self,b): self.p1, self.p2 = b.p1, b.p2 This trims up the absurdity of using the code but not the class code itself. So, I'd like to do th...
[ "Generally speaking, you likely don't need the parameter object refactor technique. Python has several collections in the standard library that already have the core benefits that a parameter object refactor would provide.\nAdditionally, the cost/benefit analysis for a refactor like the parameter object design patt...
[ 3, 2, 1 ]
[]
[]
[ "inheritance", "parameter_object", "python", "refactoring" ]
stackoverflow_0001995622_inheritance_parameter_object_python_refactoring.txt
Q: applying image decoration (border) in Python (programmatically) I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border. Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GI...
applying image decoration (border) in Python (programmatically)
I am looking for a way to create a border in python.Is there any library in Python which we can import to create a border. Note that I do not want to use any image masks to create this effect (e.g. I don't want to use any image editing package like GIMP to create a border image mask) . Here is what I am looking for: i...
[ "Look at the ImageOps module within the PIL.\nimport Image\nimport ImageOps\n\nx = Image.open('test.png')\ny = ImageOps.expand(x,border=5,fill='red')\ny.save('test2.png')\n\n", "You can use the PythonMagick module. the documentation for this module is here (Magic ++ documentation)\nExample: To add a red 2 pixel b...
[ 11, 2, 1 ]
[]
[]
[ "image", "image_processing", "python" ]
stackoverflow_0001995772_image_image_processing_python.txt
Q: Python execution Is it possible for a python script to execute at a low run level? Edit: To clarify, is it possible for a python script to run in the background, kind of like a daemon. A: I put this file nice.py in my site-packages directory (on Windows): import win32api,win32process,win32con pid = win32api.Ge...
Python execution
Is it possible for a python script to execute at a low run level? Edit: To clarify, is it possible for a python script to run in the background, kind of like a daemon.
[ "I put this file nice.py in my site-packages directory (on Windows):\nimport win32api,win32process,win32con\npid = win32api.GetCurrentProcessId()\nhandle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)\nwin32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)\n\nThen I just imp...
[ 5, 0 ]
[]
[]
[ "python", "runlevel" ]
stackoverflow_0001995102_python_runlevel.txt
Q: is my google app engine deployed source code secure? I'm thinking about good ways to store third party credentials, which basically means there needs to be a secret somewhere, either in code or data. I'm deploying on google app engine. If the 'secret' was something like pw_passphrase = sha2(username + 'global-pass...
is my google app engine deployed source code secure?
I'm thinking about good ways to store third party credentials, which basically means there needs to be a secret somewhere, either in code or data. I'm deploying on google app engine. If the 'secret' was something like pw_passphrase = sha2(username + 'global-password') pw_plaintext = aes_decrypt(pw_passphrase, pw_cipher...
[ "Yes: your source code is secure (as secure as Google can make it), and there's no way for unauthorized third parties to peek.\n", "Also remember to handle exceptions in your code with an error page, or else an exception thrown might uncover your source code to an unsigned user.\n" ]
[ 4, 2 ]
[]
[]
[ "credentials", "google_app_engine", "passwords", "python", "security" ]
stackoverflow_0001994182_credentials_google_app_engine_passwords_python_security.txt
Q: Upgrade Python to 2.6 on Mac I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this. Thanks A: When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Ma...
Upgrade Python to 2.6 on Mac
I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this. Thanks
[ "When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Mac OS X, as well as many Linux distros &c), you should not tamper in any way with the system-supplied Python (as in, \"upgrading\" it and the like): while Python strives for backwards compatibili...
[ 20, 8, 6, 5, 4, 1, 0 ]
[]
[]
[ "installation", "macos", "python", "upgrade" ]
stackoverflow_0001541776_installation_macos_python_upgrade.txt
Q: django unprintable templatesyntaxerror object caused by urlconf? I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actuall...
django unprintable templatesyntaxerror object caused by urlconf?
I'm trying to get a django project set up, and I seem to be having trouble with my urlconf. I'm not sure what the deal is, and the error below isn't entirely helpful to me. I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before the ...
[ "Make sure each of your .py files is syntactically correct. Run python manage.py shell and then import each of your modules and make sure it loads with no errors. Since syntax errors are runtime errors in python, mistakes sometimes show up at odd times and in odd places.\n", "Here's another suggestion which could...
[ 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001788245_django_google_app_engine_python.txt
Q: How can I get the depth of a jpg file? I want to retrieve the bit depth for a jpeg file using Python. Using the Python Imaging Library: import Image data = Image.open('file.jpg') print data.depth However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do...
How can I get the depth of a jpg file?
I want to retrieve the bit depth for a jpeg file using Python. Using the Python Imaging Library: import Image data = Image.open('file.jpg') print data.depth However, this gives me a depth of 8 for an obviously 24-bit image. Am I doing something wrong? Is there some way to do it with pure Python code? Thanks in advance...
[ "I don't see the depth attribute documented anywhere in the Python Imaging Library handbook. However, it looks like only a limited number of modes are supported. You could use something like this:\nmode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}\n\ndata = Image.open...
[ 14, 8, 4, 2 ]
[]
[]
[ "imaging", "jpeg", "python" ]
stackoverflow_0001996577_imaging_jpeg_python.txt
Q: All Possible combination for an HEX Value from a given set of chars I am new to python and programming, I am looking for a code, or a sample code that can have a predefined set of hex values and that can find the 3 used values within to generate a certain value. lets say I have a value of : 0x50158A51 this is a 4...
All Possible combination for an HEX Value from a given set of chars
I am new to python and programming, I am looking for a code, or a sample code that can have a predefined set of hex values and that can find the 3 used values within to generate a certain value. lets say I have a value of : 0x50158A51 this is a 4 byte (32 bit) hex value now i need to find the values which when added o...
[ "What you're asking for isn't possible. There will be infinite sequences of numbers that when added together will continue to produce the same result, modulo 2^32.\nAs a trivial example, say that your target number is 0x10000000 and the only hex values you allow are zero and one. Then the following sequences of num...
[ 1, 1, 0 ]
[]
[]
[ "dataset", "hex", "python", "subtraction" ]
stackoverflow_0001996184_dataset_hex_python_subtraction.txt
Q: Reference function or create a new function that only calls another? def a(something): return something*something #Case I - referencing b = a #Case II - creating a new function to call the first def b(something): return a(something) Which is better style? Are there drawbacks to either? A: Depends on wh...
Reference function or create a new function that only calls another?
def a(something): return something*something #Case I - referencing b = a #Case II - creating a new function to call the first def b(something): return a(something) Which is better style? Are there drawbacks to either?
[ "Depends on what you need.\ndef a(something):\n return something*something\n\nb = a\n\ndef a(something):\n return something+something\n\n>>> b(3)\n9\n>>> a(3)\n7\n\nWhereas if you did:\nb = lambda x:a(x)\n\nb and a will always returns the same\nIf you want to optimize an extra function call out the first way ...
[ 5, 2, 0, 0 ]
[]
[]
[ "coding_style", "function", "python" ]
stackoverflow_0001996680_coding_style_function_python.txt
Q: How to get a Blob size? (Python Google App Engine) http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#Blob A: {{ theblob|length }} if you're using a Django template (as you seem to indicate in a comment, although you give absolutely no indication of this in your question -- I sug...
How to get a Blob size? (Python Google App Engine)
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#Blob
[ "{{ theblob|length }} if you're using a Django template (as you seem to indicate in a comment, although you give absolutely no indication of this in your question -- I suggest editing the question to add that crucial bit of info!-).\n" ]
[ 3 ]
[ "Try blob.getSize()\n" ]
[ -1 ]
[ "blob", "google_app_engine", "python" ]
stackoverflow_0001996591_blob_google_app_engine_python.txt
Q: Wildcard matching a string in Python regex search I thought I would write some quick code to download the number of "fans" a Facebook page has. For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I ...
Wildcard matching a string in Python regex search
I thought I would write some quick code to download the number of "fans" a Facebook page has. For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case...
[ "Evan Fosmark already gave a good answer. This is just more info.\nYou have this line:\npattern = \"6 of(.*)fans\"\n\nIn general, this isn't a good regular expression. If the input text was:\n\"6 of 99 fans in the whole galaxy of fans\"\nThen the match group (the stuff inside the parentheses) would be:\n\" 99 fan...
[ 15, 14, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001996482_python_regex.txt
Q: Reading from an SSL Socket in Twisted I'm trying to implement an SSL client in Twisted that simply must connect to a socket and read binary data (specifically, tuples of data). I've gotten the code to a point where it seems to connect and disconnect successfully but no data is ever read from the socket. class Fee...
Reading from an SSL Socket in Twisted
I'm trying to implement an SSL client in Twisted that simply must connect to a socket and read binary data (specifically, tuples of data). I've gotten the code to a point where it seems to connect and disconnect successfully but no data is ever read from the socket. class FeedbackHandler(LineReceiver): MAX_LENGTH = ...
[ "Take a look at ssldump or wireshark. Since you're not seeing any data delivered at this level, you should drop down a level to one of these tools. One of them might reveal an SSL negotiation error, or that the server never sends any bytes, or something else that's hard to guess based just on what you've discover...
[ 2 ]
[]
[]
[ "openssl", "python", "sockets", "twisted" ]
stackoverflow_0001991399_openssl_python_sockets_twisted.txt
Q: Error in imitating memoize() from django.utils.functional.py def a(): print 'aa' def b(): print 'bb' def c(*x): print x def d(x,y): c(*(x+y)) d(a,b) Traceback (most recent call last): File "D:\zjm_code\mysite\zjmbooks\a.py", line 15, in <module> d(a,b) File "D:\zjm_code\mysite\zjmbooks\...
Error in imitating memoize() from django.utils.functional.py
def a(): print 'aa' def b(): print 'bb' def c(*x): print x def d(x,y): c(*(x+y)) d(a,b) Traceback (most recent call last): File "D:\zjm_code\mysite\zjmbooks\a.py", line 15, in <module> d(a,b) File "D:\zjm_code\mysite\zjmbooks\a.py", line 13, in d c(*(x+y)) TypeError: unsupported operand ...
[ "Your code (in x+y, where x is a and y is b) is trying to sum two functions (instead of calling them and summing their results, for example): function objects cannot be summed, so your code raises an exeption.\nThe code you quote, in args+moreargs, is summing two tuples: tuples can of course perfectly well be summe...
[ 3 ]
[]
[]
[ "caching", "python" ]
stackoverflow_0001997094_caching_python.txt
Q: How to connect two state circles with an arrow in tkinter? I am currently writing a fsm editor with tkinter. But, I stuck on connecting two states. I have two questions: 1) How can make the transition arrow growable according to mouse movement? 2) How can I stick the starting point of the arrow on a state and the ...
How to connect two state circles with an arrow in tkinter?
I am currently writing a fsm editor with tkinter. But, I stuck on connecting two states. I have two questions: 1) How can make the transition arrow growable according to mouse movement? 2) How can I stick the starting point of the arrow on a state and the end point of the arrow on another state? PS. Do you think the do...
[ "Here's an example that shows the concept. In a nutshell, use tags to associate lines with boxes, and simply adjust the coordinates appropriately when the user moves the mouse.\nRun the example, then click and drag from within the beige box.\nOf course, for production code you need to make a more general solution, ...
[ 5, 3 ]
[]
[]
[ "fsm", "python", "tkinter" ]
stackoverflow_0001996377_fsm_python_tkinter.txt
Q: How to get something to appear on every page in Django? I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so: # views.py def page0(request): return render_to_response( "core/ind...
How to get something to appear on every page in Django?
I'm curious as to the best-practise way to handle having something appear on every page, or on a number of pages without having to assign the data manually to every page like so: # views.py def page0(request): return render_to_response( "core/index.html", { "locality": getCityForm(reque...
[ "You want a context processor. The data they generate is included in every context created as a RequestContext. They are perfect for this.\nCombined with base templates that show common things, you can get rid of lots of need for copying and pasting code.\n", "use inheritance in the templating engine:\nhave a b...
[ 16, 3, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001997109_django_python.txt
Q: How are exceptions implemented under the hood? Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start...
How are exceptions implemented under the hood?
Just about everyone uses them, but many, including me simply take it for granted that they just work. I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me. Now, C++ is probably a good place to start since you can throw anything in that language. Als...
[ "Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are:\n\nnotifications (a generalization of exceptions, originally from some old Lisp object system, now implemented in e.g. CommonLisp and Ioke), \ncontinuations (a more structured form of GO...
[ 50, 24, 19, 7, 6, 5, 4, 3, 1, 1 ]
[]
[]
[ "c", "c++", "exception", "python" ]
stackoverflow_0001995734_c_c++_exception_python.txt
Q: Can't find thread.py What does this code mean? try: import thread except ImportError: del _sys.modules[__name__]#why raise But I can't find thread.py. why,del _sys.modules[__name__] A: That code from Python's threading.py is trying to load the C implementation of the thread module. If it fails (for...
Can't find thread.py
What does this code mean? try: import thread except ImportError: del _sys.modules[__name__]#why raise But I can't find thread.py. why,del _sys.modules[__name__]
[ "That code from Python's threading.py is trying to load the C implementation of the thread module. If it fails (for some reason this hasn't been compiled, as it would be with all Python distributions) then it deletes itself from the list of modules so that threading doesn't show up as having been imported.\nIf you...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001997244_python.txt
Q: How to install imagingft in OSX and Ubuntu? I'm using PIL 1.1.6 to render a truetype font on my local Windows machine. I'd like to be able to get the application running in OSX and Ubuntu (server). So far the instructions I've found all deal with specific ports repositories on OSX (Darwinports, Macports, etc.) o...
How to install imagingft in OSX and Ubuntu?
I'm using PIL 1.1.6 to render a truetype font on my local Windows machine. I'd like to be able to get the application running in OSX and Ubuntu (server). So far the instructions I've found all deal with specific ports repositories on OSX (Darwinports, Macports, etc.) or very outdated instructions for Linux. Has anyon...
[ "Long ago I'd switched my OSX (Snow Leopard) python version from the default 2.6 back to 2.5 for compatibility reasons on a project I had been working on. I switched it back to 2.6 and was then able to compile imagingft normally:\n./configure\nmake\nmake install\n\nI was able to do the same thing on my Ubuntu serv...
[ 0 ]
[]
[]
[ "macos", "python", "python_imaging_library", "ubuntu" ]
stackoverflow_0001967674_macos_python_python_imaging_library_ubuntu.txt
Q: How does Gedit expose its api to python for plugins? I'm starting a medium (academic) project in C++ for which I need users to be able to write small scripts, which interact directly with the main program. My first thought as an aproach to this was to make something like Gedit does with it's plugins (in fact I tho...
How does Gedit expose its api to python for plugins?
I'm starting a medium (academic) project in C++ for which I need users to be able to write small scripts, which interact directly with the main program. My first thought as an aproach to this was to make something like Gedit does with it's plugins (in fact I thought about it because it is something very similar to what...
[ "Fortunately, gedit's plugin framework can be used. You could use Ethos, which is the same plugin framework gedit uses, only without gedit.\n" ]
[ 3 ]
[]
[]
[ "c++", "gedit", "plugins", "python" ]
stackoverflow_0001997427_c++_gedit_plugins_python.txt
Q: Find which python modules are being imported What's an easy way of finding all the python modules from a particular package that are being used in an application? A: sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules. See: http://docs.python.org/library...
Find which python modules are being imported
What's an easy way of finding all the python modules from a particular package that are being used in an application?
[ "sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules.\nSee: http://docs.python.org/library/sys.html#sys.modules\n", "You could use python -v, which will emit messages about every imported module:\n$ echo 'print \"hello world\"' > helo.py\n$ python -v helo...
[ 40, 35, 1, 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0001997449_package_python.txt
Q: Django -vs- Grails -vs-? I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java mon...
Django -vs- Grails -vs-?
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ...
[ "You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts:\nIDE's:\nDjango works really well in Eclipse, Grails works really well in IntelliJ Idea.\nDebugging:\nPractically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debuggi...
[ 32, 10, 10, 10, 3, 3, 1, 1, 1 ]
[]
[]
[ "django", "frameworks", "python" ]
stackoverflow_0000075798_django_frameworks_python.txt
Q: Determining the number of possible combinations I'm trying to figure out how many possible ways there are to combine various elements form this string. "{Hello|Hi|Hey} {world|earth}{!|.|?}" Where one item (separated by a pipe/|) is selected at random from each group ({}) and combined into a single string. So the ...
Determining the number of possible combinations
I'm trying to figure out how many possible ways there are to combine various elements form this string. "{Hello|Hi|Hey} {world|earth}{!|.|?}" Where one item (separated by a pipe/|) is selected at random from each group ({}) and combined into a single string. So the above "template" could produce: Hello world. Hi earth...
[ "Well, there are 3 x 2 x 3 = 18 combinations in your first example.\nYour second example is 3 x 4 x 2 x 3 = 72 combinations.\nI'm not entirely sure what you mean by {a|b}|{c|d} though, I'm assuming you mean pick one of either (a or b) or (c or d), which is 4 choices.\nYou might want to read up on combinations here ...
[ 6, 0 ]
[]
[]
[ "combinatorics", "math", "python", "statistics" ]
stackoverflow_0001997614_combinatorics_math_python_statistics.txt
Q: sharing objects between module in GAE To share a state(e.g. user) between a module in django people sometime use thread local storage, but as google app engine follows CGI standard and keeps state of a request in os.environ , can I share objects between two modules just by setting it e.g. mod1.my_data = {} and now...
sharing objects between module in GAE
To share a state(e.g. user) between a module in django people sometime use thread local storage, but as google app engine follows CGI standard and keeps state of a request in os.environ , can I share objects between two modules just by setting it e.g. mod1.my_data = {} and now any other module can get handle to my_data...
[ "Later requests that happen to be served on the same process (you can't control that) would access just the same mod1.my_data object (unless you take pains to reassign it as a fresh object at the start of each request, of course).\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001997663_google_app_engine_python.txt
Q: how to start a thread when django runserver? I want to start a thread when django project runserver successfully. where can I put the create-thread-and-start code? Is there any hook for the django runserver? A: Why would you want to do that? runserver is for development only, it should never be used in producti...
how to start a thread when django runserver?
I want to start a thread when django project runserver successfully. where can I put the create-thread-and-start code? Is there any hook for the django runserver?
[ "Why would you want to do that? runserver is for development only, it should never be used in production. And if you're running via Apache, it should manage threads/processes for you anyway.\n", "Agree with the above answer, you probably don't want to do this. Runserver should be used for development only. Once y...
[ 7, 0 ]
[]
[]
[ "django", "multithreading", "python" ]
stackoverflow_0001994507_django_multithreading_python.txt
Q: what is the 'decimal.getcontext().copy()' mean import decimal # Decimals a=decimal.getcontext().copy() print a what is the useful of a. A: I am answering assuming a novice. "a" is a variable. Variable is a logical unit that keeps a value/string etc on computer's memory while execut...
what is the 'decimal.getcontext().copy()' mean
import decimal # Decimals a=decimal.getcontext().copy() print a what is the useful of a.
[ "I am answering assuming a novice.\n\"a\" is a variable. Variable is a logical unit that keeps a value/string etc on computer's memory while executing a program. As an example if you are going to add 1 and 2 and get the answer, you should create a \"variable\" in memory say \"a\" and assign the value of 1 + 2 for \...
[ 7, 5, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001997795_python.txt
Q: How to query a contact for its PubSub using Python's xmpp? I'm writing a XMPP bot in Python (using xmpppy). I want (after user's request) check his PubSub status (mood, tune) and do something with it. How do I do that? I know how to parse a stanza send by user when he changes status but I don't know how to force h...
How to query a contact for its PubSub using Python's xmpp?
I'm writing a XMPP bot in Python (using xmpppy). I want (after user's request) check his PubSub status (mood, tune) and do something with it. How do I do that? I know how to parse a stanza send by user when he changes status but I don't know how to force him to send me such stanza.
[ "Read XEP-163. Essentially, you need to implement the send-side of entity caps (XEP-115), so that you send your presence like this:\n<presence from='romeo@example.net/home'>\n <c xmlns='http://jabber.org/protocol/caps' \n hash='sha-1'\n node='http://example.com/MYBOT'\n ver='/FpawanrJ31ymsv4ApCMGcyJmU...
[ 3 ]
[]
[]
[ "bots", "python", "xmpp" ]
stackoverflow_0001986169_bots_python_xmpp.txt
Q: Datetime problem at start of month in Python I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this t...
Datetime problem at start of month in Python
I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date ...
[ "minus_seven = today - datetime.timedelta(days = 7)\n\n", "The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:\n\nBetween 1 and the number of days in the given month of the given year.\n\nYou can see why this works later in the month; but for the first few d...
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001998198_python.txt
Q: Python's Regular Expression Source String Length In Python Regular Expressions, re.compile("x"*50000) gives me OverflowError: regular expression code size limit exceeded but following one does not get any error, but it hits 100% CPU, and took 1 minute in my PC >>> re.compile(".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000...
Python's Regular Expression Source String Length
In Python Regular Expressions, re.compile("x"*50000) gives me OverflowError: regular expression code size limit exceeded but following one does not get any error, but it hits 100% CPU, and took 1 minute in my PC >>> re.compile(".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?"*50000) <_sre.SRE_Pattern object at 0x03FB0020> Is that nor...
[ "The difference is that \".*?.*?.*?.*?.*?.*?.*?.*?.*?.*?\"*50000 can be reduced to \".*?\", while \"x\"*50000 has to generate 50000 nodes in the FSM (or a similar structure used by the regex engine).\nEDIT: Ok, I was wrong. It's not that smart. The reason why \"x\"*50000 fails, but \".*?x\"*50000 doesn't is that th...
[ 6, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001998261_python_regex.txt
Q: Replace string in a specific line using python I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names a...
Replace string in a specific line using python
I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The...
[ "some notes: \n\nstring.replace and re.sub are not in-place so you should be assigning the return value back to your variable.\nglob.glob is better for finding files in a directory matching a defined pattern...\nmaybe you should be checking if the directory already exists before creating it (I just assumed this, t...
[ 9, 5, 5, 4, 0 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0001998233_python_replace.txt
Q: Wrong encoding of text, in Django? "query" = джазовыми For some reason...when I display it via: {{ query|safe }} I get this: %u0434%u0436%u0430%u0437%u043E%u0432%u044B%u043C%u0438 A: Would the query be set from the source, this would solve it: query = u"джазовыми" (provided that for example your file encoding...
Wrong encoding of text, in Django?
"query" = джазовыми For some reason...when I display it via: {{ query|safe }} I get this: %u0434%u0436%u0430%u0437%u043E%u0432%u044B%u043C%u0438
[ "Would the query be set from the source, this would solve it:\nquery = u\"джазовыми\"\n\n(provided that for example your file encoding is utf-8 and you have corresponding line\n# -*- coding: UTF-8 -*-\n\nin the beginning)\nBut I guess the query is entered by user. The error seems to be located in that part of your ...
[ 2 ]
[]
[]
[ "django", "encoding", "python", "templates", "utf_8" ]
stackoverflow_0001998362_django_encoding_python_templates_utf_8.txt
Q: Is it safe to use user input for Python's regular expressions? I would like to let my users use regular expressions for some features. I'm curious what the implications are of passing user input to re.compile(). I assume there is no way for a user to give me a string that could let them execute arbitrary code. ...
Is it safe to use user input for Python's regular expressions?
I would like to let my users use regular expressions for some features. I'm curious what the implications are of passing user input to re.compile(). I assume there is no way for a user to give me a string that could let them execute arbitrary code. The dangers I have thought of are: The user could pass input that r...
[ "I have worked on a program that allows users to enter their own regex and you are right - they can (and do) enter regex that can take a long time to finish - sometimes longer than than the lifetime of the universe. What is worse, while processing a regex Python holds the GIL, so it will not only hang the thread t...
[ 22, 6, 4, 1, 0, 0 ]
[]
[]
[ "python", "regex", "sanitize", "user_input" ]
stackoverflow_0001998104_python_regex_sanitize_user_input.txt
Q: Parsing XML with SAX/Python + no validation I am new to python and I'm trying to parse a XML file with SAX without validating it. The head of my xml file is: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE n:document SYSTEM "schema.dtd"> <n:document.... and I've tried to parse it with python 2.5.2: from xml.sax ...
Parsing XML with SAX/Python + no validation
I am new to python and I'm trying to parse a XML file with SAX without validating it. The head of my xml file is: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE n:document SYSTEM "schema.dtd"> <n:document.... and I've tried to parse it with python 2.5.2: from xml.sax import make_parser, handler import sys parser = ...
[ "expatreader considers the DTD external subset as an external general entity. So the feature you want is:\nparser.setFeature(handler.feature_external_ges, False)\n\nHowever, it's a bit dodgy pointing the DTD external subset to a non-existant URL; as this shows, it's not only validating parsers that read it.\n" ]
[ 4 ]
[]
[]
[ "python", "sax", "validation", "xml" ]
stackoverflow_0001998425_python_sax_validation_xml.txt
Q: How can I create a static variable in a Python class via the C API? I want to do the equivalent of class Foo(object): bar = 1 using Python's C API. In other words, I want to create a Python class which has a static variable, using C. How can I do this? A: Found it! It's just a matter of setting the tp_dict el...
How can I create a static variable in a Python class via the C API?
I want to do the equivalent of class Foo(object): bar = 1 using Python's C API. In other words, I want to create a Python class which has a static variable, using C. How can I do this?
[ "Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:\nPyTypeObject type;\n// ...other initialisation...\ntype.tp_dict = PyDict_New();\nPyDict_...
[ 5, 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001952379_c_python.txt
Q: How do i use Django and UTF-8 content-type for template? When I do: return render_to_response() in Django. How do I set the content-type to UTF-8? So that everything displayed is UTF-8? A: django use UTF-8 as default encoding, but this can be modified with settings.DEFAULT_CHARSET. Be sure, in your HTML templat...
How do i use Django and UTF-8 content-type for template?
When I do: return render_to_response() in Django. How do I set the content-type to UTF-8? So that everything displayed is UTF-8?
[ "django use UTF-8 as default encoding, but this can be modified with settings.DEFAULT_CHARSET.\nBe sure, in your HTML template, to set UTF-8 for the HTML page also :\n<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" /> \n\n" ]
[ 5 ]
[]
[]
[ "django", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0001998987_django_encoding_python_unicode_utf_8.txt
Q: Understanding while loop I am a newbie in Python. I can understand what a for loop does, but can't really understand what a while loop does. I knew it does repeat something while the condition is true, easy to say, but it's really hard to use it as far as I think. Say, an example here: while 1: rate(100) #what ...
Understanding while loop
I am a newbie in Python. I can understand what a for loop does, but can't really understand what a while loop does. I knew it does repeat something while the condition is true, easy to say, but it's really hard to use it as far as I think. Say, an example here: while 1: rate(100) #what does this rate(100) do? try...
[ "The example code you have provided is equivalent to this:\nwhile True:\n rate(100) #what does this rate(100) do?\n try:\n 'something'\n except:\n 'something else'\n\nIn Python many expressions can be tested for truth (that is evaluate to True or False when used in conditions and logical oper...
[ 3, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0001999026_python_while_loop.txt
Q: Calling a variable from another function Python I am trying to call a variable for use in another function. The variable is only in the other function and not declared as a global variable. Does anyone know how to call the other variable. The code below shows the 'retval' variable being used but it is declared in ...
Calling a variable from another function Python
I am trying to call a variable for use in another function. The variable is only in the other function and not declared as a global variable. Does anyone know how to call the other variable. The code below shows the 'retval' variable being used but it is declared in the other function. def email_results(): if make...
[ "Your make.retval is (I'm guessing from your vague question) the result of another function, make, which for some reason doesn't return retval.\nDo this\ndef make( ):\n etc. \n return retval\n\ndef email_results( retval ):\n etc.\n\nif __name__ == \"__main__\":\n retval= make()\n email_results( retva...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001999144_python.txt
Q: Determine where documents differ with Python I have been using the Python difflib library to find where 2 documents differ. The Differ().compare() method does this, but it is very slow - atleast 100x slower for large HTML documents compared to the diff command. How can I efficiently determine where 2 documents dif...
Determine where documents differ with Python
I have been using the Python difflib library to find where 2 documents differ. The Differ().compare() method does this, but it is very slow - atleast 100x slower for large HTML documents compared to the diff command. How can I efficiently determine where 2 documents differ in Python? (Ideally I am after the positions r...
[ "a = open(\"file1.txt\").readlines()\nb = open(\"file2.txt\").readlines()\ncount = 0\npos = 0\n\nwhile 1:\n count += 1\n try:\n al = a.pop(0)\n bl = b.pop(0)\n if al != bl:\n print \"files differ on line %d, byte %d\" % (count,pos)\n pos += len(al)\n except IndexError...
[ 3, 2, 1 ]
[]
[]
[ "diff", "difflib", "document", "python", "sequencematcher" ]
stackoverflow_0001999019_diff_difflib_document_python_sequencematcher.txt
Q: Is there a Scrum plugin for the Roundup Issue Tracker? Is there a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac? I realize that Roundup is an issue tracking system, whereas Trac is designed to be an integrated project management, SCM, and issue tracker. Therefore, maybe a better question wou...
Is there a Scrum plugin for the Roundup Issue Tracker?
Is there a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac? I realize that Roundup is an issue tracking system, whereas Trac is designed to be an integrated project management, SCM, and issue tracker. Therefore, maybe a better question would be—Is anyone aware of a, preferably Python based, Scrum t...
[ "After researching this some more, it appears that there is not a Scrum plugin for the Roundup Issue Tracker similar to Agilo for Trac. However, I was able to find Ajellito (formerly Agilito). From the Ajellito website:\n\nSimple, web-based Agile / Scrum project management tool built in Django\n Ajellito aims to d...
[ 0 ]
[]
[]
[ "agile", "python", "roundup", "scrum", "trac" ]
stackoverflow_0001977458_agile_python_roundup_scrum_trac.txt
Q: How to use Staticgenerator with Django + Apache + mod_python I have currently an enviroment with Django + Apache via mod_python. How can I use Staticgenerator without nginx, just with Apache and mod_python? Thank you. A: Perhaps this page from the webfaction forum will help: http://forum.webfaction.com/viewtopi...
How to use Staticgenerator with Django + Apache + mod_python
I have currently an enviroment with Django + Apache via mod_python. How can I use Staticgenerator without nginx, just with Apache and mod_python? Thank you.
[ "Perhaps this page from the webfaction forum will help:\n\nhttp://forum.webfaction.com/viewtopic.php?id=1945\n\n", "Staticgenerator is designed to be used with a front-end http server. The example configuration as shown on the Github Staticgenerator page is using Nginx as the front-end http server and Apache as t...
[ 0, 0 ]
[]
[]
[ "apache", "django", "mod_python", "python" ]
stackoverflow_0001275270_apache_django_mod_python_python.txt
Q: Django: Is there a way to have the "through" model in a ManyToManyField in a different app to the model containing the ManyToManyField? Lets say I have two django apps: competitions - which will handle competition data entries - which will handle functionality relating to entering competitors into competitions I...
Django: Is there a way to have the "through" model in a ManyToManyField in a different app to the model containing the ManyToManyField?
Lets say I have two django apps: competitions - which will handle competition data entries - which will handle functionality relating to entering competitors into competitions In the competitions app I have a model which represents a section of a competition: class Division(models.Model): competition = models.For...
[ "It seems like I've found an answer, which works more consistently :)\nThe Django documentation on the ForeignKey class says:\n\nTo refer to models defined in another\n application, you can explicitly\n specify a model with the full\n application label. For example, if the\n Manufacturer model above is defined ...
[ 16, 5 ]
[]
[]
[ "django", "django_apps", "django_models", "manytomanyfield", "python" ]
stackoverflow_0001970365_django_django_apps_django_models_manytomanyfield_python.txt
Q: "download link " fails in IE I was trying to implement a "download link" and put it beside one of my report table so that users can download a csv file and open it with applications like Excel. The records are generated dynamically based on the query made by users. So somewhere in my controller there's something l...
"download link " fails in IE
I was trying to implement a "download link" and put it beside one of my report table so that users can download a csv file and open it with applications like Excel. The records are generated dynamically based on the query made by users. So somewhere in my controller there's something like: response.headers['Content-Typ...
[ "I'm not sure what Cache control headers are/were being sent but IE has a bug with downloaded files like you are experiencing.\nFor IE, you MUST enable caching. When IE loads files (e.g. Excel files), in Excel, it loads them from the cache directory, thus if you don't cache it, Excel (or your other app) will fail ...
[ 5, 2, 0 ]
[]
[]
[ "internet_explorer", "python", "web2py" ]
stackoverflow_0001999950_internet_explorer_python_web2py.txt
Q: Python string splitting If I have a string 'x=10', how can I extract the 10 as an integer using one line of code? A: >>> s = "x=10" >>> int(s.split('=')[-1]) 10 A: s = 'x=10' i = int(s[2:]) A: Sure: a = "x=10" b = int(a.split('=')[1]) A: result = int(my_string.rpartition("=")[-1]) Note, however, that if ...
Python string splitting
If I have a string 'x=10', how can I extract the 10 as an integer using one line of code?
[ ">>> s = \"x=10\"\n>>> int(s.split('=')[-1])\n10\n\n", "s = 'x=10' \ni = int(s[2:])\n\n", "Sure:\na = \"x=10\"\nb = int(a.split('=')[1])\n\n", "result = int(my_string.rpartition(\"=\")[-1])\n\nNote, however, that if there is anything else after the = sign the function will break.\nSo x=10, x=560, and x=101000...
[ 7, 3, 3, 3, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0002000202_python_split_string.txt
Q: sqlalchemy cascade and association objects My database structure is something like this (I'm using declarative style): class Character(Base): __tablename__="characters" id = Column(Integer, primary_key=True) name = Column(String) player = Column(String) inventory = relation(Inventory) class It...
sqlalchemy cascade and association objects
My database structure is something like this (I'm using declarative style): class Character(Base): __tablename__="characters" id = Column(Integer, primary_key=True) name = Column(String) player = Column(String) inventory = relation(Inventory) class Item(Base): __tablename__="items" id = Col...
[ "Session.delete() method just marks an instance as \"to be deleted\", so your relation won't change untill you flush changes to database independent on cascade rules. On other hand you can just remove Inventory instance from character.inventory collection, then having 'delete-orphan' cascade rule will mark removed ...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001998962_python_sqlalchemy.txt