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: Can anyone summarize the noticeable difference between list, tuple, dictionary in Python? A little bit confusion about some data structure in Python. Could any expert give some rules of thumb in order to help me get out of this mess? A: They are all covered in: Python - Data Structures List - when you have dat...
Can anyone summarize the noticeable difference between list, tuple, dictionary in Python?
A little bit confusion about some data structure in Python. Could any expert give some rules of thumb in order to help me get out of this mess?
[ "They are all covered in:\nPython - Data Structures\n\nList - when you have data that has some order\nTuple - when ordered data is to be immutable\nDictionary - when data is related by key - value pairs\n\n", "My take on the most important concepts regarding list/tuple/dict:\nList - When you have a collection of ...
[ 8, 4 ]
[]
[]
[ "dictionary", "list", "python", "tuples" ]
stackoverflow_0005003229_dictionary_list_python_tuples.txt
Q: Problem with static variable I'm trying to declare static variable and now my code is: class StaticClass: varA = 'hello' @staticmethod def staticMethod(): varA='bye' Result of code below is hello. Why not 'bye' ? StaticClass.staticMethod() print StaticClass.varA A: The code in staticMethod...
Problem with static variable
I'm trying to declare static variable and now my code is: class StaticClass: varA = 'hello' @staticmethod def staticMethod(): varA='bye' Result of code below is hello. Why not 'bye' ? StaticClass.staticMethod() print StaticClass.varA
[ "The code in staticMethod() assigns the string bye to the local variable varA, then returns, dropping the local variable. An assignment inside a function always creates local variables in Python. A staticmethod in Python has no means of accessing the class at all -- you need a classmethod for this purpose:\nclass...
[ 4, 1 ]
[]
[]
[ "python", "static" ]
stackoverflow_0005003584_python_static.txt
Q: Whitespace problem with python and lxml I'm trying do scrape this website with python and lxml. Its working greate on my local machine, but when i try to deploy it on my server and run the script i got problems with whitespaces. URL: http://www.samsungapps.com/topApps/topAppsDetail.as?productId=G00000467050&listYN...
Whitespace problem with python and lxml
I'm trying do scrape this website with python and lxml. Its working greate on my local machine, but when i try to deploy it on my server and run the script i got problems with whitespaces. URL: http://www.samsungapps.com/topApps/topAppsDetail.as?productId=G00000467050&listYN=Y Problem part in html: <tr> ...
[ "Adding .strip() works for me\nimport urllib2,StringIO\nfrom lxml import etree\n\nseite = urllib2.urlopen(\"http://www.samsungapps.com/topApps/topAppsDetail.as?productId=G00000467050&listYN=Y\")\nhtml = seite.read()\nseite.close()\nparser = etree.HTMLParser()\ntree = etree.parse(StringIO.StringIO(html), parser)\nxp...
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0004992946_lxml_python.txt
Q: Decode the bytes Following piece of code is from zipfile.py. self.fp.write(zinfo.FileHeader()) def FileHeader(self): header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, flag_bits, self.compress_type, CRC, dosdate, CRC, ...
Decode the bytes
Following piece of code is from zipfile.py. self.fp.write(zinfo.FileHeader()) def FileHeader(self): header = struct.pack(structFileHeader, stringFileHeader, self.extract_version, self.reserved, flag_bits, self.compress_type, CRC, dosdate, CRC, compress...
[ "There's nothing to decode. The bytes make up a zip file, and you can extract the contents of the archive with creative use of zipfile.\n" ]
[ 4 ]
[]
[]
[ "byte", "decode", "porting", "python" ]
stackoverflow_0005004201_byte_decode_porting_python.txt
Q: Python: Using locals() to print dictionary value One of the nicest tools in Python is locals() in string formatting: >>> st="asdasd" >>> print "%(st)s" % locals() asdasd However, this can't be done with dictionary values: >>> d={1:2, 3:4} >>> print "%(d[1])s" % locals() Traceback (most recent call last): File "...
Python: Using locals() to print dictionary value
One of the nicest tools in Python is locals() in string formatting: >>> st="asdasd" >>> print "%(st)s" % locals() asdasd However, this can't be done with dictionary values: >>> d={1:2, 3:4} >>> print "%(d[1])s" % locals() Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'd[1]' Any id...
[ ">>> d={1:2, 3:4}\n>>> print '{0[1]}'.format(d)\n2\n>>> print '{0[d][1]}'.format(locals())\n2\n>>> print '{[d][1]}'.format(locals())\n2\n>>>\n\nthe last one only works with 2.7\n" ]
[ 6 ]
[]
[]
[ "dictionary", "python", "string_formatting", "syntactic_sugar" ]
stackoverflow_0005004314_dictionary_python_string_formatting_syntactic_sugar.txt
Q: Python MySQLdb string substitution without added quotations I'd like to use string substitution for a comma-separated list, such as: query = """SELECT id, name, image_id FROM users WHERE id IN (%s) """ values = (','.join(uids)) results = dbc.getAll(query, values This executes the ...
Python MySQLdb string substitution without added quotations
I'd like to use string substitution for a comma-separated list, such as: query = """SELECT id, name, image_id FROM users WHERE id IN (%s) """ values = (','.join(uids)) results = dbc.getAll(query, values This executes the query: SELECT id, name, image_id FROM users WHERE id IN ('1,2,3')...
[ "Let MySQLdb do the entire argument substitution. In this case, the expected argument, values, should be the sequence (1,2,3), rather than the string '1,2,3':\nquery = \"\"\"SELECT id, name, image_id\n FROM users\n WHERE id IN %s\n \"\"\" \nvalues = uids\nresults = dbc.getAll(query,...
[ 3, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003936957_mysql_python.txt
Q: Global variables in Ironpython I'm having terrible trouble trying to understand ironpython scoping rules. With the following script: global data // function for call xml-rpc def CallListDatabases(self): global synC, synCtx, result, data self.synCtx = synC.Current service = XmlRpcService("h...
Global variables in Ironpython
I'm having terrible trouble trying to understand ironpython scoping rules. With the following script: global data // function for call xml-rpc def CallListDatabases(self): global synC, synCtx, result, data self.synCtx = synC.Current service = XmlRpcService("http://localhost:8000/rpc") r...
[ "First of all, you don't seem to ever be calling any of the functions you have defined. If you are calling the functions, it appears that the return value of response.TryCast(clr.GetClrType(Array[str])) is an empty list. Have you tried printing the value of result within SetCallResult()? I'd bet that it's [].\n" ]
[ 1 ]
[]
[]
[ "ironpython", "python", "xml_rpc" ]
stackoverflow_0005003778_ironpython_python_xml_rpc.txt
Q: Can not see the DB query output in python I'm execute a simple mssql query from python. I can see in the profiler that the query reach the DB. The query has 1 row of answer. I fail to see the output in the Python shell I run the code below import pymssql conn = pymssql.connect(host='SQL01', user='user', password=...
Can not see the DB query output in python
I'm execute a simple mssql query from python. I can see in the profiler that the query reach the DB. The query has 1 row of answer. I fail to see the output in the Python shell I run the code below import pymssql conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True...
[ "You can call fetchone() or fetchall() after execute to get the data from that query. \nimport pymssql \nconn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True) \ncur = conn.cursor() \ncur.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') \nprint cur...
[ 3, 1 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0005004472_pymssql_python.txt
Q: Advantages of creating own corpus in NLTK I have a large amount of text in Mysql tables. I want to do some statistical analysis and later on some NLP on my text using the NLTK toolkit. I have two choices: Extract all the text at once from my DB table (maybe putting them in a file if needed) and use the NLTK funct...
Advantages of creating own corpus in NLTK
I have a large amount of text in Mysql tables. I want to do some statistical analysis and later on some NLP on my text using the NLTK toolkit. I have two choices: Extract all the text at once from my DB table (maybe putting them in a file if needed) and use the NLTK functions Extract the text and turning it into a "co...
[ "Well after reading a lot I found out the answer.\nThere are several very useful functions such as collocations,search,common_context,similar that can be used on texts that are saved as corpus in NLTK. implementing them yourself takes quite some time. If Select my text from the database and put in a file and use th...
[ 3 ]
[]
[]
[ "database", "mysql", "nltk", "python" ]
stackoverflow_0005002913_database_mysql_nltk_python.txt
Q: Control access to WebDav/Apache using Python I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help ...
Control access to WebDav/Apache using Python
I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user and p...
[ "First, for you other readers, my authentication was done against Django using a WSGI authentication script.\nThen, there's the meat of the question, giving each Django user, in this case, their own WebDav dir separated from other users. Assuming the following WebDAV setup in the Apache virtual sites configuration ...
[ 1, 0, 0 ]
[]
[]
[ "apache", "django", "python", "webdav" ]
stackoverflow_0000700480_apache_django_python_webdav.txt
Q: Has anyone used Sphinx to document a C++ project? Sphinx is a new documentation tool for Python. It looks very nice. What I'm wondering is: How suitable this is for documenting a C++ project? Are there any tools for converting existing documentation (e.g. doxygen) to Sphinx format? Are there online/downloadable e...
Has anyone used Sphinx to document a C++ project?
Sphinx is a new documentation tool for Python. It looks very nice. What I'm wondering is: How suitable this is for documenting a C++ project? Are there any tools for converting existing documentation (e.g. doxygen) to Sphinx format? Are there online/downloadable examples of C++ projects that use Sphinx? Any tips from ...
[ "As mentioned here and here, \n\nSphinx native C++ support is related to highlighting/formatting/referencing, not in-code documentation extraction\nbreathe has developed out of the discussion that chrisdew referenced\n\n[Edit inserted below]: \nI tested the doxygen+breathe+sphinx toolchain on a multi-10k \nC++ libr...
[ 23, 11, 4 ]
[]
[]
[ "c++", "documentation_generation", "python", "python_sphinx" ]
stackoverflow_0000835043_c++_documentation_generation_python_python_sphinx.txt
Q: PyYaml to SnakeYaml --- AWT-EventQueue-0" Can't construct a java object for tag:yaml.org,2002:java/object: I am passing Yaml created with PyYaml to SnakeYaml and Snakeyaml does not seem to recognize anything beyond the first line where !! exists and python/object is declared. I already have identical objects setup...
PyYaml to SnakeYaml --- AWT-EventQueue-0" Can't construct a java object for tag:yaml.org,2002:java/object:
I am passing Yaml created with PyYaml to SnakeYaml and Snakeyaml does not seem to recognize anything beyond the first line where !! exists and python/object is declared. I already have identical objects setup in Java. Is there an example out there that shows a loadAll into an object array where the object type is asser...
[ "To achieve the same result you may:\n\nconfigure PyYAML to skip the tag (exactly as you did with the comment \"Convert objects to a dictionary of their representation\")\nconfigure SnakeYAML to create the object you expect (exactly as you did with \"projectData = gson.fromJson(mystr, ProjectData[].class); \")\n\nI...
[ 2, 0 ]
[]
[]
[ "java", "python", "pyyaml", "snakeyaml", "yaml" ]
stackoverflow_0004977135_java_python_pyyaml_snakeyaml_yaml.txt
Q: Django: how to use upload_to property of an ImageField I'm writing a large application with image uploads. Here is my model: class GallryImage(models.Model): # ... image = models.ImageField(max_length=255, upload_to='gallery', height_field='width', width_field='height') width = models.IntegerField(...
Django: how to use upload_to property of an ImageField
I'm writing a large application with image uploads. Here is my model: class GallryImage(models.Model): # ... image = models.ImageField(max_length=255, upload_to='gallery', height_field='width', width_field='height') width = models.IntegerField() height = models.IntegerField() # ... And here is...
[ "The forms framework should take care of this for you. No need to save the files by hand unless you want to store them in some container other than your filesystem.\nclass UploadImageForm(forms.ModelForm):\n class Meta:\n model = GallryImage\n...\n# Sample view\ndef upload_file(request):\n if request.m...
[ 5 ]
[]
[]
[ "django", "dry", "file_upload", "python" ]
stackoverflow_0005005181_django_dry_file_upload_python.txt
Q: Calling activateWindow on QDialog sends window to background I am debugging certain application written with C++/Qt4. On Linux it has problems that with certain window managers (gnome-wm/metacity), the main window (based on QDialog) is created in the background (it's not raised). I managed to re-create the scenari...
Calling activateWindow on QDialog sends window to background
I am debugging certain application written with C++/Qt4. On Linux it has problems that with certain window managers (gnome-wm/metacity), the main window (based on QDialog) is created in the background (it's not raised). I managed to re-create the scenario using PyQt4 and following code: from PyQt4.QtCore import * from ...
[ "I. too, have seen this behaviour. \nAccording to the documentation: \n\nOn X11, the result depends on the Window Manager\n\nIt appears that Gnome is taking the same stance as Microsoft Windows in not allowing an application to interrupt what the user is currently doing in another application (in this case Terminal...
[ 1, 0 ]
[]
[]
[ "c++", "linux", "pyqt", "python", "qt" ]
stackoverflow_0002788518_c++_linux_pyqt_python_qt.txt
Q: From where can we download the python dlls email, getpass, imaplib, os I am searching to download the python dlls email, getpass, imaplib, os and use that in vb.net to get the gmail email with attachments A: If you're using VB.net, I would look into some libraries written for the .NET platform. Just googling f...
From where can we download the python dlls email, getpass, imaplib, os
I am searching to download the python dlls email, getpass, imaplib, os and use that in vb.net to get the gmail email with attachments
[ "If you're using VB.net, I would look into some libraries written for the .NET platform. Just googling for \".NET IMAP client\" revealed several seemingly good links for a Open Source .NET IMAP Client, IMAP Client library using C# and Accessing Imap in C#.\n", "Python doesn't have DLLs which you can simply use w...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005005613_python.txt
Q: Python 3 hosting I am looking for companies hosting websites developed in Python 3 and CherryPy. Webfaction looks good, but it is limited to Linux servers, and my site has been designed and tested under Windows. Can anyone summarise (or point me to) the changes I will have to make to my code in order to get it t...
Python 3 hosting
I am looking for companies hosting websites developed in Python 3 and CherryPy. Webfaction looks good, but it is limited to Linux servers, and my site has been designed and tested under Windows. Can anyone summarise (or point me to) the changes I will have to make to my code in order to get it to run under Linux? I g...
[ "You can use amazon EC2 and configure your OS as you wish.\nhttp://aws.amazon.com/ec2/\n", "You can buy inexpensive VPS hosting and configure it the way you like, Python and all. This way is preferable if you want to tweak other parts of the stack later, e.g. switch to a different WSGI implementation.\nAlso you c...
[ 3, 1 ]
[]
[]
[ "cherrypy", "hosting", "python", "python_3.x" ]
stackoverflow_0004965114_cherrypy_hosting_python_python_3.x.txt
Q: unable to access website with urllib and proxy I've opened a ssh tunnel with ssh -D localhost:5678 me@server.com and I want to use it in my python3 application. #!/usr/bin/python3.1 # -*- coding:Utf-8 -*- import urllib.request proxyhand = urllib.request.ProxyHandler({"socks" : "http://localhost:5678"}) opener = ...
unable to access website with urllib and proxy
I've opened a ssh tunnel with ssh -D localhost:5678 me@server.com and I want to use it in my python3 application. #!/usr/bin/python3.1 # -*- coding:Utf-8 -*- import urllib.request proxyhand = urllib.request.ProxyHandler({"socks" : "http://localhost:5678"}) opener = urllib.request.build_opener(proxyhand) page = opener...
[ "Should you be using http as the protocol, not socks? Thus:\nproxyhand = urllib.request.ProxyHandler({\"http\" : \"http://localhost:5678\"})\n\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "ssh_tunnel", "urllib" ]
stackoverflow_0005006249_proxy_python_ssh_tunnel_urllib.txt
Q: Specifying end of string sentinels in Python prior to constructing a suffix array I'm implementing algorithms in http://portal.acm.org/citation.cfm?id=1813708 that utilize suffix arrays to find longest common substrings. The algorithms involve constructing a suffix array for a string that is the concatenation of a...
Specifying end of string sentinels in Python prior to constructing a suffix array
I'm implementing algorithms in http://portal.acm.org/citation.cfm?id=1813708 that utilize suffix arrays to find longest common substrings. The algorithms involve constructing a suffix array for a string that is the concatenation of a set of given strings with string separators called sentinels. So for example, if we ar...
[ "You can do this using Unicode (not UTF-8) strings. In Python 3, all strings are Unicode but in Python 2, you need the u prefix (ie. \"hello\" is not Unicode but u\"world\" is).\n>>> s = u\"string one\"\n>>> N = 3\n>>> \"\".join(unichr(ord(x) + N) for x in s)\nu'vwulqj#rqh'\n\nFor Python 3, this would be slightly s...
[ 1, 0 ]
[]
[]
[ "longest_substring", "python", "suffix_array" ]
stackoverflow_0004951982_longest_substring_python_suffix_array.txt
Q: Processing the string separated by ":" with C# I need to parse the string separated with ":" to process the contents one by one. I can implement the function with Python as follows: st = "a:b:c" h = st.split(":") for item in h: print item How can I do the same thing with C#? A: var st = "a:b:c"; foreach(var...
Processing the string separated by ":" with C#
I need to parse the string separated with ":" to process the contents one by one. I can implement the function with Python as follows: st = "a:b:c" h = st.split(":") for item in h: print item How can I do the same thing with C#?
[ "var st = \"a:b:c\";\nforeach(var item in st.Split(':'))\n Console.WriteLine(item);\n\n", "string st = \"a:b:c\";\nforeach(string item in st.Split(':'))\n Console.Write(item);\n\n", "C# has a String.Split function as well, you shouldn't need to change anything in your approach except the syntax.\n", "It'...
[ 6, 3, 1, 0 ]
[]
[]
[ "c#", "python", "split" ]
stackoverflow_0005006375_c#_python_split.txt
Q: need the average from a list of timedelta objects I have created a list of timedelta objects and i need to get the average of this list. when i try to do return (sum(delta_list)/(len(delta_list)-1)) i get TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta' I am new at working with pyth...
need the average from a list of timedelta objects
I have created a list of timedelta objects and i need to get the average of this list. when i try to do return (sum(delta_list)/(len(delta_list)-1)) i get TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta' I am new at working with python's datetime classes. I also would like to know how to...
[ "sum wants a starting value, which is 0 by default, but 0 can't be added to a timedelta so you get the error. \nYou just have to give sum a timedelta() as the start value:\n# this is the average\nreturn sum(delta_list, timedelta()) / len(delta_list)\n\nTo print it out you can do this:\nprint str(some_delta)\n\nIf y...
[ 31, 4, 3, 1 ]
[]
[]
[ "datetime", "python", "timedelta" ]
stackoverflow_0005006258_datetime_python_timedelta.txt
Q: Shear a numpy array I'd like to 'shear' a numpy array. I'm not sure I'm using the term 'shear' correctly; by shear, I mean something like: Shift the first column by 0 places Shift the second column by 1 place Shift the third colum by 2 places etc... So this array: array([[11, 12, 13], [17, 18, 19], [...
Shear a numpy array
I'd like to 'shear' a numpy array. I'm not sure I'm using the term 'shear' correctly; by shear, I mean something like: Shift the first column by 0 places Shift the second column by 1 place Shift the third colum by 2 places etc... So this array: array([[11, 12, 13], [17, 18, 19], [35, 36, 37]]) would turn...
[ "This can be done using a trick described in this answer by Joe Kington:\nfrom numpy.lib.stride_tricks import as_strided\na = numpy.array([[11, 12, 13],\n [17, 18, 19],\n [35, 36, 37]])\nshift_axis = 0\nincrease_axis = 1\nb = numpy.vstack((a, a))\nstrides = list(b.strides)\nstrides[i...
[ 8, 8, 8, 2, 0 ]
[]
[]
[ "numpy", "optimization", "premature_optimization", "python" ]
stackoverflow_0004998587_numpy_optimization_premature_optimization_python.txt
Q: Parsing pseudo code/language in Python So I need to write a parser (or simulator) which would take an input file with simple code written in my own pseudo code like language, for instance: a = 5 b = 5 * a [FOR 10] b = b * 5 [ENDFOR] [IF b>30] a = a + 3 [ENDIF] So the pseudo language only supports integer ...
Parsing pseudo code/language in Python
So I need to write a parser (or simulator) which would take an input file with simple code written in my own pseudo code like language, for instance: a = 5 b = 5 * a [FOR 10] b = b * 5 [ENDFOR] [IF b>30] a = a + 3 [ENDIF] So the pseudo language only supports integer variables, basic operations with them (+,-,/...
[ "Take a look at PLY. Python's implementation of glorious LEX/YACC. You can definitely write a compiler or interpreter for your language with this tool.\n", "Much of this may already be implemented using the examples from the pyparsing wiki, such as this one, or this one, which uses the more current operatorPreced...
[ 0, 0 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0005006774_parsing_python_xml.txt
Q: How to programmatically blur an area in a movie (in python)? I have a movie, and I want to produce a new movie out of it with an area blurred (e.g. an object, a writing or a face). The area is moving, so I must have fine control of the current frame and move the position of the blur area accordingly. Blur is an op...
How to programmatically blur an area in a movie (in python)?
I have a movie, and I want to produce a new movie out of it with an area blurred (e.g. an object, a writing or a face). The area is moving, so I must have fine control of the current frame and move the position of the blur area accordingly. Blur is an option, but also a dark mask is fine too. Now, I have a question ope...
[ "Definetively you'll need to use OpenCV, mainly due to performance issues you may have to process it in Python. See the Smooth function from the Image Filtering section of the Python documentation from OpenCV.\n", "Blurring is easy, either Avisynth or openCV will do that. If you need to track the position of a mo...
[ 0, 0 ]
[]
[]
[ "movie", "python" ]
stackoverflow_0002624091_movie_python.txt
Q: need help regarding the following regular expression i am using python with re module for regular expressions i want to remove all the characters from the string except numbers and characters. To achieve this i am using sub function Code Snippet:- >>> text="foo.bar" >>> re.sub("[^A-Z][^a-z]","",text) 'fobar' I ...
need help regarding the following regular expression
i am using python with re module for regular expressions i want to remove all the characters from the string except numbers and characters. To achieve this i am using sub function Code Snippet:- >>> text="foo.bar" >>> re.sub("[^A-Z][^a-z]","",text) 'fobar' I wanted to know why above expression removes the "o."? I am...
[ "A very important aspect to realize is that [^A-Z][^a-z] represents two characters (one for each character group), while [^A-Za-z] represents only one.\n", "Explained in detail:\nThe [^A-Z] means all characters except uppercase A to Z, the second o in foo.bar is not uppercase so it matches as a matter of fact eve...
[ 3, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005003241_python_regex.txt
Q: Trouble with Tkinter event handler inside of a class My problem is that I have a class that creates a Tkinter topclass object and then puts a field into it and I want to add an event handler that runs a method (that is also in the class) every time a button is pressed but when the event is called it says Attribu...
Trouble with Tkinter event handler inside of a class
My problem is that I have a class that creates a Tkinter topclass object and then puts a field into it and I want to add an event handler that runs a method (that is also in the class) every time a button is pressed but when the event is called it says AttributeError: Toplevel instance has no attribute 'updateSearch'...
[ "Judging solely on the indentation of your example, it appears that updateSearch is indeed not part of the class definition. \nAssuming the indentation is a markup mistake, and based on the error message you report, the other problem is that you redefine self, so 'self.updateSearch' points to the toplevel rather th...
[ 1 ]
[]
[]
[ "class", "event_handling", "python", "tkinter" ]
stackoverflow_0005007379_class_event_handling_python_tkinter.txt
Q: Twisted Threading + MapReduce on a single node/server? I'm confused about Twisted threading. I've heard and read more than a few articles, books, and sat through a few presentations on the subject of threading vs processes in Python. It just seems to me that unless one is doing lots of IO or wanting to utilize sh...
Twisted Threading + MapReduce on a single node/server?
I'm confused about Twisted threading. I've heard and read more than a few articles, books, and sat through a few presentations on the subject of threading vs processes in Python. It just seems to me that unless one is doing lots of IO or wanting to utilize shared memory across jobs, then the right choice is to use mul...
[ "The short answer to your question: no, twisted threading is not the right solution for heavy processing.\nIf you have a lot of processing to do, twisted's threading will still be subject to the GIL (Global Interpreter Lock). Without going into a long in depth explanation, the GIL is what allows only one thread at ...
[ 6 ]
[]
[]
[ "mapreduce", "multithreading", "python", "twisted" ]
stackoverflow_0005007184_mapreduce_multithreading_python_twisted.txt
Q: subprocess, Popen to run command in a module i want to call a binary program from within my module. i am having problem with subprocess finding the binary. so i have myModule/ -classWrappingBinary.py -binary_file.out and in classWrappingBinary.py i have somthing like sbp.Popen(['./binary_file.out'] which does...
subprocess, Popen to run command in a module
i want to call a binary program from within my module. i am having problem with subprocess finding the binary. so i have myModule/ -classWrappingBinary.py -binary_file.out and in classWrappingBinary.py i have somthing like sbp.Popen(['./binary_file.out'] which doesnt work. so how can i successfully call the Popen ...
[ "You can look at the variable __file__ and extract the directory information from it. The most reliable way is\nname = os.path.join(os.path.dirname(__file__) or \".\", \"binary_file.out\")\nsubprocess.Popen(name)\n\n" ]
[ 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005007842_python_subprocess.txt
Q: python style question Is it better to pass in a zipped list of pairs, or two lists that must agree in length? With two lists, I have to assert their lengths agree, but at least the parameters are named. I am asking about the prevailing style. Are there any examples of choosing one over the other from major librar...
python style question
Is it better to pass in a zipped list of pairs, or two lists that must agree in length? With two lists, I have to assert their lengths agree, but at least the parameters are named. I am asking about the prevailing style. Are there any examples of choosing one over the other from major libraries? For example, I guess ...
[ "If your function is going to effectively zip the lists anyway, I would probably prefer to zip the lists in the caller. Then the caller can decide what to do if the lists are not the same length. Also, if your pairs are logically related then the caller might already have the data as a list of pairs, and it would b...
[ 4, 4 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0005007900_coding_style_python.txt
Q: Impossible to pass a variable in key return in MongoDB or NoSQL DB? Here's my code: dob = 1 email = 1 nationality = 1 work = 1 situation = 1 skype = 1 user_id = ObjectId(self.get_argument("id")) contact_id = ObjectId(self.get_argument("contactId")) contact_confidentiality = db....
Impossible to pass a variable in key return in MongoDB or NoSQL DB?
Here's my code: dob = 1 email = 1 nationality = 1 work = 1 situation = 1 skype = 1 user_id = ObjectId(self.get_argument("id")) contact_id = ObjectId(self.get_argument("contactId")) contact_confidentiality = db.cara.users.find_one({"_id" : contact_id}, {"profil.private.confidential" ...
[ "Currently, there is a limitation that you can only include or exclude, but not both in a projection. So if you are going to pass a projection, they need to either be all 1's or all 0's. \nThere is one exception to this which is when you are using covered indexes, you can exclude the _id field, and include other fi...
[ 0 ]
[]
[]
[ "mongodb", "nosql", "python" ]
stackoverflow_0005008061_mongodb_nosql_python.txt
Q: Problem with using system call to execute python script from MATLAB I have a MATLAB function that needs to communicate (not rapidly, and not often) with python code. I have MATLAB write numbers to a file. Python reads the file, does some calculations, and writes some results to another file. MATLAB then reads that...
Problem with using system call to execute python script from MATLAB
I have a MATLAB function that needs to communicate (not rapidly, and not often) with python code. I have MATLAB write numbers to a file. Python reads the file, does some calculations, and writes some results to another file. MATLAB then reads that file and continues on its way. The problem I am having is when I want to...
[ "It looks like you're using OS X. It is highly advisable not to attempt to screw around with the global definition of what python interpreter to use in OS X. \nYou can probably just call the desired interpreter directly. So instead of calling system('python myscript.py'), get the desired interpreter's full path int...
[ 3, 0 ]
[]
[]
[ "matlab", "numpy", "python" ]
stackoverflow_0005006837_matlab_numpy_python.txt
Q: Python's xml.etree getiterator equivalent to C# I have this XML file : http://dl.dropbox.com/u/10773282/2011/perf.xml It has two Class elements as is marked. I need to get two nodes with C#. With Python, I can easily get them with etree.ElementTree as follows. from xml.etree import ElementTree as et from xml.etre...
Python's xml.etree getiterator equivalent to C#
I have this XML file : http://dl.dropbox.com/u/10773282/2011/perf.xml It has two Class elements as is marked. I need to get two nodes with C#. With Python, I can easily get them with etree.ElementTree as follows. from xml.etree import ElementTree as et from xml.etree.ElementTree import Element tree = et.parse("perf.x...
[ "You should try Linq to XML... Quite easy to use:\nvar xml = XDocument.Load(filename);\nvar res = from p in xml.Root.Elements(\"Class\").Elements(\"ClassKeyName\") select p.Value;\n\n", "Try:\nusing System.Xml;\n// ...\nXmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(filename);\nvar matches = xmlDoc.SelectNo...
[ 1, 0 ]
[]
[]
[ "c#", "python", "xml" ]
stackoverflow_0005008423_c#_python_xml.txt
Q: How to make a progress bar/meter in web2py? I made a progress meter in web2py, but it only shows up in the terminal window. How can I make the progress bar/meter to work in the web2py's HTML page? Here's a part of the code: k = 1 # This is the loop variable for subplots. for counter in nus: fig = plt.figure() ...
How to make a progress bar/meter in web2py?
I made a progress meter in web2py, but it only shows up in the terminal window. How can I make the progress bar/meter to work in the web2py's HTML page? Here's a part of the code: k = 1 # This is the loop variable for subplots. for counter in nus: fig = plt.figure() D = E*(h**3)/(12*(1-counter**2)) # Cylindrica...
[ "You might be better off asking the mailing list.\nIs your code inside (or called by) a controller function? Note, print statements don't send any output to web pages (i.e., they don't affect the HTTP response) -- to do that, your controller needs to return a dict to a view (or return a string). For a progress bar,...
[ 2 ]
[]
[]
[ "html", "progress_bar", "python", "web2py" ]
stackoverflow_0005002650_html_progress_bar_python_web2py.txt
Q: Slicing with python on a single line I have data "line" FF= ['123451234512345678901234512345', '123451234512345678901234512345'] I need to slice line 1-5, 6-10, 11, 12-22. How do I slice? data= [] for col in FF: data.append(col) A: Something like: a = [(s[:5], s[5:10], s[10], s[11:]) for s in FF] A: Wi...
Slicing with python on a single line
I have data "line" FF= ['123451234512345678901234512345', '123451234512345678901234512345'] I need to slice line 1-5, 6-10, 11, 12-22. How do I slice? data= [] for col in FF: data.append(col)
[ "Something like:\na = [(s[:5], s[5:10], s[10], s[11:]) for s in FF]\n\n", "With struct.\n>>> struct.unpack('5s5sc11s8x', '123451234512345678901234512345')\n('12345', '12345', '1', '23456789012')\n\n" ]
[ 2, 1 ]
[]
[]
[ "line", "python", "slice" ]
stackoverflow_0005008760_line_python_slice.txt
Q: UTF-8 in Python This seems to be a common question among international developers but I haven't found a straight answer yet. I'm getting from a feed the following string: "Carlos e Carlos mostram o que há de melhor na internet" The following error is returned to the console: UnicodeDecodeError: 'utf8' codec can't...
UTF-8 in Python
This seems to be a common question among international developers but I haven't found a straight answer yet. I'm getting from a feed the following string: "Carlos e Carlos mostram o que há de melhor na internet" The following error is returned to the console: UnicodeDecodeError: 'utf8' codec can't decode bytes in posi...
[ "You can't just decode using some random encoding, even if it is UTF-8; you must decode using the encoding returned in the HTTP headers or an equivalent within the document (such as within the META element of HTML).\nIf the encoding isn't available or is incorrect then you should specify in the decode operation wha...
[ 3 ]
[]
[]
[ "encoding", "python", "utf_8" ]
stackoverflow_0005008901_encoding_python_utf_8.txt
Q: Should I conditionally require simplejson in my setup.py? I'm importing simplejson/json conditionally in my module like so: try: import simplejson as json except ImportError: import json In my setup.py, however, I don't want to require simplejson if the user has json from the standard libraries. I could d...
Should I conditionally require simplejson in my setup.py?
I'm importing simplejson/json conditionally in my module like so: try: import simplejson as json except ImportError: import json In my setup.py, however, I don't want to require simplejson if the user has json from the standard libraries. I could do that like so: requires = ['kitchen'] try: import simplejs...
[ "Short answer - no, this is not a good practice.\nOne of key concepts of using distutils, zc.buildout and so on is repeatability. When you add such conditionals you cannot package an egg because it will only work on some machines. When you install it manually on each machine, differences between simplejson and json...
[ 3 ]
[]
[]
[ "json", "python" ]
stackoverflow_0005008759_json_python.txt
Q: Adding items to an object with ObjectListView After reading some items here I have decided to rewrite a little project using ObjectListView. My problem is that when I try to do self.ListObject.AddObject(object) to add an item to my list it fails, and I am not sure why. Here is the code where I let the user select...
Adding items to an object with ObjectListView
After reading some items here I have decided to rewrite a little project using ObjectListView. My problem is that when I try to do self.ListObject.AddObject(object) to add an item to my list it fails, and I am not sure why. Here is the code where I let the user select a destination dir. At the end of the selection pr...
[ "I figured the issue out. I needed to use AddObjects, no AddObject\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005009142_python_wxpython.txt
Q: manipulating and searching within large files in python I apologize if this question has been answered already, but I cannot seem to find a page that describes this process. What I am trying to do is to take a large file (The new york times corpus), change it to a list of words using the split function, and then s...
manipulating and searching within large files in python
I apologize if this question has been answered already, but I cannot seem to find a page that describes this process. What I am trying to do is to take a large file (The new york times corpus), change it to a list of words using the split function, and then search through that long list for certain words. I have been a...
[ "What you probably want is called a generator. In your case, it could look like this:\ndef words(lines):\n for line in lines:\n for word in line.split():\n yield word\n\nThis processes the file line by line, so it doesn't have to read the entire file into memory at once. The yield keyword turns...
[ 1, 0, 0, 0 ]
[]
[]
[ "file", "python", "search" ]
stackoverflow_0005008053_file_python_search.txt
Q: Import external libraries in an Hadoop MapReduce script I am running a python MapReduce script on top of Amazons EMR Hadoop implementation. As a result from the main scripts, I get item item similiarities. In an aftercare step, I want to split this output into a seperate S3 bucket for each item, so each item-bucke...
Import external libraries in an Hadoop MapReduce script
I am running a python MapReduce script on top of Amazons EMR Hadoop implementation. As a result from the main scripts, I get item item similiarities. In an aftercare step, I want to split this output into a seperate S3 bucket for each item, so each item-bucket contains a list of items similiar to it. To achieve this, I...
[ "When launching a hadoop process you can specify external files that should be made available. This is done by using the -files argument.\n$HADOOP_HOME/bin/hadoop jar /usr/lib/COMPANY/analytics/libjars/MyJar.jar -files hdfs://PDHadoop1.corp.COMPANY.com:54310/data/geoip/GeoIPCity.dat\nI don't know if the files HAVE ...
[ 4 ]
[]
[]
[ "amazon_emr", "amazon_web_services", "hadoop", "mapreduce", "python" ]
stackoverflow_0004984894_amazon_emr_amazon_web_services_hadoop_mapreduce_python.txt
Q: Python's 'in' operator equivalent to C# With Python, I can use 'in' operator for set operation as follows : x = ['a','b','c'] if 'a' in x: do something What's the equivalent in C#? A: Most collections declare a Contains method (e.g. through the ICollection<T> interface), but there's always the more general-pu...
Python's 'in' operator equivalent to C#
With Python, I can use 'in' operator for set operation as follows : x = ['a','b','c'] if 'a' in x: do something What's the equivalent in C#?
[ "Most collections declare a Contains method (e.g. through the ICollection<T> interface), but there's always the more general-purpose LINQ Enumerable.Contains method: \nchar[] x = { 'a', 'b', 'c' };\n\nif(x.Contains('a'))\n{\n ... \n}\n\nIf you think that's the 'wrong way around', you could write an extension t...
[ 26, 2 ]
[]
[]
[ "c#", "operators", "python" ]
stackoverflow_0005009882_c#_operators_python.txt
Q: creating deformations on a sphere surface (using python?) Hi :) i have the following python code that generates points lying on a sphere's surface from math import sin, cos, pi toRad = pi / 180 ox = 10 oy = -10 oz = 50 radius = 10.0 radBump = 3.0 angleMin = 0 angleMax = 360 angleOffset = angleMin * toRad angle...
creating deformations on a sphere surface (using python?)
Hi :) i have the following python code that generates points lying on a sphere's surface from math import sin, cos, pi toRad = pi / 180 ox = 10 oy = -10 oz = 50 radius = 10.0 radBump = 3.0 angleMin = 0 angleMax = 360 angleOffset = angleMin * toRad angleRange = (angleMax - angleMin) * toRad steps = 48 angleStep = a...
[ "The approach that springs to my mind, especially with the way you compute a set of points that are not explicitly connected, is to find where the point goes on the sphere's surface, then move it by a distance and direction determined by a set of control points. The control points could have smaller effects the fur...
[ 2, 1, 0 ]
[]
[]
[ "computational_geometry", "geometry", "python" ]
stackoverflow_0004998733_computational_geometry_geometry_python.txt
Q: Python splitting string. Need help I'm trying to split a string into two different words. I have the following string: test / I want to split it so I can do os.chdir('/') I've tried different splitting techniques but they split by letter so it becomes 't','e','s','t', '', '/' A: 'test /'.split() will give you ...
Python splitting string. Need help
I'm trying to split a string into two different words. I have the following string: test / I want to split it so I can do os.chdir('/') I've tried different splitting techniques but they split by letter so it becomes 't','e','s','t', '', '/'
[ "'test /'.split() will give you ['test', '/']. os.path.split() is for splitting paths and you might find it useful.\n", "Splitting on a space isn't working? What are you trying to do eventually?\n'test /'.split(' ')\n\nor no parameters at all:\ntst, path = 'test /'.split()\nos.chdir(path)\n\n" ]
[ 3, 2 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0005010396_python_split_string.txt
Q: Python, ImageMagick and `subprocess` I'm trying to assemble images with a call to ImageMagick's montage from a Python script like this: command = "montage" args = "-tile {}x{} -geometry +0+0 \"*.png\" out.png".format( width, height) sys.stdout.write( " {} {}\n".format(command, args) ) print subprocess.call( [...
Python, ImageMagick and `subprocess`
I'm trying to assemble images with a call to ImageMagick's montage from a Python script like this: command = "montage" args = "-tile {}x{} -geometry +0+0 \"*.png\" out.png".format( width, height) sys.stdout.write( " {} {}\n".format(command, args) ) print subprocess.call( [command, args] ) However, montage only sh...
[ "Instead of [command, args], you should pass ['montage', '-tile', '{}x{}'.format(...), '-geometry'...] as first argument. You might need shell=True as well.\n", "jd already gave you the solution, but you didn't read it carefully ;)\nThis is incorrect:\nsubprocess.call( ['montage', '-tile 9x6', '-geometry +0+0', '...
[ 4, 3, 0 ]
[]
[]
[ "glob", "imagemagick", "parameters", "python" ]
stackoverflow_0005009907_glob_imagemagick_parameters_python.txt
Q: Combining lists with python using two lists I have two lists: f= ['A', 'A'] d = [(2096, 222, 2640), (1494, 479, 1285)] I want a list! LL = [('A', 2096, 222, 2640), ('A', 1494, 479, 1285)] I am close with dic = zip(f,d) but this give me this: [('A', (2096, 222, 2640)), ('A', (1494, 479, 1285))] How can i get...
Combining lists with python using two lists
I have two lists: f= ['A', 'A'] d = [(2096, 222, 2640), (1494, 479, 1285)] I want a list! LL = [('A', 2096, 222, 2640), ('A', 1494, 479, 1285)] I am close with dic = zip(f,d) but this give me this: [('A', (2096, 222, 2640)), ('A', (1494, 479, 1285))] How can i get LL?
[ "Try:\nLL = [ (x,) + y for x, y in zip(f, d) ]\n\nThis iterates through the convoluted arrays and adds the string outside the tuple to the tuple (by creating a new tuple, due to the fact tuples are immutable).\n", "the zip command does that along with dict:\n>>>dict(zip([1,2,3],[1,2,3]))\n{1:1,2:2,3:3}\n\n", "Y...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005010435_list_python.txt
Q: MySQLdb input where strings contain string delimiters I'm working on a project in Python with MySQLdb. As part of this, I'm moving user details, including salted passwords from one system that generates them to a new one that simply uses them. Single, double or triple quotes can delineate your string start and end...
MySQLdb input where strings contain string delimiters
I'm working on a project in Python with MySQLdb. As part of this, I'm moving user details, including salted passwords from one system that generates them to a new one that simply uses them. Single, double or triple quotes can delineate your string start and end. However, single and double quotes are part of several has...
[ "Query parameters should provide all the proper escaping, for example:\ncursor.execute('INSERT INTO auth_user (password) VALUES (%s)', [password])\n\nFrom the Django docs at: http://docs.djangoproject.com/en/dev/topics/db/sql/\n\nIf you're not familiar with\n the Python DB-API, note that the SQL\n statement in c...
[ 2 ]
[]
[]
[ "database", "migration", "passwords", "python" ]
stackoverflow_0005010555_database_migration_passwords_python.txt
Q: Building ranges using python set-builder notation Hey, I am trying to build a set of ranges in python like so: Given (0.1, 0.2, 0.7) I want to build [(0, 0.1), (0.1, 0.3), (0.3, 1)] While this could be achieved easily through a regular for-loop, as a learning exercise I wanted to see if this could be achieved via ...
Building ranges using python set-builder notation
Hey, I am trying to build a set of ranges in python like so: Given (0.1, 0.2, 0.7) I want to build [(0, 0.1), (0.1, 0.3), (0.3, 1)] While this could be achieved easily through a regular for-loop, as a learning exercise I wanted to see if this could be achieved via a set-builder expression. My first thought was to do [(...
[ "A possible solution is:\na = (0.1, 0.2, 0.7)\nl = [(sum(a[:ii]), sum(a[:ii+1])) for ii, v in enumerate(a)]\n\nYet being pythonic does not mean being the most concise, or using comprehensions at any place possible - if a simple loop is more readable, go for it (if there are no other factors hinting to a list compre...
[ 3, 2 ]
[]
[]
[ "list", "python", "set" ]
stackoverflow_0005010489_list_python_set.txt
Q: GAE Howto get Date from form Request I have a form where the user can select a date. I would like to store that as a date time. # Throws error 'duedate must be datetime' goal.duedate = self.request.get('duedate') Obviously this doens't work because the form field is a string. What is the best way to convert form ...
GAE Howto get Date from form Request
I have a form where the user can select a date. I would like to store that as a date time. # Throws error 'duedate must be datetime' goal.duedate = self.request.get('duedate') Obviously this doens't work because the form field is a string. What is the best way to convert form fields that are dates into GAE datetime ob...
[ "Use the datetime class's strptime function.\nFor example, if your form submits the date like '2011-02-15' then you could do this:\nimport datetime\nstr_due_date = self.request.get('duedate')\ngoal.duedate = datetime.datetime.strptime(str_due_date, '%Y-%m-%d')\n\n", "Use the strptime() method of the datetime.date...
[ 4, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005010945_google_app_engine_python.txt
Q: Check if the filesystem supports hardlinks I'm writing a backup script, which uses hard links to not consume space for unmodified files. I'd like to check if a given file system (as determined from a specific directory) supports hard links at the start of the script - otherwise, it could get half-way through (copy...
Check if the filesystem supports hardlinks
I'm writing a backup script, which uses hard links to not consume space for unmodified files. I'd like to check if a given file system (as determined from a specific directory) supports hard links at the start of the script - otherwise, it could get half-way through (copying multiple files) before the first hard link n...
[ "I'd tackle this problem this way: There are 3 alternatives for copying a file:\n\nOn Unix, you can use os.link.\nOn Windows, you can use a function like this:\ndef CreateHardLink(src, dst):\n import ctypes \n if not ctypes.windll.kernel32.CreateHardLinkA(dst, src, 0):\n raise OSError\n\n(Disclaimer: I...
[ 5 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0005010120_filesystems_python.txt
Q: Ignore_user_abort php simil in Django/python? Somebody know how set this behavior in Django/python? I need send an Ajax request and keep it living if the user close the page A: I guess you want to use something like this : http://celeryproject.org/ Or simply execute script in separate thread like this: subproces...
Ignore_user_abort php simil in Django/python?
Somebody know how set this behavior in Django/python? I need send an Ajax request and keep it living if the user close the page
[ "I guess you want to use something like this :\nhttp://celeryproject.org/\nOr simply execute script in separate thread like this:\nsubprocess.Popen([sys.executable, '/path/to/script.py'])\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004925629_django_python.txt
Q: How do I clear the cookies in urllib.request (python3) Looking through the docs my first guess was that I call urllib.request.HTTPCookieProcessor().cookiejar.clear(), however that didn't work. My next guess is maybe I need to subclass it and build/install it with an opener? I don't know how to do that, I can if ne...
How do I clear the cookies in urllib.request (python3)
Looking through the docs my first guess was that I call urllib.request.HTTPCookieProcessor().cookiejar.clear(), however that didn't work. My next guess is maybe I need to subclass it and build/install it with an opener? I don't know how to do that, I can if need be of course, but it really seems like overkill for what ...
[ "By default, urllib.request won't store any cookies, so there is nothing to clear. If you build an OpenerDirector containing and HTTPCookieProcessor instance as one of the handlers, you have to clear the cookiejar of this instance. Example from the docs:\nimport http.cookiejar, urllib.request\ncj = http.cookiejar...
[ 17 ]
[]
[]
[ "python", "python_3.x", "urllib" ]
stackoverflow_0005010915_python_python_3.x_urllib.txt
Q: How would a python program check its own md5sum? I was playing a game about a year ago. Wanting to speed it up a bit, I edited the main .py file and added psyco to the very beginning. The game ran faster and better, but it would not let me send my scores. I went into the file and it was checking its own md5sum. Th...
How would a python program check its own md5sum?
I was playing a game about a year ago. Wanting to speed it up a bit, I edited the main .py file and added psyco to the very beginning. The game ran faster and better, but it would not let me send my scores. I went into the file and it was checking its own md5sum. The part that confused me is that they had its md5 in th...
[ "You can't (easily) embed an MD5 of a program inside the program that it is computing the MD5, because when you change the MD5 of that you are embedding, the program's MD5 changes. Loop for a while and eventually you may reach a stable point. Then again, you may not. \"a while\" typically means 2^128 steps, so that...
[ 5, 1, 0 ]
[]
[]
[ "md5", "md5sum", "python", "security" ]
stackoverflow_0005011151_md5_md5sum_python_security.txt
Q: How to use filter for field in django-admin Hello How to I'm can use template filter for some field in django-admin? I'm have read-only TextField and want use |linebreaks for this field, how to I'm can enable this? Thank You A: You can create a custom widget for this field and set it to work with this field.
How to use filter for field in django-admin
Hello How to I'm can use template filter for some field in django-admin? I'm have read-only TextField and want use |linebreaks for this field, how to I'm can enable this? Thank You
[ "You can create a custom widget for this field and set it to work with this field.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004999085_django_django_admin_python.txt
Q: Listing all possible values for SOAP enumeration with Python SUDS I'm connecting with a SUDS client to a SOAP Server whose wsdl contains many enumerations like the following: </simpleType> <simpleType name="FOOENUMERATION"> <restriction base="xsd:string"> <enumeration value="ALPHA"><!-- enum const = 0 --> ...
Listing all possible values for SOAP enumeration with Python SUDS
I'm connecting with a SUDS client to a SOAP Server whose wsdl contains many enumerations like the following: </simpleType> <simpleType name="FOOENUMERATION"> <restriction base="xsd:string"> <enumeration value="ALPHA"><!-- enum const = 0 --> <enumeration value="BETA"/><!-- enum const = 1 --> <enumeration va...
[ "If you know the name of the enum you want, you should be able to treat the enumeration object suds gives you like a dictionary, and do a direct lookup with that name. For example, if your enumeration type is called SOAPIPMode and you want the enum named STATIC_MANUAL in that enumeration:\nsoapIPMode = client.facto...
[ 3, 1, 0 ]
[]
[]
[ "enumeration", "python", "soap", "suds" ]
stackoverflow_0003027307_enumeration_python_soap_suds.txt
Q: numpy.linalg.lstsq equivalent in Apache Commons Math Java library? I have the following call to numpy.linalg.lstsq: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html x = [[ 0.69314718] [ 1.09861229] [ 1.38629436] [ 1.60943791] [ 1.79175947] [ 1.94591015]] y = [ 0. 0.20273255 0.58157...
numpy.linalg.lstsq equivalent in Apache Commons Math Java library?
I have the following call to numpy.linalg.lstsq: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html x = [[ 0.69314718] [ 1.09861229] [ 1.38629436] [ 1.60943791] [ 1.79175947] [ 1.94591015]] y = [ 0. 0.20273255 0.5815754 0.7520387 0.96885669 1.09861229] l = numpy.linalg.lstsq(x, y) whi...
[ "Thank you for the pointer Joe.\nHere is the code for reference:\ndouble[][] testSquare = {{0.69314718}, {1.09861229}, {1.38629436}, {1.60943791}, {1.79175947}, {1.94591015}};\nRealMatrix matrix = MatrixUtils.createRealMatrix(testSquare);\nSingularValueDecomposition svd = new SingularValueDecomposition(matrix);\nDe...
[ 2 ]
[]
[]
[ "apache_commons", "java", "math", "python", "scipy" ]
stackoverflow_0005010682_apache_commons_java_math_python_scipy.txt
Q: wxPython Altering Native Window Styles One of the things I like about Google Chrome is that the tabs are placed in the top bar so that precious viewing space is conserved. I was wondering if wxPython facilitated the placing of widgets in the native OS's top bar. Similar to how Chrome places tabs in the native OS's...
wxPython Altering Native Window Styles
One of the things I like about Google Chrome is that the tabs are placed in the top bar so that precious viewing space is conserved. I was wondering if wxPython facilitated the placing of widgets in the native OS's top bar. Similar to how Chrome places tabs in the native OS's topbar. The program I'm currently writing ...
[ "Unfortunately, no. Perhaps in future version of wx, but this is some \"custom\" thing that Chrome does.\n" ]
[ 0 ]
[]
[]
[ "native", "nativewindow", "python", "wxpython" ]
stackoverflow_0005010989_native_nativewindow_python_wxpython.txt
Q: Generating a audio waveform graphic within Python Is it possible? I'd like run over a batch of audio files and produce graphic waveform files from them. Similar to what SoundCloud displays, but perhaps the module(s) im seeking will offer a few more options. Whats out there? whats good? A: See this example, it is...
Generating a audio waveform graphic within Python
Is it possible? I'd like run over a batch of audio files and produce graphic waveform files from them. Similar to what SoundCloud displays, but perhaps the module(s) im seeking will offer a few more options. Whats out there? whats good?
[ "See this example, it is exactly what you want in pure Python. You have another options too, but using audiolab.\n" ]
[ 16 ]
[]
[]
[ "audio", "python", "waveform" ]
stackoverflow_0005010941_audio_python_waveform.txt
Q: python: can't delete open file from os.execl'd python script on windows Consider delfoo.py and its partner, lol.py: #----delfoo.py----- import os os.unlink("foo.txt") #----lol.py---- import os,sys f = open("foo.txt","w") f.write("HI") #not closing f on purpose! os.execl(sys.executable, sys.executable, "delfoo.py...
python: can't delete open file from os.execl'd python script on windows
Consider delfoo.py and its partner, lol.py: #----delfoo.py----- import os os.unlink("foo.txt") #----lol.py---- import os,sys f = open("foo.txt","w") f.write("HI") #not closing f on purpose! os.execl(sys.executable, sys.executable, "delfoo.py") print "If this line shows, then something is broken." Invoking python lol...
[ "You forgot to close the file handler:\n#----lol.py----\nimport os,sys\n\nf = open(\"foo.txt\",\"w\")\nf.write(\"HI\")\nf.close() # HERE !\nos.execl(sys.executable, sys.executable, \"delfoo.py\")\n\n", "Just checking the os.execl*() gave me this:\n\nThe current process is replaced\n immediately. Open file object...
[ 2, 0 ]
[]
[]
[ "file", "operating_system", "python", "windows" ]
stackoverflow_0005011379_file_operating_system_python_windows.txt
Q: Python: inspecting module to pick out classes of certain type? I have a module where all classes that implement my "policies" are defined. class Policy_Something(Policy_Base): slug='policy-something' ... class Policy_Something_Else(Policy_Base): slug='policy-something-else' ... I need to create ...
Python: inspecting module to pick out classes of certain type?
I have a module where all classes that implement my "policies" are defined. class Policy_Something(Policy_Base): slug='policy-something' ... class Policy_Something_Else(Policy_Base): slug='policy-something-else' ... I need to create a mapping from slug to class. Something like: slug_to_class = { ...
[ "Since your \"policy\" classes inherit from Policy_Base, why not import all relevant modules and then do something like this?:\nimport re\n\ndef slugify(s):\n return re.sub(r'\\W+', '-', s.lower().replace('_', '-'))\n\ndef get_slug_to_class_items(policy_class):\n yield (slugify(policy_class.__name__), policy_...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005011329_python.txt
Q: How to repeatedly show a Dialog with PyGTK / Gtkbuilder? I have created a PyGTK application that shows a Dialog when the user presses a button. The dialog is loaded in my __init__ method with: builder = gtk.Builder() builder.add_from_file("filename") builder.connect_signals(self) self.myDialog = builder.get_obje...
How to repeatedly show a Dialog with PyGTK / Gtkbuilder?
I have created a PyGTK application that shows a Dialog when the user presses a button. The dialog is loaded in my __init__ method with: builder = gtk.Builder() builder.add_from_file("filename") builder.connect_signals(self) self.myDialog = builder.get_object("dialog_name") In the event handler, the dialog is shown w...
[ "Actually, read the documentation on Dialog.run(). The dialog isn't automatically destroyed. If you hide() it when the run() method exits, then you should be able to run() it as many times as you want.\nAlternatively, you can set the dialog to be modal in your builder file, and then just show() it. This will achiev...
[ 7, 2, 2 ]
[]
[]
[ "dialog", "gtk", "gtkbuilder", "pygtk", "python" ]
stackoverflow_0004657344_dialog_gtk_gtkbuilder_pygtk_python.txt
Q: How to identify non-photograph or 'uninteresting' images using Python Imaging Library (PIL) I have thousands of images and I need to weed out the ones which are not photographs, or otherwise 'interesting'. An 'uninteresting' image, for example, may be all one color, or mostly one color, or a simple icon/logo. The ...
How to identify non-photograph or 'uninteresting' images using Python Imaging Library (PIL)
I have thousands of images and I need to weed out the ones which are not photographs, or otherwise 'interesting'. An 'uninteresting' image, for example, may be all one color, or mostly one color, or a simple icon/logo. The solution doesn't have to be perfect, just good enough to remove the least interesting images. My ...
[ "Danphe beat me to it. Here's my method for calculating image entropy:\nimport Image\nfrom math import log\n\ndef get_histogram_dispersion(histogram):\n log2 = lambda x:log(x)/log(2)\n\n total = len(histogram)\n counts = {}\n for item in histogram:\n counts.setdefault(item,0)\n counts[ite...
[ 2 ]
[]
[]
[ "imaging", "python", "python_imaging_library" ]
stackoverflow_0005011505_imaging_python_python_imaging_library.txt
Q: "Counting" with multiple regular expressions matches in Python Let's say I have the following multi-line string: # Section ## Subsection ## Subsection # Section ## Subsection ### Subsubsection ### Subsubsection # Section ## Subsection and I want it to become: # 1 Section ## 1.1 Subsection ## 1.2 Subsection # 2 Se...
"Counting" with multiple regular expressions matches in Python
Let's say I have the following multi-line string: # Section ## Subsection ## Subsection # Section ## Subsection ### Subsubsection ### Subsubsection # Section ## Subsection and I want it to become: # 1 Section ## 1.1 Subsection ## 1.2 Subsection # 2 Section ## 2.1 Subsection ### 2.1.1 Subsubsection ### 2.1.2 Subsubsect...
[ "« Ok, sure, but what if the 'variable manipulation' is being done in a callback function of re.sub, can it be done then? I guess a simplified form of my question is: \"Can one use regular expressions to substitue differently based on previous matches?\" »\nIt sounds like we need a generator function as a callback;...
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005010631_python_regex.txt
Q: Create a GUI from a XML schema automatically I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have exp...
Create a GUI from a XML schema automatically
I have to write a desktop application to edit data stored in a XML file. The format is defined by a XML schema file (.xsd). The format is quite complex. Are there tools which can generate a basic GUI automatically? It's not yet decided which language to use. I have experience in Python and C++ using wxWidgets and C# (...
[ "Go For PyQt:\nhttp://www.riverbankcomputing.co.uk/software/pyqt/download\nDownload The Qt Developers tool to generate the gui automatically\nwww.qtsoftware.com/products/developer-tools\nFor schema validation try lxml\nhttp://lxml.de/validation.html\n", "It's worth taking a look at Jaxfront which is able to consu...
[ 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "c#", "c++", "python", "schema", "xml" ]
stackoverflow_0000983399_c#_c++_python_schema_xml.txt
Q: How do you update an attribute in a user profile in Django with a command? In Django, the standard way to add additional information to be associated with a user is to use a user profile. To do this, I have an app called, "accounts" accounts __init__.py models.py admin.py (we'll ignore this for no...
How do you update an attribute in a user profile in Django with a command?
In Django, the standard way to add additional information to be associated with a user is to use a user profile. To do this, I have an app called, "accounts" accounts __init__.py models.py admin.py (we'll ignore this for now, it works fine) <br> management __init__.py c...
[ "user.profile retrieves the profile, but nowhere do you ever make an attempt to actually save it. Put the result into a variable, mutate it, and then save it.\nprofile = user.profile\nprofile.age = 34\nprofile.save()\n\n" ]
[ 3 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0005011077_django_models_python.txt
Q: Managing two instances of the same GAE application I have an GAE app, and I deploy it on 2 different domains, and they use separate datastores. However, right now it is done by having two identical folders with different app.yaml configurations. If I make changes I need to copy all files again. Is there an elegan...
Managing two instances of the same GAE application
I have an GAE app, and I deploy it on 2 different domains, and they use separate datastores. However, right now it is done by having two identical folders with different app.yaml configurations. If I make changes I need to copy all files again. Is there an elegant solution for that, like having two app.yaml files in t...
[ "Use a single application, with namespaces to separate data between domains.\n", "Appcfg.py has a --application command line option that is supposed to override the value in your app.yaml. Using that you could deploy the same directory to two different apps.\n", "Assuming you are avoiding Nick's suggestion for...
[ 5, 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005010906_google_app_engine_python.txt
Q: How can I read to dictionary keys in a way that make sense? I have about a thousand files that are named in a semi-sensible way like the following: aaa.ba.ca.01 aaa.ba.ca.02 aaa.ba.ca.03 aaa.ba.da.01 aaa.ba.da.02 aaa.ba.da.03 and so on. Let's say each file contains 2 columns of numbers which I need to read in t...
How can I read to dictionary keys in a way that make sense?
I have about a thousand files that are named in a semi-sensible way like the following: aaa.ba.ca.01 aaa.ba.ca.02 aaa.ba.ca.03 aaa.ba.da.01 aaa.ba.da.02 aaa.ba.da.03 and so on. Let's say each file contains 2 columns of numbers which I need to read in to the dictionaries: wavelength, flux. The reading in part is easy...
[ "A simple, but not efficient, way to do so is to subclass Pythons dictionary, so that when given one non-complete key, it concatenates the contents of all matching keys, in alphabetical order.\nThere could be more efficient designs: this one major drawback being it will sort and verify all existing dictionary keys ...
[ 5, 1, 0 ]
[]
[]
[ "dictionary", "glob", "python" ]
stackoverflow_0005011859_dictionary_glob_python.txt
Q: python parse xml text I would like to parse xml in python, but as a string, not taken from a file. Can someone help me do this? A: From a file, you could normally do it as from xml.dom import minidom xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml') ...
python parse xml text
I would like to parse xml in python, but as a string, not taken from a file. Can someone help me do this?
[ "From a file, you could normally do it as\nfrom xml.dom import minidom \nxmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml') \n\nFor a string, you can change it to\nfrom xml.dom import minidom \nxmldoc = minidom.parse...
[ 13, 3, 2, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0005011645_python_xml.txt
Q: mod_wsgi for Django on Mac OSX 10.5.8 I'm a newbie learning Django, and couldn't get the development server accessible externally. So I'm looking into other deployment options. It seems that mod_wsgi is the way to go (with Apache), but it only supports OSX 10.6+. Are there any alternatives if you own 10.5.8? A: ...
mod_wsgi for Django on Mac OSX 10.5.8
I'm a newbie learning Django, and couldn't get the development server accessible externally. So I'm looking into other deployment options. It seems that mod_wsgi is the way to go (with Apache), but it only supports OSX 10.6+. Are there any alternatives if you own 10.5.8?
[ "Taking @Endophage's warning into consideration, if you still want to do this you probably need to start the server like this:\npython manage.py runserver 0.0.0.0:8000\n\nBy default, the dev server only listens on localhost so you need to explicitly tell it to listen on external interfaces. If you have a firewall o...
[ 1, 0, 0 ]
[]
[]
[ "apache", "deployment", "django", "mod_wsgi", "python" ]
stackoverflow_0004997366_apache_deployment_django_mod_wsgi_python.txt
Q: OS X: Determine Trash location for a given path Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive.. Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user...
OS X: Determine Trash location for a given path
Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive.. Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user's ID is) Given a file or folder path, what is the co...
[ "Based upon code from http://www.cocoadev.com/index.pl?MoveToTrash I have came up with the following:\ndef get_trash_path(input_file):\n path, file = os.path.split(input_file)\n if path.startswith(\"/Volumes/\"):\n # /Volumes/driveName/.Trashes/<uid>\n s = path.split(os.path.sep)\n # s[2]...
[ 6, 5, 3, 3, 2, 1 ]
[]
[]
[ "filesystems", "macos", "python" ]
stackoverflow_0000249785_filesystems_macos_python.txt
Q: Django, svglib and images Im using svglib to render my svg files (rendered from a template) in django. There seems to be a problem with how the library resolves the path of the image when rendering. I was wondering if anyone has implemented this or knows a better way to convert svg (that includes images) to PDF? E...
Django, svglib and images
Im using svglib to render my svg files (rendered from a template) in django. There seems to be a problem with how the library resolves the path of the image when rendering. I was wondering if anyone has implemented this or knows a better way to convert svg (that includes images) to PDF? EDIT: My view: def certificate_i...
[ "What about SVG to HTML? It depends what SVG you are converting but sometimes the results are identical.\nLet me know if this is relevant and helps or if you have any query.\nGo the instruction page where the tool is also located.\nhttp://irunmywebsite.com/raphael/svgsource.php\n", "I haven't used svglib, but the...
[ 0, 0 ]
[]
[]
[ "django", "pdf", "python", "svg" ]
stackoverflow_0004976738_django_pdf_python_svg.txt
Q: how to convert this date string to "2011-02-15T12:00+00:00" python datetime object how to convert this date string to "2011-02-15T12:00+00:00" python datetime object in following format "Wed, Feb, 15, 2011 15:00" ? A: It seems ISO 8601 format. Try using iso8601 package — you can install it through pip or easy_in...
how to convert this date string to "2011-02-15T12:00+00:00" python datetime object
how to convert this date string to "2011-02-15T12:00+00:00" python datetime object in following format "Wed, Feb, 15, 2011 15:00" ?
[ "It seems ISO 8601 format. Try using iso8601 package — you can install it through pip or easy_install.\n\nMany file formats and standards use the ISO 8601 date format (e.g. 2007-01-14T20:34:22+00:00) to store dates in a neutral, unambiguous manner. This simple module parses the most common forms encountered and ret...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005012592_python.txt
Q: SQL Database GUI written in Python I've been ripping my face off trying to find a SQL database GUI client that is written in Python. I know that a particular project already exists and I can only remember that it was written in Python (and had a FOSS licence). I know there are many questions (without the Python-sp...
SQL Database GUI written in Python
I've been ripping my face off trying to find a SQL database GUI client that is written in Python. I know that a particular project already exists and I can only remember that it was written in Python (and had a FOSS licence). I know there are many questions (without the Python-specific requirement) floating around SO -...
[ "crunchyfrog\n" ]
[ 3 ]
[]
[]
[ "client", "database", "python", "sql", "user_interface" ]
stackoverflow_0005012746_client_database_python_sql_user_interface.txt
Q: Which Python (sqlalchemy) mssql DB API works in Cygwin? I'm trying to use sqlalchemy on Cygwin with a MSSQL backend but I cannot seem to get any of the MSSQL Python DB APIs installed on Cygwin. Is there one that is known to work? A: FreeTDS + unixodbc + pyodbc stack will work on Unix-like systems and should ther...
Which Python (sqlalchemy) mssql DB API works in Cygwin?
I'm trying to use sqlalchemy on Cygwin with a MSSQL backend but I cannot seem to get any of the MSSQL Python DB APIs installed on Cygwin. Is there one that is known to work?
[ "FreeTDS + unixodbc + pyodbc stack will work on Unix-like systems and should therefore work just as well in Cygwin. You should use version 8.0 of TDS protocol. This can be configured in connection string.\n" ]
[ 0 ]
[]
[]
[ "cygwin", "python", "sql_server", "sqlalchemy" ]
stackoverflow_0004770083_cygwin_python_sql_server_sqlalchemy.txt
Q: How to restrict user to select date between range of years in django? models.py class Completion(models.Model): start_date = models.DateField() end_date = models.DateField() batch = models.ForeignKey(Batch) topic = models.ForeignKey(Topic) In above code DateField() generates a date selecting widge...
How to restrict user to select date between range of years in django?
models.py class Completion(models.Model): start_date = models.DateField() end_date = models.DateField() batch = models.ForeignKey(Batch) topic = models.ForeignKey(Topic) In above code DateField() generates a date selecting widget in admin site where you can select proper date or enter it manually in a ...
[ "Check out validators!\nFirst, define your validator:\nfrom django.core.exceptions import ValidationError\n\ndef validate_current_century(value):\n if value < 2000 or value > 2100:\n raise ValidationError(u'%s is not a valid year!' % value)\n\nNow you can use it in your model field:\nclass Completion(mode...
[ 11 ]
[]
[]
[ "datefield", "django", "model", "python" ]
stackoverflow_0005013041_datefield_django_model_python.txt
Q: If a command line program is unsure of stdout's encoding, what encoding should it output? I have a command line program written in Python, and when I pipe it through another program on the command line, sys.stdout.encoding is None. This makes sense, I suppose -- the output could be another program, or a file you'...
If a command line program is unsure of stdout's encoding, what encoding should it output?
I have a command line program written in Python, and when I pipe it through another program on the command line, sys.stdout.encoding is None. This makes sense, I suppose -- the output could be another program, or a file you're redirecting it into, or whatever, and it doesn't know what encoding is desired. But neither...
[ "I suggest you use the current locale. \nPython2> import locale\nPython2> locale.getpreferredencoding()\n'UTF-8'\n\nThe system knows what it should be, and the other side, if it also uses the current locale, will do the right thing.\n", "You should use the value returned by locale.getpreferredencoding().\n", "i...
[ 7, 4, 1, 0 ]
[]
[]
[ "command_line", "linux", "python", "shell", "unicode" ]
stackoverflow_0005013599_command_line_linux_python_shell_unicode.txt
Q: XMLSerializer (C#) equivalent in Python? I learned in this post that with XmlSerializer, one can generate XML based on the class structure with C#. Does Python have similar/equivalent method to get XML file based on its class structure? A: There's a Pyxer that can be used to Serialize Objects to XML. The (pyxe...
XMLSerializer (C#) equivalent in Python?
I learned in this post that with XmlSerializer, one can generate XML based on the class structure with C#. Does Python have similar/equivalent method to get XML file based on its class structure?
[ "There's a Pyxer that can be used to Serialize Objects to XML.\nThe (pyxer) Python XML Serialization and is a Python object to XML serializer and deserializer. In other words, it can convert a Python object into XML and also, convert that XML back into the original Python object. It uses a preorder traversal tree a...
[ 1 ]
[]
[]
[ "c#", "python", "xmlserializer" ]
stackoverflow_0005013694_c#_python_xmlserializer.txt
Q: QWebView not laying out properly Even if I set the geometry for the QWebView it occupies the whole left over screen. Even worse if I maxmize the window, there is a gap between the two widgets Below is my code I wrote: from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * class twsear...
QWebView not laying out properly
Even if I set the geometry for the QWebView it occupies the whole left over screen. Even worse if I maxmize the window, there is a gap between the two widgets Below is my code I wrote: from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * class twsearchbox(QWidget): def __init__(self)...
[ "I investigated this in code (in c++) and found it a bit puzzling until finally I took a look at the source code for QWebView. It seems that QWebView::sizeHint() is hard coded to 800 x 600 (Qt 4.6).\nThis seems a bit odd to me but I'm not sure enough to report a bug for it. If somebody can post a comment to confirm...
[ 0, 0 ]
[]
[]
[ "layout", "pyqt", "python" ]
stackoverflow_0003951915_layout_pyqt_python.txt
Q: Can somenone translate this from Ruby to Python. Its a basic map function This function is from the mongodb site: http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails def self.threaded_with_field(story, field_name='votes') comments = find(:all, :conditions => {:story_id => story.id}, :order => ...
Can somenone translate this from Ruby to Python. Its a basic map function
This function is from the mongodb site: http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails def self.threaded_with_field(story, field_name='votes') comments = find(:all, :conditions => {:story_id => story.id}, :order => "path asc, #{field_name} desc") results, map = [], {} comments.each do...
[ "This method can't be translated directly. It relies on several framework methods that would exist only in an ActiveRecord or Mongoid::Document class (e.g. Model#find) -- unless you're using an identical framework in Python, you would also have to implement these methods yourself.\n", "So to answer your questions...
[ 1, 1 ]
[]
[]
[ "mongodb", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0005008713_mongodb_python_ruby_ruby_on_rails.txt
Q: 2011 Web Scripting Languages and Dynamic Reloading This has been bugging me for awhile now. In a deployed PHP web application one can upload a changed php script and have the updated file picked up by the web server without having to restart. The problem? Ruby, Groovy, & Python, etc. are all "better" than PHP in...
2011 Web Scripting Languages and Dynamic Reloading
This has been bugging me for awhile now. In a deployed PHP web application one can upload a changed php script and have the updated file picked up by the web server without having to restart. The problem? Ruby, Groovy, & Python, etc. are all "better" than PHP in terms of language expressiveness, concision, power, ......
[ "You haven't specified a web server. If you're using Apache, mod_wsgi is your best bet for running Python web apps, and it has a reloading mechanism that doesn't require a server restart.\n", "I think you're making a bigger deal out of this than it really is.\nAny application for which it is that important that ...
[ 4, 4 ]
[]
[]
[ "groovy", "php", "python", "reloading", "ruby" ]
stackoverflow_0005013863_groovy_php_python_reloading_ruby.txt
Q: how to get the next obj in this place this is my python code : a=['aaa','bbb','oooo','qqqq','gggg'] for i in a: print i #how to get the next obj in this place . i want to get next code when i get the i element , thanks A: You could use the zip function to get both the current and next item in the list in t...
how to get the next obj in this place
this is my python code : a=['aaa','bbb','oooo','qqqq','gggg'] for i in a: print i #how to get the next obj in this place . i want to get next code when i get the i element , thanks
[ "You could use the zip function to get both the current and next item in the list in the for loop. So the for loop is iterating through the list and the list offset by 1 at the same time: \nfor this,after in zip(a,a[1:]):\n print this,after\n\nHowever, zip stops at the end of the shortest list so you won't get ...
[ 2, 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0005013086_loops_python.txt
Q: How to force iPython to use an older version of Python? I have to use a very outdated version of python (2.4) at work, so I'd like to tell ipython to use that version instead of the default one on the system. How can I do that? ( I know there is a dupe question, but the accepted answer doesn't work for me, because...
How to force iPython to use an older version of Python?
I have to use a very outdated version of python (2.4) at work, so I'd like to tell ipython to use that version instead of the default one on the system. How can I do that? ( I know there is a dupe question, but the accepted answer doesn't work for me, because I only have one ipython on my system, and there are no other...
[ "Install it using the other Python version's executable.\npython2.9 setup.py install\n\n" ]
[ 2 ]
[]
[]
[ "backwards_compatibility", "ipython", "python", "version" ]
stackoverflow_0005014400_backwards_compatibility_ipython_python_version.txt
Q: How to convert list to tuple and search for max and min I am currently learning python coding and I come across this qns on a learning site: Create a function that takes a sequence of inputs (may be a list, a tuple, or just a bunch of inputs). The function should return the minimum and the maximum of the list. Th...
How to convert list to tuple and search for max and min
I am currently learning python coding and I come across this qns on a learning site: Create a function that takes a sequence of inputs (may be a list, a tuple, or just a bunch of inputs). The function should return the minimum and the maximum of the list. This are some of the test values that are using: minmax(5,4)...
[ "def minmax(*a):\n\n if len(a) == 1: # Single (list, tuple, or scalar) argument\n try:\n return minmax(*a[0]) # Expansion of sequence elements, if possible\n except TypeError: # Case of minmax(42)\n pass # The general code below handles this directly\n\n return (min(a),...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005013886_python.txt
Q: how to use "group" in pymongo to group similar rows? I am very new to mongodb/pymongo. I have successfully imported my data into mongo and would like to use the group function to group similar row together. For example, if my data set looks like this: data = [{uid: 1 , event: 'a' , time: 1} , {uid: 1 , ev...
how to use "group" in pymongo to group similar rows?
I am very new to mongodb/pymongo. I have successfully imported my data into mongo and would like to use the group function to group similar row together. For example, if my data set looks like this: data = [{uid: 1 , event: 'a' , time: 1} , {uid: 1 , event: 'b' , time: 2} , {uid: 2 , event: 'c' , time:...
[ "You needn't use the reduce function to actually reduce anything. For example:\n>>> coll.insert(dict(uid=1,event='a',time=1))\nObjectId('4d5b91d558839f06a8000000')\n>>> coll.insert(dict(uid=1,event='b',time=2))\nObjectId('4d5b91e558839f06a8000001')\n>>> coll.insert(dict(uid=2,event='c',time=2))\nObjectId('4d5b91f35...
[ 16 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0005010624_mongodb_pymongo_python.txt
Q: Replace integer value via regular expression with python Well, I am trying to apply some regular expression(search/replace) on xml. Yes I have to use some lib.'s but in that case I cannot. My problem is ,as you may figure out, replacing value of node with an integer. When I try that, it gives me grouping error.Her...
Replace integer value via regular expression with python
Well, I am trying to apply some regular expression(search/replace) on xml. Yes I have to use some lib.'s but in that case I cannot. My problem is ,as you may figure out, replacing value of node with an integer. When I try that, it gives me grouping error.Here are my patterns: search pattern: (<fieldset>)([^>].+)(<ipadd...
[ "From Python Regular Expression operations - re.sub(pattern, repl, string[, count, flags])\n\nIn addition to character escapes and\n backreferences as described above,\n \\g<name> will use the substring\n matched by the group named name, as\n defined by the (?P<name>...) syntax.\n \\g<number> uses the correspo...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005014488_python_regex.txt
Q: subprocess call's env passing i write a python script as bellow: #!/usr/bin/python import os, subprocess env = os.environ.copy() env['PASSWD'] = "hello jian" retcode = subprocess.call("smbclient -L //10.60.1.11 -U Mikejian"),env=env) print retcode as i execute it , it works fine ,get retcode is 0, you know , i p...
subprocess call's env passing
i write a python script as bellow: #!/usr/bin/python import os, subprocess env = os.environ.copy() env['PASSWD'] = "hello jian" retcode = subprocess.call("smbclient -L //10.60.1.11 -U Mikejian"),env=env) print retcode as i execute it , it works fine ,get retcode is 0, you know , i pass the password as an environment ...
[ "Can I shamelessy suggest pysmbclient? It's a dirty hack I wrote to replace some shell scripts at work, but it works fine for me.\n>>> smb = smbclient.SambaClient(server=\"MYSERVER\", share=\"MYSHARE\", \n... username='foo', password='bar', domain='baz')\n...\n>>> print smb.listdir(\"/\")\n[u'file1.txt', u'file...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005013944_python.txt
Q: Unicode conversion error with django Hi I've upgraded my django version to 1.2.5 and my app stopped working. The error I'm getting now is as follows: Caught DjangoUnicodeDecodeError while rendering: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128). You passed in () So far ...
Unicode conversion error with django
Hi I've upgraded my django version to 1.2.5 and my app stopped working. The error I'm getting now is as follows: Caught DjangoUnicodeDecodeError while rendering: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128). You passed in () So far I've been unsuccessful in debugging this p...
[ "Check your .po files, in particular the one for the current language; the encoding may be declared incorrectly.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005014847_django_python.txt
Q: why my django template cant show the current thing this is my views.py : a=['aaa','bbb','oooo','qqqq','gggg'] def main(request, template_name='index.html'): context ={ 'n':range(len(a)), 'a':a, } return render_to_response(template_name, context) this is my html : {% for i...
why my django template cant show the current thing
this is my views.py : a=['aaa','bbb','oooo','qqqq','gggg'] def main(request, template_name='index.html'): context ={ 'n':range(len(a)), 'a':a, } return render_to_response(template_name, context) this is my html : {% for i in n %} {{a.i}} ww {{a.i+1}} {% endfor %} it show...
[ ">>> c=Context({'a':['aaa', 'bbb', 'oooo', 'qqqq', 'gggg']})\n>>> Template(\"{% for x in a %}{% if not forloop.first %}{{ x }} {% endif %}{{ x }}ww{% endfor %}\").render(c)\nu'aaawwbbb bbbwwoooo oooowwqqqq qqqqwwgggg ggggww'\n\n", "Don't do that. Iterate on list directly.\ncontext = {\n 'a': a\n}\nreturn rende...
[ 1, 0, 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0005014254_django_python_templates.txt
Q: Celery doesn't return results For some reason, whenever I create and run a new Task in Celery there is a problem with returning the results. The first task returns perfectly, but for all subsequent tasks, the result is always pending. I checked the Celery log, and it gets the correct result with no errors, but it ...
Celery doesn't return results
For some reason, whenever I create and run a new Task in Celery there is a problem with returning the results. The first task returns perfectly, but for all subsequent tasks, the result is always pending. I checked the Celery log, and it gets the correct result with no errors, but it just can't return it. If it helps, ...
[ "Well it turns out I just needed to explicitly specify a backend.\nAdding:\nCELERY_RESULT_BACKEND = \"amqp\"\n\nto my settings file seemed to fix everything.\n", "I am also getting the same issue even if I add 'amqp' backend. \nHere is my celery config file:\nBROKER_HOST = \"localhost\"\nBROKER_PORT = 5672\nBROKE...
[ 5, 1 ]
[]
[]
[ "celery", "python", "rabbitmq" ]
stackoverflow_0004141224_celery_python_rabbitmq.txt
Q: Asynchronous PureMVC in Python Taking the following code from here, from the shortened version at the bottom, exists this proxy: class DataModelProxy(puremvc.patterns.proxy.Proxy): NAME = "DataModelProxy" def __init__(self): super(DataModelProxy, self).__init__(DataModelProxy.NAME, []) sel...
Asynchronous PureMVC in Python
Taking the following code from here, from the shortened version at the bottom, exists this proxy: class DataModelProxy(puremvc.patterns.proxy.Proxy): NAME = "DataModelProxy" def __init__(self): super(DataModelProxy, self).__init__(DataModelProxy.NAME, []) self.realdata = Data() self.sen...
[ "Your question is really interesting. I just studied PureMVC and it is just my thought, not proven.\nHow about making use of Notifier in puremvc.patterns.observer? Or much easier way, in your asynchronous data-retrieving function, send a notification when the process is done :) That way sounds much PureMVC-way: com...
[ 0 ]
[]
[]
[ "asynchronous", "model_view_controller", "puremvc", "python" ]
stackoverflow_0003450436_asynchronous_model_view_controller_puremvc_python.txt
Q: What's the best Django app/forum that is super simple and can use the existing Django authentication system? I want to wrap it inside a template. That's very important. A: There a several forum app exists for django. Look here django forums And specially look at DjangoBB
What's the best Django app/forum that is super simple and can use the existing Django authentication system?
I want to wrap it inside a template. That's very important.
[ "There a several forum app exists for django.\nLook here django forums\nAnd specially look at DjangoBB\n" ]
[ 3 ]
[]
[]
[ "django", "forum", "python", "templates" ]
stackoverflow_0004967881_django_forum_python_templates.txt
Q: How to prepopulate UserProfile fields in the Django admin? Prepopulating most model fields in the admin (useful for generating slugs) seems to be straightforward if you use: prepopulated_fields = {"slug": ("name",)} But when I use the code below to try to prepopulate a UserProfile field, it gives this error m...
How to prepopulate UserProfile fields in the Django admin?
Prepopulating most model fields in the admin (useful for generating slugs) seems to be straightforward if you use: prepopulated_fields = {"slug": ("name",)} But when I use the code below to try to prepopulate a UserProfile field, it gives this error message, even though I clearly have a slug in the UserProfile mod...
[ "slug is a field in UserProfile, but the prepopulated_fields = {\"slug\": (\"name\",)} is an attribute of UserProfileAdmin, which is applied to User.\nprepopulated_fields triggers some javascript that autogenerates the value of a SlugField out of the values of some other fields of the same model. What you are tryi...
[ 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0005014044_django_django_admin_django_models_python.txt
Q: Is there a nicer way to convert a string into a data set in python? I've just done an assignment for one of my classes in Python, it works fine and I'm satisfied with it, but it looks so ugly! I've already submitted this code as we are not being marked on how it looks, but that it runs properly. I wouldn't mind so...
Is there a nicer way to convert a string into a data set in python?
I've just done an assignment for one of my classes in Python, it works fine and I'm satisfied with it, but it looks so ugly! I've already submitted this code as we are not being marked on how it looks, but that it runs properly. I wouldn't mind some tips and pointers on how to convert strings to data sets for future pr...
[ "import re\n\n# regular expression for matching a (node1,node2;cost)\nEDGE = re.compile(r'\\((\\d+),(\\d+);(\\d+)\\)')\n\ndef parse(s):\n # Separate size from the list of edges\n size, edges = s.split(':')\n\n # Build a dictionary\n edges = dict(\n # ...where key is (node1,node2) and value is (co...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "coding_style", "dictionary", "python", "string" ]
stackoverflow_0005013571_coding_style_dictionary_python_string.txt
Q: Python automatic class assignment In python. when I write x = 5, x becomes an instance of int automatically. But suppose I have defined a new class say number and I want x to become an instance of number instead of int when I assign it the value 5. Is this possible? ie, Instead of this --> >>> x = 5 >>> type(x) <t...
Python automatic class assignment
In python. when I write x = 5, x becomes an instance of int automatically. But suppose I have defined a new class say number and I want x to become an instance of number instead of int when I assign it the value 5. Is this possible? ie, Instead of this --> >>> x = 5 >>> type(x) <type 'int'> Is this possible: >>> x = 5...
[ "No. You would have to write a monkey patch to achieve this, that is incredibly unpythonic, can you simply not write\nx = number(5)\n\n:)\n", "Note that you really should never do something like this. Jakob has the right answer, i.e. use x = number(5).\nHowever, that said, I wanted to try how it could be done in ...
[ 5, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005015268_python.txt
Q: calling class/static method from class variable in python I'm trying to make a ImageLoader class handle the loading and processing of image resources like this: class ImageLoader: TileTable = __loadTileTable('image path', some other variable) @staticmethod def _loadTileTable(arg1, arg2): blah ...
calling class/static method from class variable in python
I'm trying to make a ImageLoader class handle the loading and processing of image resources like this: class ImageLoader: TileTable = __loadTileTable('image path', some other variable) @staticmethod def _loadTileTable(arg1, arg2): blah blah however, on compile i get: NameError: name '_loadTileTabl...
[ "In Python, the code in the class block is first executed, then the resultant namespace is passed to the class initializer. The code you wrote could have also been written as:\nTileTable = _loadTileTable(arg1, arg2)\n@staticmethod\ndef _loadTileTable(arg1, arg2):\n pass # blah blah\nImageLoader = type('ImageLoad...
[ 5, 5, 3, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0005004837_class_python.txt
Q: why can't using loading python27.dll without above Python27/lib py files I have a vc6 application and using python27.dll. if the runtime environment have python27/lib/* files, it's be ok. but no python27/lib/* files,the application will termination. I have using Process Monitor and watch process will load many py....
why can't using loading python27.dll without above Python27/lib py files
I have a vc6 application and using python27.dll. if the runtime environment have python27/lib/* files, it's be ok. but no python27/lib/* files,the application will termination. I have using Process Monitor and watch process will load many py. (like os.py...) and I saw vc6 message window show "Python failed to load the ...
[ "For embedding/extending Python 2.7, use one of the newer Visual C++ Express version. I don't think it's compatible with VC 6.\n" ]
[ 0 ]
[]
[]
[ "python", "python_c_api", "visual_c++_6" ]
stackoverflow_0005016202_python_python_c_api_visual_c++_6.txt
Q: Exposing a C string without copying to python 3.x code I have a library written with cython that wraps a C library, and i'm exposing a few c strings into python code. Those strings are large, and static (can't deallocate them) so just making a python string from them (that makes a copy) is not an option - i get OO...
Exposing a C string without copying to python 3.x code
I have a library written with cython that wraps a C library, and i'm exposing a few c strings into python code. Those strings are large, and static (can't deallocate them) so just making a python string from them (that makes a copy) is not an option - i get OOM errors. I have the code working for python 2.x currently u...
[ "According to this thread the second argument to PyBuffer_FillInfo is optional. Could you pass NULL in its place? If not you could just create a PyBuffer instance yourself and fill the appropriate fields.\n", "It sounds to me as though you should create your own custom type and implement the methods in tp_as_sequ...
[ 1, 0 ]
[]
[]
[ "api", "python", "python_3.x" ]
stackoverflow_0005015884_api_python_python_3.x.txt
Q: Cannot seem to delete an object number I seem to have a problem deleting order numbers in Django. In my views, there is an order number equals to some pk value. There is also a submit button which should delete this number in the template. Unfortunately it is doing nothing (not deleting). For some reason I though...
Cannot seem to delete an object number
I seem to have a problem deleting order numbers in Django. In my views, there is an order number equals to some pk value. There is also a submit button which should delete this number in the template. Unfortunately it is doing nothing (not deleting). For some reason I thought these changes would delete an object, but ...
[ "Got the answer. :) had\norder = models.Order.objects.get(pk=1219)\nif request.POST.get('delete'):\n order.delete()\n\nin the wrong view! Can't believe I was this stupid. \n", "In the second line you are initializing order with a tuple.\nIn the fourth line you call delete() on that object.\nI don't know, if th...
[ 1, 0 ]
[]
[]
[ "django", "python", "templates", "views" ]
stackoverflow_0005015269_django_python_templates_views.txt
Q: smarter "reverse" of a dictionary in python (acc for some of values being the same)? def revert_dict(d): rd = {} for key in d: val = d[key] if val in rd: rd[val].append(key) else: rd[val] = [key] return rd >>> revert_dict({'srvc3': '1', 'srvc2': '1', 'sr...
smarter "reverse" of a dictionary in python (acc for some of values being the same)?
def revert_dict(d): rd = {} for key in d: val = d[key] if val in rd: rd[val].append(key) else: rd[val] = [key] return rd >>> revert_dict({'srvc3': '1', 'srvc2': '1', 'srvc1': '2'}) {'1': ['srvc3', 'srvc2'], '2': ['srvc1']} This obviously isn't simple exchan...
[ "That looks pretty good. You could simplify it a little bit by using defaultdict:\nimport collections\n\ndef revert_dict(d):\n rd = collections.defaultdict(list)\n\n for key, value in d.iteritems():\n rd[value].append(key)\n\n return rd\n\n", "An alternative approach. Not sure if this is faster (I...
[ 8, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004685320_dictionary_python.txt
Q: Problems with pickle and encodings I am working with sizeable set of text files. Many of them written in different encodings. I create list of objects which contains some of the substrings from those text files. I am taking care of encoding problems when opening the files (objects are created correctly and could b...
Problems with pickle and encodings
I am working with sizeable set of text files. Many of them written in different encodings. I create list of objects which contains some of the substrings from those text files. I am taking care of encoding problems when opening the files (objects are created correctly and could be used). Here is my list: len(hands) 475...
[ "You might want to try opening the file in binary mode as you are currently reading it as an ascii file.\nopen('picklefile.pkl','rb')\n\n" ]
[ 8 ]
[]
[]
[ "encoding", "pickle", "python" ]
stackoverflow_0005016078_encoding_pickle_python.txt
Q: regex to find postition between two markers in string i need to find anything between show_detail&amp; and ;session_id=1445045 in https://www.site.gov.uk//search/cgi-bin/contract_search/contract_search.cgi?rm=show_detail&amp;id=4035219;num=1;session_id=1445045;start=0;recs=20;subscription=1;value=0 using rege...
regex to find postition between two markers in string
i need to find anything between show_detail&amp; and ;session_id=1445045 in https://www.site.gov.uk//search/cgi-bin/contract_search/contract_search.cgi?rm=show_detail&amp;id=4035219;num=1;session_id=1445045;start=0;recs=20;subscription=1;value=0 using regex in python. i know i need to use lookbehind/ahead but i ca...
[ "Why use a regex?\n>>>> url = 'https://ww.site.gov.....'\n>>> start = url.index('show_detail&amp;') + len('show_detail&amp;')\n>>> end = url.index(';session_id=')\n>>> url[start:end]\n'id=4035219;num=1'\n\n", ">>> s= \"https://www.site.gov.uk//search/cgi-bin/contract_search/contract_search.cgi?rm=show_detail&amp;...
[ 5, 4, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005017308_python_regex.txt
Q: What is the difference between static files and media files in Django? I'm moving to Django 1.3 and find this separation of media and static files a bit confusing. Here is how default settings.py looks like: # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/med...
What is the difference between static files and media files in Django?
I'm moving to Django 1.3 and find this separation of media and static files a bit confusing. Here is how default settings.py looks like: # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served...
[ "Static files are meant for javascript/images etc, but media files are for user-uploaded content.\n", "As Uku Loskit said, static files are for things like your applications' css files, javascript files, images, etc. Media files are typically user or admin uploadable files.\nNormally you will want MEDIA_ROOT and ...
[ 80, 42 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005016589_django_python.txt
Q: how to get the current thing in my django filter and template this is my views.py : a=[{'s':'sss'},{'s':'wwww'},{'s':'ssaawdw'},{'s':'qqqww'}] def main(request, template_name='index.html'): context ={ 'a':a, } return render_to_response(template_name, context) this is my filter : def re...
how to get the current thing in my django filter and template
this is my views.py : a=[{'s':'sss'},{'s':'wwww'},{'s':'ssaawdw'},{'s':'qqqww'}] def main(request, template_name='index.html'): context ={ 'a':a, } return render_to_response(template_name, context) this is my filter : def return_next_element(list, index): if(index<len(list)-1): r...
[ "For your situation, I'd suggest doing the following:\n{% for dictionary in a %}\n {% for key, value in dictionary.iteritems %}\n {{ key }}ww{{ value }}\n {% endfor %}\n{% endfor %}\n\nBut to answer your question, use the with tag. \nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#with...
[ 0 ]
[]
[]
[ "django", "filter", "python", "templates" ]
stackoverflow_0005015500_django_filter_python_templates.txt