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: Find two of the same character in a string with regular expressions This is in reference to a question I asked before here I received a solution to the problem in that question but ended up needing to go with regex for this particular part. I need a regular expression to search and replace a string for instances of two vowels in a row that are the same, so the "oo" in "took", or the "ee" in "bees" and replace it with the one of the letters that was replaced and a :. Some examples of expected behavior: "took" should become "to:k" "waaeek" should become "wa:e:k" "raaag" should become "ra:ag" Thank you for the help. A: Try this: re.sub(r'([aeiou])\1', r'\1:', str) A: Search for ([aeiou])\1 and replace it with \1: I don't know about python, but you should be able to make the regex case insensitive and global with something like /([aeiou])\1/gi A: You'll need to use a back reference in your search expression. Try something like: ([a-z])+\1 (or ([a-z])\1 for just a double). A: What NOT to do: As noted, this will match any two vowels together. Leaving this answer as an example of what NOT to do. The correct answer (in this case) is to use backreferences as mentioned in numerous other answers. import re data = ["took","waaeek","raaag"] for s in data: print re.sub(r'([aeiou]){2}',r'\1:',s) This matches exactly two occurrences {2} of any member of the set [aeiou]. and replaces it with the vowel, captured with the parens () and placed in the sub string by the \1 followed by a ':' Output: to:k wa:e:k ra:ag
Find two of the same character in a string with regular expressions
This is in reference to a question I asked before here I received a solution to the problem in that question but ended up needing to go with regex for this particular part. I need a regular expression to search and replace a string for instances of two vowels in a row that are the same, so the "oo" in "took", or the "ee" in "bees" and replace it with the one of the letters that was replaced and a :. Some examples of expected behavior: "took" should become "to:k" "waaeek" should become "wa:e:k" "raaag" should become "ra:ag" Thank you for the help.
[ "Try this:\nre.sub(r'([aeiou])\\1', r'\\1:', str)\n\n", "Search for ([aeiou])\\1 and replace it with \\1:\nI don't know about python, but you should be able to make the regex case insensitive and global with something like /([aeiou])\\1/gi\n", "You'll need to use a back reference in your search expression. Try something like: ([a-z])+\\1 (or ([a-z])\\1 for just a double). \n", "What NOT to do:\nAs noted, this will match any two vowels together. Leaving this answer as an example of what NOT to do. The correct answer (in this case) is to use backreferences as mentioned in numerous other answers.\nimport re\n\ndata = [\"took\",\"waaeek\",\"raaag\"]\n\nfor s in data:\n print re.sub(r'([aeiou]){2}',r'\\1:',s)\n\nThis matches exactly two occurrences {2} of any member of the set [aeiou]. and replaces it with the vowel, captured with the parens () and placed in the sub string by the \\1 followed by a ':'\nOutput:\nto:k\nwa:e:k\nra:ag\n\n" ]
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0001868481_python_regex_replace.txt
Q: In Google App Engines, how to display the HTML source of a page of a fetched URL in Python? On Google App Engine I found this code that is fetching a web page's URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) Is this the right code to fecth that page's HTML source? Does the result variable contain HTML sorce of http://www.google.com/? If yes, what Python command I should use here instead of doSomethingWithResult(result.content) in order to display that HTML source? print result doesn't seem to be the right way. A: Yes, result.content will contain the raw content of that page. You should check the Content-Type header and verify that it's either text/html or application/xhtml+xml. To write the content of that page to the response, first write your status and headers and then: self.response.out.write(result.content)
In Google App Engines, how to display the HTML source of a page of a fetched URL in Python?
On Google App Engine I found this code that is fetching a web page's URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) Is this the right code to fecth that page's HTML source? Does the result variable contain HTML sorce of http://www.google.com/? If yes, what Python command I should use here instead of doSomethingWithResult(result.content) in order to display that HTML source? print result doesn't seem to be the right way.
[ "Yes, result.content will contain the raw content of that page. You should check the Content-Type header and verify that it's either text/html or application/xhtml+xml.\nTo write the content of that page to the response, first write your status and headers and then:\nself.response.out.write(result.content)\n\n" ]
[ 5 ]
[]
[]
[ "fetch", "google_app_engine", "html", "python", "url" ]
stackoverflow_0001868587_fetch_google_app_engine_html_python_url.txt
Q: WxPython, Windows Vista 64-bit, and failure I have Windows Vista 64-bit SP2. I am trying to use wxPython for GUI development with Python, because all my research pointed to that as the way to go. I have downloaded and installed the win64 wxPython. I get the same error every time. Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 4 5, in <module> from wx._core import * File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, i n <module> import _core_ ImportError: DLL load failed: %1 is not a valid Win32 application. I have installed on my python off the c, I have installed python26 in c:\program files (x86) and installing wxPython there, I have used 32bit, 64bit. I have tried searching everywhere for a similar problem, and I have hardly seen anyone else with this issue. Any help would be greatly appreciated. A: It looks like you're trying to run 64-bit wxPython on 32-bit Python. You need them both to be for the same architecture.
WxPython, Windows Vista 64-bit, and failure
I have Windows Vista 64-bit SP2. I am trying to use wxPython for GUI development with Python, because all my research pointed to that as the way to go. I have downloaded and installed the win64 wxPython. I get the same error every time. Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 4 5, in <module> from wx._core import * File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, i n <module> import _core_ ImportError: DLL load failed: %1 is not a valid Win32 application. I have installed on my python off the c, I have installed python26 in c:\program files (x86) and installing wxPython there, I have used 32bit, 64bit. I have tried searching everywhere for a similar problem, and I have hardly seen anyone else with this issue. Any help would be greatly appreciated.
[ "It looks like you're trying to run 64-bit wxPython on 32-bit Python. You need them both to be for the same architecture.\n" ]
[ 6 ]
[]
[]
[ "64_bit", "python", "windows_vista", "wxpython" ]
stackoverflow_0001868749_64_bit_python_windows_vista_wxpython.txt
Q: Convert and merge strings into a list in Python In Python I have four strings that include the formatting of a list: line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" How do I merge them all so I get a valid Python list such as: SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','f','g'] A: import ast line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" SumLine = [] for x in (line1, line2, line3, line4): SumLine.extend(ast.literal_eval(x)) print SumLine Don't use the built-in eval unless you have preternatural trust in the strings you're evaluating; ast.literal_eval, while limited to simple constants, is totally safe and therefore, most often, way preferable. A: The simple way is to concetenate the strings to an expression that can be evaulated to give the required result: line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" lines = [line1, line2, line3, line4] print eval('+'.join(lines)) However this is unsafe if you can't trust your input, so if you're using Python 2.6 or higher you should use the safe eval function ast.literal_eval in the ast module, although this doesn't work with the '+' trick so you will have to iterate over each element instead. A: Try eval: >>> line1 ="['a.b.c','b.c.a','c.d.e']" >>> line2 ="['def','efg']" >>> line3 ="['f']" >>> line4 ="['g']" >>> eval(line1) + eval(line2) + eval(line3) + eval(line4) ['a.b.c', 'b.c.a', 'c.d.e', 'def', 'efg', 'f', 'g'] But be careful, because eval can be dangerous. Don't use it on input that you receive from the user and haven't validated. A: The quick and dirty way is to use eval: SumLine = eval(line1) + eval(line2) + eval(line3) + eval(line4) But dont do this if you are getting these strings from someone else (ie user input) A: Where did you get these strings? Anything short of a real parser will be fragile. Below is what I would recommed, if I had not seen Alex Martelli's brilliant answer before! You may parse them as JSON arrays, but JSON wants to read double-quoted strings, not single quotes. This introduces fragility to the method, but still much preferable to eval() which is unsafe. import json line1 ="['a.b.c','b.c.a','c.d.e']" json.loads(line1.replace("'", '"')) The result is a parsed list like [u'a.b.c', u'b.c.a', u'c.d.e'], you may than go on to join the parsed lists. A: you need to eval them first and then you could sum the results. But I wonder how do you get this strings in the first place?
Convert and merge strings into a list in Python
In Python I have four strings that include the formatting of a list: line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" How do I merge them all so I get a valid Python list such as: SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','f','g']
[ "import ast\n\nline1 =\"['a.b.c','b.c.a','c.d.e']\"\nline2 =\"['def','efg']\"\nline3 =\"['f']\"\nline4 =\"['g']\"\n\nSumLine = []\n\nfor x in (line1, line2, line3, line4):\n SumLine.extend(ast.literal_eval(x))\n\nprint SumLine\n\nDon't use the built-in eval unless you have preternatural trust in the strings you're evaluating; ast.literal_eval, while limited to simple constants, is totally safe and therefore, most often, way preferable.\n", "The simple way is to concetenate the strings to an expression that can be evaulated to give the required result:\nline1 =\"['a.b.c','b.c.a','c.d.e']\"\nline2 =\"['def','efg']\"\nline3 =\"['f']\"\nline4 =\"['g']\"\nlines = [line1, line2, line3, line4]\n\nprint eval('+'.join(lines))\n\nHowever this is unsafe if you can't trust your input, so if you're using Python 2.6 or higher you should use the safe eval function ast.literal_eval in the ast module, although this doesn't work with the '+' trick so you will have to iterate over each element instead.\n", "Try eval:\n>>> line1 =\"['a.b.c','b.c.a','c.d.e']\"\n>>> line2 =\"['def','efg']\"\n>>> line3 =\"['f']\"\n>>> line4 =\"['g']\"\n>>> eval(line1) + eval(line2) + eval(line3) + eval(line4)\n['a.b.c', 'b.c.a', 'c.d.e', 'def', 'efg', 'f', 'g']\n\nBut be careful, because eval can be dangerous. Don't use it on input that you receive from the user and haven't validated.\n", "The quick and dirty way is to use eval:\nSumLine = eval(line1) + eval(line2) + eval(line3) + eval(line4)\n\nBut dont do this if you are getting these strings from someone else (ie user input)\n", "Where did you get these strings? Anything short of a real parser will be fragile. Below is what I would recommed, if I had not seen Alex Martelli's brilliant answer before!\nYou may parse them as JSON arrays, but JSON wants to read double-quoted strings, not single quotes. This introduces fragility to the method, but still much preferable to eval() which is unsafe.\nimport json\nline1 =\"['a.b.c','b.c.a','c.d.e']\"\njson.loads(line1.replace(\"'\", '\"'))\n\nThe result is a parsed list like [u'a.b.c', u'b.c.a', u'c.d.e'], you may than go on to join the parsed lists.\n", "you need to eval them first and then you could sum the results. But I wonder how do you get this strings in the first place?\n" ]
[ 11, 2, 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0001868857_list_python_string.txt
Q: Calling a function using ctypes with pointers to structs I am trying to call a C function sitting in a shared object from python, and using ctypes seems to be the best way of accomplishing this. I have to pass derived types to this function, with the following function prototype: int MyFunc (Config *config, int *argc, char **argv ) The Config struct is defined as typedef struct{ char *some_filename ; char **some_other_filenames ; int some_value ; Coord resolution; } Config; Coord is defined as typdef struct { double x, y, area } Coord ; The python ctypes code is then just a re-write of the derived types: class COORD ( ctypes.Structure ): _fields = [ ("lon",ctypes.c_double),\ ("lat", ctypes.c_double),\ ("area", ctypes.c_double)] coords = COORD() class CONFIG( ctypes.Structure ): _fields = [ ("some_filename", ctypes.c_char_p),\ ("some_other_filenames", ctypes.c_char_p('\0' * 256)),\ ("some_value", ctypes.c_int ),\ ("resolution", coords ) ] I then set up the arguments for MyFunc: MyFunc.argtypes = [ctypes.byref(CONFIG ) , ctypes.POINTER(ctypes.c_int),\ ctypes.POINTER (ctypes.c_char_p)] MyFunc.restype = ctypes.c_int myargv = ctypes.c_char_p * 2 argv = myargv("One", "Two") argc = ctypes.c_int ( 2 ) retval = MyFunc ( ctypes.byref(config), ctypes.byref(argc), ctypes(argv)) This, however, produces a segfault. Anyone have any ideas what's going on in here? UPDATE There was a typo in my question, from cutting and pasting, problem is still there! A: char** corresponds to POINTER(c_char_p), not to c_char_p. A: It doesn't look like your rewritten config structure is the same as the original one. If you're passing it back and forth the alignment would be off. Edit: I see you've fixed part of it. But I'm not sure that c_char_p is the same as char**.
Calling a function using ctypes with pointers to structs
I am trying to call a C function sitting in a shared object from python, and using ctypes seems to be the best way of accomplishing this. I have to pass derived types to this function, with the following function prototype: int MyFunc (Config *config, int *argc, char **argv ) The Config struct is defined as typedef struct{ char *some_filename ; char **some_other_filenames ; int some_value ; Coord resolution; } Config; Coord is defined as typdef struct { double x, y, area } Coord ; The python ctypes code is then just a re-write of the derived types: class COORD ( ctypes.Structure ): _fields = [ ("lon",ctypes.c_double),\ ("lat", ctypes.c_double),\ ("area", ctypes.c_double)] coords = COORD() class CONFIG( ctypes.Structure ): _fields = [ ("some_filename", ctypes.c_char_p),\ ("some_other_filenames", ctypes.c_char_p('\0' * 256)),\ ("some_value", ctypes.c_int ),\ ("resolution", coords ) ] I then set up the arguments for MyFunc: MyFunc.argtypes = [ctypes.byref(CONFIG ) , ctypes.POINTER(ctypes.c_int),\ ctypes.POINTER (ctypes.c_char_p)] MyFunc.restype = ctypes.c_int myargv = ctypes.c_char_p * 2 argv = myargv("One", "Two") argc = ctypes.c_int ( 2 ) retval = MyFunc ( ctypes.byref(config), ctypes.byref(argc), ctypes(argv)) This, however, produces a segfault. Anyone have any ideas what's going on in here? UPDATE There was a typo in my question, from cutting and pasting, problem is still there!
[ "char** corresponds to POINTER(c_char_p), not to c_char_p.\n", "It doesn't look like your rewritten config structure is the same as the original one. If you're passing it back and forth the alignment would be off.\nEdit: I see you've fixed part of it. But I'm not sure that c_char_p is the same as char**.\n" ]
[ 2, 1 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0001835429_c_ctypes_python.txt
Q: Basic easy_install question on python 2.6 I'm trying to install a python api for controlling imagemagick (this) and followed the instructions. I imported easy_install: import easy_install and then input the line: easy_install http://svn2.assembla.com/svn/pythonmagickwand/trunk However I got the error SyntaxError: invalid syntax and 'http' was highlighted. I'm wondering what causes the error - this is on Windows XP. A: Check http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install for a good reference. also, easy_install is run from the command line. A: easy_install is a shell command, run at the shell. It's not a python command; it's not run from within Python. A: I believe easy_install is a script that should be run from the command line A: Typical easy_install usage would be more like "easy_install imagemagick", a package name rather than a pointer to an svn repository. It looks like you can install from svn via easy_install with the -i flag. Long-term, I'd suggest looking at pip: it does everything easy_install does, but with a lot more flexibility and without creating eggs for everything (which makes it easier to edit and modify by hand when you need to patch something).
Basic easy_install question on python 2.6
I'm trying to install a python api for controlling imagemagick (this) and followed the instructions. I imported easy_install: import easy_install and then input the line: easy_install http://svn2.assembla.com/svn/pythonmagickwand/trunk However I got the error SyntaxError: invalid syntax and 'http' was highlighted. I'm wondering what causes the error - this is on Windows XP.
[ "Check\nhttp://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install\nfor a good reference.\nalso, easy_install is run from the command line.\n", "easy_install is a shell command, run at the shell.\nIt's not a python command; it's not run from within Python.\n", "I believe easy_install is a script that should be run from the command line\n", "Typical easy_install usage would be more like \"easy_install imagemagick\", a package name rather than a pointer to an svn repository. It looks like you can install from svn via easy_install with the -i flag. Long-term, I'd suggest looking at pip: it does everything easy_install does, but with a lot more flexibility and without creating eggs for everything (which makes it easier to edit and modify by hand when you need to patch something). \n" ]
[ 4, 2, 1, 0 ]
[]
[]
[ "easy_install", "imagemagick", "python" ]
stackoverflow_0001868798_easy_install_imagemagick_python.txt
Q: how to set the unique identifier key dynamically from a list containing unique numbers from a csv file? I would like to know if there is a way to set the key of an entity in google app engine dynamically from a list of unique numbers stored in a csv file and bulkload it to the datastore. Also is it possible to have an entity model with out any properties and just use the the set of predefined unique numbers as keys. Thanks, Arun A: Yes, I think that is completely possible. Only keep in mind that a key has to be unique across the whole application, so if you use it as the key for an entity in the data model you design to keep the keys, you won't be able to use it in your application's real data models entities (wherever you intend to use the key in the end). I presume you want to create an entity per entry in the csv file and that's why you ask about the empty data model, all you want is to store the key until it gets assigned. For the reason I gave you above I think you should have another Property, probably a StringProperty, to hold the key. Just make sure that when you do the key assignment by doing something like class PrecalculatedKey(db.Model): precalc_key = db.StringProperty(required=True) precalculated_key = PrecalculatedKey.all().fetch(1) s = AppModel(key_name=precalculated_key.precalc_key)` the whole thing (fetching a new key, using it on an AppModel and deleting the used key from the model) happens inside a transaction, you don't want to give the same key to two different AppModel entities.
how to set the unique identifier key dynamically from a list containing unique numbers from a csv file?
I would like to know if there is a way to set the key of an entity in google app engine dynamically from a list of unique numbers stored in a csv file and bulkload it to the datastore. Also is it possible to have an entity model with out any properties and just use the the set of predefined unique numbers as keys. Thanks, Arun
[ "Yes, I think that is completely possible. \nOnly keep in mind that a key has to be unique across the whole application, so if you use it as the key for an entity in the data model you design to keep the keys, you won't be able to use it in your application's real data models entities (wherever you intend to use the key in the end).\nI presume you want to create an entity per entry in the csv file and that's why you ask about the empty data model, all you want is to store the key until it gets assigned. For the reason I gave you above I think you should have another Property, probably a StringProperty, to hold the key.\nJust make sure that when you do the key assignment by doing something like\nclass PrecalculatedKey(db.Model):\n precalc_key = db.StringProperty(required=True)\n\nprecalculated_key = PrecalculatedKey.all().fetch(1)\ns = AppModel(key_name=precalculated_key.precalc_key)`\n\nthe whole thing (fetching a new key, using it on an AppModel and deleting the used key from the model) happens inside a transaction, you don't want to give the same key to two different AppModel entities.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001866727_google_app_engine_python.txt
Q: media.set_xx ValueError I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now the program is telling me that I have an invalid value specified for the red component of my colour. ValueError: Invalid red value specified. Even though it's only being changed from 64 to 56. Any help on the matter would be appreciated! Here's the Python code: import os import media import sys def recolour(old, new, folder): old_list = old.split(' ') new_list = new.split(' ') folder_location = os.path.join('C:\\', 'Users', 'Owner', 'Spriting', folder) for filename in os.listdir (folder): current_file = media.load_picture(folder_location + '\\' + filename) for pix in current_file: if (media.get_red(pix) == int(old_list[0])) and \ (media.get_green(pix) == int(old_list[1])) and \ (media.get_blue(pix) == int(old_list[2])): media.set_red(pix, new_list[0]) media.set_green(pix, new_list[1]) media.set_blue(pix, new_list[2]) media.save(pic) if name == 'main': while 1: old = str(raw_input('Please insert the original RGB component, separated by a single space: ')) if old == 'quit': sys.exit(0) new = str(raw_input('Please insert the new RGB component, separated by a single space: ')) if new == 'quit': sys.exit(0) folder = str(raw_input('Please insert the name of the folder you wish to modify: ')) if folder == 'quit': sys.exit(0) else: recolour(old, new, folder) A: Slow going; but no worries I got it. Didn't convert the values to integers, was trying to use strings as arguments...
media.set_xx ValueError
I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now the program is telling me that I have an invalid value specified for the red component of my colour. ValueError: Invalid red value specified. Even though it's only being changed from 64 to 56. Any help on the matter would be appreciated! Here's the Python code: import os import media import sys def recolour(old, new, folder): old_list = old.split(' ') new_list = new.split(' ') folder_location = os.path.join('C:\\', 'Users', 'Owner', 'Spriting', folder) for filename in os.listdir (folder): current_file = media.load_picture(folder_location + '\\' + filename) for pix in current_file: if (media.get_red(pix) == int(old_list[0])) and \ (media.get_green(pix) == int(old_list[1])) and \ (media.get_blue(pix) == int(old_list[2])): media.set_red(pix, new_list[0]) media.set_green(pix, new_list[1]) media.set_blue(pix, new_list[2]) media.save(pic) if name == 'main': while 1: old = str(raw_input('Please insert the original RGB component, separated by a single space: ')) if old == 'quit': sys.exit(0) new = str(raw_input('Please insert the new RGB component, separated by a single space: ')) if new == 'quit': sys.exit(0) folder = str(raw_input('Please insert the name of the folder you wish to modify: ')) if folder == 'quit': sys.exit(0) else: recolour(old, new, folder)
[ "Slow going; but no worries I got it. Didn't convert the values to integers, was trying to use strings as arguments...\n" ]
[ 0 ]
[]
[]
[ "media", "python" ]
stackoverflow_0001829810_media_python.txt
Q: Design principles for complete noobs? I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning programmer? I don't think I'd have as many problems if I knew a little about the thought processes that go into software design. A: Head First Design Patterns might be a gentler intro to the GoF "Design Patterns" book Steve McConnell's Code Complete is a good guide to many things code, including how to use good strategies in languages that don't natively support them. Martin Fowler's Refactoring refers heavily to Design Patterns, but is a great catalog of so-so code, and better ways of writing it (I read it about the same time I read "Code Complete", a couple of years [tsk tsk] before reading Design Patterns, and "Refactoring" had a major impact in how I looked at code I wrote. For the better, I like to think). None of these are "free." But how good of advice do you want? If you're trying to invest in your career, this is the cheapest way to do it. A: DRY and YAGNI are good starting points for beginners and you need to study and understand OOP. Regarding Design Patterns (which are a bit more advanced and abstract than DRY and OOP) you can study from the free Design Patterns - Java Companion. The fact that it's not Python should not bother you - classic design patterns are applicable everywhere. When you feel like going further have a look at DDD (free DDD book from Eric Evans) and of course Unit Testing which, believe it or not, will improve your code and you as a designer. A: Sounds like you want a book on design patterns. Take a look at: Design Patterns - Elements of Reusable Object-Oriented Software. Warning it is not Python specific though. You could also take at this online resource for Python design patterns. Stackoverflow user @S.Lott also has a lot of really good Python resources that he wrote. You can see them on his Stackoverflow page. A: Read other people's code. That is the best way to learn better design principles. Read people's code at your work, read people's code on forums, take a look at open source projects... and never stop coding, because the best teacher is the mistakes you make along the way... Check out the book, Pragmatic Programmer, from Journeyman to Master. This is a great book to help fill that gap in knowledge you are looking for. A: A couple of other principles that may be worth noting: C.R.A.P.:The Four Principles of Sound Design - For usability these are good principles to know. Pablo's Topic of the Month - March: SOLID Principles - Has some good ideas as well. A: With a year of programming experience, I won't suggest Design Patterns (or Head First Design Patterns), as I think Design Patterns (the concepts) is best processed once you have more programming experience, perhaps more like 5-10 years of experience. I think the book, The Pragmatic Programmer: from Journeyman to Master by Andrew Hunt and David Thomas is perhaps your best bet for the most bang for your buck at the level you are at currently. Here is an excellent summary of the topics and contents (from Jeff Atwood at Coding Horror). Use inter-library loan if you cannot afford to purchase your own copy. Two other titles that are also language-agnostic yet classic books highly recommended for new programmers that you can keep in mind are The Mythical Man-Month (anniversary edition published in 1995) by Fred Brooks, and Code Complete (second edition) by Steven McConnell. These books will help expand your programming knowledge without overwhelming you at your current stage of development, and make for a solid foundation for becoming a better programmer. All of these books are constantly on the top of recommended programming books for serious programmers, and they are all "old" enough that they are clearly not a fad, but enduring recommendations not limited by a particular language, environment or tool-set. A: Check out this book: Head First Design Patterns ...literally. Check it out. From the library. A: It's not a book (books are so passé), but it's definitely good to spend a few hours reading through the Portland Pattern Repository. While it's also not a tutorial, it has great code examples, and equally great discussion on design patterns and programming in general. It's an excellent resource on learning how to think like a programmer. A: I suggest Structure and Interpretation of Computer Programs, which is available on-line in book form, as well as an on-line course. It's not a book on design patterns, but it will help you develop good fundamentals for building applications. A: I would definitely add another book. I think that Clean Code by Bob Martin is a very good book to tell you how to write code that is maintainable. It introduces several easy rules that leads to code that is very well structured and readable. A: The best way to learn good software design is to write code in a bunch of different ways, read code written by others, and learn what works and what doesn't first-hand. When you are writing code, ask the following questions: How will I test it? How will I debug it? What do I find myself doing over and over again? I'm sure other people have other ideas, based on their own experiences. A: Head First Design Patterns would be a good place to start for a beginner. It's probably easier to get into than the Gang of four book. A: You should probably learn more about object oriented programming. Here is a nice tutorial that's based on Python: OOP Tutorial in Python Object oriented programming is a way to organize you programs in a way that mirrors the things in the problem you are trying to solve. HIH ...richie A: Learn a different language! I love python, and, despite what everyone says, my python is better because I know java. (Some people complain that starting with java causes one to initially write clunky python, but if you already know more or less the easy way to do something in python, you will be safe from this.) Let me do a little bit of chainsaw surgery here. It is easy to write python the first time. I write it in vim, because I can and because I love vim. It is easy to maintain and refactor java if you have an IDE. I write java in Eclipse, because I'd be hopeless without it. But the point is, writing in a language that forces you to use abstractions with a tool that makes abstractions easier will slowly shape your brain to code more abstractly. You will bring that back to python, even though the preferred abstractions will be slightly different. A: Wow, I wonder why nobody said until now that U really should not go too deep into theory. After one year Ur code is ugly. Nothing to do about it. If U get most things done U want to finish, it is already very awesome. But U cannot cheat Ur brain with theory. Just go on writing and be angry about Ur code. That is the best way to write better. Take Ur time to think about how to write working code in a more readable/usable/maintainable way as often as U can. AND: Read other peoples code + get reviews on Ur code! There should be people out there who can write better then U. Learn by example! And maybe 20% of Ur programming time (that means if U code every day, not more than 2 months a year!) get some theory. Why not start with masses of theory? U kill Ur motivation and Ur instinct. But when U sit there and try to solve a problem it is mostly about the right instinct. With too much theory U overthink the problem and Ur solutions. But Ur instinct will be still on the level of Ur experience, no matter how much U read. (sorry, if bad english. not my mothertounge) A: Get the Gang of four book - Design Patterns.. But please don't over follow it and try to use Singleton everywhere :) Just know it and use it wisely. Also after that look into good open source code and try to learn from their structures.. I suggest google code and sourceforge A: Depending on your background (and to some degree, experience) you might also want to look into how basic algorithms. A book like Introduction to Algorithms is a good start. Besides that, I also vote for Head First Design Patterns. The GoF works better as a reference later on. A: Forget the books. In my experience (which includes time as an instructor and writer of OO design courses) some people can do design and some pople can't - it's a talent, like being a sculptor. At best, reading books on the subject will enable you to design badly, if you don't have the talent.
Design principles for complete noobs?
I've been programming for around a year now, and all the stuff that I've written works - it's just extremely poorly written from my point of view. I'd like to know if there are any (free) good books on Software Design out there that can offer a little guidance to the beginning programmer? I don't think I'd have as many problems if I knew a little about the thought processes that go into software design.
[ "Head First Design Patterns might be a gentler intro to the GoF \"Design Patterns\" book\nSteve McConnell's Code Complete is a good guide to many things code, including how to use good strategies in languages that don't natively support them.\nMartin Fowler's Refactoring refers heavily to Design Patterns, but is a great catalog of so-so code, and better ways of writing it (I read it about the same time I read \"Code Complete\", a couple of years [tsk tsk] before reading Design Patterns, and \"Refactoring\" had a major impact in how I looked at code I wrote. For the better, I like to think).\nNone of these are \"free.\" But how good of advice do you want? If you're trying to invest in your career, this is the cheapest way to do it.\n", "DRY and YAGNI are good starting points for beginners and you need to study and understand OOP.\nRegarding Design Patterns (which are a bit more advanced and abstract than DRY and OOP) you can study from the free Design Patterns - Java Companion. The fact that it's not Python should not bother you - classic design patterns are applicable everywhere.\nWhen you feel like going further have a look at DDD (free DDD book from Eric Evans) and of course Unit Testing which, believe it or not, will improve your code and you as a designer.\n", "Sounds like you want a book on design patterns. \nTake a look at: Design Patterns - Elements of Reusable Object-Oriented Software. Warning it is not Python specific though. \nYou could also take at this online resource for Python design patterns.\nStackoverflow user @S.Lott also has a lot of really good Python resources that he wrote. You can see them on his Stackoverflow page. \n", "Read other people's code. That is the best way to learn better design principles. Read people's code at your work, read people's code on forums, take a look at open source projects... and never stop coding, because the best teacher is the mistakes you make along the way...\nCheck out the book, Pragmatic Programmer, from Journeyman to Master. This is a great book to help fill that gap in knowledge you are looking for.\n", "A couple of other principles that may be worth noting:\nC.R.A.P.:The Four Principles of Sound Design - For usability these are good principles to know.\nPablo's Topic of the Month - March: SOLID Principles - Has some good ideas as well.\n", "With a year of programming experience, I won't suggest Design Patterns (or Head First Design Patterns), as I think Design Patterns (the concepts) is best processed once you have more programming experience, perhaps more like 5-10 years of experience.\nI think the book, The Pragmatic Programmer: from Journeyman to Master by Andrew Hunt and David Thomas is perhaps your best bet for the most bang for your buck at the level you are at currently. Here is an excellent summary of the topics and contents (from Jeff Atwood at Coding Horror). Use inter-library loan if you cannot afford to purchase your own copy.\n\nTwo other titles that are also language-agnostic yet classic books highly recommended for new programmers that you can keep in mind are The Mythical Man-Month (anniversary edition published in 1995) by Fred Brooks, and Code Complete (second edition) by Steven McConnell. \nThese books will help expand your programming knowledge without overwhelming you at your current stage of development, and make for a solid foundation for becoming a better programmer. All of these books are constantly on the top of recommended programming books for serious programmers, and they are all \"old\" enough that they are clearly not a fad, but enduring recommendations not limited by a particular language, environment or tool-set.\n", "Check out this book: Head First Design Patterns ...literally. Check it out. From the library.\n", "It's not a book (books are so passé), but it's definitely good to spend a few hours reading through the Portland Pattern Repository. \nWhile it's also not a tutorial, it has great code examples, and equally great discussion on design patterns and programming in general. It's an excellent resource on learning how to think like a programmer. \n", "I suggest Structure and Interpretation of Computer Programs, which is available on-line in book form, as well as an on-line course.\nIt's not a book on design patterns, but it will help you develop good fundamentals for building applications.\n", "I would definitely add another book. I think that Clean Code by Bob Martin is a very good book to tell you how to write code that is maintainable. It introduces several easy rules that leads to code that is very well structured and readable.\n", "The best way to learn good software design is to write code in a bunch of different ways, read code written by others, and learn what works and what doesn't first-hand.\nWhen you are writing code, ask the following questions:\n\nHow will I test it?\nHow will I debug it?\nWhat do I find myself doing over and over again?\n\nI'm sure other people have other ideas, based on their own experiences. \n", "Head First Design Patterns would be a good place to start for a beginner. It's probably easier to get into than the Gang of four book.\n", "You should probably learn more about object oriented programming. Here is a nice tutorial that's based on Python:\nOOP Tutorial in Python\nObject oriented programming is a way to organize you programs in a way that mirrors the things in the problem you are trying to solve.\nHIH\n...richie\n", "Learn a different language! I love python, and, despite what everyone says, my python is better because I know java. (Some people complain that starting with java causes one to initially write clunky python, but if you already know more or less the easy way to do something in python, you will be safe from this.)\nLet me do a little bit of chainsaw surgery here. It is easy to write python the first time. I write it in vim, because I can and because I love vim. It is easy to maintain and refactor java if you have an IDE. I write java in Eclipse, because I'd be hopeless without it. But the point is, writing in a language that forces you to use abstractions with a tool that makes abstractions easier will slowly shape your brain to code more abstractly. You will bring that back to python, even though the preferred abstractions will be slightly different.\n", "Wow, I wonder why nobody said until now that U really should not go too deep into theory. After one year Ur code is ugly. Nothing to do about it. If U get most things done U want to finish, it is already very awesome. But U cannot cheat Ur brain with theory. Just go on writing and be angry about Ur code. That is the best way to write better. Take Ur time to think about how to write working code in a more readable/usable/maintainable way as often as U can.\nAND: Read other peoples code + get reviews on Ur code! There should be people out there who can write better then U. Learn by example!\nAnd maybe 20% of Ur programming time (that means if U code every day, not more than 2 months a year!) get some theory.\nWhy not start with masses of theory? U kill Ur motivation and Ur instinct. But when U sit there and try to solve a problem it is mostly about the right instinct. With too much theory U overthink the problem and Ur solutions. But Ur instinct will be still on the level of Ur experience, no matter how much U read.\n(sorry, if bad english. not my mothertounge)\n", "Get the Gang of four book - Design Patterns..\nBut please don't over follow it and try to use Singleton everywhere :)\nJust know it and use it wisely. Also after that look into good open source code and try to learn from their structures.. I suggest google code and sourceforge\n", "Depending on your background (and to some degree, experience) you might also want to look into how basic algorithms. A book like Introduction to Algorithms is a good start.\nBesides that, I also vote for Head First Design Patterns. The GoF works better as a reference later on.\n", "Forget the books. In my experience (which includes time as an instructor and writer of OO design courses) some people can do design and some pople can't - it's a talent, like being a sculptor. At best, reading books on the subject will enable you to design badly, if you don't have the talent.\n" ]
[ 12, 7, 4, 4, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "software_design" ]
stackoverflow_0001868879_python_software_design.txt
Q: Hook into and log "everything" in the windows message queue Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input. A: There's actually a package that wraps the SetWindowsHookEx function, called pyHook. I've used it before to write a primitive key-logger (as an experiment in monitoring myself to assist with reporting work hours) and it worked fine for that. A: Usually this is done with SetWindowsHookEx Function. In Python you probably must use 3rd party libraries, like Python for Windows extensions. PyCWnd.HookMessage and PyCWnd.HookAllKeyStrokes might be what you need. A: You can use SetWinEventHook to catch most system windowing activity. The advantage from traditional hooks is that you can do it from your process, that is, you don't need to write a hooking DLL. Also, when the thread that called SetWinEventHook finishes, Windows releases the handler automatically. Having out of context hooking prevents you from crashing other applications, as a minimal error on an injected DLL will possibly do.
Hook into and log "everything" in the windows message queue
Has anyone got a working code example of how to connect to the windows message queue(post/sendMessage) and log all messages there? Preferably in Python. I'm interrested in this to easier be able to create test-scripts that emulates user input.
[ "There's actually a package that wraps the SetWindowsHookEx function, called pyHook. I've used it before to write a primitive key-logger (as an experiment in monitoring myself to assist with reporting work hours) and it worked fine for that.\n", "Usually this is done with SetWindowsHookEx Function.\n\nIn Python you probably must use 3rd party libraries, like Python for Windows extensions.\nPyCWnd.HookMessage and PyCWnd.HookAllKeyStrokes might be what you need.\n", "You can use SetWinEventHook to catch most system windowing activity. The advantage from traditional hooks is that you can do it from your process, that is, you don't need to write a hooking DLL. Also, when the thread that called SetWinEventHook finishes, Windows releases the handler automatically. Having out of context hooking prevents you from crashing other applications, as a minimal error on an injected DLL will possibly do.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "message_queue", "python", "windows" ]
stackoverflow_0001305847_message_queue_python_windows.txt
Q: Python unable to acquire Oracle environment handle in Apache I can run my django application using the developer server, but it does not run under apache. The error is: Unable to acquire Oracle environment handle Adding an ORACLE_HOME environment variable pointing to my 10g client did not fix the issue. NOTE: the ORACLE_HOME did not end with a slash. Also, this is using the XAMPP version of Apache if that makes a difference. Apache, Python, Django, and Oracle are all installed on the C: of a Windows 2003 32bit server. (No spaces in the name). Final NOTE: The issue is in the use of XAMPP for the Apache server. When I installed the normal Apache, the issue did not appear. XAMPP must be modifying the path so that it cannot see the Oracle home. A: What is path to where your django application resides? If it's in c:\Program Files (x86)\XXX (as seen on 64-bit Windows), this is a known issue
Python unable to acquire Oracle environment handle in Apache
I can run my django application using the developer server, but it does not run under apache. The error is: Unable to acquire Oracle environment handle Adding an ORACLE_HOME environment variable pointing to my 10g client did not fix the issue. NOTE: the ORACLE_HOME did not end with a slash. Also, this is using the XAMPP version of Apache if that makes a difference. Apache, Python, Django, and Oracle are all installed on the C: of a Windows 2003 32bit server. (No spaces in the name). Final NOTE: The issue is in the use of XAMPP for the Apache server. When I installed the normal Apache, the issue did not appear. XAMPP must be modifying the path so that it cannot see the Oracle home.
[ "What is path to where your django application resides?\nIf it's in c:\\Program Files (x86)\\XXX (as seen on 64-bit Windows), this is a known issue\n" ]
[ 0 ]
[]
[]
[ "oracle10g", "python", "windows" ]
stackoverflow_0001869832_oracle10g_python_windows.txt
Q: Scaffolding in pylons Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model. A: The question is super old, but hell: http://code.google.com/p/formalchemy/ Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic). A: I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see AdminPylon and Restin) but none have really kept up with SQLAlchemy's rapidly developing orm api. Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that. A: Just updating an old question. DBSprockets has been replaced by sprox which learns a lot of lessons from it and is pretty cool. It isn't quite the throwaway 'scaffolding' that Rails provides, it is more like an agile form generation tool that is highly extensible.
Scaffolding in pylons
Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model.
[ "The question is super old, but hell: http://code.google.com/p/formalchemy/\nGives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic).\n", "I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see AdminPylon and Restin) but none have really kept up with SQLAlchemy's rapidly developing orm api.\nSince DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.\n", "Just updating an old question. DBSprockets has been replaced by sprox which learns a lot of lessons from it and is pretty cool.\nIt isn't quite the throwaway 'scaffolding' that Rails provides, it is more like an agile form generation tool that is highly extensible.\n" ]
[ 7, 5, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0000034916_pylons_python.txt
Q: Recreating Postgres COPY directly in Python? I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB. What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk load all of this into the database. This works, but is suboptimal, I'd prefer to be able to do this all directly from python. Is there a method from within python to replicate the COPY type bulk load in Postgres? A: If you're using the psycopg2 driver, the cursors provide a copy_to and copy_from function that can read from any file-like object (including a StringIO buffer). There are examples in the files examples/copy_from.py and examples/copy_to.py that come with the psycopg2 source distribution. This excerpt is from the copy_from.py example: conn = psycopg2.connect(DSN) curs = conn.cursor() curs.execute("CREATE TABLE test_copy (fld1 text, fld2 text, fld3 int4)") # anything can be used as a file if it has .read() and .readline() methods data = StringIO.StringIO() data.write('\n'.join(['Tom\tJenkins\t37', 'Madonna\t\N\t45', 'Federico\tDi Gregorio\t\N'])) data.seek(0) curs.copy_from(data, 'test_copy')
Recreating Postgres COPY directly in Python?
I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB. What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk load all of this into the database. This works, but is suboptimal, I'd prefer to be able to do this all directly from python. Is there a method from within python to replicate the COPY type bulk load in Postgres?
[ "If you're using the psycopg2 driver, the cursors provide a copy_to and copy_from function that can read from any file-like object (including a StringIO buffer).\nThere are examples in the files examples/copy_from.py and examples/copy_to.py that come with the psycopg2 source distribution.\nThis excerpt is from the copy_from.py example:\nconn = psycopg2.connect(DSN)\ncurs = conn.cursor()\ncurs.execute(\"CREATE TABLE test_copy (fld1 text, fld2 text, fld3 int4)\")\n\n# anything can be used as a file if it has .read() and .readline() methods\ndata = StringIO.StringIO()\ndata.write('\\n'.join(['Tom\\tJenkins\\t37',\n 'Madonna\\t\\N\\t45',\n 'Federico\\tDi Gregorio\\t\\N']))\ndata.seek(0)\n\ncurs.copy_from(data, 'test_copy')\n\n" ]
[ 53 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0001869973_postgresql_psycopg2_python.txt
Q: How to get the URL Image which is displyed by script When I view the source of page, I do not find the image src. but the image is displayed on the page. This image is generated by some server side code. I am using the selenium for testing. I want to download this image for verification/comparison. How to get that image using python? A: You need to step through the Javascript on that page which might be calling some server-side code to generate that image (e.g. a Captcha image). Using the tools-> page info-> media in Firefox also gives you images on the page that the browser knows about. This post for example gives me https://stackoverflow.com/posts/1838047/ivc/44ca as an image. That clearly points to some server side code. A: If you aren't seeing an actual image tag in the HTML, your next step would seem to be figuring out how its being displayed. The first place I'd suggest looking is in the .css files for this page. Images can actually be embedded using CSS, and this seems like the next likely option after being in the HTML code itself. If it isn't in there, you may be dealing with some form of technique deliberately intended to prevent you from being able to download the image with a script. This may use obfuscated JavaScript or something similar and I wouldn't expect people to be able to give you an easy solution to bypass it (since it was carefully designed to resist exactly that). A: if you just want to download the image, theres two strategies you can try: use a something like Firebug or Chrome developer tools. right click the element in question, click "inspect element", and look at the css properties of the element. if you look around, you should find something like background-image style or maybe just a normal tag. then you'll have the url to the image. use a something like Firebug or Chrome developer tools: look in the "resources" tab, and look for image files that show up.
How to get the URL Image which is displyed by script
When I view the source of page, I do not find the image src. but the image is displayed on the page. This image is generated by some server side code. I am using the selenium for testing. I want to download this image for verification/comparison. How to get that image using python?
[ "You need to step through the Javascript on that page which might be calling some server-side code to generate that image (e.g. a Captcha image). Using the tools-> page info-> media in Firefox also gives you images on the page that the browser knows about. This post for example gives me https://stackoverflow.com/posts/1838047/ivc/44ca as an image. That clearly points to some server side code.\n", "If you aren't seeing an actual image tag in the HTML, your next step would seem to be figuring out how its being displayed. \nThe first place I'd suggest looking is in the .css files for this page. Images can actually be embedded using CSS, and this seems like the next likely option after being in the HTML code itself.\nIf it isn't in there, you may be dealing with some form of technique deliberately intended to prevent you from being able to download the image with a script. This may use obfuscated JavaScript or something similar and I wouldn't expect people to be able to give you an easy solution to bypass it (since it was carefully designed to resist exactly that).\n", "if you just want to download the image, theres two strategies you can try:\n\nuse a something like Firebug or Chrome developer tools. right click the element in question, click \"inspect element\", and look at the css properties of the element. if you look around, you should find something like background-image style or maybe just a normal tag. then you'll have the url to the image.\nuse a something like Firebug or Chrome developer tools: look in the \"resources\" tab, and look for image files that show up.\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001838047_python.txt
Q: Python to generate output ready for Excel I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now. Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around the world. There is no ftp, scp, or anything like that, so I can't generate the excel on the Linux device and transfer it locally. The ONLY way to get the info is to copy/paste from the ssh window into the local machine and post-process it My question is what would be the best (from a user point of view as others will be using it) format to generate? 1.as it is now (spaces & tabs), 2.reformat as csv or as 3.convert to xml A: CSV is more robust than your current format under "copy and paste transfer" -- spaces and tabs can easily get confused, commas and doublequotes aren't. And the Python standard library's csv module makes it pretty easy to solidly generate good CSV output. A: Reformat it as CSV. It's dead easy to do, is fairly human readable, and can be read by loads of pieces of spreadsheet software. A: Are you sure copy-paste is the only way? If you can interactively ssh to the Linux device, then you can also ssh plus run a command plus redirect the output. So: ssh remote-linux-box command-to-run >output-file This doesn't involve any manual copy and paste at all.
Python to generate output ready for Excel
I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now. Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around the world. There is no ftp, scp, or anything like that, so I can't generate the excel on the Linux device and transfer it locally. The ONLY way to get the info is to copy/paste from the ssh window into the local machine and post-process it My question is what would be the best (from a user point of view as others will be using it) format to generate? 1.as it is now (spaces & tabs), 2.reformat as csv or as 3.convert to xml
[ "CSV is more robust than your current format under \"copy and paste transfer\" -- spaces and tabs can easily get confused, commas and doublequotes aren't. And the Python standard library's csv module makes it pretty easy to solidly generate good CSV output.\n", "Reformat it as CSV. It's dead easy to do, is fairly human readable, and can be read by loads of pieces of spreadsheet software.\n", "Are you sure copy-paste is the only way? If you can interactively ssh to the Linux device, then you can also ssh plus run a command plus redirect the output. So:\nssh remote-linux-box command-to-run >output-file\n\nThis doesn't involve any manual copy and paste at all.\n" ]
[ 7, 0, 0 ]
[]
[]
[ "csv", "excel", "python", "xml" ]
stackoverflow_0001870383_csv_excel_python_xml.txt
Q: skip an element in zip I have two files that are zipped with something like the following: for line in zip(open(file1), open(file2)): # do-something Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an additional script/program), but since the actual number of involved files is huge, I'd prefer to solve the problem at this level. So, what I want is something like the following (which would be valid, if open(file) were subscriptable): for line in zip(open(file1), open(file2)[1:]): # do-something A: open gives you an iterator, so it's not "subscriptable" but it can easily be advanced by one (with the next builtin in 2.6 or better, the .next() method in older Python versions -- I'm assuming 2.6 or better here). So where you'd like to say: for line in zip(open(file1), open(file2)[1:]): say, instead: f2 = open(file2) next(f2) for line in zip(open(file1), f2): or, if you're keen on one-liners: import itertools as it for line in it.izip(open(file1), it.islice(open(f2), 1, None)): In the latter case, since I'm importing itertools anyway, I also take advantage to use its izip approach rather than the memory-wasting zip built-in;-). A: Take a look at itertools: for line in itertools.izip( open(file1), itertools.islice(open(file2), 1, None) ): # do something Edit: changed from zip to the itertools.izip function. A: f1 = open(file1) f2 = open(file2) f2.next() # Skip the first line of file2 (used to be readline() - thanks, Alex) for line in zip(f1, f2): # do-something
skip an element in zip
I have two files that are zipped with something like the following: for line in zip(open(file1), open(file2)): # do-something Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an additional script/program), but since the actual number of involved files is huge, I'd prefer to solve the problem at this level. So, what I want is something like the following (which would be valid, if open(file) were subscriptable): for line in zip(open(file1), open(file2)[1:]): # do-something
[ "open gives you an iterator, so it's not \"subscriptable\" but it can easily be advanced by one (with the next builtin in 2.6 or better, the .next() method in older Python versions -- I'm assuming 2.6 or better here).\nSo where you'd like to say:\nfor line in zip(open(file1), open(file2)[1:]):\n\nsay, instead:\nf2 = open(file2)\nnext(f2)\nfor line in zip(open(file1), f2):\n\nor, if you're keen on one-liners:\nimport itertools as it\nfor line in it.izip(open(file1), it.islice(open(f2), 1, None)):\n\nIn the latter case, since I'm importing itertools anyway, I also take advantage to use its izip approach rather than the memory-wasting zip built-in;-).\n", "Take a look at itertools:\nfor line in itertools.izip(\n open(file1),\n itertools.islice(open(file2), 1, None)\n ):\n # do something\n\nEdit: changed from zip to the itertools.izip function.\n", "f1 = open(file1)\nf2 = open(file2)\nf2.next() # Skip the first line of file2 (used to be readline() - thanks, Alex)\nfor line in zip(f1, f2):\n # do-something\n\n" ]
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001870372_python.txt
Q: Recognizing newline characters in Python So I would like to grab stdout from a subprocess and then write the output to a file using python. The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of one line containg \n's, the file contains newlines where there are \n's. Here is my existing code: import os, subprocess from cStringIO import StringIO proc = subprocess.Popen('foo.exe', shell=True, stdout=subprocess.PIPE,) stdout_value = proc.communicate()[0] f=open('fooOut.txt', 'w') f.write(str(repr(stdout_value))) f.close() Current File Text: abbbb\nabbbb\naaaaab What I would like: abbbb bbbb aaaaab A: Don't call repr(), ie. just call f.write(stdout_value) A: Why repr? That turns a object into its representation, which for strings means converting things like chr(10) (newline) into '\n'. A: The repr (which doubles up the "escapes", i.e. backslash characters) is what's causing you to "lose formatting" -- why are you doing that at all? And btw the str call is totally redundant (innocuous, but totally useless -- why have it there?!).
Recognizing newline characters in Python
So I would like to grab stdout from a subprocess and then write the output to a file using python. The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of one line containg \n's, the file contains newlines where there are \n's. Here is my existing code: import os, subprocess from cStringIO import StringIO proc = subprocess.Popen('foo.exe', shell=True, stdout=subprocess.PIPE,) stdout_value = proc.communicate()[0] f=open('fooOut.txt', 'w') f.write(str(repr(stdout_value))) f.close() Current File Text: abbbb\nabbbb\naaaaab What I would like: abbbb bbbb aaaaab
[ "Don't call repr(), ie. just call\nf.write(stdout_value)\n\n", "Why repr? That turns a object into its representation, which for strings means converting things like chr(10) (newline) into '\\n'.\n", "The repr (which doubles up the \"escapes\", i.e. backslash characters) is what's causing you to \"lose formatting\" -- why are you doing that at all? And btw the str call is totally redundant (innocuous, but totally useless -- why have it there?!).\n" ]
[ 3, 1, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0001870435_formatting_python.txt
Q: Quickly alphabetize a large file via python #!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(chars + ":" + chars2 + "\n") appendToFile.close() Code modified from this question. The above code generates 100,000 lines of random text in the format of STRING:STRING. Resultant text file is 3.1 MB. How would one rapidly alphabetise the file, using the first STRING in STRING:STRING? Case is irrelevant. Bubble sort is very slow, no? A: The obvious first approach is simply to use the built-in sort feature in Python. Is this not what you had in mind? If not, why? With only 100,000 lines of random text, the built-in sort would be very fast. lst = open("appendedFile", "rt").readlines() lst.sort(key=str.lower) Done. We could do it as a one-liner if you really wanted to: lst = sorted(open("appendedFile", "rt").readlines(), key=str.lower) EDIT: I just checked, and strings.letters includes both upper-case and lower-case letters. So, above code is modified to be case-insensitive. EDIT: more on sorting in Python: http://wiki.python.org/moin/HowTo/Sorting A: This is very fast (under 1 second on my computer). It uses a case-insensitive sort, which is assume what you mean by "case is irrelevant"? #!/usr/bin/python appendToFile = open("appendedFile", "r") sortToFile = open("sortedFile", "w") for line in sorted(appendToFile, key = str.lower): sortToFile.write(line) A: Try this (case insensitive): l=file(appendedFile).readlines() l.sort(key=lambda x:x.lower()) For these kinds of sizes optimalisation is not really necessary (timings on my slow machine ;-): christophe@orion:~$ time python -c "l=file('appendedFile').readlines();l.sort(key=lambda x:x.lower())" real 0m0.615s user 0m0.576s sys 0m0.024s
Quickly alphabetize a large file via python
#!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(chars + ":" + chars2 + "\n") appendToFile.close() Code modified from this question. The above code generates 100,000 lines of random text in the format of STRING:STRING. Resultant text file is 3.1 MB. How would one rapidly alphabetise the file, using the first STRING in STRING:STRING? Case is irrelevant. Bubble sort is very slow, no?
[ "The obvious first approach is simply to use the built-in sort feature in Python. Is this not what you had in mind? If not, why? With only 100,000 lines of random text, the built-in sort would be very fast.\nlst = open(\"appendedFile\", \"rt\").readlines()\nlst.sort(key=str.lower)\n\nDone. We could do it as a one-liner if you really wanted to:\nlst = sorted(open(\"appendedFile\", \"rt\").readlines(), key=str.lower)\n\nEDIT: I just checked, and strings.letters includes both upper-case and lower-case letters. So, above code is modified to be case-insensitive.\nEDIT: more on sorting in Python: http://wiki.python.org/moin/HowTo/Sorting\n", "This is very fast (under 1 second on my computer). It uses a case-insensitive sort, which is assume what you mean by \"case is irrelevant\"?\n#!/usr/bin/python\n\nappendToFile = open(\"appendedFile\", \"r\")\nsortToFile = open(\"sortedFile\", \"w\")\n\nfor line in sorted(appendToFile, key = str.lower):\n sortToFile.write(line)\n\n", "Try this (case insensitive):\nl=file(appendedFile).readlines()\nl.sort(key=lambda x:x.lower())\n\nFor these kinds of sizes optimalisation is not really necessary (timings on my slow machine ;-):\nchristophe@orion:~$ time python -c \"l=file('appendedFile').readlines();l.sort(key=lambda x:x.lower())\"\n\nreal 0m0.615s\nuser 0m0.576s\nsys 0m0.024s\n\n" ]
[ 8, 5, 1 ]
[]
[]
[ "alphabetical", "file", "python" ]
stackoverflow_0001870541_alphabetical_file_python.txt
Q: Is there any python package that could configure IP address of network interface? I am writing a server application which allow remote client to show/add/change/delete IP addresses of network interfaces of the machine where the host is running. The OS is Linux(CentOS 5.2), so I could do that by simply parse and edit configure file. But is there any package that could simplify the job? And if there is none such package, if I open source my implementation, will that help other people? A: It looks like the open source project confparse should be able to easily do what you're looking for. In fact, one of their examples is parsing and modifying /etc/sysconfig/network-scripts/ifcfg-eth0 with ease. If you find this isn't what you need, I say that any efforts towards open sourcing software will inevitably help other people at some point, given that it is actually useful. ;)
Is there any python package that could configure IP address of network interface?
I am writing a server application which allow remote client to show/add/change/delete IP addresses of network interfaces of the machine where the host is running. The OS is Linux(CentOS 5.2), so I could do that by simply parse and edit configure file. But is there any package that could simplify the job? And if there is none such package, if I open source my implementation, will that help other people?
[ "It looks like the open source project confparse should be able to easily do what you're looking for. In fact, one of their examples is parsing and modifying /etc/sysconfig/network-scripts/ifcfg-eth0 with ease.\nIf you find this isn't what you need, I say that any efforts towards open sourcing software will inevitably help other people at some point, given that it is actually useful. ;)\n" ]
[ 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001865920_linux_python.txt
Q: Render in infinity loop Question for Python 2.6 I would like to create an simple web application which in specified time interval will run a script that modifies the data (in database). My problem is code for infinity loop or some other method to achieve this goal. The script should be run only once by the user. Next iterations should run automatically, even when the user leaves the application. If someone have idea for method detecting apps breaks it would be great to show it too. I think that threads can be the best way to achive that. Unfortunately, I just started my adventure with Python and don't know yet how to use them. The application will have also views showing database and for control of loop script. Any ideas? A: You mentioned that you're using Google App Engine. You can schedule recurring tasks by placing a cron.yaml file in your application folder. The details are here. Update: It sounds like you're not looking for GAE-specific solutions, so the more general advice I'd give is to use the native scheduling abilities of whatever platform you're using. Cron jobs on a *nix host, scheduled tasks on Windows, cron.yaml on GAE, etc. In your other comments you've suggested wanting something in Python that doesn't leave your script executing, and I don't think there's any way to do this. Some process has to be responsible for kicking off whatever it is you need done, so either you do it in Python and keep a process executing (even if it's just sleeping), or you use the platform's scheduling tools. The OS is almost guaranteed to do a better job of this than your code. A: i think you'd want to use cron. write your script, and have cron run it every X minutes / hours. if you really want to do this in Python, you can do something like this: while(True): <your app logic here> sleep(TIME_INTERVAL) A: Can you use cron to schedule the job to run at certain intervals? It's usually considered better than infinite loops, and was designed to help solve this sort of problem. A: There's a very primitive cron in the Python standard library: import sched. There's also threading.Timer. But as others say, you probably should just use the real cron.
Render in infinity loop
Question for Python 2.6 I would like to create an simple web application which in specified time interval will run a script that modifies the data (in database). My problem is code for infinity loop or some other method to achieve this goal. The script should be run only once by the user. Next iterations should run automatically, even when the user leaves the application. If someone have idea for method detecting apps breaks it would be great to show it too. I think that threads can be the best way to achive that. Unfortunately, I just started my adventure with Python and don't know yet how to use them. The application will have also views showing database and for control of loop script. Any ideas?
[ "You mentioned that you're using Google App Engine. You can schedule recurring tasks by placing a cron.yaml file in your application folder. The details are here.\nUpdate: It sounds like you're not looking for GAE-specific solutions, so the more general advice I'd give is to use the native scheduling abilities of whatever platform you're using. Cron jobs on a *nix host, scheduled tasks on Windows, cron.yaml on GAE, etc. \nIn your other comments you've suggested wanting something in Python that doesn't leave your script executing, and I don't think there's any way to do this. Some process has to be responsible for kicking off whatever it is you need done, so either you do it in Python and keep a process executing (even if it's just sleeping), or you use the platform's scheduling tools. The OS is almost guaranteed to do a better job of this than your code.\n", "i think you'd want to use cron. write your script, and have cron run it every X minutes / hours.\nif you really want to do this in Python, you can do something like this:\nwhile(True):\n <your app logic here>\n sleep(TIME_INTERVAL)\n\n", "Can you use cron to schedule the job to run at certain intervals? It's usually considered better than infinite loops, and was designed to help solve this sort of problem.\n", "There's a very primitive cron in the Python standard library: import sched. There's also threading.Timer.\nBut as others say, you probably should just use the real cron.\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0001870140_cron_google_app_engine_python.txt
Q: In Python, how do I refer to an identifier by its absolute fully-qualified name? I have a project with a directory structure that looks like: /foo/baz/__init__.py /bar/foo.py /bar/splat.py Problem is, /bar/splat.py refers to the foo.baz module. This fails with the error No module named baz because it's trying to search for this module within /bar/foo.py. I don't want Python to search the bar module, I want to tell it to search the root foo module for baz. How do I do that? In Ruby you'd just prefix the identifier with :: (In this case, ::Foo::Baz), is there a Python equivalent to this? A: In Python 2.5 and 2.6, from __future__ import absolute_import should change Python's import behavior to do what you want (if the very root, /, is on sys.path of course;-). This becomes the normal Python behavior in 2.7 (not released yet, but an early alpha is already tagged, if you're curious).
In Python, how do I refer to an identifier by its absolute fully-qualified name?
I have a project with a directory structure that looks like: /foo/baz/__init__.py /bar/foo.py /bar/splat.py Problem is, /bar/splat.py refers to the foo.baz module. This fails with the error No module named baz because it's trying to search for this module within /bar/foo.py. I don't want Python to search the bar module, I want to tell it to search the root foo module for baz. How do I do that? In Ruby you'd just prefix the identifier with :: (In this case, ::Foo::Baz), is there a Python equivalent to this?
[ "In Python 2.5 and 2.6,\nfrom __future__ import absolute_import\n\nshould change Python's import behavior to do what you want (if the very root, /, is on sys.path of course;-). This becomes the normal Python behavior in 2.7 (not released yet, but an early alpha is already tagged, if you're curious).\n" ]
[ 4 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0001870718_namespaces_python.txt
Q: python regular expression across multiple lines I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate routine to parse the data. If the switch is stacked you see the following (extracted from the sho ver output) Top Assembly Part Number : 800-25858-06 Top Assembly Revision Number : A0 Version ID : V08 CLEI Code Number : COMDE10BRA Hardware Board Revision Number : 0x01 Switch Ports Model SW Version SW Image ------ ----- ----- ---------- ---------- * 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M Switch 02 --------- Switch Uptime : 11 weeks, 2 days, 16 hours, 27 minutes Base ethernet MAC Address : 00:26:52:96:2A:80 Motherboard assembly number : 73-9675-15 When I encounter this I need to extract the switch number & model for each in the table of 4, (sw can be ignored, but there can be between 1 and 9 switches) It's the multiple line thing that has got me as I've been ok with the rest. Any ideas please? OK apologies. My regex simply started looking at the last group of - until.. then I couldn't work ou where to go! -{10]\s-{10}(.+)Switch The model will change and the number of switches will change, I need to capture the 4 lines in this example which are * 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M But each switch could be a different model and there could be between 1 and 9. For this example ideally i'd like to get *,1,WS-C3750-48P ,2,WS-C3750-48P ,3,WS-C3750-48P ,4,WS-C3750-48P (the asterisk means master) but getting those lines would set me on the right track A: To have . match any character, including a newline, compile your RE with re.DOTALL among the options (remember, if you have multiple options, use |, the bit-or operator, between them, in order to combine them). In this case I'm not sure you actually do need this -- why not something like re.findall(r'(\d+)\s+\d+\s+(WS-\S+)') assuming for example that the way you identify a "model" is that it starts with WS-? The fact that there will be newlines between one result of findall and the next one is not a problem here. Can you explain exactly how you identify a "model" and why "multiline" is an issue? Maybe you want the re.MULTILINE to make ^ match at each start-of-line, to grab your data with some reference to the start of the lines...? A: x="""Top Assembly Part Number : 800-25858-06 Top Assembly Revision Number : A0 Version ID : V08 CLEI Code Number : COMDE10BRA Hardware Board Revision Number : 0x01 Switch Ports Model SW Version SW Image ------ ----- ----- ---------- ---------- * 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M Switch 02 --------- Switch Uptime : 11 weeks, 2 days, 16 hours, 27 minutes Base ethernet MAC Address : 00:26:52:96:2A:80 Motherboard assembly number : 73-9675-15""" >>> import re >>> re.findall("^\*?\s*(\d)\s*\d+\s*([A-Z\d-]+)",x,re.MULTILINE) [('1', 'WS-C3750-48P'), ('2', 'WS-C3750-48P'), ('3', 'WS-C3750-48P'), ('4', 'WS-C3750-48P')] UPDATE: because OP edited question, and Thanks Tom for pointing out for + >>> re.findall("^(\*?)\s+(\d)\s+\d+\s+([A-Z\d-]+)",x,re.MULTILINE) [('*', '1', 'WS-C3750-48P'), ('', '2', 'WS-C3750-48P'), ('', '3', 'WS-C3750-48P'), ('', '4', 'WS-C3750-48P')] >>>
python regular expression across multiple lines
I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate routine to parse the data. If the switch is stacked you see the following (extracted from the sho ver output) Top Assembly Part Number : 800-25858-06 Top Assembly Revision Number : A0 Version ID : V08 CLEI Code Number : COMDE10BRA Hardware Board Revision Number : 0x01 Switch Ports Model SW Version SW Image ------ ----- ----- ---------- ---------- * 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M Switch 02 --------- Switch Uptime : 11 weeks, 2 days, 16 hours, 27 minutes Base ethernet MAC Address : 00:26:52:96:2A:80 Motherboard assembly number : 73-9675-15 When I encounter this I need to extract the switch number & model for each in the table of 4, (sw can be ignored, but there can be between 1 and 9 switches) It's the multiple line thing that has got me as I've been ok with the rest. Any ideas please? OK apologies. My regex simply started looking at the last group of - until.. then I couldn't work ou where to go! -{10]\s-{10}(.+)Switch The model will change and the number of switches will change, I need to capture the 4 lines in this example which are * 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M But each switch could be a different model and there could be between 1 and 9. For this example ideally i'd like to get *,1,WS-C3750-48P ,2,WS-C3750-48P ,3,WS-C3750-48P ,4,WS-C3750-48P (the asterisk means master) but getting those lines would set me on the right track
[ "To have . match any character, including a newline, compile your RE with re.DOTALL among the options (remember, if you have multiple options, use |, the bit-or operator, between them, in order to combine them).\nIn this case I'm not sure you actually do need this -- why not something like\nre.findall(r'(\\d+)\\s+\\d+\\s+(WS-\\S+)')\n\nassuming for example that the way you identify a \"model\" is that it starts with WS-? The fact that there will be newlines between one result of findall and the next one is not a problem here. Can you explain exactly how you identify a \"model\" and why \"multiline\" is an issue? Maybe you want the re.MULTILINE to make ^ match at each start-of-line, to grab your data with some reference to the start of the lines...?\n", "x=\"\"\"Top Assembly Part Number : 800-25858-06\nTop Assembly Revision Number : A0\nVersion ID : V08\nCLEI Code Number : COMDE10BRA\nHardware Board Revision Number : 0x01\n\n\nSwitch Ports Model SW Version SW Image\n------ ----- ----- ---------- ----------\n* 1 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M\n 2 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M\n 3 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M\n 4 52 WS-C3750-48P 12.2(35)SE5 C3750-IPBASE-M\n\n\nSwitch 02\n---------\nSwitch Uptime : 11 weeks, 2 days, 16 hours, 27 minutes\nBase ethernet MAC Address : 00:26:52:96:2A:80\nMotherboard assembly number : 73-9675-15\"\"\"\n\n>>> import re\n>>> re.findall(\"^\\*?\\s*(\\d)\\s*\\d+\\s*([A-Z\\d-]+)\",x,re.MULTILINE)\n[('1', 'WS-C3750-48P'), ('2', 'WS-C3750-48P'), ('3', 'WS-C3750-48P'), ('4', 'WS-C3750-48P')]\n\nUPDATE: because OP edited question, and Thanks Tom for pointing out for +\n>>> re.findall(\"^(\\*?)\\s+(\\d)\\s+\\d+\\s+([A-Z\\d-]+)\",x,re.MULTILINE)\n[('*', '1', 'WS-C3750-48P'), ('', '2', 'WS-C3750-48P'), ('', '3', 'WS-C3750-48P'), ('', '4', 'WS-C3750-48P')]\n>>>\n\n" ]
[ 16, 8 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001870954_python_regex.txt
Q: Python String parse Im working on a data packet retrieval system which will take a packet, and process the various parts of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files]. Each part of the packet is contained between two identical tags, and here is a sample packet: "<PACKET><HEAD><ID><ID><SEQ><SEQ><FILENAME><FILENAME><HEAD><DATA><DATA><PACKET>" The entire packet is contained within the <PACKET><PACKET> tags. All meta-data is contained within the <HEAD><HEAD> tags and the filename from which the packet is part of is contained within the, you guessed it, the <FILENAME><FILENAME> tags. Lets say, for example, a single packet is received and stored in a temporary string variable called sTemp. How do you efficiently retrieve, for example, only the contents of a single pair of tags, for example the contents of the <FILENAME><FILENAME> tags? I was hoping for such functionality as saying getTagFILENAME( packetX ), which would return the textual string contents of the <FILENAME><FILENAME> tags of the packet. Is this possible using Python? Any suggestions or comments appreciated. A: Something like this? import re def getPacketContent ( code, packetName ): match = re.search( '<' + packetName + '>(.*?)<' + packetName + '>', code ) return match.group( 1 ) if match else '' # usage code = "<PACKET><HEAD><ID><ID><SEQ><SEQ><FILENAME><FILENAME><HEAD><DATA><DATA><PACKET>" print( getPacketContent( code, 'HEAD' ) ) print( getPacketContent( code, 'SEQ' ) ) A: If the packet format effectively uses XML-looking syntax (i.e., if the "closing tags" actually include a slash), the xml.etree.ElementTree could be used. This libray is part of Python Standard Library, starting in Py2.5. I find it a very convenient one to deal with this kind of data. It provides many ways to read and to modify this kind of tree structure. Thanks to the generic nature of XML languages and to the XML awareness built-in the ElementTree library, the packet syntax could evolve easily for example to support repeating elements, element attributes. Example: >>> import xml.etree.ElementTree >>> myPacket = '<PACKET><HEAD><ID>123</ID><SEQ>1</SEQ><FILENAME>Test99.txt</FILE NAME></HEAD><DATA>spam and cheese</DATA></PACKET>' >>> xt = xml.etree.ElementTree.fromstring(myPacket) >>> wrk_ele = xt.find('HEAD/FILENAME') >>> wrk_ele.text 'Test99.txt' >>> A: As mjv points out, there's not the least sense in inventing an XML-like format if you can just use XML. But: If you're going to use XML for your packet format, you need to really use XML for it. You should use an XML library to create your packets, not just to parse them. Otherwise you will come to grief the first time one of your field values contains an XML markup character. You can, of course, write your own code to do the necessary escaping, filter out illegal characters, guarantee well-formedness, etc. For a format this simple, that may be all you need to do. But going down that path is a way to learn things about XML that you perhaps would rather not have to learn. If using an XML library to create your packets is a problem, you're probably better off defining a custom format (and I'd define one that didn't look anything like XML, to keep people from getting ideas) and building a parser for it using pyparsing.
Python String parse
Im working on a data packet retrieval system which will take a packet, and process the various parts of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files]. Each part of the packet is contained between two identical tags, and here is a sample packet: "<PACKET><HEAD><ID><ID><SEQ><SEQ><FILENAME><FILENAME><HEAD><DATA><DATA><PACKET>" The entire packet is contained within the <PACKET><PACKET> tags. All meta-data is contained within the <HEAD><HEAD> tags and the filename from which the packet is part of is contained within the, you guessed it, the <FILENAME><FILENAME> tags. Lets say, for example, a single packet is received and stored in a temporary string variable called sTemp. How do you efficiently retrieve, for example, only the contents of a single pair of tags, for example the contents of the <FILENAME><FILENAME> tags? I was hoping for such functionality as saying getTagFILENAME( packetX ), which would return the textual string contents of the <FILENAME><FILENAME> tags of the packet. Is this possible using Python? Any suggestions or comments appreciated.
[ "Something like this?\nimport re\ndef getPacketContent ( code, packetName ):\n match = re.search( '<' + packetName + '>(.*?)<' + packetName + '>', code )\n return match.group( 1 ) if match else ''\n\n# usage\ncode = \"<PACKET><HEAD><ID><ID><SEQ><SEQ><FILENAME><FILENAME><HEAD><DATA><DATA><PACKET>\"\nprint( getPacketContent( code, 'HEAD' ) )\nprint( getPacketContent( code, 'SEQ' ) )\n\n", "If the packet format effectively uses XML-looking syntax (i.e., if the \"closing tags\" actually include a slash), the xml.etree.ElementTree could be used.\nThis libray is part of Python Standard Library, starting in Py2.5. I find it a very convenient one to deal with this kind of data. It provides many ways to read and to modify this kind of tree structure. Thanks to the generic nature of XML languages and to the XML awareness built-in the ElementTree library, the packet syntax could evolve easily for example to support repeating elements, element attributes.\nExample:\n>>> import xml.etree.ElementTree\n>>> myPacket = '<PACKET><HEAD><ID>123</ID><SEQ>1</SEQ><FILENAME>Test99.txt</FILE\nNAME></HEAD><DATA>spam and cheese</DATA></PACKET>'\n>>> xt = xml.etree.ElementTree.fromstring(myPacket)\n>>> wrk_ele = xt.find('HEAD/FILENAME')\n>>> wrk_ele.text\n'Test99.txt'\n>>>\n\n", "As mjv points out, there's not the least sense in inventing an XML-like format if you can just use XML.\nBut: If you're going to use XML for your packet format, you need to really use XML for it. You should use an XML library to create your packets, not just to parse them. Otherwise you will come to grief the first time one of your field values contains an XML markup character. \nYou can, of course, write your own code to do the necessary escaping, filter out illegal characters, guarantee well-formedness, etc. For a format this simple, that may be all you need to do. But going down that path is a way to learn things about XML that you perhaps would rather not have to learn.\nIf using an XML library to create your packets is a problem, you're probably better off defining a custom format (and I'd define one that didn't look anything like XML, to keep people from getting ideas) and building a parser for it using pyparsing.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001870044_python.txt
Q: What are the advantages and disadvantages of the require vs. import methods of loading code? Ruby uses require, Python uses import. They're substantially different models, and while I'm more used to the require model, I can see a few places where I think I like import more. I'm curious what things people find particularly easy — or more interestingly, harder than they should be — with each of these models. In particular, if you were writing a new programming language, how would you design a code-loading mechanism? Which "pros" and "cons" would weigh most heavily on your design choice? A: The Python import has a major feature in that it ties two things together -- how to find the import and under what namespace to include it. This creates very explicit code: import xml.sax This specifies where to find the code we want to use, by the rules of the Python search path. At the same time, all objects that we want to access live under this exact namespace, for example xml.sax.ContentHandler. I regard this as an advantage to Ruby's require. require 'xml' might in fact make objects inside the namespace XML or any other namespace available in the module, without this being directly evident from the require line. If xml.sax.ContentHandler is too long, you may specify a different name when importing: import xml.sax as X And it is now avalable under X.ContentHandler. This way Python requires you to explicitly build the namespace of each module. Python namespaces are thus very "physical", and I'll explain what I mean: By default, only names directly defined in the module are available in its namespace: functions, classes and so. To add to a module's namespace, you explicitly import the names you wish to add, placing them (by reference) "physically" in the current module. For example, if we have the small Python package "process" with internal submodules machine and interface, and we wish to present this as one convenient namespace directly under the package name, this is and example of what we could write in the "package definition" file process/__init__.py: from process.interface import * from process.machine import Machine, HelperMachine Thus we lift up what would normally be accessible as process.machine.Machine up to process.Machine. And we add all names from process.interface to process namespace, in a very explicit fashion. The advantages of Python's import that I wrote about were simply two: Clear what you include when using import Explicit how you modify your own module's namespace (for the program or for others to import) A: A nice property of require is that it is actually a method defined in Kernel. Thus you can override it and implement your own packaging system for Ruby, which is what e.g. Rubygems does! PS: I am not selling monkey patching here, but the fact that Ruby's package system can be rewritten by the user (even to work like python's system). When you write a new programming language, you cannot get everything right. Thus if your import mechanism is fully extensible (into totally all directions) from within the language, you do your future users the best service. A language that is not fully extensible from within itself is an evolutionary dead-end. I'd say this is one of the things Matz got right with Ruby. A: Disclaimer, I am by no means a Python expert. The biggest advantage I see to require over import is simply that you don't have to worry about understanding the mapping between namespaces and file paths. It's obvious: it's just a standard file path. I really like the emphasis on namespacing that import has, but can't help but wonder if this particular approach isn't too inflexible. As far as I can tell, the only means of controlling a module's naming in Python is by altering the filename of the module being imported or using an as rename. Additionally, with explicit namespacing, you have a means by which you can refer to something by its fully-qualified identifier, but with implicit namespacing, you have no means to do this inside the module itself, and that can lead to potential ambiguities that are difficult to resolve without renaming. i.e., in foo.py: class Bar: def myself(self): return foo.Bar This fails with: Traceback (most recent call last): File "", line 1, in ? File "foo.py", line 3, in myself return foo.Bar NameError: global name 'foo' is not defined Both implementations use a list of locations to search from, which strikes me as a critically important component, regardless of the model you choose. What if a code-loading mechanism like require was used, but the language simply didn't have a global namespace? i.e., everything, everywhere must be namespaced, but the developer has full control over which namespace the class is defined in, and that namespace declaration occurs explicitly in the code rather than via the filename. Alternatively, defining something in the global namespace generates a warning. Is that a best-of-both-worlds approach, or is there an obvious downside to it that I'm missing? A: Python's import provides a very explicit kind of namespace: the namespace is the path, you don't have to look into files to know what namespace they do their definitions in, and your file is not cluttered with namespace definitions. This makes the namespace scheme of an application simple and fast to understand (just look at the source tree), and avoids simple mistakes like mistyping a namespace declaration. A nice side effect is every file has its own private namespace, so you don't have to worry about conflicts when naming things. Sometimes namespaces can get annoying too, having things like some.module.far.far.away.TheClass() everywhere can quickly make your code very long and boring to type. In these cases you can import ... from ... and inject bits of another namespace in the current one. If the injection causes a conflict with the module you are importing in, you can simply rename the thing you imported: from some.other.module import Bar as BarFromOtherModule. Python is still vulnerable to problems like circular imports, but it's the application design more than the language that has to be blamed in these cases. So python took C++ namespace and #include and largely extended on it. On the other hand I don't see in which way ruby's module and require add anything new to these, and you have the exact same horrible problems like global namespace cluttering.
What are the advantages and disadvantages of the require vs. import methods of loading code?
Ruby uses require, Python uses import. They're substantially different models, and while I'm more used to the require model, I can see a few places where I think I like import more. I'm curious what things people find particularly easy — or more interestingly, harder than they should be — with each of these models. In particular, if you were writing a new programming language, how would you design a code-loading mechanism? Which "pros" and "cons" would weigh most heavily on your design choice?
[ "The Python import has a major feature in that it ties two things together -- how to find the import and under what namespace to include it.\nThis creates very explicit code:\nimport xml.sax\nThis specifies where to find the code we want to use, by the rules of the Python search path.\nAt the same time, all objects that we want to access live under this exact namespace, for example xml.sax.ContentHandler.\nI regard this as an advantage to Ruby's require. require 'xml' might in fact make objects inside the namespace XML or any other namespace available in the module, without this being directly evident from the require line.\nIf xml.sax.ContentHandler is too long, you may specify a different name when importing:\nimport xml.sax as X\n\nAnd it is now avalable under X.ContentHandler.\nThis way Python requires you to explicitly build the namespace of each module. Python namespaces are thus very \"physical\", and I'll explain what I mean:\n\nBy default, only names directly defined in the module are available in its namespace: functions, classes and so.\nTo add to a module's namespace, you explicitly import the names you wish to add, placing them (by reference) \"physically\" in the current module.\n\nFor example, if we have the small Python package \"process\" with internal submodules machine and interface, and we wish to present this as one convenient namespace directly under the package name, this is and example of what we could write in the \"package definition\" file process/__init__.py:\nfrom process.interface import *\nfrom process.machine import Machine, HelperMachine\n\nThus we lift up what would normally be accessible as process.machine.Machine up to process.Machine. And we add all names from process.interface to process namespace, in a very explicit fashion.\nThe advantages of Python's import that I wrote about were simply two:\n\nClear what you include when using import\nExplicit how you modify your own module's namespace (for the program or for others to import)\n\n", "A nice property of require is that it is actually a method defined in Kernel. Thus you can override it and implement your own packaging system for Ruby, which is what e.g. Rubygems does!\nPS: I am not selling monkey patching here, but the fact that Ruby's package system can be rewritten by the user (even to work like python's system). When you write a new programming language, you cannot get everything right. Thus if your import mechanism is fully extensible (into totally all directions) from within the language, you do your future users the best service. A language that is not fully extensible from within itself is an evolutionary dead-end. I'd say this is one of the things Matz got right with Ruby.\n", "Disclaimer, I am by no means a Python expert.\nThe biggest advantage I see to require over import is simply that you don't have to worry about understanding the mapping between namespaces and file paths. It's obvious: it's just a standard file path.\nI really like the emphasis on namespacing that import has, but can't help but wonder if this particular approach isn't too inflexible. As far as I can tell, the only means of controlling a module's naming in Python is by altering the filename of the module being imported or using an as rename. Additionally, with explicit namespacing, you have a means by which you can refer to something by its fully-qualified identifier, but with implicit namespacing, you have no means to do this inside the module itself, and that can lead to potential ambiguities that are difficult to resolve without renaming.\ni.e., in foo.py:\nclass Bar:\n def myself(self):\n return foo.Bar\n\nThis fails with:\n\nTraceback (most recent call last):\n File \"\", line 1, in ?\n File \"foo.py\", line 3, in myself\n return foo.Bar\nNameError: global name 'foo' is not defined\n\nBoth implementations use a list of locations to search from, which strikes me as a critically important component, regardless of the model you choose.\nWhat if a code-loading mechanism like require was used, but the language simply didn't have a global namespace? i.e., everything, everywhere must be namespaced, but the developer has full control over which namespace the class is defined in, and that namespace declaration occurs explicitly in the code rather than via the filename. Alternatively, defining something in the global namespace generates a warning. Is that a best-of-both-worlds approach, or is there an obvious downside to it that I'm missing?\n", "Python's import provides a very explicit kind of namespace: the namespace is the path, you don't have to look into files to know what namespace they do their definitions in, and your file is not cluttered with namespace definitions. This makes the namespace scheme of an application simple and fast to understand (just look at the source tree), and avoids simple mistakes like mistyping a namespace declaration.\nA nice side effect is every file has its own private namespace, so you don't have to worry about conflicts when naming things.\nSometimes namespaces can get annoying too, having things like some.module.far.far.away.TheClass() everywhere can quickly make your code very long and boring to type. In these cases you can import ... from ... and inject bits of another namespace in the current one. If the injection causes a conflict with the module you are importing in, you can simply rename the thing you imported: from some.other.module import Bar as BarFromOtherModule.\nPython is still vulnerable to problems like circular imports, but it's the application design more than the language that has to be blamed in these cases.\nSo python took C++ namespace and #include and largely extended on it. On the other hand I don't see in which way ruby's module and require add anything new to these, and you have the exact same horrible problems like global namespace cluttering.\n" ]
[ 17, 4, 1, 1 ]
[]
[]
[ "language_design", "language_features", "programming_languages", "python", "ruby" ]
stackoverflow_0001849376_language_design_language_features_programming_languages_python_ruby.txt
Q: Dictionary (same value, different key) Newbie Alert: I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key. Seems like a pointer issue? Here's a snippet when using the event-based XML parser (SAX): Basically with every end element of "row", I'm storing the element by it's key: self.Id, where self is the element. def endElement(self, name): if name == "row": self.mapping[self.Id] = self print "Storing...: " + self.DisplayName + " at Id: " + self.Id A: You'll get the value self for every single entry in self.mapping, of course, since that's the only value you ever store there. Did you rather mean to take a copy/snapshot of self or some of its attributes at that point, then have self change before it gets stored again...? Edit: as the OP has clarified (in comments) that they do indeed need to take a copy: import copy ... self.mapping[self.Id] = copy.copy(self) or, use copy.deepcopy(self) if self has, among its attributes, dictionaries, lists etc that need to be recursively copied (that would of course include self.mapping, leading to rather peculiar results -- if the normal, shallow copy.copy is not sufficient, it's probably worth adding the special method to self's class to customize deep copying, to avoid the explosion of copies of copies of copies of ... that would normally result;-). A: If I understand what you're saying, then this is probably expected behaviour. When you make an assignment in Python, you're just assigning the reference (sort of like a pointer). When you do: self.mapping[self.Id] = self then future changes to self will be reflected in the value for that mapping you just did. Python does not "copy" objects (unless you specifically write code to do so), it only assigns references.
Dictionary (same value, different key)
Newbie Alert: I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key. Seems like a pointer issue? Here's a snippet when using the event-based XML parser (SAX): Basically with every end element of "row", I'm storing the element by it's key: self.Id, where self is the element. def endElement(self, name): if name == "row": self.mapping[self.Id] = self print "Storing...: " + self.DisplayName + " at Id: " + self.Id
[ "You'll get the value self for every single entry in self.mapping, of course, since that's the only value you ever store there. Did you rather mean to take a copy/snapshot of self or some of its attributes at that point, then have self change before it gets stored again...?\nEdit: as the OP has clarified (in comments) that they do indeed need to take a copy:\nimport copy\n\n...\n\n self.mapping[self.Id] = copy.copy(self)\n\nor, use copy.deepcopy(self) if self has, among its attributes, dictionaries, lists etc that need to be recursively copied (that would of course include self.mapping, leading to rather peculiar results -- if the normal, shallow copy.copy is not sufficient, it's probably worth adding the special method to self's class to customize deep copying, to avoid the explosion of copies of copies of copies of ... that would normally result;-).\n", "If I understand what you're saying, then this is probably expected behaviour. When you make an assignment in Python, you're just assigning the reference (sort of like a pointer). When you do:\nself.mapping[self.Id] = self\n\nthen future changes to self will be reflected in the value for that mapping you just did. Python does not \"copy\" objects (unless you specifically write code to do so), it only assigns references.\n" ]
[ 4, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001871296_dictionary_python.txt
Q: Python ctypes: initializing c_char_p() I wrote a simple C++ program to illustrate my problem: extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } I compile this into an so. From python I call: from ctypes import * libso = CDLL("Debug/libctypesTest.so") func = libso.test func.res_type = c_int for i in xrange(5): charP = c_char_p('bye') func(i,charP) print charP.value When I run this, my output is: bye hi hi hi hi I expected: bye hi bye bye bye What am I missing? Thanks. A: The string which you initialized with the characters "bye", and whose address you keep taking and assigning to charP, does not get re-initialized after the first time. Follow the advice here: You should be careful, however, not to pass them to functions expecting pointers to mutable memory. If you need mutable memory blocks, ctypes has a create_string_buffer function which creates these in various ways. A "pointer to mutable memory" is exactly what your C function expects, and so you should use the create_string_buffer function to create that buffer, as the docs explain. A: I am guessing python is reusing the same buffer for all 5 passes. once you set it to "hi", you never set it back to "bye" You can do something like this: extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } else { strcpy(var, "bye"); } return 1; } but be careful, strcpy is just asking for a buffer overflow
Python ctypes: initializing c_char_p()
I wrote a simple C++ program to illustrate my problem: extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } I compile this into an so. From python I call: from ctypes import * libso = CDLL("Debug/libctypesTest.so") func = libso.test func.res_type = c_int for i in xrange(5): charP = c_char_p('bye') func(i,charP) print charP.value When I run this, my output is: bye hi hi hi hi I expected: bye hi bye bye bye What am I missing? Thanks.
[ "The string which you initialized with the characters \"bye\", and whose address you keep taking and assigning to charP, does not get re-initialized after the first time.\nFollow the advice here:\n\nYou should be careful, however, not to\n pass them to functions expecting\n pointers to mutable memory. If you\n need mutable memory blocks, ctypes has\n a create_string_buffer function which\n creates these in various ways.\n\nA \"pointer to mutable memory\" is exactly what your C function expects, and so you should use the create_string_buffer function to create that buffer, as the docs explain.\n", "I am guessing python is reusing the same buffer for all 5 passes. once you set it to \"hi\", you never set it back to \"bye\" You can do something like this:\nextern \"C\"{\n int test(int, char*);\n}\n\nint test(int i, char* var){\n if (i == 1){\n strcpy(var,\"hi\");\n } else {\n strcpy(var, \"bye\");\n }\n return 1;\n}\n\nbut be careful, strcpy is just asking for a buffer overflow\n" ]
[ 8, 2 ]
[]
[]
[ "c++", "ctypes", "python", "shared_objects" ]
stackoverflow_0001871375_c++_ctypes_python_shared_objects.txt
Q: Plotting color map with zip codes in R or Python I have some US demographic and firmographic data. I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to http://maps.huge.info/ but a) with annotated text; b) pdf output; c) scriptable in R or Python. Is there any package and code that allows me to do this? A: I am assuming you want static maps. (source: eduardoleoni.com) 1) Get the shapefiles of the zip boundaries and state boundaries at census.gov: 2) Use the plot.heat function I posted in this SO question. For example (assumes you have the maryland shapefiles in the map subdirectory): library(maptools) ##substitute your shapefiles here state.map <- readShapeSpatial("maps/st24_d00.shp") zip.map <- readShapeSpatial("maps/zt24_d00.shp") ## this is the variable we will be plotting zip.map@data$noise <- rnorm(nrow(zip.map@data)) ## put the lab point x y locations of the zip codes in the data frame for easy retrieval labelpos <- data.frame(do.call(rbind, lapply(zip.map@polygons, function(x) x@labpt))) names(labelpos) <- c("x","y") zip.map@data <- data.frame(zip.map@data, labelpos) ## plot it png(file="map.png") ## plot colors plot.heat(zip.map,state.map,z="noise",breaks=c(-Inf,-2,-1,0,1,2,Inf)) ## plot text with(zip.map@data[sample(1:nrow(zip.map@data), 10),] , text(x,y,NAME)) dev.off() A: There are many ways to do this in R (see the spatial view); many of these depend on the "maps" package. Check out this cool example of the US 2004 election. It ends up looking like this: Here's a slightly ugly example of a model that uses the "maps" package with "lattice". Andrew Gelman made some very nice plots like this. See, for instance, this blog post on red states/blue states and this follow up post. Here's a very simple example using the "gmaps" package, which shows a map of Arrests by state for arrests per 100,000 for Murder: require(gmaps) data(USArrests) attach(USArrests) grid.newpage() grid.frame(name="map") grid.pack("map",USALevelPlot(states=rownames(USArrests),levels=Murder,col.fun=reds),height=unit(1,'null')) grid.pack("map",gradientLegendGrob(at=quantile(Murder),col.fun=reds),side="bottom",height=unit(.2,'npc')) detach(USArrests) A: Someone may have something more direct for you, but I found O'Reilly's 'Data Mashups in R' very interesting... in part, it's a spatial mapping of home foreclosure auctions. http://oreilly.com/catalog/9780596804770/ A: In Python, you can use shapefiles from the US census along with the basemap package. Here is an example of filling in states according to population. A: There is a rich and sophisticated series of packages in R to plot, do analysis, and other functions related to GIS. One place to get started is the CRAN task view on Spatial Data: This is a complex and sometimes arcane world, and takes some work to understand. If you are looking for a free, very functional mapping application, may I suggest: MapWindow ( mapwindow.com) A: Daniel Levine at TechCrunch Trends has done nice things with the maps package in R. He has code available on his site, too. Paul's suggestion of looking into Processing - which Ben Fry used to make zipdecode - is also a good one, if you're up for learning a (Java-like) new language. A: Depending on your application, a long way around might be to use something like this: http://googlemapsmania.blogspot.com/2006/07/new-google-maps-us-zip-code-mashups.html To map your data. If that wasn't quite what you wanted, you can get raw zip code shapefiles from census.gov and do it manually, which is quite a pain. Also, if you haven't seen it, this is a neat way to interact with similar data, and might offer some pointers: http://benfry.com/zipdecode/ A: Check out this excellent online visualization tool by IBM http://manyeyes.alphaworks.ibm.com/manyeyes/ EDIT FYI, ManyEyes uses the Prefuse visualization toolkit for some of its viz. Even though it is a java-based framework, they also provide a Flash/ActionScript tool for the web.
Plotting color map with zip codes in R or Python
I have some US demographic and firmographic data. I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to http://maps.huge.info/ but a) with annotated text; b) pdf output; c) scriptable in R or Python. Is there any package and code that allows me to do this?
[ "I am assuming you want static maps. \n\n(source: eduardoleoni.com) \n1) Get the shapefiles of the zip boundaries and state boundaries at census.gov: \n2) Use the plot.heat function I posted in this SO question.\nFor example (assumes you have the maryland shapefiles in the map subdirectory):\nlibrary(maptools)\n##substitute your shapefiles here\nstate.map <- readShapeSpatial(\"maps/st24_d00.shp\")\nzip.map <- readShapeSpatial(\"maps/zt24_d00.shp\")\n## this is the variable we will be plotting\nzip.map@data$noise <- rnorm(nrow(zip.map@data))\n## put the lab point x y locations of the zip codes in the data frame for easy retrieval\nlabelpos <- data.frame(do.call(rbind, lapply(zip.map@polygons, function(x) x@labpt)))\nnames(labelpos) <- c(\"x\",\"y\") \nzip.map@data <- data.frame(zip.map@data, labelpos)\n## plot it\npng(file=\"map.png\")\n## plot colors\nplot.heat(zip.map,state.map,z=\"noise\",breaks=c(-Inf,-2,-1,0,1,2,Inf))\n## plot text\nwith(zip.map@data[sample(1:nrow(zip.map@data), 10),] , text(x,y,NAME))\ndev.off()\n\n", "There are many ways to do this in R (see the spatial view); many of these depend on the \"maps\" package.\n\nCheck out this cool example of the US 2004 election. It ends up looking like this:\nHere's a slightly ugly example of a model that uses the \"maps\" package with \"lattice\".\nAndrew Gelman made some very nice plots like this. See, for instance, this blog post on red states/blue states and this follow up post.\nHere's a very simple example using the \"gmaps\" package, which shows a map of Arrests by state for arrests per 100,000 for Murder:\nrequire(gmaps)\ndata(USArrests)\nattach(USArrests)\ngrid.newpage()\ngrid.frame(name=\"map\")\ngrid.pack(\"map\",USALevelPlot(states=rownames(USArrests),levels=Murder,col.fun=reds),height=unit(1,'null'))\ngrid.pack(\"map\",gradientLegendGrob(at=quantile(Murder),col.fun=reds),side=\"bottom\",height=unit(.2,'npc'))\ndetach(USArrests)\n\n\n", "Someone may have something more direct for you, but I found O'Reilly's 'Data Mashups in R' very interesting... in part, it's a spatial mapping of home foreclosure auctions.\nhttp://oreilly.com/catalog/9780596804770/\n", "In Python, you can use shapefiles from the US census along with the basemap package. Here is an example of filling in states according to population.\n", "There is a rich and sophisticated series of packages in R to plot, do analysis, and other functions related to GIS. One place to get started is the CRAN task view on Spatial Data:\nThis is a complex and sometimes arcane world, and takes some work to understand. \nIf you are looking for a free, very functional mapping application, may I suggest:\nMapWindow ( mapwindow.com)\n", "Daniel Levine at TechCrunch Trends has done nice things with the maps package in R. He has code available on his site, too.\nPaul's suggestion of looking into Processing - which Ben Fry used to make zipdecode - is also a good one, if you're up for learning a (Java-like) new language.\n", "Depending on your application, a long way around might be to use something like this:\nhttp://googlemapsmania.blogspot.com/2006/07/new-google-maps-us-zip-code-mashups.html\nTo map your data. If that wasn't quite what you wanted, you can get raw zip code shapefiles from census.gov and do it manually, which is quite a pain.\nAlso, if you haven't seen it, this is a neat way to interact with similar data, and might offer some pointers:\nhttp://benfry.com/zipdecode/\n", "Check out this excellent online visualization tool by IBM\nhttp://manyeyes.alphaworks.ibm.com/manyeyes/\nEDIT FYI, ManyEyes uses the Prefuse visualization toolkit for some of its viz. Even though it is a java-based framework, they also provide a Flash/ActionScript tool for the web.\n" ]
[ 39, 10, 3, 3, 1, 1, 0, 0 ]
[]
[]
[ "graphics", "python", "r", "zipcode" ]
stackoverflow_0001441717_graphics_python_r_zipcode.txt
Q: Debugging Django/Python on Dreamhost Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions? A: The Django Debug Toolbar, as already mentioned, is damn useful. But as long as Django is running in debug mode, the brute force method equivalent to the print statement is to simply throw an exception. Put whatever output you want in the exception's text, whenever you need a quick idea of you code's state, and voila... instant output and stacktrace. This isn't a comprehensive solution, but it is a quick print statement style hack. A: Have you tried the Django Debug Toolbar? For a summary of the features, watch the video here.
Debugging Django/Python on Dreamhost
Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions?
[ "The Django Debug Toolbar, as already mentioned, is damn useful.\nBut as long as Django is running in debug mode, the brute force method equivalent to the print statement is to simply throw an exception. Put whatever output you want in the exception's text, whenever you need a quick idea of you code's state, and voila... instant output and stacktrace. This isn't a comprehensive solution, but it is a quick print statement style hack.\n", "Have you tried the Django Debug Toolbar?\nFor a summary of the features, watch the video here.\n" ]
[ 3, 1 ]
[]
[]
[ "debugging", "django", "dreamhost", "python" ]
stackoverflow_0001871252_debugging_django_dreamhost_python.txt
Q: While loop example x = y // 2 # For some y > 1 while x > 1: if y % x == 0: # Remainder print(y, 'has factor', x) break # Skip else x -= 1 else: # Normal exit print(y, 'is prime') This is an example for understanding while loop in a book I'm reading, I don't quite understand why a floor division and then y % x? Can someone please explain this piece of code, whats it doing? Thanks! A: This is a lame primality test. % is the mod operator. It performs division and returns the remainder rather than the result of the division. For example, 5 // 2 == 2, and 5 % 2 == 1. Commented: x = y // 2 # For some y > 1 ##Reduce search space to half of y while x > 1: if y % x == 0: # Remainder ##If x divides y cleanly (4 / 2 == 2) print(y, 'has factor', x) ##y is not prime break # Skip else ##Exit the loop x -= 1 # Normal exit ##Try the next value else: print(y, 'is prime') A: the logic is: if y modulo x is 0, it means that x is a dividor of y, so y has a factor. print that, and break out of the loop. if not, decrease x by 1, and try again. but some things are broken in this code: the else statement position the fact the 'print y is prime' is after the loop - it will always print it. A: The program prints at least one factor of an integer y, or if it has no factors (other than itself and 1), prints that y is prime. It uses the variable x to try all possible factors greater than one. It starts at the floor of y divided by 2, because no number larger than half of y could be a factor. Using normal division rather than floor division could give you a fractional value if y is odd. (An even better solution is to start with the square root of y - if y is not prime, one of its factors will be less than or equal to its square root.) Inside the loop, it tests y % x, which is the remainder after dividing y by x. If the remainder is zero, that means that x is a factor of y, and it prints it. The else clause is executed at the end of the loop, unless a factor is found, in which case the "break" skips out of the loop and the else clause. So either a factor is found, or it's prime. Here's the improved code with the indentation fixed: import math def check_primality(y): x = int(math.sqrt(y)) while x > 1: if y % x == 0: print y, 'has factor', x break x -= 1 else: print y, 'is prime' A: The code simply checks if the square root of x has been reached. Note that you can check the primality of a number by checking if the integers from 2 up to the square root of x divides x perfectly (without a remainder). A: For any number (x) which is not prime, there would be a factor greater than 1 and less than (x/2). 9 = 3*3 The logic is to iterate through all the numbers <= x/2 and check if the number divides. A: I think the program tries to find the biggest prime factors of y. If y is a prime factor it prints this as well. A: x = y // 2 is for testing the numbers in the range x: 2..y/2. A better approach would be to test only the numbers x: 2..sqrt(y) A: the % denotes a modulus which gives you the remainder of division... and this code checks for prime Y and also checks if Y is a multiplier of x... x = y // 2 #x=the division or modulus of y , 2 while x > 1: #you want to check if this is a division result or a modulus if y % x == 0: # if y is a multiplier of x print(y, 'has factor', x) break # break the while loop x -= 1 # decreament x else: # this line executes if the wihle reached x > 1 and didnt break print(y, 'is prime') so if y is a multiplier of x it will decreament x and the loop continue otherwise it will print y is prime
While loop example
x = y // 2 # For some y > 1 while x > 1: if y % x == 0: # Remainder print(y, 'has factor', x) break # Skip else x -= 1 else: # Normal exit print(y, 'is prime') This is an example for understanding while loop in a book I'm reading, I don't quite understand why a floor division and then y % x? Can someone please explain this piece of code, whats it doing? Thanks!
[ "This is a lame primality test.\n% is the mod operator. It performs division and returns the remainder rather than the result of the division. For example, 5 // 2 == 2, and 5 % 2 == 1.\nCommented:\nx = y // 2 # For some y > 1 ##Reduce search space to half of y\nwhile x > 1:\n if y % x == 0: # Remainder ##If x divides y cleanly (4 / 2 == 2)\n print(y, 'has factor', x) ##y is not prime\n break # Skip else ##Exit the loop\n x -= 1 # Normal exit ##Try the next value\nelse:\n print(y, 'is prime')\n\n", "the logic is:\nif y modulo x is 0, it means that x is a dividor of y, so y has a factor. print that, and break out of the loop.\nif not, decrease x by 1, and try again.\nbut some things are broken in this code:\n\nthe else statement position\nthe fact the 'print y is prime' is after the loop - it will always print it. \n\n", "The program prints at least one factor of an integer y, or if it has no factors (other than itself and 1), prints that y is prime.\nIt uses the variable x to try all possible factors greater than one. It starts at the floor of y divided by 2, because no number larger than half of y could be a factor. Using normal division rather than floor division could give you a fractional value if y is odd. (An even better solution is to start with the square root of y - if y is not prime, one of its factors will be less than or equal to its square root.)\nInside the loop, it tests y % x, which is the remainder after dividing y by x. If the remainder is zero, that means that x is a factor of y, and it prints it.\nThe else clause is executed at the end of the loop, unless a factor is found, in which case the \"break\" skips out of the loop and the else clause. So either a factor is found, or it's prime.\nHere's the improved code with the indentation fixed:\nimport math\n\ndef check_primality(y):\n x = int(math.sqrt(y))\n while x > 1:\n if y % x == 0: \n print y, 'has factor', x\n break\n x -= 1\n else:\n print y, 'is prime'\n\n", "The code simply checks if the square root of x has been reached. Note that you can check the primality of a number by checking if the integers from 2 up to the square root of x divides x perfectly (without a remainder).\n", "For any number (x) which is not prime, there would be a factor greater than 1 and less than (x/2). \n9 = 3*3\nThe logic is to iterate through all the numbers <= x/2 and check if the number divides.\n", "I think the program tries to find the biggest prime factors of y.\nIf y is a prime factor it prints this as well.\n", "x = y // 2 is for testing the numbers in the range x: 2..y/2.\nA better approach would be to test only the numbers x: 2..sqrt(y)\n", "the % denotes a modulus which gives you the remainder of division...\nand this code checks for prime Y and also checks if Y is a multiplier of x...\nx = y // 2 #x=the division or modulus of y , 2\nwhile x > 1: #you want to check if this is a division result or a modulus\nif y % x == 0: # if y is a multiplier of x \n print(y, 'has factor', x) \n\n break # break the while loop\n\nx -= 1 # decreament x \n\nelse: # this line executes if the wihle reached x > 1 and didnt break \n print(y, 'is prime')\nso if y is a multiplier of x it will decreament x and the loop continue\notherwise it will print y is prime\n" ]
[ 4, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "prime_factoring", "python", "while_loop" ]
stackoverflow_0001872261_prime_factoring_python_while_loop.txt
Q: Writing my own django-cms plugin. Any recommendations? I don't see any possibility for creating a table in django-cms. I need this functionnality so I am evaluating the possibility to write my own plugin. I am getting started with this product. I've read the documentation carefully and I see more or less how to do that. However, I would be happy to hear some tips and tricks before starting this task. Does anybody have experience with django-cms plugin? Thanks in advance A: This all depends on your model. Plugins use standard django admin features. This also depends on the source data for the table. If you have a CSV or Exel sheet as source i only would make a file field and render the file in the render function with some optional caching. If you want to enter data by hand: A Table model. An Row model with a foreign key to table. The row model can then be used as a django-admin Inline. So you can add new rows as needed. Be aware that CMSPluginBase extends ModelAdmin so you can define inlines like you would do in normal admin.
Writing my own django-cms plugin. Any recommendations?
I don't see any possibility for creating a table in django-cms. I need this functionnality so I am evaluating the possibility to write my own plugin. I am getting started with this product. I've read the documentation carefully and I see more or less how to do that. However, I would be happy to hear some tips and tricks before starting this task. Does anybody have experience with django-cms plugin? Thanks in advance
[ "This all depends on your model. Plugins use standard django admin features.\nThis also depends on the source data for the table. \nIf you have a CSV or Exel sheet as source i only would make a file field and render the file in the render function with some optional caching.\nIf you want to enter data by hand:\nA Table model.\nAn Row model with a foreign key to table.\nThe row model can then be used as a django-admin Inline. So you can add new rows as needed.\nBe aware that CMSPluginBase extends ModelAdmin so you can define inlines like you would do in normal admin.\n" ]
[ 1 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0001861267_django_django_cms_python.txt
Q: Pymsn/Papyon contact memberships Dear Stackoverflow, I'm having the following problem: I'm programming a bot for MSN Messenger in python with the pymsn/papyon library. I have everything running, except that I don't know how to accept new contacts already pending or new requests. Sadly the documentation of the library is very bad. I've achieved to retrieve all pending contacts in the contact list. My precise question is: - Is there a handler that accept incoming requests (new and old) and how can I implement it. or - If I have the email of the pending contact, what is the function to accept the request or how can I change the membership from Pending to Allow. I appreciate all your help and/or all the information you can provide. A: if you want check there is any contact, just list all you contact and check if the contact status is pending. Short code like: for contact in self.client._address_book.contacts: if contact.is_pending: self.client._address_book.accept_contact_invitation(contact) is_pending is my implement but you are easily to write it your own. And you just have a thread monitor this all will be fine.
Pymsn/Papyon contact memberships
Dear Stackoverflow, I'm having the following problem: I'm programming a bot for MSN Messenger in python with the pymsn/papyon library. I have everything running, except that I don't know how to accept new contacts already pending or new requests. Sadly the documentation of the library is very bad. I've achieved to retrieve all pending contacts in the contact list. My precise question is: - Is there a handler that accept incoming requests (new and old) and how can I implement it. or - If I have the email of the pending contact, what is the function to accept the request or how can I change the membership from Pending to Allow. I appreciate all your help and/or all the information you can provide.
[ "if you want check there is any contact, just list all you contact and check if the contact status is pending. Short code like:\nfor contact in self.client._address_book.contacts:\n if contact.is_pending:\n self.client._address_book.accept_contact_invitation(contact)\n\nis_pending is my implement but you are easily to write it your own. \nAnd you just have a thread monitor this all will be fine.\n" ]
[ 0 ]
[]
[]
[ "bots", "msn_messenger", "python" ]
stackoverflow_0001498634_bots_msn_messenger_python.txt
Q: Questionnaire/survey app like Google Form - (python+javascript) Django-survey or django-questionnaire is too admin-centric for me (beside tied to django). I want my user to create their own survey. Something like Google Form survey (view example), where form creation feels fluid and intuitive (because of js magic). I've googling around with no luck. Is there any python-based survey app/library/package out there? I'm OK if i have to write my own model/python-wise but not so sure in designing the creation process (javascript). Do you have suggestion of what Javascript library may suit this? Thanks. A: Have tried taking a look at google app engine? It really is not just a survey library, but much much more - and since it gives you Python APIs it probably is not too hard to create a web service that can be used by your users to create new surveys. Here is the python documentation and here are the docs for form handling
Questionnaire/survey app like Google Form - (python+javascript)
Django-survey or django-questionnaire is too admin-centric for me (beside tied to django). I want my user to create their own survey. Something like Google Form survey (view example), where form creation feels fluid and intuitive (because of js magic). I've googling around with no luck. Is there any python-based survey app/library/package out there? I'm OK if i have to write my own model/python-wise but not so sure in designing the creation process (javascript). Do you have suggestion of what Javascript library may suit this? Thanks.
[ "Have tried taking a look at google app engine?\nIt really is not just a survey library, but much much more - and since it gives you Python APIs it probably is not too hard to create a web service that can be used by your users to create new surveys.\nHere is the python documentation and here are the docs for form handling\n" ]
[ 1 ]
[]
[]
[ "python", "survey" ]
stackoverflow_0001857739_python_survey.txt
Q: Django and multiple databases My current Django setup uses MySQL as the main database to store models. Now for my project I need to connect to a remote PostgreSQL database and retrieve data from it. Is it possible to do this by using built-in Django and Python features or I will need to use library such as Psycopg2? It would be great for me, if I will be able to use the Object-relational mapper of Django for this remote database. Any ideas would be more than welcome. A: Django Project is working on Multiple Database Support. There is also a recent (Nov 10 2009) blog post about "The state of MultiDB (in Django)". Update: Multiple Databases is supported since Django v1.2 (release May 2010).
Django and multiple databases
My current Django setup uses MySQL as the main database to store models. Now for my project I need to connect to a remote PostgreSQL database and retrieve data from it. Is it possible to do this by using built-in Django and Python features or I will need to use library such as Psycopg2? It would be great for me, if I will be able to use the Object-relational mapper of Django for this remote database. Any ideas would be more than welcome.
[ "Django Project is working on Multiple Database Support. There is also a recent (Nov 10 2009) blog post about \"The state of MultiDB (in Django)\".\nUpdate: Multiple Databases is supported since Django v1.2 (release May 2010).\n" ]
[ 4 ]
[]
[]
[ "django", "multiple_databases", "postgresql", "python" ]
stackoverflow_0001872456_django_multiple_databases_postgresql_python.txt
Q: Not possible to do (a, b) += (1, 2) in python? The following line doesn't seem to work: (count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2])) I guess it is not possible to use the += operator in this case. I wonder why? edit: Actually what I want is to add to variables count and total the values given by the tuple returned by that function. Now that I think of it, it doesn't make sense to allow (a, b) += (1, 2), as it would be creating a new tuple, right? In other words, s there a way to simplify this? res = self._GetNumberOfNonZeroActions((state[0] + x, state[1] + ring, state[2])) count, total = res[0], res[1] A: Your observation is right: a += b for any a and b means the same as a = a + b (except that it may save one evaluation of a). So if a is a tuple, the only thing that can be +='d to it is another tuple; if a is a temporary unnamed tuple, that += will of course be unobservable -- Python helps you out by catching that special case as a syntax error. You need to give the tuple a name (or other reassignable reference) before you += to it...: >>> thetup = (a, b) >>> thetup += (1, 2) >>> thetup (23, 45, 1, 2) if the syntax (a, b) += (1, 2) was accepted, it would of course have to imply the same functionality... but without any possible observable way to check that the appending had actually occurred, which really makes just about no sense. Good thing the syntax is NOT accepted, therefore!-) A: You are mixing two concepts together. Python supports tuple unpacking which allows you to assign more that one variable in a single line. The += operator gets expanded by the interpreter since it is only a shorthand. Your example ((a, b) += (1, 2)) would be expanded to this: (a, b) = (a, b) + (1, 2) which, when you look at it, doesn't make a whole lot of sense. Just remember that tuple unpacking only works for the assignment of values to variables. A: If you want to work on numeric arrays, I recommend using numpy http://numpy.scipy.org/. It allows you to do this: >>> from numpy import * >>> count_total = array((0,0)) >>> count_total += (1,2) >>> count_total array([1, 2])
Not possible to do (a, b) += (1, 2) in python?
The following line doesn't seem to work: (count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2])) I guess it is not possible to use the += operator in this case. I wonder why? edit: Actually what I want is to add to variables count and total the values given by the tuple returned by that function. Now that I think of it, it doesn't make sense to allow (a, b) += (1, 2), as it would be creating a new tuple, right? In other words, s there a way to simplify this? res = self._GetNumberOfNonZeroActions((state[0] + x, state[1] + ring, state[2])) count, total = res[0], res[1]
[ "Your observation is right: a += b for any a and b means the same as a = a + b (except that it may save one evaluation of a). So if a is a tuple, the only thing that can be +='d to it is another tuple; if a is a temporary unnamed tuple, that += will of course be unobservable -- Python helps you out by catching that special case as a syntax error. You need to give the tuple a name (or other reassignable reference) before you += to it...:\n>>> thetup = (a, b)\n>>> thetup += (1, 2)\n>>> thetup\n(23, 45, 1, 2)\n\nif the syntax (a, b) += (1, 2) was accepted, it would of course have to imply the same functionality... but without any possible observable way to check that the appending had actually occurred, which really makes just about no sense. Good thing the syntax is NOT accepted, therefore!-)\n", "You are mixing two concepts together. Python supports tuple unpacking which allows you to assign more that one variable in a single line.\nThe += operator gets expanded by the interpreter since it is only a shorthand. Your example ((a, b) += (1, 2)) would be expanded to this:\n(a, b) = (a, b) + (1, 2)\n\nwhich, when you look at it, doesn't make a whole lot of sense. Just remember that tuple unpacking only works for the assignment of values to variables.\n", "If you want to work on numeric arrays, I recommend using numpy http://numpy.scipy.org/.\nIt allows you to do this:\n>>> from numpy import *\n>>> count_total = array((0,0))\n>>> count_total += (1,2)\n>>> count_total\narray([1, 2])\n\n" ]
[ 10, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001871786_python.txt
Q: Django Admin doesn't show entries If I create a new entry for one particular model it doesn't show up in the django admin. The Agency Model is causing the trouble. # catalog.models class Content(models.Model): class Meta: abstract = True BUNDESLAND_CHOICES = ( ('bw', 'Baden-Württemberg'), ('by', 'Bayern'), ('be', 'Berlin'), ('bb', 'Brandenburg'), ('hb', 'Bremen'), ('hh', 'Hamburg'), ('he', 'Hessen'), ('mv', 'Mecklenburg-Vorpommern'), ('ni', 'Niedersachsen'), ('nw', 'Nordrhein-Westfalen'), ('rp', 'Rheinland-Pfalz'), ('sl', 'Saarland'), ('sn', 'Sachsen'), ('st', 'Sachsen-Anhalt'), ('sh', 'Schleswig-Holstein'), ('th', 'Thüringen'), ) name = models.CharField(max_length=255, verbose_name='Agentur') address = models.CharField(max_length=255, verbose_name='Straße') state = models.CharField(max_length=2, choices=BUNDESLAND_CHOICES, verbose_name='Bundesland') city = models.CharField(max_length=255, verbose_name='Stadt') zip = models.CharField(max_length=10, verbose_name='PLZ') phone = models.CharField(max_length=40, blank=True, verbose_name='Telefonnr.') fax = models.CharField(max_length=40, blank=True, verbose_name='Fax') email = models.EmailField(verbose_name='E-Mail', help_text='Offizielle E-Mail') url = models.URLField(verbose_name='URL') owner = models.CharField(max_length=255, verbose_name='Besitzer') description = models.TextField(verbose_name='Beschreibung') category = models.ManyToManyField(Category, verbose_name='Kategorie') user = models.ForeignKey(User, verbose_name='Benutzer', null=True, blank=True) slug = models.SlugField(max_length=80, blank=True) identity = models.CharField(max_length=64, unique=True, blank=True) identity_used = models.BooleanField(default=False) show = models.BooleanField(default=False, verbose_name='Anzeigen') tp = models.DateTimeField(auto_now_add=True) # agency.models class AgencyActiveManager(models.Manager): def get_query_set(self): return super(AgencyActiveManager,self).get_query_set().filter(show=True) class Agency(Content): clients = models.TextField(verbose_name='Klienten') active = AgencyActiveManager() objects = models.Manager() def __unicode__(self): return self.name def save(self, **kwargs): if not self.identity: self.identity = hashlib.sha256('%s:%s' %(get_word(),datetime.datetime.now())).hexdigest() if not self.slug: self.slug = slugify(self.name, instance=self) super(Agency, self).save(**kwargs) # agency.admin from django.contrib import admin from agency.models import Agency admin.site.register(Agency) I created a new Agency entry in the admin and saved it. Querying via the python shell shows that the save worked In [15]: Agency.objects.all() Out[15]: [<Agency: Argentur>] The admin page says: '0 agencys' If I try manually calling the url /admin/agency/agency/1/ I get a 404 saying that there is no agency object with a primarykey 1 Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin/agency/agency/1/ Das agency-Objekt mit dem Primärschlüssel u'1' ist nicht vorhanden. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. But pythons shell says: In [16]: Agency.objects.all()[0].pk Out[16]: 1 Am I missing something extremely obvious? My guess would be that it has something todo with the abstract model but I can't figure out what. A: The first manager listed in the model class definition is the one that is used for the admin site and a number of other operations. There have been a number of bugs in Django related to using a manager that does not return all instances as the default manager. IMHO, you are best to use a standard manager as the default, and add any more restrictive ones afterwards. In fact, I no longer write models that use more than one manager. I would write class AgencyManger(models.Manager): def active(self): return self.filter(show=True) and use this as Agency.objects, so a root QuerySet for active objects is Agency.objects.active() rather than Agency.active.all(). This means .objects. will always have the same well-known behaviour. It's also easier to spot and understand in code.
Django Admin doesn't show entries
If I create a new entry for one particular model it doesn't show up in the django admin. The Agency Model is causing the trouble. # catalog.models class Content(models.Model): class Meta: abstract = True BUNDESLAND_CHOICES = ( ('bw', 'Baden-Württemberg'), ('by', 'Bayern'), ('be', 'Berlin'), ('bb', 'Brandenburg'), ('hb', 'Bremen'), ('hh', 'Hamburg'), ('he', 'Hessen'), ('mv', 'Mecklenburg-Vorpommern'), ('ni', 'Niedersachsen'), ('nw', 'Nordrhein-Westfalen'), ('rp', 'Rheinland-Pfalz'), ('sl', 'Saarland'), ('sn', 'Sachsen'), ('st', 'Sachsen-Anhalt'), ('sh', 'Schleswig-Holstein'), ('th', 'Thüringen'), ) name = models.CharField(max_length=255, verbose_name='Agentur') address = models.CharField(max_length=255, verbose_name='Straße') state = models.CharField(max_length=2, choices=BUNDESLAND_CHOICES, verbose_name='Bundesland') city = models.CharField(max_length=255, verbose_name='Stadt') zip = models.CharField(max_length=10, verbose_name='PLZ') phone = models.CharField(max_length=40, blank=True, verbose_name='Telefonnr.') fax = models.CharField(max_length=40, blank=True, verbose_name='Fax') email = models.EmailField(verbose_name='E-Mail', help_text='Offizielle E-Mail') url = models.URLField(verbose_name='URL') owner = models.CharField(max_length=255, verbose_name='Besitzer') description = models.TextField(verbose_name='Beschreibung') category = models.ManyToManyField(Category, verbose_name='Kategorie') user = models.ForeignKey(User, verbose_name='Benutzer', null=True, blank=True) slug = models.SlugField(max_length=80, blank=True) identity = models.CharField(max_length=64, unique=True, blank=True) identity_used = models.BooleanField(default=False) show = models.BooleanField(default=False, verbose_name='Anzeigen') tp = models.DateTimeField(auto_now_add=True) # agency.models class AgencyActiveManager(models.Manager): def get_query_set(self): return super(AgencyActiveManager,self).get_query_set().filter(show=True) class Agency(Content): clients = models.TextField(verbose_name='Klienten') active = AgencyActiveManager() objects = models.Manager() def __unicode__(self): return self.name def save(self, **kwargs): if not self.identity: self.identity = hashlib.sha256('%s:%s' %(get_word(),datetime.datetime.now())).hexdigest() if not self.slug: self.slug = slugify(self.name, instance=self) super(Agency, self).save(**kwargs) # agency.admin from django.contrib import admin from agency.models import Agency admin.site.register(Agency) I created a new Agency entry in the admin and saved it. Querying via the python shell shows that the save worked In [15]: Agency.objects.all() Out[15]: [<Agency: Argentur>] The admin page says: '0 agencys' If I try manually calling the url /admin/agency/agency/1/ I get a 404 saying that there is no agency object with a primarykey 1 Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin/agency/agency/1/ Das agency-Objekt mit dem Primärschlüssel u'1' ist nicht vorhanden. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. But pythons shell says: In [16]: Agency.objects.all()[0].pk Out[16]: 1 Am I missing something extremely obvious? My guess would be that it has something todo with the abstract model but I can't figure out what.
[ "The first manager listed in the model class definition is the one that is used for the admin site and a number of other operations.\nThere have been a number of bugs in Django related to using a manager that does not return all instances as the default manager. IMHO, you are best to use a standard manager as the default, and add any more restrictive ones afterwards.\nIn fact, I no longer write models that use more than one manager. I would write\nclass AgencyManger(models.Manager):\n def active(self):\n return self.filter(show=True)\n\nand use this as Agency.objects, so a root QuerySet for active objects is Agency.objects.active() rather than Agency.active.all(). This means .objects. will always have the same well-known behaviour. It's also easier to spot and understand in code.\n" ]
[ 3 ]
[]
[]
[ "django_admin", "django_models", "python" ]
stackoverflow_0001873177_django_admin_django_models_python.txt
Q: Level Design in Pygame Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks! A: With this type of game your maps are in terms of tiles (I'm assuming that by level you mean an individual level, not managing all of your levels). Each tile has an associated picture (what it looks like on the display) a type (ie, a wall, the ground, a trap, etc.) When I create tile-based games in Pygame, I usually have a Map class which contains the current map: the pygame.Surface of the map (what you'll be blitting to the display) a list of lists (ie, a matrix) where each item is a Tile object (I've also done games where you just have a string that tells you what type of tile it is, and then you don't need a separate Tile class) The map should be relatively static - you could have that traps become normal tiles after you step on them (this is pretty easy - when you do collision detection and it's a hit, just change that tile to a different Tile object (presumably the one for an empty tile)), but you don't want characters or movable blocks in the map if you can help it. Since the movable blocks have their own rules for how they can be moved, it's not as simple as just changing a tile - you'd have a whole set of logic, and at least two tiles would have to be changed (and what if you could move the blocks onto traps - you'd then have to remember, separately, what was below it - bleh). In my opinion it's easier to just have a class for each moving object and item. In short, you have: Tile Map Block other movable objects/sprites And that's basically your whole level. For multiple levels, if individual levels are always the same, you can just have a list of Map objects, one for each level. A: If this is your first Pygame application, don't spend time worrying about "object oriented design patterns for managing levels". What you need to do now is to figure out how to make Pygame do what you want it to do. Can you display everything you want to? Is your display flicker-free? Can you read the user input controls properly? etc. Object oriented patterns for managing levels comes later, much later. A: Generally speaking, a simple way to do it is using matrices (or multidimensional arrays - they work the same way here). Basically, each Map is an Array, with each item in the array being a square on the grid. For example a 3 by 3 grid would be as follows: (Psuedocode) var Map = [[1,2,3][1,2,3][1,2,3]]; In place of numbers, you could put strings for a function to parse and draw or take action based on what the value of the cell is.
Level Design in Pygame
Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks!
[ "With this type of game your maps are in terms of tiles (I'm assuming that by level you mean an individual level, not managing all of your levels). Each tile has\n\nan associated picture (what it looks like on the display)\na type (ie, a wall, the ground, a trap, etc.)\n\nWhen I create tile-based games in Pygame, I usually have a Map class which contains the current map:\n\nthe pygame.Surface of the map (what you'll be blitting to the display)\na list of lists (ie, a matrix) where each item is a Tile object (I've also done games where you just have a string that tells you what type of tile it is, and then you don't need a separate Tile class)\n\nThe map should be relatively static - you could have that traps become normal tiles after you step on them (this is pretty easy - when you do collision detection and it's a hit, just change that tile to a different Tile object (presumably the one for an empty tile)), but you don't want characters or movable blocks in the map if you can help it. Since the movable blocks have their own rules for how they can be moved, it's not as simple as just changing a tile - you'd have a whole set of logic, and at least two tiles would have to be changed (and what if you could move the blocks onto traps - you'd then have to remember, separately, what was below it - bleh). In my opinion it's easier to just have a class for each moving object and item.\nIn short, you have:\n\nTile\nMap\nBlock\nother movable objects/sprites\n\nAnd that's basically your whole level. For multiple levels, if individual levels are always the same, you can just have a list of Map objects, one for each level.\n", "If this is your first Pygame application, don't spend time worrying about \"object oriented design patterns for managing levels\". What you need to do now is to figure out how to make Pygame do what you want it to do.\n\nCan you display everything you want to?\nIs your display flicker-free?\nCan you read the user input controls properly?\netc.\n\nObject oriented patterns for managing levels comes later, much later.\n", "Generally speaking, a simple way to do it is using matrices (or multidimensional arrays - they work the same way here).\nBasically, each Map is an Array, with each item in the array being a square on the grid. \nFor example a 3 by 3 grid would be as follows:\n(Psuedocode)\nvar Map = [[1,2,3][1,2,3][1,2,3]];\nIn place of numbers, you could put strings for a function to parse and draw or take action based on what the value of the cell is.\n" ]
[ 7, 6, 1 ]
[]
[]
[ "design_patterns", "oop", "pygame", "python" ]
stackoverflow_0001871672_design_patterns_oop_pygame_python.txt
Q: String Conversion s='This is sample' i need to convert like this s='"This is sample"' output="This is sample" how to do this in dynamic Thanks in advance A: orig = 'This is sample' converted = '"%s"' % orig A: >>> s= 'This is a sample' >>> s = '"' + s + '"' # or s = '"%s"' % s >>> s '"This is a sample"' >>> print(s) "This is a sample" >>>
String Conversion
s='This is sample' i need to convert like this s='"This is sample"' output="This is sample" how to do this in dynamic Thanks in advance
[ "orig = 'This is sample'\nconverted = '\"%s\"' % orig\n\n", ">>> s= 'This is a sample'\n>>> s = '\"' + s + '\"' # or s = '\"%s\"' % s\n>>> s\n'\"This is a sample\"'\n>>> print(s)\n\"This is a sample\"\n>>>\n\n" ]
[ 5, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001873659_python_string.txt
Q: How to detect an invalid C escaped string using a regular expression? I would like to find a regular expression (regex) that does detect if you have some invalid escapes in a C double quoted escaped string (where you can find double quotes only escaped). I consider valid \\ \n \r \" (the test string is using ") A partial solution to this is to use (?<!\\)\\[^\"\\nr] but this one fails to detect bad escapes like \\\. Here is a test string that I use to test the matching: ...\n...\\b...\"...\\\\...\\\E...\...\\\...\\\\\..."...\E... The expression should match the last 6 blocks as invalid, the first 4 are valid. The problem is that my current version does find only 2/5 errors. A: (?:^|[^\\])(?:\\\\)*((?:\"|\\(?:[^\"\\nr]|$))) That's the start of a string, or something that's not a backslash. Then some (possibly zero) properly escaped backslashes, then either an unescaped " or another backslash; if it's another backslash, it must be followed by something that is neither ", \, n, nor r, or the end of the string. The incorrect escape is captured for you as well. A: Try this regular expression: ^(?:[^\\]+|\\[\\rn"])*(\\(?:[^\\rn"]|$)) If you have a match, you have an invalid escape sequence.
How to detect an invalid C escaped string using a regular expression?
I would like to find a regular expression (regex) that does detect if you have some invalid escapes in a C double quoted escaped string (where you can find double quotes only escaped). I consider valid \\ \n \r \" (the test string is using ") A partial solution to this is to use (?<!\\)\\[^\"\\nr] but this one fails to detect bad escapes like \\\. Here is a test string that I use to test the matching: ...\n...\\b...\"...\\\\...\\\E...\...\\\...\\\\\..."...\E... The expression should match the last 6 blocks as invalid, the first 4 are valid. The problem is that my current version does find only 2/5 errors.
[ "(?:^|[^\\\\])(?:\\\\\\\\)*((?:\\\"|\\\\(?:[^\\\"\\\\nr]|$)))\n\nThat's the start of a string, or something that's not a backslash. Then some (possibly zero) properly escaped backslashes, then either an unescaped \" or another backslash; if it's another backslash, it must be followed by something that is neither \", \\, n, nor r, or the end of the string.\nThe incorrect escape is captured for you as well.\n", "Try this regular expression:\n^(?:[^\\\\]+|\\\\[\\\\rn\"])*(\\\\(?:[^\\\\rn\"]|$))\n\nIf you have a match, you have an invalid escape sequence.\n" ]
[ 3, 0 ]
[]
[]
[ "c", "escaping", "python", "regex" ]
stackoverflow_0001873652_c_escaping_python_regex.txt
Q: Pros and Cons of different approaches to web programming in Python I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide and Django. What are the pros and cons of the frameworks or approaches that you've worked on? What trade-offs are there? For what kind of projects they do well and for what they don't? Edit: I haven't got much experience with web programing yet. I would like to avoid the basic and tedious things like parsing the URL for parameters, etc. On the other hand, while the video of blog created in 15 minutes with Ruby on Rails left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now. A: CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight WSGI app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI). Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive. Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :) How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one. A: The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, but scales badly both in terms of performance and organization. So when I need a very dynamic page very quickly that won't grow into a larger system, I use a CGI script. One step up from this is embedding your Python code in your HTML code, such as with PSP. I don't think many people use this nowadays, since modern template systems have made this pretty obsolete. I worked with PSP for awhile and found that it had basically the same organizational limits as CGI scripts (every page has its own file) plus some whitespace-related annoyances from trying to mix whitespace-ignorant HTML with whitespace-sensitive Python. The next step up is very simple web frameworks such as web.py, which I've also used. Like CGI scripts, it's very simple to get something up and running, and you don't need any complex configuration or automatically generated code. Your own code will be pretty simple to understand, so you can see what's happening. However, it's not as feature-rich as other web frameworks; last time I used it, there was no session tracking, so I had to roll my own. It also has "too much magic behavior" to quote Guido ("upvars(), bah"). Finally, you have feature-rich web frameworks such as Django. These will require a bit of work to get simple Hello World programs working, but every major one has a great, well-written tutorial (especially Django) to walk you through it. I highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation, etc. Ultimately you'll have to decide what you prefer. For example, frameworks all use template languages (special code/tags) to generate HTML files. Some of them such as Cheetah templates let you write arbitrary Python code so that you can do anything in a template. Others such as Django templates are more restrictive and force you to separate your presentation code from your program logic. It's all about what you personally prefer. Another example is URL handling; some frameworks such as Django have you define the URLs in your application through regular expressions. Others such as CherryPy automatically map your functions to urls by your function names. Again, this is a personal preference. I personally use a mix of web frameworks by using CherryPy for my web server stuff (form parameters, session handling, url mapping, etc) and Django for my object-relational mapping and templates. My recommendation is to start with a high level web framework, work your way through its tutorial, then start on a small personal project. I've done this with all of the technologies I've mentioned and it's been really beneficial. Eventually you'll get a feel for what you prefer and become a better web programmer (and a better programmer in general) in the process. A: If you decide to go with a framework that is WSGI-based (for instance TurboGears), I would recommend you go through the excellent article Another Do-It-Yourself Framework by Ian Bicking. In the article, he builds a simple web application framework from scratch. Also, check out the video Creating a web framework with WSGI by Kevin Dangoor. Dangoor is the founder of the TurboGears project. A: If you want to go big, choose Django and you are set. But if you want just to learn, roll your own framework using already mentioned WebOb - this can be really fun and I am sure you'll learn much more (plus you can use components you like: template system, url dispatcher, database layer, sessions, et caetera). In last 2 years I built few large sites using Django and all I can say, Django will fill 80% of your needs in 20% of time. Remaining 20% of work will take 80% of the time, no matter which framework you'd use. A: It's always worth doing something the hard way - once - as a learning exercise. Once you understand how it works, pick a framework that suits your application, and use that. You don't need to reinvent the wheel once you understand angular velocity. :-) It's also worth making sure that you have a fairly robust understanding of the programming language behind the framework before you jump in -- trying to learn both Django and Python at the same time (or Ruby and Rails, or X and Y), can lead to even more confusion. Write some code in the language first, then add the framework. We learn to develop, not by using tools, but by solving problems. Run into a few walls, climb over, and find some higher walls! A: If you've never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach. You'll learn a lot more about how all the various parts work than you would by using a framework. This will help in you design and debug and so on all your future web applications however you write them. Personally I now use Django. The real benefit is very fast application deployment. The object relational mapping gets things moving fast and the template library is a joy to use. Also the admin interface gives you basic CRUD screens for all your objects so you don't need to write any of the "boring" stuff. The downside of using an ORM based solution is that if you do want to handcraft some SQL, say for performance reasons, it much harder than it would have been otherwise, although still very possible. A: If you are using Python you should not start with CGI, instead start with WSGI (and you can use wsgiref.handlers.CGIHandler to run your WSGI script as a CGI script. The result is something that is basically as low-level as CGI (which might be useful in an educational sense, but will also be somewhat annoying), but without having to write to an entirely outdated interface (and binding your application to a single process model). If you want a less annoying, but similarly low-level interface, using WebOb would provide that. You would be implementing all the logic, and there will be few dark corners that you won't understand, but you won't have to spend time figuring out how to parse HTTP dates (they are weird!) or parse POST bodies. I write applications this way (without any other framework) and it is entirely workable. As a beginner, I'd advise this if you were interested in understanding what frameworks do, because it is inevitable you will be writing your own mini framework. OTOH, a real framework will probably teach you good practices of application design and structure. To be a really good web programmer, I believe you need to try both seriously; you should understand everything a framework does and not be afraid of its internals, but you should also spend time in a thoughtful environment someone else designed (i.e., an existing framework) and understand how that structure helps you. A: OK, rails is actually pretty good, but there is just a little bit too much magic going on in there (from the Ruby world I would much prefer merb to rails). I personally use Pylons, and am pretty darn happy. I'd say (compared to django), that pylons allows you to interchange ints internal parts easier than django does. The downside is that you will have to write more stuff all by youself (like the basic CRUD). Pros of using a framework: get stuff done quickly (and I mean lighning fast once you know the framework) everything is compying to standards (which is probably not that easy to achieve when rolling your own) easier to get something working (lots of tutorials) without reading gazillion articles and docs Cons: you learn less harder to replace parts (not that much of an issue in pylons, more so with django) harder to tweak some low-level stuff (like the above mentioned SQLs) From that you can probably devise what they are good for :-) Since you get all the code it is possible to tweak it to fit even the most bizzare situations (pylons supposedly work on the Google app engine now...). A: For smaller projects, rolling your own is fairly easy. Especially as you can simply import a templating engine like Genshi and get alot happening quite quickly and easily. Sometimes it's just quicker to use a screwdriver than to go looking for the power drill. Full blown frameworks provide alot more power, but do have to be installed and setup first before you can leverage that power. For larger projects, this is a negligible concern, but for smaller projects this might wind up taking most of your time - especially if the framework is unfamiliar.
Pros and Cons of different approaches to web programming in Python
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide and Django. What are the pros and cons of the frameworks or approaches that you've worked on? What trade-offs are there? For what kind of projects they do well and for what they don't? Edit: I haven't got much experience with web programing yet. I would like to avoid the basic and tedious things like parsing the URL for parameters, etc. On the other hand, while the video of blog created in 15 minutes with Ruby on Rails left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.
[ "CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight WSGI app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI).\nOther than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive.\nPersonally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :)\nHow much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one.\n", "The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, but scales badly both in terms of performance and organization. So when I need a very dynamic page very quickly that won't grow into a larger system, I use a CGI script.\nOne step up from this is embedding your Python code in your HTML code, such as with PSP. I don't think many people use this nowadays, since modern template systems have made this pretty obsolete. I worked with PSP for awhile and found that it had basically the same organizational limits as CGI scripts (every page has its own file) plus some whitespace-related annoyances from trying to mix whitespace-ignorant HTML with whitespace-sensitive Python.\nThe next step up is very simple web frameworks such as web.py, which I've also used. Like CGI scripts, it's very simple to get something up and running, and you don't need any complex configuration or automatically generated code. Your own code will be pretty simple to understand, so you can see what's happening. However, it's not as feature-rich as other web frameworks; last time I used it, there was no session tracking, so I had to roll my own. It also has \"too much magic behavior\" to quote Guido (\"upvars(), bah\").\nFinally, you have feature-rich web frameworks such as Django. These will require a bit of work to get simple Hello World programs working, but every major one has a great, well-written tutorial (especially Django) to walk you through it. I highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation, etc.\nUltimately you'll have to decide what you prefer. For example, frameworks all use template languages (special code/tags) to generate HTML files. Some of them such as Cheetah templates let you write arbitrary Python code so that you can do anything in a template. Others such as Django templates are more restrictive and force you to separate your presentation code from your program logic. It's all about what you personally prefer.\nAnother example is URL handling; some frameworks such as Django have you define the URLs in your application through regular expressions. Others such as CherryPy automatically map your functions to urls by your function names. Again, this is a personal preference.\nI personally use a mix of web frameworks by using CherryPy for my web server stuff (form parameters, session handling, url mapping, etc) and Django for my object-relational mapping and templates. My recommendation is to start with a high level web framework, work your way through its tutorial, then start on a small personal project. I've done this with all of the technologies I've mentioned and it's been really beneficial. Eventually you'll get a feel for what you prefer and become a better web programmer (and a better programmer in general) in the process.\n", "If you decide to go with a framework that is WSGI-based (for instance TurboGears), I would recommend you go through the excellent article Another Do-It-Yourself Framework by Ian Bicking.\nIn the article, he builds a simple web application framework from scratch.\nAlso, check out the video Creating a web framework with WSGI by Kevin Dangoor. Dangoor is the founder of the TurboGears project.\n", "If you want to go big, choose Django and you are set. But if you want just to learn, roll your own framework using already mentioned WebOb - this can be really fun and I am sure you'll learn much more (plus you can use components you like: template system, url dispatcher, database layer, sessions, et caetera).\nIn last 2 years I built few large sites using Django and all I can say, Django will fill 80% of your needs in 20% of time. Remaining 20% of work will take 80% of the time, no matter which framework you'd use.\n", "It's always worth doing something the hard way - once - as a learning exercise. Once you understand how it works, pick a framework that suits your application, and use that. You don't need to reinvent the wheel once you understand angular velocity. :-)\nIt's also worth making sure that you have a fairly robust understanding of the programming language behind the framework before you jump in -- trying to learn both Django and Python at the same time (or Ruby and Rails, or X and Y), can lead to even more confusion. Write some code in the language first, then add the framework.\nWe learn to develop, not by using tools, but by solving problems. Run into a few walls, climb over, and find some higher walls!\n", "If you've never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach. You'll learn a lot more about how all the various parts work than you would by using a framework. This will help in you design and debug and so on all your future web applications however you write them.\nPersonally I now use Django. The real benefit is very fast application deployment. The object relational mapping gets things moving fast and the template library is a joy to use. Also the admin interface gives you basic CRUD screens for all your objects so you don't need to write any of the \"boring\" stuff.\nThe downside of using an ORM based solution is that if you do want to handcraft some SQL, say for performance reasons, it much harder than it would have been otherwise, although still very possible. \n", "If you are using Python you should not start with CGI, instead start with WSGI (and you can use wsgiref.handlers.CGIHandler to run your WSGI script as a CGI script. The result is something that is basically as low-level as CGI (which might be useful in an educational sense, but will also be somewhat annoying), but without having to write to an entirely outdated interface (and binding your application to a single process model).\nIf you want a less annoying, but similarly low-level interface, using WebOb would provide that. You would be implementing all the logic, and there will be few dark corners that you won't understand, but you won't have to spend time figuring out how to parse HTTP dates (they are weird!) or parse POST bodies. I write applications this way (without any other framework) and it is entirely workable. As a beginner, I'd advise this if you were interested in understanding what frameworks do, because it is inevitable you will be writing your own mini framework. OTOH, a real framework will probably teach you good practices of application design and structure. To be a really good web programmer, I believe you need to try both seriously; you should understand everything a framework does and not be afraid of its internals, but you should also spend time in a thoughtful environment someone else designed (i.e., an existing framework) and understand how that structure helps you.\n", "OK, rails is actually pretty good, but there is just a little bit too much magic going on in there (from the Ruby world I would much prefer merb to rails). I personally use Pylons, and am pretty darn happy. I'd say (compared to django), that pylons allows you to interchange ints internal parts easier than django does. The downside is that you will have to write more stuff all by youself (like the basic CRUD). \nPros of using a framework:\n\nget stuff done quickly (and I mean lighning fast once you know the framework)\neverything is compying to standards (which is probably not that easy to achieve when rolling your own)\neasier to get something working (lots of tutorials) without reading gazillion articles and docs\n\nCons:\n\nyou learn less\nharder to replace parts (not that much of an issue in pylons, more so with django)\nharder to tweak some low-level stuff (like the above mentioned SQLs)\n\nFrom that you can probably devise what they are good for :-) Since you get all the code it is possible to tweak it to fit even the most bizzare situations (pylons supposedly work on the Google app engine now...).\n", "For smaller projects, rolling your own is fairly easy. Especially as you can simply import a templating engine like Genshi and get alot happening quite quickly and easily. Sometimes it's just quicker to use a screwdriver than to go looking for the power drill.\nFull blown frameworks provide alot more power, but do have to be installed and setup first before you can leverage that power. For larger projects, this is a negligible concern, but for smaller projects this might wind up taking most of your time - especially if the framework is unfamiliar.\n" ]
[ 17, 12, 7, 4, 3, 2, 2, 1, 1 ]
[]
[]
[ "cgi", "frameworks", "python", "wsgi" ]
stackoverflow_0000043709_cgi_frameworks_python_wsgi.txt
Q: Pygame: Blitting a moving background creates too much blur What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in). However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the code. I was looking for examples on how others blit or create scrolling backgrounds and found this article: Scrolling Games I used their simple example and sure enough the background appears blurry as you scroll (aka blit the background with an offset). I also thought it might be the FPS dropping for whatever reason however it doesn't deviate at all. I can't recall an issue like this with other 2D games. I understand there may be some motion blur due to it constantly shifting. Just wondering if I can do anything to alleviate this. Can someone chime in on anything I may be missing? I would appreciate any feedback or help. Thank you A: I couldn't know what caused the problem you faced, but I guess it is related to double buffering. Did you use at least two surfaces? # preparing two surfaces in __init__() screen = pygame.display.set_mode((800,600)) background = pygame.Surface(screen.get_size()) background.fill((250, 250, 250)) # called at every step in main loop # draw images on the background surface background.blit(image, position) .... # blit background to screen screen.blit(background, (0, 0)) pygame.display.flip() If images are drawn on the screen surface directly, flicking occurs. A: By "blurry" do you mean that the background appears "doubled"? Do you get the same effect when moving a normal-sized (e.g., 64x64) sprite? If you are seeing double, then it's probably a refresh rate problem. Turning on vsync may help. What frame rate are you getting? If you slow down the animation to around 10 FPS, do you have the same problem?
Pygame: Blitting a moving background creates too much blur
What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in). However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the code. I was looking for examples on how others blit or create scrolling backgrounds and found this article: Scrolling Games I used their simple example and sure enough the background appears blurry as you scroll (aka blit the background with an offset). I also thought it might be the FPS dropping for whatever reason however it doesn't deviate at all. I can't recall an issue like this with other 2D games. I understand there may be some motion blur due to it constantly shifting. Just wondering if I can do anything to alleviate this. Can someone chime in on anything I may be missing? I would appreciate any feedback or help. Thank you
[ "I couldn't know what caused the problem you faced, but I guess it is related to double buffering. \nDid you use at least two surfaces? \n# preparing two surfaces in __init__()\nscreen = pygame.display.set_mode((800,600))\nbackground = pygame.Surface(screen.get_size())\nbackground.fill((250, 250, 250))\n\n# called at every step in main loop\n# draw images on the background surface\nbackground.blit(image, position)\n....\n\n# blit background to screen\nscreen.blit(background, (0, 0))\npygame.display.flip()\n\nIf images are drawn on the screen surface directly, flicking occurs. \n", "By \"blurry\" do you mean that the background appears \"doubled\"? Do you get the same effect when moving a normal-sized (e.g., 64x64) sprite? \nIf you are seeing double, then it's probably a refresh rate problem. Turning on vsync may help. \nWhat frame rate are you getting? \nIf you slow down the animation to around 10 FPS, do you have the same problem? \n" ]
[ 3, 0 ]
[]
[]
[ "blit", "pygame", "python", "sprite" ]
stackoverflow_0001871607_blit_pygame_python_sprite.txt
Q: Display the result on the webpage as soon as the data is available at server I am writing a cgi page in Python. Let's say a client sends request to my cgi page. My cgi page does the calculation and as soon as it has the first output, it sends back that output to the client, but it will CONTINUE to do the calculation and send other responses AFTER the first response is sent. Is what I have presented here possible? I ask this question because in my limited knowledge, in a cgi page responses are sent back on one-time basic, once a response is sent, cgi-page stops running. This thing is made on server side or client side, and how do I implement it? My server is running Apache. Thank you very much. I have tried a client code from "dbr" in this forum (thanks to him I got the idea of how long-polling works). <html> <head> <title>BargePoller</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> body{ background:#000;color:#fff;font-size:.9em; } .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid} .old{ background-color:#246499;} .new{ background-color:#3B9957;} .error{ background-color:#992E36;} </style> <script type="text/javascript" charset="utf-8"> function addmsg(type, msg){ /* Simple helper to add a div. type is the name of a CSS class (old/new/error). msg is the contents of the div */ $("#messages").append( "<div class='msg "+ type +"'>"+ msg +"</div>" ); } function waitForMsg(){ /* This requests the url "msgsrv.php" When it complete (or errors)*/ $.ajax({ type: "GET", url: "msgsrv.php", async: true, /* If set to non-async, browser shows page as "Loading.."*/ cache: false, timeout:50000, /* Timeout in ms */ success: function(data){ /* called when request to barge.php completes */ addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/ setTimeout( 'waitForMsg()', /* Request next message */ 1000 /* ..after 1 seconds */ ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ addmsg("error", textStatus + " (" + errorThrown + ")"); setTimeout( 'waitForMsg()', /* Try again after.. */ "15000"); /* milliseconds (15seconds) */ }, }); }; $(document).ready(function(){ waitForMsg(); /* Start the inital request */ }); </script> </head> <body> <div id="messages"> <div class="msg old"> BargePoll message requester! </div> </div> </body> </html> And here is my server code: import sys if __name__ == "__main__": sys.stdout.write("Content-Type: text/html\r\n\r\n") print "<html><body>" for i in range(10): print "<div>%s</div>" % i sys.stdout.flush() print "</body></html>" I am expecting my client page to display 1 number at a time (0,1,2,...), but the data always comes out all at once (01234...). Please help me figure it out. Thanks you guys so much. Just a little out-track, I am trying to use jquery comet plugin, but I couldn't find sufficient documentation though. Helps would be much appreciated. Thanks again :D [edit] Ok guys, finally thanks to your guides I have managed to make it work. You're right when predict that mod_deflate is the source of all this. To sum up, what I have done here: For client, make a long poll page as the html code above For server, disable the mod_deflate by: editing file /etc/apache2/mods-available/deflate.conf, comment out the line with text/html part and restart the server. To ensure that Python doesn't buffer the output itself, include #!/usr/bin/python -u in the beginning of the page. Remember to use sys.stdout.flush() after each printing that you want to appear at the client. The effect may not be transparent, should include time.sleep(1) to test. :D Thanks you guys very much for supporting and helping solving this :D A: Sure. There's traditional server-driven approach, where the script runs just once, but takes a long time to complete, spitting out bits of page as it goes: import sys, time sys.stdout.write('Content-Type: text/html;charset=utf-8\r\n\r\n') print '<html><body>' for i in range(10): print '<div>%i</div>'%i sys.stdout.flush() time.sleep(1) When writing an app to WSGI, this is done by having the application return an iterable which outputs each block it wants sent separately one at a time. I'd really recommend writing to WSGI; you can deploy it through CGI now, but in the future when your app needs better performance you can deploy it through a faster server/interface without having to rewrite. WSGI-over-CGI example: import time, wsgiref.handlers class MyApplication(object): def __call__(self, environ, start_response): start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')]) return self.page() def page(self): yield '<html><body>' for i in range(10): yield '<div>%i</div>'%i time.sleep(1) application= MyApplication() if __name__=='__main__': wsgiref.handlers.CGIHandler().run(application) Note that your web server may foil this approach (for CGI or WSGI) by adding buffering of its own. This typically happens if you're using output-transforming filters like mod_deflate to automatically compress webapp output. You'll need to turn compression off for partial-response-generating scripts. This limits you to rendering the page bit-by-bit as new data comes in. You can make it prettier by having the client-side take care of altering the page as new data comes in, eg.: def page(self): yield ( '<html><body><div id="counter">-</div>' '<script type="text/javascript">' ' function update(n) {' ' document.getElementById("counter").firstChild.data= n;' ' }' '</script>' ) for i in range(10): yield '<script type="text/javascript">update(%i);</script>'%i time.sleep(1) This relies on client-side scripting so it might be a good idea to include backup non-script-based final output at the end. All the while doing this, the page will appear to be still loading. If you don't want that, then you'd need to split the script into a first request that just spits out the static content, including client-side script that checks back with the server using either one XMLHttpRequest that it polls for new data through, or, for the really long-running cases, many XMLHttpRequests each of which returns the status and any new data. This approach is much more complicated as it means you have to run your work process as a background daemon process apart from the web server, and pass data between the daemon and the front-end CGI/WSGI request using eg. pipes or a database. A: Yes thats possible and you don't have do much, as you print data out, server will send it, just to be sure keep flushing stdout A: There are a few techniques. The old-fashioned way is to continue to stream data, and have the browser continue to render it using progressive rendering. So as an old-fashioned CGI, just do sys.stdout.flush(). This shows a partial page that you can keep adding to, but it looks clumsy in the browser because the throbber will keep spinning and it looks much like the server is hung or overloaded. Some browsers support a special multipart mimetype multipart/x-mixed-replace that allows you to do the same trick of keeping the connection open, but the browser will replace the page completely when you send the next multipart chunk (which must be MIME-formatted). I don't know if that's usable - Internet Explorer doesn't support it and it may not work well in other browser either. The next most modern way is polling the server for results with Javascript's XMLHttpRequest. This requires that you can check the results of the operation from a different webserver thread or process, which can be quite a bit more difficult to achieve in the server-side code. It allows you to create a much nicer web page though. If you want to get even more complicated, check out the "Comet" model or "Web Sockets". A: The trick in old-fashioned CGI programs is using the Transfer-Encoding: chunked HTTP header: 3.6.1 Chunked Transfer Coding The chunked encoding modifies the body of a message in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer containing entity-header fields. This allows dynamically produced content to be transferred along with the information necessary for the recipient to verify that it has received the full message. When a result is available, send it as a separate chunk - the browser will display this self-contained HTTP message. When another chunk arrives later, a NEW PAGE is displayed. You'll have to produce the correct headers for each chunk inside the CGI program. Also, remember to flush the CGI output at the end of each chunk. In Python this is done with sys.stdout.flush()
Display the result on the webpage as soon as the data is available at server
I am writing a cgi page in Python. Let's say a client sends request to my cgi page. My cgi page does the calculation and as soon as it has the first output, it sends back that output to the client, but it will CONTINUE to do the calculation and send other responses AFTER the first response is sent. Is what I have presented here possible? I ask this question because in my limited knowledge, in a cgi page responses are sent back on one-time basic, once a response is sent, cgi-page stops running. This thing is made on server side or client side, and how do I implement it? My server is running Apache. Thank you very much. I have tried a client code from "dbr" in this forum (thanks to him I got the idea of how long-polling works). <html> <head> <title>BargePoller</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css" media="screen"> body{ background:#000;color:#fff;font-size:.9em; } .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid} .old{ background-color:#246499;} .new{ background-color:#3B9957;} .error{ background-color:#992E36;} </style> <script type="text/javascript" charset="utf-8"> function addmsg(type, msg){ /* Simple helper to add a div. type is the name of a CSS class (old/new/error). msg is the contents of the div */ $("#messages").append( "<div class='msg "+ type +"'>"+ msg +"</div>" ); } function waitForMsg(){ /* This requests the url "msgsrv.php" When it complete (or errors)*/ $.ajax({ type: "GET", url: "msgsrv.php", async: true, /* If set to non-async, browser shows page as "Loading.."*/ cache: false, timeout:50000, /* Timeout in ms */ success: function(data){ /* called when request to barge.php completes */ addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/ setTimeout( 'waitForMsg()', /* Request next message */ 1000 /* ..after 1 seconds */ ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ addmsg("error", textStatus + " (" + errorThrown + ")"); setTimeout( 'waitForMsg()', /* Try again after.. */ "15000"); /* milliseconds (15seconds) */ }, }); }; $(document).ready(function(){ waitForMsg(); /* Start the inital request */ }); </script> </head> <body> <div id="messages"> <div class="msg old"> BargePoll message requester! </div> </div> </body> </html> And here is my server code: import sys if __name__ == "__main__": sys.stdout.write("Content-Type: text/html\r\n\r\n") print "<html><body>" for i in range(10): print "<div>%s</div>" % i sys.stdout.flush() print "</body></html>" I am expecting my client page to display 1 number at a time (0,1,2,...), but the data always comes out all at once (01234...). Please help me figure it out. Thanks you guys so much. Just a little out-track, I am trying to use jquery comet plugin, but I couldn't find sufficient documentation though. Helps would be much appreciated. Thanks again :D [edit] Ok guys, finally thanks to your guides I have managed to make it work. You're right when predict that mod_deflate is the source of all this. To sum up, what I have done here: For client, make a long poll page as the html code above For server, disable the mod_deflate by: editing file /etc/apache2/mods-available/deflate.conf, comment out the line with text/html part and restart the server. To ensure that Python doesn't buffer the output itself, include #!/usr/bin/python -u in the beginning of the page. Remember to use sys.stdout.flush() after each printing that you want to appear at the client. The effect may not be transparent, should include time.sleep(1) to test. :D Thanks you guys very much for supporting and helping solving this :D
[ "Sure.\nThere's traditional server-driven approach, where the script runs just once, but takes a long time to complete, spitting out bits of page as it goes:\nimport sys, time\n\nsys.stdout.write('Content-Type: text/html;charset=utf-8\\r\\n\\r\\n')\n\nprint '<html><body>'\nfor i in range(10):\n print '<div>%i</div>'%i\n sys.stdout.flush()\n time.sleep(1)\n\nWhen writing an app to WSGI, this is done by having the application return an iterable which outputs each block it wants sent separately one at a time. I'd really recommend writing to WSGI; you can deploy it through CGI now, but in the future when your app needs better performance you can deploy it through a faster server/interface without having to rewrite.\nWSGI-over-CGI example:\nimport time, wsgiref.handlers\n\nclass MyApplication(object):\n def __call__(self, environ, start_response):\n start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])\n return self.page()\n\n def page(self):\n yield '<html><body>'\n for i in range(10):\n yield '<div>%i</div>'%i\n time.sleep(1)\n\napplication= MyApplication()\nif __name__=='__main__':\n wsgiref.handlers.CGIHandler().run(application)\n\nNote that your web server may foil this approach (for CGI or WSGI) by adding buffering of its own. This typically happens if you're using output-transforming filters like mod_deflate to automatically compress webapp output. You'll need to turn compression off for partial-response-generating scripts.\nThis limits you to rendering the page bit-by-bit as new data comes in. You can make it prettier by having the client-side take care of altering the page as new data comes in, eg.:\ndef page(self):\n yield (\n '<html><body><div id=\"counter\">-</div>'\n '<script type=\"text/javascript\">'\n ' function update(n) {'\n ' document.getElementById(\"counter\").firstChild.data= n;'\n ' }'\n '</script>'\n )\n for i in range(10):\n yield '<script type=\"text/javascript\">update(%i);</script>'%i\n time.sleep(1)\n\nThis relies on client-side scripting so it might be a good idea to include backup non-script-based final output at the end.\nAll the while doing this, the page will appear to be still loading. If you don't want that, then you'd need to split the script into a first request that just spits out the static content, including client-side script that checks back with the server using either one XMLHttpRequest that it polls for new data through, or, for the really long-running cases, many XMLHttpRequests each of which returns the status and any new data. This approach is much more complicated as it means you have to run your work process as a background daemon process apart from the web server, and pass data between the daemon and the front-end CGI/WSGI request using eg. pipes or a database.\n", "Yes thats possible and you don't have do much,\nas you print data out, server will send it, just to be sure keep flushing stdout\n", "There are a few techniques.\nThe old-fashioned way is to continue to stream data, and have the browser continue to render it using progressive rendering. So as an old-fashioned CGI, just do sys.stdout.flush(). This shows a partial page that you can keep adding to, but it looks clumsy in the browser because the throbber will keep spinning and it looks much like the server is hung or overloaded.\nSome browsers support a special multipart mimetype multipart/x-mixed-replace that allows you to do the same trick of keeping the connection open, but the browser will replace the page completely when you send the next multipart chunk (which must be MIME-formatted). I don't know if that's usable - Internet Explorer doesn't support it and it may not work well in other browser either.\nThe next most modern way is polling the server for results with Javascript's XMLHttpRequest. This requires that you can check the results of the operation from a different webserver thread or process, which can be quite a bit more difficult to achieve in the server-side code. It allows you to create a much nicer web page though.\nIf you want to get even more complicated, check out the \"Comet\" model or \"Web Sockets\".\n", "The trick in old-fashioned CGI programs is using the Transfer-Encoding: chunked HTTP header:\n\n3.6.1 Chunked Transfer Coding\nThe chunked encoding modifies the body of a message in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer containing entity-header fields. This allows dynamically produced content to be transferred along with the information necessary for the recipient to verify that it has received the full message.\n\nWhen a result is available, send it as a separate chunk - the browser will display this self-contained HTTP message. When another chunk arrives later, a NEW PAGE is displayed.\nYou'll have to produce the correct headers for each chunk inside the CGI program. Also, remember to flush the CGI output at the end of each chunk. In Python this is done with sys.stdout.flush()\n" ]
[ 10, 1, 1, 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0001873735_cgi_python.txt
Q: Extract resulted list data to a xml file in python How can I extract my resulted list data to an xml file? My resulted list is given below: week=[{'item': Electrelane, 'weight': 140}, {'item': Kraftwerk, 'weight': 117},{'item': The Flaming Lips, 'weight': 113}] A: You can trivially adjust this to your needs. A: Since you don't provide any information on how you want to format your XML, i just invented my own notation. week=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}] print "<?xml version='1.0' ?>" print "<week>" for day in week: print " <day>" for key, value in day.items(): print " <%s>%s</%s>" % (key, value, key) print " </day>" print "</week>" EDIT To print to console, iterate over items in a similar way but change the output (by the print commands) # enumerate the days in the week for i, day in enumerate(week): print "day %d" % i # show values in sorted order for key in sorted(day): print " - %s\t: %s" % (key, day[key]) A: Here's some code that uses xml.dom.minidom to build up the XML document. week=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}] from xml.dom.minidom import getDOMImplementation impl = getDOMImplementation() document = impl.createDocument(None, "week", None) week_element = document.documentElement for entry in week: node = document.createElement("entry") for attr,value in entry.iteritems(): node.setAttribute(attr,str(value)) week_element.appendChild(node) print document.toprettyxml() Produces: <?xml version="1.0" ?> <week> <entry item="Electrelane" weight="140"/> <entry item="Kraftwerk" weight="117"/> <entry item="The Flaming Lips" weight="113"/> </week>
Extract resulted list data to a xml file in python
How can I extract my resulted list data to an xml file? My resulted list is given below: week=[{'item': Electrelane, 'weight': 140}, {'item': Kraftwerk, 'weight': 117},{'item': The Flaming Lips, 'weight': 113}]
[ "You can trivially adjust this to your needs.\n", "Since you don't provide any information on how you want to format your XML, i just invented my own notation.\nweek=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}]\n\nprint \"<?xml version='1.0' ?>\"\nprint \"<week>\"\nfor day in week:\n print \" <day>\"\n for key, value in day.items():\n print \" <%s>%s</%s>\" % (key, value, key)\n print \" </day>\"\nprint \"</week>\"\n\nEDIT\nTo print to console, iterate over items in a similar way but change the output (by the print commands)\n# enumerate the days in the week\nfor i, day in enumerate(week):\n print \"day %d\" % i\n # show values in sorted order\n for key in sorted(day):\n print \" - %s\\t: %s\" % (key, day[key])\n\n", "Here's some code that uses xml.dom.minidom to build up the XML document.\nweek=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}]\n\nfrom xml.dom.minidom import getDOMImplementation\n\nimpl = getDOMImplementation()\ndocument = impl.createDocument(None, \"week\", None)\nweek_element = document.documentElement\n\nfor entry in week:\n node = document.createElement(\"entry\")\n\n for attr,value in entry.iteritems():\n node.setAttribute(attr,str(value))\n\n week_element.appendChild(node)\n\nprint document.toprettyxml()\n\nProduces:\n<?xml version=\"1.0\" ?>\n<week>\n <entry item=\"Electrelane\" weight=\"140\"/>\n <entry item=\"Kraftwerk\" weight=\"117\"/>\n <entry item=\"The Flaming Lips\" weight=\"113\"/>\n</week>\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001872861_python_xml.txt
Q: Send raw ethernet packet with data field length in type field I'm trying to send a raw ethernet frame with the length of my data written in the type field. This should be a valid ethernet frame. My code for this looks like this: ethData = "foobar" proto =len(ethData) if proto < 46: proto = 46 soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, proto) soc.bind((iface, proto)) For some reason I cant read package on the other end. I wonder why. I try to get this package in the interrupt handler of my wireless driver, so this packet has to be droped by my hardware directly or it doesn't get send at all. The question is why. A: Sorry, my fault. I just parsed the wrong portion of the packet and didn't get any output. My bad. The package gets there just like it is supposed to.
Send raw ethernet packet with data field length in type field
I'm trying to send a raw ethernet frame with the length of my data written in the type field. This should be a valid ethernet frame. My code for this looks like this: ethData = "foobar" proto =len(ethData) if proto < 46: proto = 46 soc = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, proto) soc.bind((iface, proto)) For some reason I cant read package on the other end. I wonder why. I try to get this package in the interrupt handler of my wireless driver, so this packet has to be droped by my hardware directly or it doesn't get send at all. The question is why.
[ "Sorry, my fault. I just parsed the wrong portion of the packet and didn't get any output. My bad. The package gets there just like it is supposed to.\n" ]
[ 0 ]
[]
[]
[ "ethernet", "python", "sockets" ]
stackoverflow_0001873427_ethernet_python_sockets.txt
Q: How to implement objects modification trace With django admin, we have an history of who altered an object and when. I would like to add an "old value", "new value" to this to be able to roll back if needed. Plus I would like every modification made to my objects (also outside of admin) to be recorded as well. The final objective is to be able to trace every modification of every object in the models and be able to roll back if needed. Do you know if such a module already exists. If not what would be the good start point ? Thanks A: I haven't personally tried it but it sounds like you should check out django-reversion.
How to implement objects modification trace
With django admin, we have an history of who altered an object and when. I would like to add an "old value", "new value" to this to be able to roll back if needed. Plus I would like every modification made to my objects (also outside of admin) to be recorded as well. The final objective is to be able to trace every modification of every object in the models and be able to roll back if needed. Do you know if such a module already exists. If not what would be the good start point ? Thanks
[ "I haven't personally tried it but it sounds like you should check out django-reversion.\n" ]
[ 3 ]
[]
[]
[ "django", "django_admin", "django_models", "python", "trace" ]
stackoverflow_0001873966_django_django_admin_django_models_python_trace.txt
Q: How to use re to search for items in one list inside another list in Python I am reading a list of strings, each of which relate to a file name. However, each string is minus the extension. I have come up with the following code: import re item_list = ['item1', 'item2'] search_list = ['item1.exe', 'item2.pdf'] matches = [] for item in item_list: # Match item in search_list using re - I assume this is the best way to do this regex = re.compile("^"+item+"\.") for file in search_list: if regex.match(file): matches.append((item, file)) As for duplicate matches, I'm not intensely worried about two files being named 'foo.bar' and 'foo.foo.bar'. That being said, is there a better way of doing this? Thank you. A: You could combine all the items into one regexp like this which will be more efficient import re item_list = ['item1', 'item2'] regex = re.compile("^("+"|".join(item_list)+")\.") search_list = ['item1.exe', 'item2.pdf'] matches = [] for file in search_list: match = regex.match(file) if match: matches.append((match.group(1), file)) A better solution might be to parse the filenames using os.path functions though to parse out the basenames and look for them in a set. A: Use splitext to get the filename without the extension: import os.path for item in item_list: for filename in search_list: if item == os.path.splitext(filename)[0]: matches.append((item, file)) It's more correct, but it's also easier to understand what your intention is from reading the code. Alternatively, if you want to allow foo to match foo.bar.txt then use filename.startswith(item + '.') instead. A: You do not need to use a regex for this since you are doing exact string matches (no wildcards, groups etc) - you can use str.startswith(..) instead. This is equivalent to your code: for item in item_list: match = item + "." for file in search_list: if file.startswith(match) matches.append((item, file)) However Nick Craig-Wood's suggestion of compiling all the matches into a single regex may be more efficient - I suggest you benchmark both if speed is an issue. A: Avoid re unless you really need it. For simple string matching, you don't really need it. Mark Byers's answer duplicates the original behaviour of keeping matches in item_list-order. If you don't need that, you could do it even more simply/quickly: for file in search_list: item= os.path.splitext(file)[0] if item in item_list: matches.append((item, file)) If you don't need to keep the (item) matched either (since it's redundant from the filename anyway), you've got a one-liner: matches= [file for file in search_list if os.path.splitext(file)[0] in item_list] A: Here's another way to do it that is likely faster than Alex's original code: item_list = ['item1', 'item2'] search_list = ['item1.exe', 'item2.pdf'] matches = [] for item in item_list: for filename in search_list: if filename.partition(".")[0] == item: matches.append((item,filename)) A: I think you should use .rsplit(".",1) for that purpose, regex aren't overkill? >>> item_list = ['item1', 'item2','item3'] >>> search_list = ['item1.exe', 'item2.pdf','item9999.txt'] >>> >>> [(x.rsplit(".",1)[0],x) for x in search_list if x.rsplit(".",1)[0] in item_list] [('item1', 'item1.exe'), ('item2', 'item2.pdf')] or with for loop matches=[] for x in search_list: y=x.rsplit(".",1)[0] if y in item_list: matches.append((y,x)) A: >>> for file in search_list: ... tomatch=file.split(".")[0] ... if tomatch in item_list: ... found=item_list.index(tomatch) ... matches.append( ( file, item_list[found] ) ) ... >>> print matches [('item1.exe', 'item1'), ('item2.pdf', 'item2')] >>> No need for regex.
How to use re to search for items in one list inside another list in Python
I am reading a list of strings, each of which relate to a file name. However, each string is minus the extension. I have come up with the following code: import re item_list = ['item1', 'item2'] search_list = ['item1.exe', 'item2.pdf'] matches = [] for item in item_list: # Match item in search_list using re - I assume this is the best way to do this regex = re.compile("^"+item+"\.") for file in search_list: if regex.match(file): matches.append((item, file)) As for duplicate matches, I'm not intensely worried about two files being named 'foo.bar' and 'foo.foo.bar'. That being said, is there a better way of doing this? Thank you.
[ "You could combine all the items into one regexp like this which will be more efficient\nimport re\nitem_list = ['item1', 'item2']\nregex = re.compile(\"^(\"+\"|\".join(item_list)+\")\\.\")\nsearch_list = ['item1.exe', 'item2.pdf']\nmatches = []\nfor file in search_list:\n match = regex.match(file)\n if match:\n matches.append((match.group(1), file))\n\nA better solution might be to parse the filenames using os.path functions though to parse out the basenames and look for them in a set.\n", "Use splitext to get the filename without the extension:\nimport os.path\n\nfor item in item_list:\n for filename in search_list:\n if item == os.path.splitext(filename)[0]:\n matches.append((item, file))\n\nIt's more correct, but it's also easier to understand what your intention is from reading the code. Alternatively, if you want to allow foo to match foo.bar.txt then use filename.startswith(item + '.') instead.\n", "You do not need to use a regex for this since you are doing exact string matches (no wildcards, groups etc) - you can use str.startswith(..) instead. This is equivalent to your code:\nfor item in item_list:\n match = item + \".\"\n for file in search_list:\n if file.startswith(match)\n matches.append((item, file))\n\nHowever Nick Craig-Wood's suggestion of compiling all the matches into a single regex may be more efficient - I suggest you benchmark both if speed is an issue.\n", "Avoid re unless you really need it. For simple string matching, you don't really need it.\nMark Byers's answer duplicates the original behaviour of keeping matches in item_list-order. If you don't need that, you could do it even more simply/quickly:\nfor file in search_list:\n item= os.path.splitext(file)[0]\n if item in item_list:\n matches.append((item, file))\n\nIf you don't need to keep the (item) matched either (since it's redundant from the filename anyway), you've got a one-liner:\nmatches= [file for file in search_list if os.path.splitext(file)[0] in item_list]\n\n", "Here's another way to do it that is likely faster than Alex's original code:\nitem_list = ['item1', 'item2']\nsearch_list = ['item1.exe', 'item2.pdf']\nmatches = []\nfor item in item_list:\n for filename in search_list:\n if filename.partition(\".\")[0] == item:\n matches.append((item,filename))\n\n", "I think you should use .rsplit(\".\",1) for that purpose, regex aren't overkill?\n>>> item_list = ['item1', 'item2','item3']\n>>> search_list = ['item1.exe', 'item2.pdf','item9999.txt']\n>>>\n>>> [(x.rsplit(\".\",1)[0],x) for x in search_list if x.rsplit(\".\",1)[0] in item_list]\n[('item1', 'item1.exe'), ('item2', 'item2.pdf')]\n\nor with for loop\nmatches=[]\nfor x in search_list:\n y=x.rsplit(\".\",1)[0]\n if y in item_list:\n matches.append((y,x))\n\n", ">>> for file in search_list:\n... tomatch=file.split(\".\")[0]\n... if tomatch in item_list:\n... found=item_list.index(tomatch)\n... matches.append( ( file, item_list[found] ) )\n...\n>>> print matches\n[('item1.exe', 'item1'), ('item2.pdf', 'item2')]\n>>>\n\nNo need for regex.\n" ]
[ 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001872016_python_regex.txt
Q: I need a clean approach for range-checking floats in Python I'm looking for a simple way of range checking floats in Python where the minimum and maximum bounds may be null. The code in question is: tval = float(-b - discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval tval = float(-b + discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval # Neither solution was within the acceptable range. return None However, this completely fails to handle the case where tmin or tmax is None (which should be interpreted to mean that there is no minimum or maximum respectively). So far the best I've been able to come up with is: tval = float(-b - discriminant) / float (2*a) if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax): return tval tval = float(-b + discriminant) / float (2*a) if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax): return tval # Neither solution was within the acceptable range. return None I keep thinking there has to be a better (cleaner, more readable) way to write that. Any ideas? A: First, some setup: we'll need a float infinity constant. INF = float(1e3000) or INF = float('inf') # Python 2.6+ First option can be considered portable for practical purposes; just use some really huge value which is guaranteed to be outside the range representable by your platform's floating point type. Second option is "truly" portable, but requires Python 2.6 or newer. Now, your condition can be written this way (edit: only if tmin and tmax cannot be zero!): if (tmin or -INF) <= tval <= (tmax or +INF) : return tval Edit I made a crude error by missing that 0.0 is a legitimate value for tmin or tmax. Thanks to Roger Pate for noticing. A: Maybe I'd define a checker function first, for readability: def inrange(x, min, max): return (min is None or min <= x) and (max is None or max >= x) tval = float(-b - discriminant) / float (2*a) if inrange(tval, tmin, tmax): return tval tval = float(-b + discriminant) / float (2*a) if inrange(tval, tmin, tmax): return tval # Neither solution was within the acceptable range. return None There must be a module defining such an inrange method somewhere, I bet. But I did not find it (nor look for it, though). :) A: Using INF from atzz's answer (in a way that won't fail when 0.0 is used): def coalesce(*values): for v in values: if v is not None: return v if coalesce(tmin, -INF) <= tval <= coalesce(tmax, INF): return tval However, what you have is clear enough for me: if ((tmin is None or tmin <= tval) and (tmax is None or tval <= tmax)): return tval A: Using INF from atzz's answer if tmin is None: tmin = -INF if tmax is None: tmax = +INF tval = float(-b - discriminant) / float (2*a) if tmin <= tval <= tmax: return tval tval = float(-b + discriminant) / float (2*a) if tmin <= tval <= tmax: return tval # Neither solution was within the acceptable range. return None
I need a clean approach for range-checking floats in Python
I'm looking for a simple way of range checking floats in Python where the minimum and maximum bounds may be null. The code in question is: tval = float(-b - discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval tval = float(-b + discriminant) / float (2*a) if tval >= tmin and tval <= tmax: return tval # Neither solution was within the acceptable range. return None However, this completely fails to handle the case where tmin or tmax is None (which should be interpreted to mean that there is no minimum or maximum respectively). So far the best I've been able to come up with is: tval = float(-b - discriminant) / float (2*a) if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax): return tval tval = float(-b + discriminant) / float (2*a) if (tmin == None or tval >= tmin) and (tmax == None or tval <= tmax): return tval # Neither solution was within the acceptable range. return None I keep thinking there has to be a better (cleaner, more readable) way to write that. Any ideas?
[ "First, some setup: we'll need a float infinity constant.\nINF = float(1e3000)\n\nor\nINF = float('inf') # Python 2.6+\n\nFirst option can be considered portable for practical purposes; just use some really huge value which is guaranteed to be outside the range representable by your platform's floating point type. Second option is \"truly\" portable, but requires Python 2.6 or newer.\nNow, your condition can be written this way (edit: only if tmin and tmax cannot be zero!):\nif (tmin or -INF) <= tval <= (tmax or +INF) :\n return tval\n\nEdit\nI made a crude error by missing that 0.0 is a legitimate value for tmin or tmax. Thanks to Roger Pate for noticing.\n", "Maybe I'd define a checker function first, for readability:\ndef inrange(x, min, max):\n return (min is None or min <= x) and (max is None or max >= x)\n\ntval = float(-b - discriminant) / float (2*a)\nif inrange(tval, tmin, tmax):\n return tval \n\ntval = float(-b + discriminant) / float (2*a)\nif inrange(tval, tmin, tmax):\n return tval \n\n# Neither solution was within the acceptable range.\nreturn None\n\nThere must be a module defining such an inrange method somewhere, I bet. But I did not find it (nor look for it, though). :)\n", "Using INF from atzz's answer (in a way that won't fail when 0.0 is used):\ndef coalesce(*values):\n for v in values:\n if v is not None:\n return v\n\nif coalesce(tmin, -INF) <= tval <= coalesce(tmax, INF):\n return tval\n\nHowever, what you have is clear enough for me:\nif ((tmin is None or tmin <= tval) and\n (tmax is None or tval <= tmax)):\n return tval\n\n", "Using INF from atzz's answer\nif tmin is None: tmin = -INF\nif tmax is None: tmax = +INF\n\ntval = float(-b - discriminant) / float (2*a)\nif tmin <= tval <= tmax:\n return tval \n\ntval = float(-b + discriminant) / float (2*a)\nif tmin <= tval <= tmax:\n return tval\n\n# Neither solution was within the acceptable range.\nreturn None\n\n" ]
[ 4, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001873625_python.txt
Q: unhexlify in objective c is there something like Python's unhexlify for objc / cocoa? >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). This function is also available as "unhexlify()" >>> unhexlify('abc123d35d') '\xab\xc1#\xd3]' A: Edit: I didn't grok what unhexlify does. I still don't grok why it might be useful (commenters?). You would have to pick off the hex characters two at a time, convert them to an int, and spit out the characters. char *hex = "abc123d35d"; NSData *data = [NSData dataWithBytesNoCopy:hex length:strlen(hex)]; NSInputStream *input = [NSInputStream inputStreamWithWithData:data]; NSOutputStream *output = [NSOutputStream outputStreamToMemory]; [input open]; [output open]; uint8_t buffer[2], result; while ([input hasBytesAvailable]) { [input read:buffer maxLength:2]; if (sscanf(buffer, "%x", &result) != 1) // die if (![output hasSpaceAvailable]) // die [output write:&result length:1]; } [input close]; [output close]; id output = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; This solution would only really be useful if you were reading a fair amount of data. But as others have said, there may be a better way to do what you're trying to do that doesn't involve unhexlify. By way of analogy, there's no built-in way to read a YAML file, but reading a plist is a one-liner, and they can both do roughly the same things. A: Here is some very rough, naive, inefficient, and insecure code that implements unhexlify. It's main limitation is that it doesn't check that hexstr contains only hex digits. But this should be enough to get you started. #include <stdio.h> #include <string.h> #include <assert.h> void unhexlify(const char *hexstr, char *binstr) { char *p, *q; assert(strlen(hexstr) > 0); assert(strlen(hexstr) % 2 == 0); // even length for (p=hexstr,q=binstr; *p; p+=2,q++) sscanf(p, "%2x", q); *q = '\0'; } int main() { char *s = "abc123d35d"; char buf[100]; unhexlify(s, buf); printf(buf); } Call this unhexlify.c, then running this program: $ ./unhexlify | hexdump -C 00000000 ab c1 23 d3 5d |..#.]| EDIT: A more robust example of Python's unhexlify is of course to be found in the actual Python source code for the binascii module which can be viewed here. Look at the to_int() and binascii_unhexlify() functions. A: How about just the strtol function? It'd be something like this: NSString * abc = @"abc"; NSInteger intVal = strtol([abc cStringUsingEncoding:NSASCIIStringEncoding], nil, 16); NSLog(@"%lld", intVal); //prints 2748
unhexlify in objective c
is there something like Python's unhexlify for objc / cocoa? >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). This function is also available as "unhexlify()" >>> unhexlify('abc123d35d') '\xab\xc1#\xd3]'
[ "Edit: I didn't grok what unhexlify does. I still don't grok why it might be useful (commenters?). \nYou would have to pick off the hex characters two at a time, convert them to an int, and spit out the characters. \nchar *hex = \"abc123d35d\";\n\nNSData *data = [NSData dataWithBytesNoCopy:hex length:strlen(hex)];\n\nNSInputStream *input = [NSInputStream inputStreamWithWithData:data];\nNSOutputStream *output = [NSOutputStream outputStreamToMemory];\n\n[input open];\n[output open];\n\nuint8_t buffer[2], result;\n\nwhile ([input hasBytesAvailable]) {\n [input read:buffer maxLength:2];\n\n if (sscanf(buffer, \"%x\", &result) != 1)\n // die\n\n if (![output hasSpaceAvailable])\n // die\n\n [output write:&result length:1];\n}\n\n[input close];\n[output close];\n\nid output = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey];\n\nThis solution would only really be useful if you were reading a fair amount of data.\nBut as others have said, there may be a better way to do what you're trying to do that doesn't involve unhexlify. By way of analogy, there's no built-in way to read a YAML file, but reading a plist is a one-liner, and they can both do roughly the same things. \n", "Here is some very rough, naive, inefficient, and insecure code that implements unhexlify. It's main limitation is that it doesn't check that hexstr contains only hex digits. But this should be enough to get you started.\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n\nvoid unhexlify(const char *hexstr, char *binstr)\n{\n char *p, *q;\n\n assert(strlen(hexstr) > 0);\n assert(strlen(hexstr) % 2 == 0); // even length\n\n for (p=hexstr,q=binstr; *p; p+=2,q++)\n sscanf(p, \"%2x\", q);\n *q = '\\0';\n}\n\nint main()\n{\n char *s = \"abc123d35d\";\n char buf[100];\n\n unhexlify(s, buf);\n printf(buf);\n}\n\nCall this unhexlify.c, then running this program:\n$ ./unhexlify | hexdump -C\n00000000 ab c1 23 d3 5d |..#.]|\n\nEDIT:\nA more robust example of Python's unhexlify is of course to be found in the actual Python source code for the binascii module which can be viewed here. Look at the to_int() and binascii_unhexlify() functions.\n", "How about just the strtol function?\nIt'd be something like this:\nNSString * abc = @\"abc\";\nNSInteger intVal = strtol([abc cStringUsingEncoding:NSASCIIStringEncoding], nil, 16);\nNSLog(@\"%lld\", intVal);\n//prints 2748\n\n" ]
[ 3, 2, 0 ]
[]
[]
[ "cocoa_touch", "iphone", "python" ]
stackoverflow_0001870475_cocoa_touch_iphone_python.txt
Q: Pip + WSGI import errors when i deploy my apps that worked fine using the django test server I usually get errors for every package I installed using pip install -e ....#egg=foo. I usually do this using virtualenv, which placed the files into env/src/foo and places another file into python/site-packages (this is an example of django-css): django-css.egg-link, which contains the following lines: /home/pinax-0.7.1/src/django-css . how do i tell wsgi that it should follow those links, or am I doing something wrong altogether. thanks, Philipp Wassibauer A: This is what my WSGI script for Django in a virtualenv looks like: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' import site site.addsitedir('/path/to/virtualenv/lib/python2.6/site-packages') from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() The key bit is site.addsitedir(...), which adds the contents of any *.pth files in the specified directory to sys.path. In this case, it's the easy-install.pth file that Python needs help finding. A: The modwsgi documentation has notes on how to use virtualenv. It is usually as simple as modifying your django.wsgi (or whatever you call it) file so that it adds the virtualenv environment to modwsgi's path. This link has some additional, distilled, notes on using pip/virtualenv/modwsgi.
Pip + WSGI import errors
when i deploy my apps that worked fine using the django test server I usually get errors for every package I installed using pip install -e ....#egg=foo. I usually do this using virtualenv, which placed the files into env/src/foo and places another file into python/site-packages (this is an example of django-css): django-css.egg-link, which contains the following lines: /home/pinax-0.7.1/src/django-css . how do i tell wsgi that it should follow those links, or am I doing something wrong altogether. thanks, Philipp Wassibauer
[ "This is what my WSGI script for Django in a virtualenv looks like:\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\n\nimport site\nsite.addsitedir('/path/to/virtualenv/lib/python2.6/site-packages')\n\nfrom django.core.handlers.wsgi import WSGIHandler\napplication = WSGIHandler()\n\nThe key bit is site.addsitedir(...), which adds the contents of any *.pth files in the specified directory to sys.path. In this case, it's the easy-install.pth file that Python needs help finding.\n", "The modwsgi documentation has notes on how to use virtualenv. It is usually as simple as modifying your django.wsgi (or whatever you call it) file so that it adds the virtualenv environment to modwsgi's path.\nThis link has some additional, distilled, notes on using pip/virtualenv/modwsgi.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "pip", "python", "virtualenv", "wsgi" ]
stackoverflow_0001875037_django_pip_python_virtualenv_wsgi.txt
Q: Data extraction and manipulation in jython For a given file For ex : 11 ,345 , sdfsfsfs , 1232 i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do for multiple rows. so finally in the other file the data should look like 11,345,sdfsfsfs,1232 Please suggest me the way. Thanks for your help. A: Open the input file (1) and the output file (2) for reading and writing respectively. file1 = open('file1', 'r') file2 = open('file2', 'w') Iterate over the input file, getting each line. Split the line on a comma. Then re-join the line using a comma, but first stripping the whitespace (using a list comprehension). for line in file1: fields = line.split(',') line = ",".join([s.strip() for s in fields]) file2.write(line + "\n") Finally, close the input and output files. file1.close() file2.close() I'm not sure of jython's capabilities when it comes to generators, so that is why I used a list comprehension. Please feel free to edit this (someone who knows jython better). A: One approach you could take would be to remove all whitespace using the string.translate function. import string #makes a 256 character string that will be used in the translate function trans_table = string.maketrans('', '') file1 = open('file1', 'r') file2 = open('file2', 'w') for line in file1: file2.write(line.translate(trans_table, string.whitespace) + '\n') #Or the above could be written as: # line = line.translate(trans_table, string.whitespace) # file2.write(line + '\n') file1.close() file2.close()
Data extraction and manipulation in jython
For a given file For ex : 11 ,345 , sdfsfsfs , 1232 i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do for multiple rows. so finally in the other file the data should look like 11,345,sdfsfsfs,1232 Please suggest me the way. Thanks for your help.
[ "Open the input file (1) and the output file (2) for reading and writing respectively. \nfile1 = open('file1', 'r')\nfile2 = open('file2', 'w')\n\nIterate over the input file, getting each line. Split the line on a comma. Then re-join the line using a comma, but first stripping the whitespace (using a list comprehension).\nfor line in file1:\n fields = line.split(',')\n line = \",\".join([s.strip() for s in fields])\n file2.write(line + \"\\n\")\n\nFinally, close the input and output files.\nfile1.close()\nfile2.close()\n\nI'm not sure of jython's capabilities when it comes to generators, so that is why I used a list comprehension. Please feel free to edit this (someone who knows jython better).\n", "One approach you could take would be to remove all whitespace using the string.translate function.\nimport string\n\n#makes a 256 character string that will be used in the translate function\ntrans_table = string.maketrans('', '')\n\nfile1 = open('file1', 'r')\nfile2 = open('file2', 'w')\n\nfor line in file1:\n file2.write(line.translate(trans_table, string.whitespace) + '\\n')\n\n #Or the above could be written as:\n# line = line.translate(trans_table, string.whitespace)\n# file2.write(line + '\\n')\n\nfile1.close()\nfile2.close()\n\n" ]
[ 2, 0 ]
[]
[]
[ "jython", "python", "string" ]
stackoverflow_0001874712_jython_python_string.txt
Q: Dynamic function with local variables I'm trying to dynamically create a bunch of class properties, but each dynamic fget accessor needs a unique local variable. Here is a simplified example: class Test(object): def __metaclass__(name, bases, dict): for i in range(5): def fget(self, i=i): return i dict['f%d' % i] = property(fget) return type(name, bases, dict) >>> t = Test() >>> print t.f0, t.f1, t.f2, t.f4 0, 1, 2, 3, 4 In order to have each correct 'i' value available to each fget function, I have to pass it as a keyword argument when creating the function. Otherwise, all functions would see the same instance of i (the last one generated from the range operation). This seems like a bad hack to me, is there a better way to do it? A: "Each dynamic fget accessor needs a unique local variable." That tells you that each "property" is a separate instance of some class. Consider using descriptors for this so that you have a complete class instead of some cobbed-up instance variable. Or consider using some variant on the Strategy design pattern to delegate this "unique local variable" to this property-related Strategy object. A: One alternative is to define a second function that captures the value of the variable as a new local. E.g.: def make_prop_that_returns(i): return property(lambda self: i) class Test(object): def __metaclass__(name, bases, dict): for i in range(5): dict['f%d' % i] = make_prop_that_returns(i) return type(name, bases, dict) I'm not sure I'd say this is much cleaner than your approach, but it's an alternative at least. Can you be more clear (less abstract) about what you're trying to accomplish? Defining dynamic fget's might not be the best way to do it. A: You could use a closure over a local variable instead of passing i as a default argument: class Test(object): def __metaclass__(name, bases, dict): for i in range(5): def asclosure(): # function to create a new local scope for |ci| ci = i def fget(self): return ci return fget dict['f%d' % i] = property(asclosure()) return type(name, bases, dict) This works, but also seems very hacky and not very readable. A: For this simplified example, I think that what you have works pretty well (aside from being a bit hacky). While the i=i part can be ugly and tricky, it is a relatively well known way to make closures. Add a comment if you're afraid someone won't get it. However, if you're doing something that's more complex, I'd definitely agree with S. Lott above. One other possible approach: def make_property(i, dict): def fget(self): return i dict['f%d' % i] = property(fget) class Test(object): def __metaclass__(name, bases, dict): for i in range(5): make_property(i, dict) return type(name, bases, dict) Personally, I feel that this makes the whole thing a lot easier to understand as you're separating out each iteration of the loop into its own function. A: You just need another function where i is a argument: class Test(object): def __metaclass__(name, bases, dict): def makeprop( i ): # a new namespace where `i` never changes def fget(self): return i return property(fget) for i in range(5): dict['f%d' % i] = makeprop(i) return type(name, bases, dict)
Dynamic function with local variables
I'm trying to dynamically create a bunch of class properties, but each dynamic fget accessor needs a unique local variable. Here is a simplified example: class Test(object): def __metaclass__(name, bases, dict): for i in range(5): def fget(self, i=i): return i dict['f%d' % i] = property(fget) return type(name, bases, dict) >>> t = Test() >>> print t.f0, t.f1, t.f2, t.f4 0, 1, 2, 3, 4 In order to have each correct 'i' value available to each fget function, I have to pass it as a keyword argument when creating the function. Otherwise, all functions would see the same instance of i (the last one generated from the range operation). This seems like a bad hack to me, is there a better way to do it?
[ "\"Each dynamic fget accessor needs a unique local variable.\"\nThat tells you that each \"property\" is a separate instance of some class.\nConsider using descriptors for this so that you have a complete class instead of some cobbed-up instance variable.\nOr consider using some variant on the Strategy design pattern to delegate this \"unique local variable\" to this property-related Strategy object.\n", "One alternative is to define a second function that captures the value of the variable as a new local. E.g.:\ndef make_prop_that_returns(i):\n return property(lambda self: i)\n\nclass Test(object):\n def __metaclass__(name, bases, dict):\n for i in range(5):\n dict['f%d' % i] = make_prop_that_returns(i)\n\n return type(name, bases, dict)\n\nI'm not sure I'd say this is much cleaner than your approach, but it's an alternative at least.\nCan you be more clear (less abstract) about what you're trying to accomplish? Defining dynamic fget's might not be the best way to do it.\n", "You could use a closure over a local variable instead of passing i as a default argument:\nclass Test(object):\n def __metaclass__(name, bases, dict):\n for i in range(5):\n def asclosure():\n # function to create a new local scope for |ci|\n ci = i\n def fget(self):\n return ci\n return fget\n\n dict['f%d' % i] = property(asclosure())\n\n return type(name, bases, dict)\n\nThis works, but also seems very hacky and not very readable.\n", "For this simplified example, I think that what you have works pretty well (aside from being a bit hacky). While the i=i part can be ugly and tricky, it is a relatively well known way to make closures. Add a comment if you're afraid someone won't get it.\nHowever, if you're doing something that's more complex, I'd definitely agree with S. Lott above.\nOne other possible approach:\ndef make_property(i, dict):\n def fget(self):\n return i\n\n dict['f%d' % i] = property(fget)\n\nclass Test(object):\n def __metaclass__(name, bases, dict):\n for i in range(5):\n make_property(i, dict)\n\n return type(name, bases, dict)\n\nPersonally, I feel that this makes the whole thing a lot easier to understand as you're separating out each iteration of the loop into its own function.\n", "You just need another function where i is a argument:\nclass Test(object):\n def __metaclass__(name, bases, dict):\n\n def makeprop( i ):\n # a new namespace where `i` never changes\n def fget(self):\n return i\n return property(fget)\n\n for i in range(5):\n dict['f%d' % i] = makeprop(i)\n\n return type(name, bases, dict)\n\n" ]
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001875497_python.txt
Q: Saving wx widget contents to a file I have created different shapes like circle/rect etc in my program using BufferedPaintDC on event. Now i want to save the file as I click the saveas button in the menu option. For that I am using memoryDC and save the contents as bmp file. def Saveas(self,event): dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", \ wx.SAVE | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: # user enters filename as something.bmp self.show_bmp = wx.StaticBitmap(self) w, h = self.GetClientSize() draw_bmp = wx.EmptyBitmap(w, h) c = wx.MemoryDC(draw_bmp) c.SetBrush(wx.Brush('white')) c.Clear() c.SetPen(wx.Pen("purple", 15)) c.DrawRectangle(30,30,60,60) ### ??????#### myimage = self.show_bmp.GetBitmap() self.filename=dlg.GetFilename() name = os.path.join('C:\mad', self.filename) myimage.SaveFile(name, wx.BITMAP_TYPE_JPEG) self.filename=name dlg.Destroy() Now my problem is how do I get the things drawn by the buffered dc on the " c ", so that they can be then converted to image?? I hope my question is clear.As u can see I am drawing the rectangle on the "c" and that is being converted to an image. But I want to get the shapes created on ONPaint . How do I extract that? Thanks A: What you're asking is very close to saying you want to take a screenshot. Although technically grabbing a copy of what the window currently looks like is not the same as cloning what the OnPaint does, it's possible it would do the job for you. If it doesn't work, take note of the technique, including the use of DC.Blit(), as those would be the tools you'd use. See this wxpython-users mailing list post by Andrea Gavana for image-grabbing code. Edit: if the problem is that because you're doing all your drawing inside the EVT_PAINT handler, then you probably need a different technique. Draw everything from a different routine to a pre-allocated buffer bitmap. Inside the OnPaint, which is just how the image actually gets to the screen, you don't draw, you just copy the already-drawn bitmap. The buffer bitmap persists between OnPaint calls (and in fact is basically independent of OnPaint), so you can add a Save() routine that works rather simply as well. See the wxPyWiki DoubleBuffererDrawing page for various snippets that will show you how to do that. (Also note, this will be a bit of a learning curve, so ask for more help if it's not enough.)
Saving wx widget contents to a file
I have created different shapes like circle/rect etc in my program using BufferedPaintDC on event. Now i want to save the file as I click the saveas button in the menu option. For that I am using memoryDC and save the contents as bmp file. def Saveas(self,event): dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", \ wx.SAVE | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: # user enters filename as something.bmp self.show_bmp = wx.StaticBitmap(self) w, h = self.GetClientSize() draw_bmp = wx.EmptyBitmap(w, h) c = wx.MemoryDC(draw_bmp) c.SetBrush(wx.Brush('white')) c.Clear() c.SetPen(wx.Pen("purple", 15)) c.DrawRectangle(30,30,60,60) ### ??????#### myimage = self.show_bmp.GetBitmap() self.filename=dlg.GetFilename() name = os.path.join('C:\mad', self.filename) myimage.SaveFile(name, wx.BITMAP_TYPE_JPEG) self.filename=name dlg.Destroy() Now my problem is how do I get the things drawn by the buffered dc on the " c ", so that they can be then converted to image?? I hope my question is clear.As u can see I am drawing the rectangle on the "c" and that is being converted to an image. But I want to get the shapes created on ONPaint . How do I extract that? Thanks
[ "What you're asking is very close to saying you want to take a screenshot. Although technically grabbing a copy of what the window currently looks like is not the same as cloning what the OnPaint does, it's possible it would do the job for you.\nIf it doesn't work, take note of the technique, including the use of DC.Blit(), as those would be the tools you'd use.\nSee this wxpython-users mailing list post by Andrea Gavana for image-grabbing code.\nEdit: if the problem is that because you're doing all your drawing inside the EVT_PAINT handler, then you probably need a different technique. Draw everything from a different routine to a pre-allocated buffer bitmap. Inside the OnPaint, which is just how the image actually gets to the screen, you don't draw, you just copy the already-drawn bitmap. The buffer bitmap persists between OnPaint calls (and in fact is basically independent of OnPaint), so you can add a Save() routine that works rather simply as well. See the wxPyWiki DoubleBuffererDrawing page for various snippets that will show you how to do that. (Also note, this will be a bit of a learning curve, so ask for more help if it's not enough.)\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0001875538_python_wxpython_wxwidgets.txt
Q: Python 2.6+ str.format() and regular expressions Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using str.format() with regular expressions. I've written a regular expression to return all domains that are a single level below a specified domain or any domains that are 2 levels below the domain specified, if the 2nd level below is www... Assuming the specified domain is delivery.com, my regex should return a.delivery.com, b.delivery.com, www.c.delivery.com ... but it should not return x.a.delivery.com. import re str1 = "www.pizza.delivery.com" str2 = "w.pizza.delivery.com" str3 = "pizza.delivery.com" if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str1): print 'String 1 matches!' if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str2): print 'String 2 matches!' if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str3): print 'String 3 matches!' Running this should give the result: String 1 matches! String 3 matches! Now, the problem is when I try to replace delivery.com dynamically using str.format... if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}{domainName}$'.format(domainName = 'delivery.com'), str1): print 'String 1 matches!' This seems to fail, because the str.format() expects the {3} and {1} to be parameters to the function. (I'm assuming) I could concatenate the string using + operator '^(w{3}\.)?([0-9A-Za-z-]+\.){1}' + domainName + '$' The question comes down to, is it possible to use str.format() when the string (usually regex) has "{n}" within it? A: you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces: >>> pat= '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com') >>> pat '^(w{3}\\.)?([0-9A-Za-z-]+\\.){1}delivery.com$' >>> re.match(pat, str1) Also, re.match is matching at the beginning of the string, you don't have to put ^ if you use re.match, you need ^ if you're using re.search, however. Please note, that {1} in regex is rather redundant. A: Per the documentation, if you need a literal { or } to survive the formatting opertation, use {{ and }} in the original string. '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
Python 2.6+ str.format() and regular expressions
Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using str.format() with regular expressions. I've written a regular expression to return all domains that are a single level below a specified domain or any domains that are 2 levels below the domain specified, if the 2nd level below is www... Assuming the specified domain is delivery.com, my regex should return a.delivery.com, b.delivery.com, www.c.delivery.com ... but it should not return x.a.delivery.com. import re str1 = "www.pizza.delivery.com" str2 = "w.pizza.delivery.com" str3 = "pizza.delivery.com" if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str1): print 'String 1 matches!' if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str2): print 'String 2 matches!' if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str3): print 'String 3 matches!' Running this should give the result: String 1 matches! String 3 matches! Now, the problem is when I try to replace delivery.com dynamically using str.format... if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}{domainName}$'.format(domainName = 'delivery.com'), str1): print 'String 1 matches!' This seems to fail, because the str.format() expects the {3} and {1} to be parameters to the function. (I'm assuming) I could concatenate the string using + operator '^(w{3}\.)?([0-9A-Za-z-]+\.){1}' + domainName + '$' The question comes down to, is it possible to use str.format() when the string (usually regex) has "{n}" within it?
[ "you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces:\n>>> pat= '^(w{{3}}\\.)?([0-9A-Za-z-]+\\.){{1}}{domainName}$'.format(domainName = 'delivery.com')\n>>> pat\n'^(w{3}\\\\.)?([0-9A-Za-z-]+\\\\.){1}delivery.com$'\n>>> re.match(pat, str1)\n\nAlso, re.match is matching at the beginning of the string, you don't have to put ^ if you use re.match, you need ^ if you're using re.search, however.\nPlease note, that {1} in regex is rather redundant.\n", "Per the documentation, if you need a literal { or } to survive the formatting opertation, use {{ and }} in the original string.\n'^(w{{3}}\\.)?([0-9A-Za-z-]+\\.){{1}}{domainName}$'.format(domainName = 'delivery.com')\n\n" ]
[ 40, 16 ]
[]
[]
[ "format", "python", "regex", "string_formatting" ]
stackoverflow_0001875676_format_python_regex_string_formatting.txt
Q: Deleting key/value from list of dictionaries using lambda and map I have a list of dictionaries that have the same keys within eg: [{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....] I'm trying to delete k1 from all dictionaries within the list. I tried map(lambda x: del x['k1'], list) but that gave me a syntax error. Where have I gone wrong? A: lambda bodies are only expressions, not statements like del. If you have to use map and lambda, then: map(lambda d: d.pop('k1'), list_of_d) A for loop is probably clearer: for d in list_of_d: del d['k1']
Deleting key/value from list of dictionaries using lambda and map
I have a list of dictionaries that have the same keys within eg: [{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....] I'm trying to delete k1 from all dictionaries within the list. I tried map(lambda x: del x['k1'], list) but that gave me a syntax error. Where have I gone wrong?
[ "lambda bodies are only expressions, not statements like del.\nIf you have to use map and lambda, then:\nmap(lambda d: d.pop('k1'), list_of_d)\n\nA for loop is probably clearer:\nfor d in list_of_d:\n del d['k1']\n\n" ]
[ 41 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0001875932_dictionary_lambda_python.txt
Q: Django password change:Reverse for '' with arguments '()' and keyword arguments '{}' not found When inckuded the following in urls.py (r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change' The following shows up on the screen, Reverse for '<function password_change_done at 0xa3b0f0c>' with arguments '()' and keyword arguments '{}' not found. And i am trying to give the access to users to change their passwords. Whats wrong with the above code..... Thanks........ A: The password_change view redirects to django.contrib.auth.views.password_change_done - this needs to be listed in your urls.py. Alternatively, add the post_change_redirect argument to your password_change view to tell it where to redirect to: (r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change', {'password_change_done': '/settings/users/password-changed'}) Also see the relevant documentation.
Django password change:Reverse for '' with arguments '()' and keyword arguments '{}' not found
When inckuded the following in urls.py (r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change' The following shows up on the screen, Reverse for '<function password_change_done at 0xa3b0f0c>' with arguments '()' and keyword arguments '{}' not found. And i am trying to give the access to users to change their passwords. Whats wrong with the above code..... Thanks........
[ "The password_change view redirects to django.contrib.auth.views.password_change_done - this needs to be listed in your urls.py.\nAlternatively, add the post_change_redirect argument to your password_change view to tell it where to redirect to:\n(r'^settings/users/change_password/$', 'django.contrib.auth.views.password_change', {'password_change_done': '/settings/users/password-changed'})\n\nAlso see the relevant documentation.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001875318_django_python.txt
Q: Fabric error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'message' I'm trying to setup a fabfile to deploy my Django app. I can't figure out why I'm getting this error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'changed settings for prodserver' $ fab create_branch_deploy_to_prodserver [localhost] run: git checkout prodserver_server [localhost] run: git merge master [localhost] run: cp settings_prodserver.py settings.py [localhost] run: git add settings.py [localhost] run: git commit -m 'changed settings for prodserver' Fatal error: local() encountered an error (return code 1) while executing 'git commit -m 'changed settings for prodserver'' Aborting. Here if the Fabric function: def create_branch_deploy_to_prodserver(): local("git checkout prodserver_server") local("git merge master") local('cp settings_prodserver.py settings.py') # #local('git rm fabfile.py') #This is also creating error so it's commented out local('git add settings.py') local("git commit -m 'changed settings for prodserver'") Is it possible to make a git commit from Fabric? A: I was able to diagnose the issue when I added capture=False to the declaration: local('git rm fabfile.py', capture=False) local('git add settings.py', capture=False) This allowed the error to be displayed more verbosely. Apparently, the maintainer of Fabric will to revert local's behavior back to not capturing by default, in 1.0. A: Is this a python-related issue like the one described in this thread? The main problem with this is that the stdout/stderr capturing is per-run/sudo invocation and not per-task. It would be wonderful if you could explain me how I could collect outputand error by only modifying the file called fabfile_runner.py. Idealy the fabric task itself could be unmodified, this would allow to upload the the factory the same file that you have tested manually. Check out the Fabric source and look in the 'tests' folder, specifically tests/utils.py. It contains a single decorator, @mock_streams, which is capable of wrapping a function (any function in any Python code -- it's not Fabric specific, as I mentioned) and redirecting sys.stdout and/or sys.stderr for capture/examination. It's designed for use around functions, being a decorator, so you could use it directly by modifying your fabfile_runner.py like so: fabfile_runner.py from StringIO import StringIO import sys from test_fabfile import hello_world def execute(task): output = StringIO() error = StringIO() sys.stdout = output sys.stderr = error task() sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return (output.getvalue(), error.getvalue()) output, error = execute(hello_world) print "output : %s" %output print "error : %s" %error
Fabric error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'message'
I'm trying to setup a fabfile to deploy my Django app. I can't figure out why I'm getting this error: Fatal error: local() encountered an error (return code 2) while executing 'git commit -m 'changed settings for prodserver' $ fab create_branch_deploy_to_prodserver [localhost] run: git checkout prodserver_server [localhost] run: git merge master [localhost] run: cp settings_prodserver.py settings.py [localhost] run: git add settings.py [localhost] run: git commit -m 'changed settings for prodserver' Fatal error: local() encountered an error (return code 1) while executing 'git commit -m 'changed settings for prodserver'' Aborting. Here if the Fabric function: def create_branch_deploy_to_prodserver(): local("git checkout prodserver_server") local("git merge master") local('cp settings_prodserver.py settings.py') # #local('git rm fabfile.py') #This is also creating error so it's commented out local('git add settings.py') local("git commit -m 'changed settings for prodserver'") Is it possible to make a git commit from Fabric?
[ "I was able to diagnose the issue when I added capture=False to the declaration:\nlocal('git rm fabfile.py', capture=False)\nlocal('git add settings.py', capture=False)\n\nThis allowed the error to be displayed more verbosely.\nApparently, the maintainer of Fabric will to revert local's behavior back to not capturing by default, in 1.0.\n", "Is this a python-related issue like the one described in this thread?\n\nThe main problem with this is that the stdout/stderr capturing is per-run/sudo invocation and not per-task.\nIt would be wonderful if you could explain me how I could collect outputand error by only modifying the file called fabfile_runner.py.\n Idealy the fabric task itself could be unmodified, this would allow to upload the the factory the same file that you have tested manually.\nCheck out the Fabric source and look in the 'tests' folder, specifically tests/utils.py. It contains a single decorator, @mock_streams, which is capable of wrapping a function (any function in any Python code -- it's not Fabric specific, as I mentioned) and redirecting sys.stdout and/or sys.stderr for capture/examination.\nIt's designed for use around functions, being a decorator, so you could use it directly by modifying your fabfile_runner.py like so:\n\nfabfile_runner.py\nfrom StringIO import StringIO\nimport sys\nfrom test_fabfile import hello_world\n\ndef execute(task):\n output = StringIO()\n error = StringIO()\n sys.stdout = output\n sys.stderr = error\n task()\n sys.stdout = sys.__stdout__\n sys.stderr = sys.__stderr__\n return (output.getvalue(), error.getvalue())\n\noutput, error = execute(hello_world)\nprint \"output : %s\" %output\nprint \"error : %s\" %error\n\n" ]
[ 7, 1 ]
[]
[]
[ "fabric", "git", "python" ]
stackoverflow_0001875306_fabric_git_python.txt
Q: How to get the REMOTE_PORT (the client port) in Python running at IIS 7.5? REMOTE_PORT server variable cannot be found! Hey. I'm coding a cgi in Python, running on an IIS 7.5 web server, on Windows. I would like to get the tcp port (usually was the server environment variable REMOTE_PORT) from which the client is connecting to it. I've tried to look up all the way throuhout the keys as in os.environ.keys() and I can get the user IP address, his browser, platform, but no remote port available. I have .NET Framework 3.5 SP1 installed already. Could anyone please figure out what's happening or a way to make it? Thanks. A: Googling suggests people with ASP.NET and PHP solutions have similar problems and that since IIS 5.0 that variable hasn't been available. I get the impression you have to call a routine called GetServerVariable() to retrieve it. That routine sounds like it's available through various libraries, which you may be able to use as-is or lift code from: PyISAPIe isapi-wsgi pywin32's isapi module (note, those pywin32 docs can be browsed only in a local copy apparently, but you can read that page to learn more) There are probably others.
How to get the REMOTE_PORT (the client port) in Python running at IIS 7.5? REMOTE_PORT server variable cannot be found!
Hey. I'm coding a cgi in Python, running on an IIS 7.5 web server, on Windows. I would like to get the tcp port (usually was the server environment variable REMOTE_PORT) from which the client is connecting to it. I've tried to look up all the way throuhout the keys as in os.environ.keys() and I can get the user IP address, his browser, platform, but no remote port available. I have .NET Framework 3.5 SP1 installed already. Could anyone please figure out what's happening or a way to make it? Thanks.
[ "Googling suggests people with ASP.NET and PHP solutions have similar problems and that since IIS 5.0 that variable hasn't been available. I get the impression you have to call a routine called GetServerVariable() to retrieve it. That routine sounds like it's available through various libraries, which you may be able to use as-is or lift code from:\n\nPyISAPIe \nisapi-wsgi\npywin32's isapi module (note, those pywin32 docs can be browsed only in a local copy apparently, but you can read that page to learn more)\n\nThere are probably others.\n" ]
[ 0 ]
[]
[]
[ "cgi", "iis_7", "python", "windows" ]
stackoverflow_0001876131_cgi_iis_7_python_windows.txt
Q: Which tools do I need to create installers multi-platform for my python application? Possible Duplicate: An executable Python app imagine that I developed the next killer application in Python using pySide and other several third party libraries. Which tools do i need to create different installers for every OS out there (windows, osx, nix)? A: You may use CXFreeze that works on all platforms that Python works. :)
Which tools do I need to create installers multi-platform for my python application?
Possible Duplicate: An executable Python app imagine that I developed the next killer application in Python using pySide and other several third party libraries. Which tools do i need to create different installers for every OS out there (windows, osx, nix)?
[ "You may use CXFreeze that works on all platforms that Python works. :)\n" ]
[ 0 ]
[]
[]
[ "installation", "multiplatform", "python" ]
stackoverflow_0001876176_installation_multiplatform_python.txt
Q: Proper help for arguments Python optparse works very good when script usage is something like this %prog [options] [args] But I need to write help for script with 1 required argument, so usage will be like this %prog action [options] [args] You can see something similar when you use Subversion - its usage string is svn <subcommand> [options] [args] So my question is: is it possible to prepare help for required argument with optparse in the manner of Subversion? As a result I want to see help like this: Usage: python myscript.py action [options] [args] Available actions: foo bar Options: --version show program's version number and exit -h, --help show this help message and exit -v, --verbose Verbose mode. Output debug log to stdout. A: I think a good solution for you is argparse, which has been proposed for inclusion in Python 2.7 and 3.2. It handles subcommands, I believe as you want, and the linked page includes a link to a page on porting your code from optparse. See also the question command-line-arguments-in-python, into which someone edited a list of references that appears to include exactly the same thing you want: A: Yes. You can set the usage string like this: usage = "%prog action [options] [args]" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") Prints the following: Usage: action [options] [args] Options: -h, --help show this help message and exit -v, --verbose make lots of noise [default] This was copied almost verbatim from the docs. Edit: Based on your comment you could use the description to achieve something similar, though you can't put new-line characters in it. parser.description = 'Available actions: foo, bar' Will look like this: Usage: action [options] [args] Available actions: foo, bar Options: -h, --help show this help message and exit -v, --verbose make lots of noise [default] A: I've run into this problem as well. My solution was to declare commands in a list or tuple, format them into the usage parameter of OptionParser and then use the args list provided by the parser to determine if a command was provided or not, since it technically has to be args[0]. Eg: self.commands = ('foo', 'bar' ...) self.parser = <initialized instance of OptionParser> (self.options, self.args) = parser.parse_args() if len(self.args) == 0: self.parser.error("Command required") self.command = self.args[0] if not self.command in self.commands: self.parser.error("Command not recognized") #... etc This kinda gets you a command system that looks like Subversion's, but admittedly optparse could be better. I've heard the argparse module is supposed to make it into the stdlib, but with 2.7 being the last of the 2 series releases, I guess you'd have to wait for it to be incorporated into 3.x. Of course you can just install argparse, but that's a drag in some cases.
Proper help for arguments
Python optparse works very good when script usage is something like this %prog [options] [args] But I need to write help for script with 1 required argument, so usage will be like this %prog action [options] [args] You can see something similar when you use Subversion - its usage string is svn <subcommand> [options] [args] So my question is: is it possible to prepare help for required argument with optparse in the manner of Subversion? As a result I want to see help like this: Usage: python myscript.py action [options] [args] Available actions: foo bar Options: --version show program's version number and exit -h, --help show this help message and exit -v, --verbose Verbose mode. Output debug log to stdout.
[ "I think a good solution for you is argparse, which has been proposed for inclusion in Python 2.7 and 3.2. It handles subcommands, I believe as you want, and the linked page includes a link to a page on porting your code from optparse.\nSee also the question command-line-arguments-in-python, into which someone edited a list of references that appears to include exactly the same thing you want:\n", "Yes. You can set the usage string like this:\nusage = \"%prog action [options] [args]\"\nparser = OptionParser(usage=usage)\nparser.add_option(\"-v\", \"--verbose\",\n action=\"store_true\", dest=\"verbose\", default=True,\n help=\"make lots of noise [default]\")\n\nPrints the following:\nUsage: action [options] [args]\n\nOptions:\n -h, --help show this help message and exit\n -v, --verbose make lots of noise [default]\n\nThis was copied almost verbatim from the docs.\nEdit:\nBased on your comment you could use the description to achieve something similar, though you can't put new-line characters in it.\nparser.description = 'Available actions: foo, bar'\n\nWill look like this:\nUsage: action [options] [args]\n\nAvailable actions: foo, bar\n\nOptions:\n -h, --help show this help message and exit\n -v, --verbose make lots of noise [default]\n\n", "I've run into this problem as well. My solution was to declare commands in a list or tuple, format them into the usage parameter of OptionParser and then use the args list provided by the parser to determine if a command was provided or not, since it technically has to be args[0]. Eg:\nself.commands = ('foo', 'bar' ...)\nself.parser = <initialized instance of OptionParser>\n(self.options, self.args) = parser.parse_args()\n\nif len(self.args) == 0:\n self.parser.error(\"Command required\")\n\nself.command = self.args[0]\nif not self.command in self.commands:\n self.parser.error(\"Command not recognized\")\n\n#... etc\n\nThis kinda gets you a command system that looks like Subversion's, but admittedly optparse could be better. I've heard the argparse module is supposed to make it into the stdlib, but with 2.7 being the last of the 2 series releases, I guess you'd have to wait for it to be incorporated into 3.x. Of course you can just install argparse, but that's a drag in some cases.\n" ]
[ 7, 2, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001876289_optparse_python.txt
Q: Python: How do I dynamically alter methods of dict and list objects? Here is a mockup of what I want to do: alist = [1,2,3,4,5] # create a vanilla python list object replacef (alist) # replace __setitem__, extend,... with custom functions alist[0]=2 # now the custom __setitem__ is called This is for a DSL project where the syntax should be as close to normal python as possible, so subclassing list and making the user call something like alist = MyList(1,2,3,4,5) is not desirable. Also, because the DSL needs to coexist with other libraries, globally changing list and dict is not an option... I have tried creating instancemethods and setting them directly on the object like alist.append = myFunc, but Python says those properties are read only. Changing the __class__ attribute seems to be not permitted as well. Is what I am trying to do even possible in Python? Update: here are some findings on what is possible with a subclass of object: Given: class y(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def f(self): print self print self.a print self.b print self.c class x(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def f(self): print "x.f()" >>> objy = y(1,2,3) >>> objx = x(4,5,6) >>> objy.f() <__main__.y object at 0x02612650> 1 2 3 >>> objx.f() x.f() It is possible to change the class of objx on the fly like this: >>> objx.__class__ = y >>> objx.f() <__main__.y object at 0x02612D90> 4 5 6 Also, one can dynamically add/change object methods on the fly, much like in javascript: >>> def g(self,p): print self print p >>> import new >>> objy.g = new.instancemethod(g,objy,y) >>> objy.g(42) <__main__.y object at 0x02612650> 42 However, both approaches will fail with objects that are implemented in C like dict and list: >>> def mypop(self): print "mypop" list.mypop(self) >>> alist.pop = new.instancemethod(mypop,alist,list) AttributeError: 'list' object attribute 'pop' is read-only >>> x = [1,2,3,4,5] >>> x.__class__ = mylist TypeError: __class__ assignment: only for heap types The suggested approach to use something like alist = replacef(alist) would not work here, because replacef could be called from a __setattribute__ call like this: alist = [1,2,3,4,5] aDSLObject.items = alist # __setattribute__ calls replacef on alist alist[0] = .... So while it indeed is possible to change object methods dynamically, it seems like it is not possible to alter the behaviour of objects implemented in C - or am I missing something? A: Maybe you can do the "alist = MyList(1,2,3,4,5)" thing inside the replaceref function? def replacef(l): return MyList(l) # Return instance of list subclass that has custom __setitem__ alist = [1,2,3,4,5] alist = replaceref(alist) This way user would still use the standard list syntax when defining a list but would get the new setitem after replaceref call. A: "Explicit is better than implicit." You should just document that your users need to use MyList() instead of list(). You and your users will be happier in the long run. Ruby allows what you want, by the way. With Ruby, you can open up global objects and just add new behaviors. I find this scary, and Ruby runs slower than Python, so I'm not actually urging you to switch to Ruby. So, provide MyList(), and provide a way to take an existing list and wrap it in a MyList(). You could write MyList() to just take a bunch of arguments, and make a list very conveniently: class MyList(object): def __init__(self, *args): self.lst = args # add other methods to MyList() here then you could call this with MyList(1, 2, 3, 4) and the instance would have a member called lst with the value: [1, 2, 3, 4] But now, if you want to make a MyList instance out of a list, how do you do that? If you do this: new_list = [1, 3, 5] x = MyList(new_list) then you have just set x to: [[1, 3, 5]] So I recommend you make MyList() just take a list argument and save it: def ensure_list(seq): try: seq[0] return seq except TypeError: return list(seq) class MyList(object): def __init__(self, seq): self.lst = ensure_list(seq) # add other methods to MyList() here I just edited this answer. Originally, I had a call to list() where I now have put a call to ensure_list(). ensure_list() checks to see if you can index its argument; if you can, it is either a list already or something that can act like a list, and it is returned unchanged. If you can't index it, then ensure_list() calls list(seq) to try to turn it into a list. This will work with iterators and generators, forcing them to expand out to a list.
Python: How do I dynamically alter methods of dict and list objects?
Here is a mockup of what I want to do: alist = [1,2,3,4,5] # create a vanilla python list object replacef (alist) # replace __setitem__, extend,... with custom functions alist[0]=2 # now the custom __setitem__ is called This is for a DSL project where the syntax should be as close to normal python as possible, so subclassing list and making the user call something like alist = MyList(1,2,3,4,5) is not desirable. Also, because the DSL needs to coexist with other libraries, globally changing list and dict is not an option... I have tried creating instancemethods and setting them directly on the object like alist.append = myFunc, but Python says those properties are read only. Changing the __class__ attribute seems to be not permitted as well. Is what I am trying to do even possible in Python? Update: here are some findings on what is possible with a subclass of object: Given: class y(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def f(self): print self print self.a print self.b print self.c class x(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def f(self): print "x.f()" >>> objy = y(1,2,3) >>> objx = x(4,5,6) >>> objy.f() <__main__.y object at 0x02612650> 1 2 3 >>> objx.f() x.f() It is possible to change the class of objx on the fly like this: >>> objx.__class__ = y >>> objx.f() <__main__.y object at 0x02612D90> 4 5 6 Also, one can dynamically add/change object methods on the fly, much like in javascript: >>> def g(self,p): print self print p >>> import new >>> objy.g = new.instancemethod(g,objy,y) >>> objy.g(42) <__main__.y object at 0x02612650> 42 However, both approaches will fail with objects that are implemented in C like dict and list: >>> def mypop(self): print "mypop" list.mypop(self) >>> alist.pop = new.instancemethod(mypop,alist,list) AttributeError: 'list' object attribute 'pop' is read-only >>> x = [1,2,3,4,5] >>> x.__class__ = mylist TypeError: __class__ assignment: only for heap types The suggested approach to use something like alist = replacef(alist) would not work here, because replacef could be called from a __setattribute__ call like this: alist = [1,2,3,4,5] aDSLObject.items = alist # __setattribute__ calls replacef on alist alist[0] = .... So while it indeed is possible to change object methods dynamically, it seems like it is not possible to alter the behaviour of objects implemented in C - or am I missing something?
[ "Maybe you can do the \"alist = MyList(1,2,3,4,5)\" thing inside the replaceref function? \ndef replacef(l):\n return MyList(l) # Return instance of list subclass that has custom __setitem__\n\nalist = [1,2,3,4,5]\nalist = replaceref(alist)\n\nThis way user would still use the standard list syntax when defining a list but would get the new setitem after replaceref call.\n", "\"Explicit is better than implicit.\" You should just document that your users need to use MyList() instead of list(). You and your users will be happier in the long run.\nRuby allows what you want, by the way. With Ruby, you can open up global objects and just add new behaviors. I find this scary, and Ruby runs slower than Python, so I'm not actually urging you to switch to Ruby.\nSo, provide MyList(), and provide a way to take an existing list and wrap it in a MyList().\nYou could write MyList() to just take a bunch of arguments, and make a list very conveniently:\nclass MyList(object):\n def __init__(self, *args):\n self.lst = args\n # add other methods to MyList() here\n\nthen you could call this with MyList(1, 2, 3, 4) and the instance would have a member called lst with the value: [1, 2, 3, 4]\nBut now, if you want to make a MyList instance out of a list, how do you do that? If you do this:\nnew_list = [1, 3, 5]\nx = MyList(new_list)\n\nthen you have just set x to: [[1, 3, 5]]\nSo I recommend you make MyList() just take a list argument and save it:\ndef ensure_list(seq):\n try:\n seq[0]\n return seq\n except TypeError:\n return list(seq)\n\nclass MyList(object):\n def __init__(self, seq):\n self.lst = ensure_list(seq)\n # add other methods to MyList() here\n\nI just edited this answer. Originally, I had a call to list() where I now have put a call to ensure_list(). ensure_list() checks to see if you can index its argument; if you can, it is either a list already or something that can act like a list, and it is returned unchanged. If you can't index it, then ensure_list() calls list(seq) to try to turn it into a list. This will work with iterators and generators, forcing them to expand out to a list.\n" ]
[ 4, 2 ]
[]
[]
[ "dictionary", "dynamic", "list", "methods", "python" ]
stackoverflow_0001876028_dictionary_dynamic_list_methods_python.txt
Q: Python print buffering Let me rephrase my previous question. I just created a tool in ArcGIS using pythong as script language. The tool executes (runs) an outside program using the subprocess.popen. When I run the tool from ArcGSIS, a window appears that only shows the following. Executing: RunFLOW C:\FLOW C:\FLOW\FLW.bat Start Time: Mon Nov 30 16:50:37 2009 Running script RunFLOW... Completed script RuFLOW... Executed (RunFLOW) successfully. End Time: Mon Nov 30 16:50:48 2009 (Elapsed Time: 11.00 seconds) The script is as follows # Import system modules import sys, string, os, arcgisscripting, subprocess # Create the Geoprocessor object gp = arcgisscripting.create() # Read the parameter values: # 1: input workspace prj_fld = gp.GetParameterAsText(0) Flow_bat = gp.GetParameterAsText(1) os.chdir(prj_fld) p=subprocess.Popen(Flow_bat,shell=True,stdout=subprocess.PIPE) stdout_value = p.communicate()[0] print '\tstdout:', repr(stdout_value) When I run the same program from command window, it prints a screen full of information (date, number of iteration, etc.). I want to see all this information in the window that appears after I run the model from ArcGIS in addition to what it is being printing right now. I tried print, communicate, flush but couldn't be able to do it. Any suggestions? When I run the script as it is right now, it runs the executable but it gives an error as follows ERROR 999998: There are no more files. Thanks A: I know nothing about ArcGIS, so I may be shooting in the dark here, but...if you want stdout, you usually don't want the communicate() method. You want something like this: p=subprocess.Popen(Flow_bat,shell=True,stdout=subprocess.PIPE) stdout_value = p.stdout.read() The communicate() method is used for interacting with a process. From the documentation: Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. I'm guessing that when ArcGIS runs your script that stdin is not connected and causes the script to exit for some reason. A: I'm not sure if you are aware of this or not but I use: gp.AddMessage('blah blah') to get messages to appear in the ArcGIS processing window. Its a method of the geoprocessor object, the library you import in Python to access the ArcGIS engine. You would already have imported this library if you are doing any geoprocessing.
Python print buffering
Let me rephrase my previous question. I just created a tool in ArcGIS using pythong as script language. The tool executes (runs) an outside program using the subprocess.popen. When I run the tool from ArcGSIS, a window appears that only shows the following. Executing: RunFLOW C:\FLOW C:\FLOW\FLW.bat Start Time: Mon Nov 30 16:50:37 2009 Running script RunFLOW... Completed script RuFLOW... Executed (RunFLOW) successfully. End Time: Mon Nov 30 16:50:48 2009 (Elapsed Time: 11.00 seconds) The script is as follows # Import system modules import sys, string, os, arcgisscripting, subprocess # Create the Geoprocessor object gp = arcgisscripting.create() # Read the parameter values: # 1: input workspace prj_fld = gp.GetParameterAsText(0) Flow_bat = gp.GetParameterAsText(1) os.chdir(prj_fld) p=subprocess.Popen(Flow_bat,shell=True,stdout=subprocess.PIPE) stdout_value = p.communicate()[0] print '\tstdout:', repr(stdout_value) When I run the same program from command window, it prints a screen full of information (date, number of iteration, etc.). I want to see all this information in the window that appears after I run the model from ArcGIS in addition to what it is being printing right now. I tried print, communicate, flush but couldn't be able to do it. Any suggestions? When I run the script as it is right now, it runs the executable but it gives an error as follows ERROR 999998: There are no more files. Thanks
[ "I know nothing about ArcGIS, so I may be shooting in the dark here, but...if you want stdout, you usually don't want the communicate() method. You want something like this:\np=subprocess.Popen(Flow_bat,shell=True,stdout=subprocess.PIPE)\nstdout_value = p.stdout.read()\n\nThe communicate() method is used for interacting with a process. From the documentation:\nInteract with process: Send data to stdin. Read data from stdout\nand stderr, until end-of-file is reached. Wait for process to\nterminate.\n\nI'm guessing that when ArcGIS runs your script that stdin is not connected and causes the script to exit for some reason.\n", "I'm not sure if you are aware of this or not but I use:\ngp.AddMessage('blah blah')\n\nto get messages to appear in the ArcGIS processing window. Its a method of the geoprocessor object, the library you import in Python to access the ArcGIS engine. You would already have imported this library if you are doing any geoprocessing.\n" ]
[ 0, 0 ]
[]
[]
[ "arcgis", "executable", "printing", "python" ]
stackoverflow_0001823528_arcgis_executable_printing_python.txt
Q: why is python reusing a class instance inside in function I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over. Is there something I'm missing about how classes and variables are handled in python methods? how can I generate a new object for each iteration of the loop class CollectionSetImages(unittest.TestCase): def test_keywordset(self): """Testing keyword queries by images equality """ for keyword in ['a','b','c','d','e','f','g']: images_by_keyword = Image.keyword_query([keyword]) collection = Collection([keyword]) class_images = collection.images print('colleciton: %s id: %s' % (collection,id(collection))) self.assertEqual(images_by_keyword, class_images,) here is the output colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 when I use seperate variable names I get seperate ids for each instance as expected: collectionA = Collection(['a']) print('collection: %s id: %s' % (collectionA,id(collectionA))) collectionB = Collection(['f']) print('collection: %s id: %s' % (collectionB,id(collectionB))) collectionC = Collection(['f']) print('collection: %s id: %s' % (collectionC,id(collectionC))) outputs: collection: <tests.fakeimages._FakeCollection object at 0xb7cbc8ac> id: 3083585708 collection: <tests.fakeimages._FakeCollection object at 0xb7cbccec> id: 3083586796 collection: <tests.fakeimages._FakeCollection object at 0xb7cbcd2c> id: 3083586860 A: All that shows is that the memory of the objects is being reused, not that new objects aren't being instantiated. In each iteration collection is being overwritten, hence the previous object's reference count drops and the Python interpreter is free to deallocate its memory and reuse it (for the next object). >>> for a in range(1,5): ... b = object() ... print b, id(b) ... <object object at 0xb7db9470> 3084620912 <object object at 0xb7db9468> 3084620904 <object object at 0xb7db9470> 3084620912 <object object at 0xb7db9468> 3084620904 <object object at 0xb7db9470> 3084620912 In this case, 2 memory locations are being reused. If you were to add it to a list (or save it elsewhere), it would be preserved: >>> a = [] >>> for b in range(1,5): ... c = object() ... a.append(c) ... print c, id(c) ... <object object at 0xb7db9470> 3084620912 <object object at 0xb7db9468> 3084620904 <object object at 0xb7db9478> 3084620920 <object object at 0xb7db9480> 3084620928 A: from python documentation: id() Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
why is python reusing a class instance inside in function
I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over. Is there something I'm missing about how classes and variables are handled in python methods? how can I generate a new object for each iteration of the loop class CollectionSetImages(unittest.TestCase): def test_keywordset(self): """Testing keyword queries by images equality """ for keyword in ['a','b','c','d','e','f','g']: images_by_keyword = Image.keyword_query([keyword]) collection = Collection([keyword]) class_images = collection.images print('colleciton: %s id: %s' % (collection,id(collection))) self.assertEqual(images_by_keyword, class_images,) here is the output colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656ec> id: 3083228908 colleciton: <tests.fakeimages._FakeCollection object at 0xb7c656cc> id: 3083228876 when I use seperate variable names I get seperate ids for each instance as expected: collectionA = Collection(['a']) print('collection: %s id: %s' % (collectionA,id(collectionA))) collectionB = Collection(['f']) print('collection: %s id: %s' % (collectionB,id(collectionB))) collectionC = Collection(['f']) print('collection: %s id: %s' % (collectionC,id(collectionC))) outputs: collection: <tests.fakeimages._FakeCollection object at 0xb7cbc8ac> id: 3083585708 collection: <tests.fakeimages._FakeCollection object at 0xb7cbccec> id: 3083586796 collection: <tests.fakeimages._FakeCollection object at 0xb7cbcd2c> id: 3083586860
[ "All that shows is that the memory of the objects is being reused, not that new objects aren't being instantiated. In each iteration collection is being overwritten, hence the previous object's reference count drops and the Python interpreter is free to deallocate its memory and reuse it (for the next object).\n>>> for a in range(1,5):\n... b = object()\n... print b, id(b)\n... \n<object object at 0xb7db9470> 3084620912\n<object object at 0xb7db9468> 3084620904\n<object object at 0xb7db9470> 3084620912\n<object object at 0xb7db9468> 3084620904\n<object object at 0xb7db9470> 3084620912\n\nIn this case, 2 memory locations are being reused. If you were to add it to a list (or save it elsewhere), it would be preserved:\n>>> a = []\n>>> for b in range(1,5):\n... c = object()\n... a.append(c)\n... print c, id(c)\n... \n<object object at 0xb7db9470> 3084620912\n<object object at 0xb7db9468> 3084620904\n<object object at 0xb7db9478> 3084620920\n<object object at 0xb7db9480> 3084620928\n\n", "from python documentation:\nid()\nReturn the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.\n" ]
[ 11, 4 ]
[]
[]
[ "class", "namespaces", "python" ]
stackoverflow_0001876905_class_namespaces_python.txt
Q: how to auto-update a Django page only when required? As described in how to update a Django page without a page reload?, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application. However, most of the time, nothing changes; the server replies with the same response and the browser updates the webpage with contents that's already been there. Obviously, the server should only reply if there is new data. A thorough web research came up with http://ajaxpatterns.org/Periodic_Refresh#Lace, but dcoumentation is terse and I'm struggling to implement the concept in my Django project. I have a hard time believing this has not been done before. Does anyone know any further resources I could use as guideline ? A: The difficulty in answering is in not knowing what the server-side resources are that are being returned to the user. I'll make up something which may serve as an example. Let's say you were developing an application that allowed you to monitor in real-time comments being made by users on your site. We can do several things to make this possible: The server keeps track of when comments were added (.created field) The API to get the latest comments requires us to specify how old of comments we want The view queries and returns only those that have been added since then models.py class Comment(models.Model): text = models.TextField() created = models.DateTimeField(default=datetime.now()) urls.py url(r'^comments/latest/(?P<seconds_old>\d+)/$',get_latest_comments), views.py def get_latest_comments(request, seconds_old): """ Returns comments that have been created since the last given number of seconds have elapsed. """ # Query comments since the past X seconds comments_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old) comments = Comments.objects.filter(created__gte=comments_since) # Return serialized data or whatever you're doing with it return HttpResponse(simplejson.dumps(comments),mimetype='application/json') On the client-side you get the JSON, check if it has a value, if so enumerate the items, and add the new items to your <div> tag or whatever. As you can see, the development of the API to return only recently updated items is going to vary based on what content the server is returning. From your question it sounds like you want the server to manage identifying what is recently updated, not the client (which is a good strategy). In that case, what you need to do is define: How is the server going to keep track of changes (in my example that's done by the 'created' field) How is the client going to request those changes How is the server going to identify which changes have happened in order to return them to the client via API?
how to auto-update a Django page only when required?
As described in how to update a Django page without a page reload?, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application. However, most of the time, nothing changes; the server replies with the same response and the browser updates the webpage with contents that's already been there. Obviously, the server should only reply if there is new data. A thorough web research came up with http://ajaxpatterns.org/Periodic_Refresh#Lace, but dcoumentation is terse and I'm struggling to implement the concept in my Django project. I have a hard time believing this has not been done before. Does anyone know any further resources I could use as guideline ?
[ "The difficulty in answering is in not knowing what the server-side resources are that are being returned to the user.\nI'll make up something which may serve as an example. Let's say you were developing an application that allowed you to monitor in real-time comments being made by users on your site. We can do several things to make this possible:\n\nThe server keeps track of when comments were added (.created field)\nThe API to get the latest comments requires us to specify how old of comments we want\nThe view queries and returns only those that have been added since then\n\nmodels.py\nclass Comment(models.Model):\n text = models.TextField()\n created = models.DateTimeField(default=datetime.now())\n\nurls.py\nurl(r'^comments/latest/(?P<seconds_old>\\d+)/$',get_latest_comments),\n\nviews.py\ndef get_latest_comments(request, seconds_old):\n \"\"\"\n Returns comments that have been created since the last given number of seconds\n have elapsed.\n \"\"\"\n\n # Query comments since the past X seconds\n comments_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old)\n comments = Comments.objects.filter(created__gte=comments_since)\n\n # Return serialized data or whatever you're doing with it\n return HttpResponse(simplejson.dumps(comments),mimetype='application/json')\n\nOn the client-side you get the JSON, check if it has a value, if so enumerate the items, and add the new items to your <div> tag or whatever.\n\nAs you can see, the development of the API to return only recently updated items is going to vary based on what content the server is returning.\nFrom your question it sounds like you want the server to manage identifying what is recently updated, not the client (which is a good strategy). In that case, what you need to do is define:\n\nHow is the server going to keep track of changes (in my example that's done by the 'created' field)\nHow is the client going to request those changes\nHow is the server going to identify which changes have happened in order to return them to the client via API?\n\n" ]
[ 9 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0001876625_ajax_django_javascript_python.txt
Q: Implementing python exceptions I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program: class InvalidProgramStateException(Exception): def __init__(self, expr, msg): self.expr = expr self.msg = msg I think msg must be a string message to be shown, but how do I fill the "expr" when I want to raise this exception? Do I have to write it by hand? raise InvalidProgramStateException(what_here?, "there was an error") A: Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine: class MyException(Exception): pass This would allow your program to catch cases of this exception by type: try: raise MyException() except MyException: print "Doing something with MyException" except: print "Some other error occurred... handling it differently" If you want the Exception to have some meaningful string representation, or have properties that would provide your application greater details on what went wrong, that's when you pass additional arguments to the constructor. The number, name and type of these arguments is not really pre-defined by Python... they can be anything. Just be sure to provide a custom __str__ or __unicode__ method so you can provide a meaningful text depiction: class MyException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return "MyException with %s" % self.msg In the case of the example you're quoting, the expr and msg parameters are specific to the fictional case of the example. A contrived scenario for how these might be used is: def do_something(expr): if 'foo' in expr: raise InvalidProgramStateException(expr, "We don't allow foos here") return 5 user_input = 'foo bar' try: do_something(user_input) except InvalidProgramStateException, e: print "%s (using expression %s)" % (e.msg, e.expr) Since it doesn't appear that your application requires it, just drop the parameters you don't require.
Implementing python exceptions
I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program: class InvalidProgramStateException(Exception): def __init__(self, expr, msg): self.expr = expr self.msg = msg I think msg must be a string message to be shown, but how do I fill the "expr" when I want to raise this exception? Do I have to write it by hand? raise InvalidProgramStateException(what_here?, "there was an error")
[ "Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine:\nclass MyException(Exception):\n pass\n\nThis would allow your program to catch cases of this exception by type:\ntry:\n raise MyException()\nexcept MyException:\n print \"Doing something with MyException\"\nexcept:\n print \"Some other error occurred... handling it differently\"\n\nIf you want the Exception to have some meaningful string representation, or have properties that would provide your application greater details on what went wrong, that's when you pass additional arguments to the constructor. The number, name and type of these arguments is not really pre-defined by Python... they can be anything. Just be sure to provide a custom __str__ or __unicode__ method so you can provide a meaningful text depiction:\nclass MyException(Exception):\n\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return \"MyException with %s\" % self.msg\n\nIn the case of the example you're quoting, the expr and msg parameters are specific to the fictional case of the example. A contrived scenario for how these might be used is:\ndef do_something(expr):\n if 'foo' in expr:\n raise InvalidProgramStateException(expr, \"We don't allow foos here\")\n return 5\n\nuser_input = 'foo bar'\ntry:\n do_something(user_input)\nexcept InvalidProgramStateException, e:\n print \"%s (using expression %s)\" % (e.msg, e.expr)\n\nSince it doesn't appear that your application requires it, just drop the parameters you don't require.\n" ]
[ 11 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001877686_exception_python.txt
Q: Setting numpy slice in lambda function I want to create a lambda function that takes two numpy arrays and sets a slice of the first to the second and returns the newly set numpy array. Considering you can't assign things in lambda functions is there a way to do something similar to this? The context of this is that I want to set the centre of a zeros array to another array in a single line, and the only solution I could come up with is to use reduce and lambda functions. I.e. I'm thinking about the condensation of this (where b is given): a = numpy.zeros( numpy.array(b.shape) + 2) a[1:-1,1:-1] = b Into a single line. Is this possible? This is just an exercise in oneliners. I have the code doing what I want it to do, I'm just wondering about this for the fun of it :). A: This is ugly; you should not use it. But it is oneline lambda as you've asked: f = lambda b, a=None, s=slice(1,-1): f(b, numpy.zeros(numpy.array(b.shape) + 2))\ if a is None else (a.__setitem__([s]*a.ndim, b), a)[1] What is __setitem__? obj.__setitem__(index, value) is equivalent to obj[index] = value in this case. Example: class A: def __setitem__(self, index, value): print 'index=%s, value=%s' % (index, value) a = A() a[1, 2] = 3 It prints: index=(1, 2), value=3 Why does __setitem__() return None? There is a general convention in Python that methods such as list.extend(), list.append() that modify an object in-place should return None. There are exceptions e.g., list.pop(). Y Combinator in Python Here's blog post On writing Python one-liners which shows how write nameless recursive functions using lambdas (the link is suggested by @Peter Hansen).
Setting numpy slice in lambda function
I want to create a lambda function that takes two numpy arrays and sets a slice of the first to the second and returns the newly set numpy array. Considering you can't assign things in lambda functions is there a way to do something similar to this? The context of this is that I want to set the centre of a zeros array to another array in a single line, and the only solution I could come up with is to use reduce and lambda functions. I.e. I'm thinking about the condensation of this (where b is given): a = numpy.zeros( numpy.array(b.shape) + 2) a[1:-1,1:-1] = b Into a single line. Is this possible? This is just an exercise in oneliners. I have the code doing what I want it to do, I'm just wondering about this for the fun of it :).
[ "This is ugly; you should not use it. But it is oneline lambda as you've asked:\nf = lambda b, a=None, s=slice(1,-1): f(b, numpy.zeros(numpy.array(b.shape) + 2))\\\n if a is None else (a.__setitem__([s]*a.ndim, b), a)[1]\n\nWhat is __setitem__?\nobj.__setitem__(index, value) is equivalent to obj[index] = value in this case. Example:\nclass A:\n def __setitem__(self, index, value):\n print 'index=%s, value=%s' % (index, value)\n\na = A()\na[1, 2] = 3\n\nIt prints:\nindex=(1, 2), value=3\n\nWhy does __setitem__() return None?\nThere is a general convention in Python that methods such as list.extend(), list.append() that modify an object in-place should return None. There are exceptions e.g., list.pop().\nY Combinator in Python\nHere's blog post On writing Python one-liners which shows how write nameless recursive functions using lambdas (the link is suggested by @Peter Hansen).\n" ]
[ 4 ]
[]
[]
[ "lambda", "numpy", "python" ]
stackoverflow_0001877437_lambda_numpy_python.txt
Q: Euclidian distance between posts based on tags I am playing with the euclidian distance example from programming collective intelligence book, # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: si[item]=1 # if they have no ratings in common, return 0 if len(si)==0: return 0 # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]]) this is the original code for ranking movie critics, i am trying to modify this to find similar posts, based on tags i build a map such as, url1 - > tag1 tag2 url2 - > tag1 tag3 but if apply this to the function, pow(prefs[person1][item]-prefs[person2][item],2) this becomes 0 cause tags don't have weight same tags has ranking 1. I modified the code to manually create a difference to test, pow(prefs[1,2) then i got a lot of 0.5 similarity, but similarity of the same post to it self is dropped down to 0.3. I can't think of a way to apply euclidian distance to my situation? A: Okay, first off, your code looks incomplete: I see only one return from your function. I think you mean something like this: def sim_distance(prefs, person1, person2): # Get the list of shared_items p1, p2 = prefs[person1], prefs[person2] si = set(p1).intersection(set(p2)) # Add up the squares of all the differences matches = (p1[item] - p2[item] for item in si) return sum(a * a for a in matches) Next, your post needs a bit of editing for clarity. I don't know what this means: "this becomes 0 cause tags don't have weight same tags has ranking 1." Lastly, it would help if you provided sample data for prefs[person1] and prefs[person2]. Then you could tell what you are getting and what you expect to get. Edit: based on my comment below, I would use code like this: def sim_distance(prefs, person1, person2): p1, p2 = prefs[person1], prefs[person2] s, t = set(p1), set(p2) return len(s.intersection(t)) / len(s.union(t)) A: Basically, tags don't have weights and can't be represented by numerical values. So you can't define a distance between two tags. If you want to find the similarity between two posts using their tags, I would suggest that you use the ratio of similar tag. For example, if you have url1 -> tag1 tag2 tag3 tag4 url2 -> tag1 tag4 tag5 tag6 then you have 2 similar tags, representing 2 (similar tags) / 4 (total tags) = 0.5. I think this would represent a good measurement for similarity, as long as you have more than 2 tags per post.
Euclidian distance between posts based on tags
I am playing with the euclidian distance example from programming collective intelligence book, # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs,person1,person2): # Get the list of shared_items si={} for item in prefs[person1]: if item in prefs[person2]: si[item]=1 # if they have no ratings in common, return 0 if len(si)==0: return 0 # Add up the squares of all the differences sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]]) this is the original code for ranking movie critics, i am trying to modify this to find similar posts, based on tags i build a map such as, url1 - > tag1 tag2 url2 - > tag1 tag3 but if apply this to the function, pow(prefs[person1][item]-prefs[person2][item],2) this becomes 0 cause tags don't have weight same tags has ranking 1. I modified the code to manually create a difference to test, pow(prefs[1,2) then i got a lot of 0.5 similarity, but similarity of the same post to it self is dropped down to 0.3. I can't think of a way to apply euclidian distance to my situation?
[ "Okay, first off, your code looks incomplete: I see only one return from your function. I think you mean something like this:\ndef sim_distance(prefs, person1, person2): \n # Get the list of shared_items\n p1, p2 = prefs[person1], prefs[person2]\n si = set(p1).intersection(set(p2))\n\n # Add up the squares of all the differences \n matches = (p1[item] - p2[item] for item in si)\n return sum(a * a for a in matches) \n\nNext, your post needs a bit of editing for clarity. I don't know what this means: \"this becomes 0 cause tags don't have weight same tags has ranking 1.\"\nLastly, it would help if you provided sample data for prefs[person1] and prefs[person2]. Then you could tell what you are getting and what you expect to get.\nEdit: based on my comment below, I would use code like this:\ndef sim_distance(prefs, person1, person2):\n p1, p2 = prefs[person1], prefs[person2]\n s, t = set(p1), set(p2)\n return len(s.intersection(t)) / len(s.union(t))\n\n", "Basically, tags don't have weights and can't be represented by numerical values. So you can't define a distance between two tags.\nIf you want to find the similarity between two posts using their tags, I would suggest that you use the ratio of similar tag. For example, if you have\nurl1 -> tag1 tag2 tag3 tag4\nurl2 -> tag1 tag4 tag5 tag6\n\nthen you have 2 similar tags, representing 2 (similar tags) / 4 (total tags) = 0.5. I think this would represent a good measurement for similarity, as long as you have more than 2 tags per post.\n" ]
[ 1, 1 ]
[]
[]
[ "euclidean_distance", "python", "similarity" ]
stackoverflow_0001877725_euclidean_distance_python_similarity.txt
Q: Optimal way to access a value from the last iteration in a loop What's the best and fastest way to access a value from the previous iteration in a for loop, assuming that the object will be very large (example, a cursor object which has 100,000+ records) Using a simple example: tmp = [ ['xyz', 335], ['zzz', 338], ['yyy', 339], ['yyy', 442], ['abc', 443], ['efg', 444], ['ttt', 446], ['fff', 447] ] for x in tmp: if not prev: prev = x[1] print 'seq: ', x[1], 'prev seq:', prev, 'variance: ', x[1]-prev prev = x[1] Is this the most optimal way to handle this? Based on the responses below i did some testing: tmp was created with 500 lists, the average of running it 20 times is shown below. results: Mines: 0,623 Dave snippet1: 0,605 Dave snippet2: 0,586 Catchmeifyoutry (edited code): 0,707 A: Just iterate over pairs, using zip(), which is much more readable. UPDATE: for python 2.x, use itertools.izip instead as it is more efficient! from itertools import izip for prev, next in izip(tmp, tmp[1:]): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] which can also use value unpacking to avoid the index: for (_, prev), (_, next) in izip(tmp, tmp[1:]): print 'seq: ', next, 'prev seq:', prev, 'variance: ', next-prev Or, if you really need the first iteration too for prev, next in izip(tmp, tmp[:1] + tmp): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] EDIT If you want to avoid the creation of a list in the second argument you can also use an explicit iterator: itr = iter(tmp) itr.next() # here I assume tmp is not empty, otherwise an exception will be thrown for prev, next in izip(tmp, itr): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] Note: This zip pattern is useful in similar problems too. For example to extract successive triplets from a list: xs = range(9) triplets = zip(xs[::3], xs[1::3], xs[2::3]) # python 2.x, zip returns a list print xs # [0, 1, 2, 3, 4, 5, 6, 7, 8] print triplets # [(0, 1, 2), (3, 4, 5), (6, 7, 8)] Also note that in python 3 zip returns an iterator, similar to itertools.izip. A: Your code is going to be doing the "if not prev" test every time round the loop, even though it only applies to the first element. Also your code seems broken to me - the first time round the loop the prev and current values are the same. I would do it like this, assuming that there is at least one element: tmp_iter = iter(tmp) prev = tmp_iter.next() for x in tmp_iter: print 'seq: ', x[1], 'prev seq:', prev[1], 'variance: ', x[1]-prev[1] prev = x this could be optimised further by getting rid of the indexing: tmp_iter = iter(tmp) [_, prev] = tmp_iter.next() for [_, x] in tmp_iter: print 'seq: ', x, 'prev seq:', prev, 'variance: ', x-prev prev = x I use the assignment to spit the list into its constituent parts, and assign the first element to _ because it is not used. A: Using itertools: from itertools import izip, islice for prev, cur in izip(l, islice(l, 1, None)): print 'seq:', cur[1], 'prev seq:', prev[1], 'delta:', cur[1]-prev[1] For the specific example given in the question, note that, if the numbers can be represented using 32-bit ints, and the list of numbers fits into memory, one of the fastest ways to compute the difference would be to use numpy: import numpy a = numpy.array([x[1] for x in tmp]) delta = numpy.diff(a) A: Guido's time machine to the rescue! From the itertools recipes page: import itertools def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) This should be the most appropriate method (consider the iterable was (random.randint(100) for x in xrange(1000)); here iter(iterable); next(iterable) as a secondary iterator might not provide correct functionality. Use it in your loop as: for prev_item, item in pairwise(iterable): … A: This code generates NameError because at if not prev, prev is not defined. Set it to False or None before the cycle. Also you may make a different loop: for i in xrange(1, len(tmp)): print 'seq: {0}, prev seq: {1}, variance: {2}'.format(tmp[i][1], tmp[i - 1][1], tmp[i] - tmp[i - 1][1]) If you'll use 100,000+ records, the bottleneck will be not the cycle, but the memory used by the app. Don't store all the data in such a format: each pair of values (a list) will eat 100+ bytes. If they're in a file, it's better to iterate over it's lines: (assuming the data is tab-separated) def reader(filename): with open(filename) as f: prev = f.next() for l in f: l = l.split('\t') yield (prev, l) prev = l for (prev, curr) in reader(myfile): print 'seq: {0}, prev seq: {1}, variance: {2}'.format(curr[1], prev[1], curr[1] - prev[1]) reader is a generator, it returns values from a sequence many times. This way, only 2 lines of data will be stored in memory at any moment, and your app will sustain even millions of rows. To make the code readable, I put it aside, so that in the program body we dealed with the sequence of data, without caring how it's composed. A: it = imap(operator.itemgetter(1), tmp) # get all 2nd items prev = next(it, None) # get 1st element (doesn't throw exception for empty `tmp`) for x in it: print 'seq: %s prev seq: %s variance: %s' % (x, prev, x-prev) prev = x
Optimal way to access a value from the last iteration in a loop
What's the best and fastest way to access a value from the previous iteration in a for loop, assuming that the object will be very large (example, a cursor object which has 100,000+ records) Using a simple example: tmp = [ ['xyz', 335], ['zzz', 338], ['yyy', 339], ['yyy', 442], ['abc', 443], ['efg', 444], ['ttt', 446], ['fff', 447] ] for x in tmp: if not prev: prev = x[1] print 'seq: ', x[1], 'prev seq:', prev, 'variance: ', x[1]-prev prev = x[1] Is this the most optimal way to handle this? Based on the responses below i did some testing: tmp was created with 500 lists, the average of running it 20 times is shown below. results: Mines: 0,623 Dave snippet1: 0,605 Dave snippet2: 0,586 Catchmeifyoutry (edited code): 0,707
[ "Just iterate over pairs, using zip(), which is much more readable.\nUPDATE: for python 2.x, use itertools.izip instead as it is more efficient!\nfrom itertools import izip\nfor prev, next in izip(tmp, tmp[1:]):\n print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1]\n\nwhich can also use value unpacking to avoid the index:\nfor (_, prev), (_, next) in izip(tmp, tmp[1:]):\n print 'seq: ', next, 'prev seq:', prev, 'variance: ', next-prev\n\nOr, if you really need the first iteration too\nfor prev, next in izip(tmp, tmp[:1] + tmp):\n print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1]\n\nEDIT\nIf you want to avoid the creation of a list in the second argument you can also use an explicit iterator:\nitr = iter(tmp)\nitr.next() # here I assume tmp is not empty, otherwise an exception will be thrown\nfor prev, next in izip(tmp, itr):\n print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1]\n\nNote: This zip pattern is useful in similar problems too.\nFor example to extract successive triplets from a list:\nxs = range(9)\ntriplets = zip(xs[::3], xs[1::3], xs[2::3]) # python 2.x, zip returns a list\n\nprint xs # [0, 1, 2, 3, 4, 5, 6, 7, 8]\nprint triplets # [(0, 1, 2), (3, 4, 5), (6, 7, 8)]\n\nAlso note that in python 3 zip returns an iterator, similar to itertools.izip.\n", "Your code is going to be doing the \"if not prev\" test every time round the loop, even though it only applies to the first element.\nAlso your code seems broken to me - the first time round the loop the prev and current values are the same.\nI would do it like this, assuming that there is at least one element:\ntmp_iter = iter(tmp)\nprev = tmp_iter.next()\n\nfor x in tmp_iter: \n print 'seq: ', x[1], 'prev seq:', prev[1], 'variance: ', x[1]-prev[1]\n prev = x\n\nthis could be optimised further by getting rid of the indexing:\ntmp_iter = iter(tmp)\n[_, prev] = tmp_iter.next()\n\nfor [_, x] in tmp_iter: \n print 'seq: ', x, 'prev seq:', prev, 'variance: ', x-prev\n prev = x\n\nI use the assignment to spit the list into its constituent parts, and assign the first element to _ because it is not used.\n", "Using itertools:\nfrom itertools import izip, islice\nfor prev, cur in izip(l, islice(l, 1, None)):\n print 'seq:', cur[1], 'prev seq:', prev[1], 'delta:', cur[1]-prev[1]\n\nFor the specific example given in the question, note that, if the numbers\ncan be represented using 32-bit ints, and the list of numbers fits into\nmemory, one of the fastest ways to compute the difference would be to\nuse numpy:\nimport numpy\na = numpy.array([x[1] for x in tmp])\ndelta = numpy.diff(a)\n\n", "Guido's time machine to the rescue!\nFrom the itertools recipes page:\nimport itertools\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return itertools.izip(a, b)\n\nThis should be the most appropriate method (consider the iterable was (random.randint(100) for x in xrange(1000)); here iter(iterable); next(iterable) as a secondary iterator might not provide correct functionality.\nUse it in your loop as:\nfor prev_item, item in pairwise(iterable):\n …\n\n", "This code generates NameError because at if not prev, prev is not defined. Set it to False or None before the cycle. Also you may make a different loop:\nfor i in xrange(1, len(tmp)):\n print 'seq: {0}, prev seq: {1}, variance: {2}'.format(tmp[i][1], tmp[i - 1][1], tmp[i] - tmp[i - 1][1])\n\nIf you'll use 100,000+ records, the bottleneck will be not the cycle, but the memory used by the app. Don't store all the data in such a format: each pair of values (a list) will eat 100+ bytes. If they're in a file, it's better to iterate over it's lines:\n(assuming the data is tab-separated)\ndef reader(filename):\n with open(filename) as f:\n prev = f.next()\n for l in f:\n l = l.split('\\t')\n yield (prev, l)\n prev = l\n\nfor (prev, curr) in reader(myfile):\n print 'seq: {0}, prev seq: {1}, variance: {2}'.format(curr[1], prev[1], curr[1] - prev[1])\n\nreader is a generator, it returns values from a sequence many times. This way, only 2 lines of data will be stored in memory at any moment, and your app will sustain even millions of rows.\nTo make the code readable, I put it aside, so that in the program body we dealed with the sequence of data, without caring how it's composed.\n", "it = imap(operator.itemgetter(1), tmp) # get all 2nd items\nprev = next(it, None) # get 1st element (doesn't throw exception for empty `tmp`)\nfor x in it:\n print 'seq: %s prev seq: %s variance: %s' % (x, prev, x-prev)\n prev = x\n\n" ]
[ 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0001876587_loops_python.txt
Q: Raise of an eoferror for a file import pickle filename=input('Enter a file name:') def commands(): f=open(filename,'w') names=[] grades=[] while True: name=input("Give a student's name:") if name.lower()=='end': f.close() print("File closed") print("Back to Menu") break else: x=names.append(name) f.write(str(x)) grade=input("Give student's grade:") try: grade=float(grade) if 0<=grade<=10: y=grades.append(grade) f.write(str(y)) else: print("Please give a grade!Between 0-10! ") except ValueError: print(grade,"is not a number...Give only Numbers!") def syn2(filename): try: f=open(filename,'r') f.read(names) f.read(grades) d1={} d1[names]=grades print(d1) print("Back to Menu") except IOError: return False WHEN I CALL syn2(filename) : Traceback (most recent call last): File "file1.py", line 68, in File "file2.py", line 45, in syn2 NameError: global name 'names' is not defined A: You're running into the end of the file "EOF" before your program expects to. A: I would suggest keeping the students/grades in a dictionary. If the user has finished her input, pickle the dictionary into a file. Like grades = {} while True: # ask for student's name n # ... if n.lower() == 'end': break # ask for student's grade g # ... grades[n] = g pickle.dump(grades, yourfile) A: You have the error global name 'names' is not defined because you have declare names within def entoles() and is only seen within this scope. You have to declare names outside the dev entoles() if you want to be able to access it. Also x=names.append(name) f.write(str(x)) append is a method that append the item passed to the list in-place. The method returns 'None' Therefore, f.write(str(x)) will write 'None'. EDIT: Python doc about Input/Output for f.read() and this Python doc for input/raw_input A: The problem is that the myfunc function reopens the file on each iteration, deleting its contents. You should move the open call to before the while loop.
Raise of an eoferror for a file
import pickle filename=input('Enter a file name:') def commands(): f=open(filename,'w') names=[] grades=[] while True: name=input("Give a student's name:") if name.lower()=='end': f.close() print("File closed") print("Back to Menu") break else: x=names.append(name) f.write(str(x)) grade=input("Give student's grade:") try: grade=float(grade) if 0<=grade<=10: y=grades.append(grade) f.write(str(y)) else: print("Please give a grade!Between 0-10! ") except ValueError: print(grade,"is not a number...Give only Numbers!") def syn2(filename): try: f=open(filename,'r') f.read(names) f.read(grades) d1={} d1[names]=grades print(d1) print("Back to Menu") except IOError: return False WHEN I CALL syn2(filename) : Traceback (most recent call last): File "file1.py", line 68, in File "file2.py", line 45, in syn2 NameError: global name 'names' is not defined
[ "You're running into the end of the file \"EOF\" before your program expects to.\n", "I would suggest keeping the students/grades in a dictionary. If the user has finished her input, pickle the dictionary into a file. Like\ngrades = {}\nwhile True:\n # ask for student's name n\n # ...\n\n if n.lower() == 'end':\n break\n\n # ask for student's grade g\n # ...\n\n grades[n] = g\n\npickle.dump(grades, yourfile)\n\n", "You have the error global name 'names' is not defined because you have declare names within def entoles() and is only seen within this scope.\nYou have to declare names outside the dev entoles() if you want to be able to access it.\nAlso\nx=names.append(name)\nf.write(str(x))\n\nappend is a method that append the item passed to the list in-place. The method returns 'None'\nTherefore, f.write(str(x)) will write 'None'. \nEDIT:\nPython doc about Input/Output for f.read() and this Python doc for input/raw_input\n", "The problem is that the myfunc function reopens the file on each iteration, deleting its contents. You should move the open call to before the while loop.\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "eoferror", "file", "python" ]
stackoverflow_0001876100_eoferror_file_python.txt
Q: Python: "unsupported operand types for +: 'long' and 'numpy.float64' " My program uses genetic techniques to build equations. It randomly assembles strings into an equation with one unknown. "(((x + 1) * x) / (4 * 6) ** 2)" One of the strings is: "math.factorial(random.randint(1,9))" So an equation is typically something like: "(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9))" Fifty different equations are generated and then assigned a fitness value according to how well they approximate the sin function over a range of values. for x in numpy.arange(1,6.4,.1): fitness += abs(eval"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9)) - numpy.sin(x))") The program often throws an exception which is caught by an 'except TypeError' clause. The error message is "unsupported operand types for +:'long' and 'numpy.float64'" When I try "type(numpy.sin(1))"it returns type: numpy.float64 How do I get 'long' and 'numpy.float64' operand types to work together? Any help would be appreciated. @catchmeifyoutry: good idea! Unfortunately it's a heck of an equation. I've never tried to take one this long apart. I have wondered if there is a parsing utility to help resolve all the brackets. (((math.factorial(random.randint(1,9))))-(((x)+((((math.factorial(random.randint(1,9))))**((math.factorial(random.randint(1,9)))))-(((6.0)/(((8.0)/(((3.0)-(8.0))/(((5.0)*((2.0)/(x)))/(8.0))))+(4.0)))/(8.0))))+(7.0))) I'll try to catch the value of x at which it failed. A: First, you are missing a closing bracket in your example, and the (+ or - or / or * or **) is confusing. What are you trying to achieve? Do you just want to insert the result in the string? Try this: for x in numpy.arange(1,6.4,.1): s = "sinus %f is %f!" % (x, numpy.sin(x)) print type(s), s See string formatting documentation. EDIT Ah yes, genetic programming, that explains what you're trying to do ;) Based on your updated information, I have to guess that your string construction is sometimes faulty somehow. Change your code to display the string that causes the exception to be thrown. Easiest way is to just print the string before calling eval on it, and when the exception is thrown you can see what the last equation was. Then, if it is not clear what is wrong with it, you can post that equation here. A: This works for me: for x in numpy.arange(1,6.4,.1): eval("( 1 + (2 * 3) / 4 ) * numpy.sin(x)")
Python: "unsupported operand types for +: 'long' and 'numpy.float64' "
My program uses genetic techniques to build equations. It randomly assembles strings into an equation with one unknown. "(((x + 1) * x) / (4 * 6) ** 2)" One of the strings is: "math.factorial(random.randint(1,9))" So an equation is typically something like: "(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9))" Fifty different equations are generated and then assigned a fitness value according to how well they approximate the sin function over a range of values. for x in numpy.arange(1,6.4,.1): fitness += abs(eval"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9)) - numpy.sin(x))") The program often throws an exception which is caught by an 'except TypeError' clause. The error message is "unsupported operand types for +:'long' and 'numpy.float64'" When I try "type(numpy.sin(1))"it returns type: numpy.float64 How do I get 'long' and 'numpy.float64' operand types to work together? Any help would be appreciated. @catchmeifyoutry: good idea! Unfortunately it's a heck of an equation. I've never tried to take one this long apart. I have wondered if there is a parsing utility to help resolve all the brackets. (((math.factorial(random.randint(1,9))))-(((x)+((((math.factorial(random.randint(1,9))))**((math.factorial(random.randint(1,9)))))-(((6.0)/(((8.0)/(((3.0)-(8.0))/(((5.0)*((2.0)/(x)))/(8.0))))+(4.0)))/(8.0))))+(7.0))) I'll try to catch the value of x at which it failed.
[ "First, you are missing a closing bracket in your example, and the (+ or - or / or * or **) is confusing.\nWhat are you trying to achieve?\nDo you just want to insert the result in the string? \nTry this:\nfor x in numpy.arange(1,6.4,.1):\n s = \"sinus %f is %f!\" % (x, numpy.sin(x))\n print type(s), s\n\nSee string formatting documentation.\nEDIT\nAh yes, genetic programming, that explains what you're trying to do ;)\nBased on your updated information, I have to guess that your string construction is sometimes faulty somehow.\nChange your code to display the string that causes the exception to be thrown. Easiest way is to just print the string before calling eval on it, and when the exception is thrown you can see what the last equation was.\nThen, if it is not clear what is wrong with it, you can post that equation here.\n", "This works for me:\nfor x in numpy.arange(1,6.4,.1):\n eval(\"( 1 + (2 * 3) / 4 ) * numpy.sin(x)\")\n\n" ]
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001877789_numpy_python.txt
Q: Search Python list and return 2 or more of the same character I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word. The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them? This is the code I'm using to map guessed letters against the randomly selected word. if user_input in choose_word: print "Good guess!" print trys_remaining, "trys remaining!" word_index = letter_list.index(user_input) correct_letters[word_index] = user_input If anyone could point me in the right direction, it would be great. A: You need to loop over all matching indices: for word_index, letter in enumerate(letter_list): if letter == user_input: correct_letters[word_index] = user_input Note: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time. See also the enumerate documentation. A: You can use a list comprehension: correct_letters = [letter if user_input == letter else correct for (correct, letter) in zip(correct_letters, letter_list)] Note that this will create a new correct_letters list, instead of modifying the original one.
Search Python list and return 2 or more of the same character
I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word. The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them? This is the code I'm using to map guessed letters against the randomly selected word. if user_input in choose_word: print "Good guess!" print trys_remaining, "trys remaining!" word_index = letter_list.index(user_input) correct_letters[word_index] = user_input If anyone could point me in the right direction, it would be great.
[ "You need to loop over all matching indices:\nfor word_index, letter in enumerate(letter_list):\n if letter == user_input:\n correct_letters[word_index] = user_input\n\nNote: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time.\nSee also the enumerate documentation.\n", "You can use a list comprehension: \ncorrect_letters = [letter if user_input == letter else correct\n for (correct, letter) in zip(correct_letters, letter_list)]\n\nNote that this will create a new correct_letters list, instead \nof modifying the original one.\n" ]
[ 4, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001875989_list_python.txt
Q: Add tuple to list of tuples in Python I am new to python and don't know the best way to do this. I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code: offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)] points = [( 1, 5),( 3, 3),( 8, 7)] So my set of combined points should be [( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5), ( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3), ( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)] I'm not able to use NumPy or any other libraries. A: result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets] For more, see list comprehensions. A: Pretty simple: >>> rslt = [] >>> for x, y in points: ... for dx, dy in offsets: ... rslt.append( (x+dx, y+dy) ) ... >>> rslt [(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4), (4, 3), (2, 3), (8, 7), (8, 6), (8, 8), (9, 7), (7, 7)] Cycle through the points and the offsets, then build new tuples of adding the offsets to the points. A: Personally, I like Alok's answer. However, for fans of itertools, the itertools-based equivalent (in Python 2.6 and later) is: import itertools as it ps = [(x+dx, y+dy) for (x, y), (dx, dy) in it.product(points, offsets)] However, in this case the itertools solution is not faster than the simple one (it's actually a tad slower because it needs to unpack each x, y repeatedly for every offset, while Alok's simple approach unpacks each x, y but once). Still, itertools.product is an excellent alternative to nested loops in other cases, so, it's worth knowing about it!-) A: If you don't care about duplicates in the result: result = [] for ox, oy in offsets: for px, py in points: result.append((px + ox, py + oy)) If you do care about duplicates in the result: result = set() for ox, oy in offsets: for px, py in points: result.add((px + ox, py + oy))
Add tuple to list of tuples in Python
I am new to python and don't know the best way to do this. I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code: offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)] points = [( 1, 5),( 3, 3),( 8, 7)] So my set of combined points should be [( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5), ( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3), ( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)] I'm not able to use NumPy or any other libraries.
[ "result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]\n\nFor more, see list comprehensions.\n", "Pretty simple:\n>>> rslt = []\n>>> for x, y in points:\n... for dx, dy in offsets:\n... rslt.append( (x+dx, y+dy) )\n... \n>>> rslt\n[(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4), (4, 3), (2, 3), (8, 7), (8, 6), (8, 8), (9, 7), (7, 7)]\n\nCycle through the points and the offsets, then build new tuples of adding the offsets to the points.\n", "Personally, I like Alok's answer. However, for fans of itertools, the itertools-based equivalent (in Python 2.6 and later) is:\nimport itertools as it\nps = [(x+dx, y+dy) for (x, y), (dx, dy) in it.product(points, offsets)]\n\nHowever, in this case the itertools solution is not faster than the simple one (it's actually a tad slower because it needs to unpack each x, y repeatedly for every offset, while Alok's simple approach unpacks each x, y but once). Still, itertools.product is an excellent alternative to nested loops in other cases, so, it's worth knowing about it!-)\n", "If you don't care about duplicates in the result:\nresult = []\nfor ox, oy in offsets:\n for px, py in points:\n result.append((px + ox, py + oy))\n\nIf you do care about duplicates in the result:\nresult = set()\nfor ox, oy in offsets:\n for px, py in points:\n result.add((px + ox, py + oy))\n\n" ]
[ 33, 15, 8, 5 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0001878470_python_tuples.txt
Q: How to Determine The Module a Particular Exception Class is Defined In Note: i edited my Q (in the title) so that it better reflects what i actually want to know. In the original title and in the text of my Q, i referred to the source of the thrown exception; what i meant, and what i should have referred to, as pointed out in one of the high-strung but otherwise helpful response below, is the module that the exception class is defined in. This is evidenced by the fact that, again, as pointed out in one of the answers below the answer to the original Q is that the exceptions were thrown from calls to cursor.execute and cursor.next, respectively--which of course, isn't the information you need to write the try/except block. For instance (the Q has nothing specifically to do with SQLite or the PySQLite module): from pysqlite2 import dbapi2 as SQ try: cursor.execute('CREATE TABLE pname (id INTEGER PRIMARY KEY, name VARCHARS(50)') except SQ.OperationalError: print("{0}, {1}".format("table already exists", "... 'CREATE' ignored")) # cursor.execute('SELECT * FROM pname') while 1: try: print(cursor.next()) except StopIteration: break # i let both snippets error out to see the exception thrown, then coded the try/finally blocks--but that didn't tell me anything about which module the exception class is defined. In my example, there's only a single imported module, but where there are many more, i am interested to know how an experienced pythonista identifies the exception source (search-the-docs-till-i-happen-to-find-it is my current method). [And yes i am aware there's a nearly identical question on SO--but for C# rather than python, plus if you read the author's edited version, you'll see he's got a different problem in mind.] A: the second [[exception was thrown]] from a python core module False: it was thrown from a call to cursor.next, exactly like the first one was thrown from a call to cursor.execute -- it's hard to say why you're baldly asserting this counterfactual, but contrary to fact it nevertheless remains. If you're speaking about, what module an exception class was defined in, as opposed to, as you say, where it was thrown from, that's a completely different thing of course: try: ...whatever... except Exception, e: print "caught an exception defined in module", e.__class__.__module__ Built-in exceptions are actually defined in module exceptions, as this code will also tell you. Of course, once you have the module name (which this snippet gives you), you can further explore, if you wish, e.g. by obtaining the module object (just index sys.modules by module name), etc. A: Usually, I just read the documentation. Part of the documentation for a Python module or function is a list of the exceptions it defines. If it doesn't list anything, I just assume I'm looking for a Python builtin exception. By the way, the StopIteration exception is the standard way for any Python "iterable" object to signal that you have come to the end of the data it will provide to you. This loop: cursor.execute('SELECT * FROM pname') while 1: try: print(cursor.next()) except StopIteration: break Can be written as: cursor.execute('SELECT * FROM pname') for x in cursor: print(x) EDIT: I have to say that, despite my cheerful confidence that the exceptions would be documented, I cannot find such a list in the Python docstring help or web page help for dbapi2. In that case I guess I just do what you did: Google search for the name of the exception and see what pops out! A: You could use python's inspect module and generic Exception handling like so: from inspect import getmodule try: # attempt some task except Exception, e: print getmodule(e) Which will spit out the module and its path like so: <module 'some.module' from '/path/to/some/module.pyc'> A: Usually I wrap the bare minimum that I can in a try..except block, e.g.: try: os.rename('foo', 'bar') except EnvironmentError: ... try: open('bar') except EnvironmentError: ... This way I can handle each exception appropriately and separately. A: Exception is somehow part of the function signature. The 1st thing to do is to read the documentation, the list of exception it can throw should be given. That's the case in most modules. In your code, you should catch the minimum exception and just have one general catch at the top of your code (in your main for example) and print somewhere the traceback in order to know where unhandled exceptions comes from. Then the right way to make sure that you didn't miss an exception is to write unit tests for your code and to cover every possible scenario. I hope it helps
How to Determine The Module a Particular Exception Class is Defined In
Note: i edited my Q (in the title) so that it better reflects what i actually want to know. In the original title and in the text of my Q, i referred to the source of the thrown exception; what i meant, and what i should have referred to, as pointed out in one of the high-strung but otherwise helpful response below, is the module that the exception class is defined in. This is evidenced by the fact that, again, as pointed out in one of the answers below the answer to the original Q is that the exceptions were thrown from calls to cursor.execute and cursor.next, respectively--which of course, isn't the information you need to write the try/except block. For instance (the Q has nothing specifically to do with SQLite or the PySQLite module): from pysqlite2 import dbapi2 as SQ try: cursor.execute('CREATE TABLE pname (id INTEGER PRIMARY KEY, name VARCHARS(50)') except SQ.OperationalError: print("{0}, {1}".format("table already exists", "... 'CREATE' ignored")) # cursor.execute('SELECT * FROM pname') while 1: try: print(cursor.next()) except StopIteration: break # i let both snippets error out to see the exception thrown, then coded the try/finally blocks--but that didn't tell me anything about which module the exception class is defined. In my example, there's only a single imported module, but where there are many more, i am interested to know how an experienced pythonista identifies the exception source (search-the-docs-till-i-happen-to-find-it is my current method). [And yes i am aware there's a nearly identical question on SO--but for C# rather than python, plus if you read the author's edited version, you'll see he's got a different problem in mind.]
[ "\nthe second [[exception was thrown]] from a python core module\n\nFalse: it was thrown from a call to cursor.next, exactly like the first one was thrown from a call to cursor.execute -- it's hard to say why you're baldly asserting this counterfactual, but contrary to fact it nevertheless remains.\nIf you're speaking about, what module an exception class was defined in, as opposed to, as you say, where it was thrown from, that's a completely different thing of course:\ntry:\n ...whatever...\nexcept Exception, e:\n print \"caught an exception defined in module\", e.__class__.__module__\n\nBuilt-in exceptions are actually defined in module exceptions, as this code will also tell you. Of course, once you have the module name (which this snippet gives you), you can further explore, if you wish, e.g. by obtaining the module object (just index sys.modules by module name), etc.\n", "Usually, I just read the documentation. Part of the documentation for a Python module or function is a list of the exceptions it defines. If it doesn't list anything, I just assume I'm looking for a Python builtin exception.\nBy the way, the StopIteration exception is the standard way for any Python \"iterable\" object to signal that you have come to the end of the data it will provide to you. This loop:\ncursor.execute('SELECT * FROM pname')\nwhile 1:\n try:\n print(cursor.next())\n except StopIteration:\n break\n\nCan be written as:\ncursor.execute('SELECT * FROM pname')\nfor x in cursor:\n print(x)\n\nEDIT: I have to say that, despite my cheerful confidence that the exceptions would be documented, I cannot find such a list in the Python docstring help or web page help for dbapi2. In that case I guess I just do what you did: Google search for the name of the exception and see what pops out!\n", "You could use python's inspect module and generic Exception handling like so:\nfrom inspect import getmodule\ntry:\n # attempt some task\nexcept Exception, e:\n print getmodule(e)\n\nWhich will spit out the module and its path like so:\n<module 'some.module' from '/path/to/some/module.pyc'>\n\n", "Usually I wrap the bare minimum that I can in a try..except block, e.g.:\ntry:\n os.rename('foo', 'bar')\nexcept EnvironmentError:\n ...\n\ntry:\n open('bar')\nexcept EnvironmentError:\n ...\n\nThis way I can handle each exception appropriately and separately.\n", "Exception is somehow part of the function signature. The 1st thing to do is to read the documentation, the list of exception it can throw should be given. That's the case in most modules.\nIn your code, you should catch the minimum exception and just have one general catch at the top of your code (in your main for example) and print somewhere the traceback in order to know where unhandled exceptions comes from.\nThen the right way to make sure that you didn't miss an exception is to write unit tests for your code and to cover every possible scenario.\nI hope it helps\n" ]
[ 5, 4, 2, 1, 1 ]
[]
[]
[ "exception", "exception_handling", "module", "python" ]
stackoverflow_0001878801_exception_exception_handling_module_python.txt
Q: Python directory searching and organizing by dict Hey all, this is my first time recently trying to get into the file and os part of Python. I am trying to search a directory then find all sub directories. If the directory has no folders, add all the files to a list. And organize them all by dict. So for instance a tree could look like this Starting Path Dir 1 Subdir 1 Subdir 2 Subdir 3 subsubdir file.jpg folder1 file1.jpg file2.jpg folder2 file3.jpg file4.jpg Even if subsubdir has a file in it, it should be skipped because it has folders in it. Now I can normally do this if I know how many directories I am going to be looking for, using os.listdir and os.path.isdir. However if I want this to be dynamic it will have to compensate for any amount of folders and subfolders. I have tried using os.walk and it will find all the files easily. The only trouble I am having is creating all the dicts with the path names that contain file. I need the foldernames organized by dict, up until the starting path. So in the end, using the example above, the dict should look like this with the files in it: dict['dir1']['subdir3']['subsubdir']['folder1'] = ['file1.jpg', 'file2.jpg'] dict['dir1']['subdir3']['subsubdir']['folder2'] = ['file3.jpg', 'file4.jpg'] Would appreciate any help on this or better ideas on organizing the information. Thanks. A: Maybe you want something like: def explore(starting_path): alld = {'': {}} for dirpath, dirnames, filenames in os.walk(starting_path): d = alld dirpath = dirpath[len(starting_path):] for subd in dirpath.split(os.sep): based = d d = d[subd] if dirnames: for dn in dirnames: d[dn] = {} else: based[subd] = filenames return alld[''] For example, given a /tmp/a such that: $ ls -FR /tmp/a b/ c/ d/ /tmp/a/b: z/ /tmp/a/b/z: /tmp/a/c: za zu /tmp/a/d: print explore('/tmp/a') emits: {'c': ['za', 'zu'], 'b': {'z': []}, 'd': []}. If this isn't exactly what you're after, maybe you can show us specifically what the differences are supposed to be? I suspect they can probably be easily fixed, if need be. A: There is a basic problem with the way you want to structure the data. If dir1/subdir1 contains subdirectories and files, should dict['dir1']['subdir1'] be a list or a dictionary? To access further subdirectories with ...['subdir2'] it needs to be a dictionary, but on the other hand dict['dir1']['subdir1'] should return a list of files. Either you have to build the tree from custom objects that combine these two aspects in some way, or you have to change the tree structure to treat files differently. A: I don't know why you would want to do this. You should be able to do your processing using os.path.walk, but in case you really need such a structure, you can do (untested): import os def dirfunc(fdict, dirname, fnames): tmpdict = fdict keys = dirname.split(os.sep)[:-1] for k in keys: tmpdict = tmpdict.setdefault(k, {}) for f in fnames: if os.path.isdir(f): return tmpdict[dirname] = fnames mydict = {} os.walk(directory_to_search, dirfunc, mydict) Also, you should not name your variable dict because it's a Python built-in. It is a very bad idea to rebind the name dict to something other than Python's dict type. Edit: edited to fix the "double last key" error and to use os.walk.
Python directory searching and organizing by dict
Hey all, this is my first time recently trying to get into the file and os part of Python. I am trying to search a directory then find all sub directories. If the directory has no folders, add all the files to a list. And organize them all by dict. So for instance a tree could look like this Starting Path Dir 1 Subdir 1 Subdir 2 Subdir 3 subsubdir file.jpg folder1 file1.jpg file2.jpg folder2 file3.jpg file4.jpg Even if subsubdir has a file in it, it should be skipped because it has folders in it. Now I can normally do this if I know how many directories I am going to be looking for, using os.listdir and os.path.isdir. However if I want this to be dynamic it will have to compensate for any amount of folders and subfolders. I have tried using os.walk and it will find all the files easily. The only trouble I am having is creating all the dicts with the path names that contain file. I need the foldernames organized by dict, up until the starting path. So in the end, using the example above, the dict should look like this with the files in it: dict['dir1']['subdir3']['subsubdir']['folder1'] = ['file1.jpg', 'file2.jpg'] dict['dir1']['subdir3']['subsubdir']['folder2'] = ['file3.jpg', 'file4.jpg'] Would appreciate any help on this or better ideas on organizing the information. Thanks.
[ "Maybe you want something like:\ndef explore(starting_path):\n alld = {'': {}}\n\n for dirpath, dirnames, filenames in os.walk(starting_path):\n d = alld\n dirpath = dirpath[len(starting_path):]\n for subd in dirpath.split(os.sep):\n based = d\n d = d[subd]\n if dirnames:\n for dn in dirnames:\n d[dn] = {}\n else:\n based[subd] = filenames\n return alld['']\n\nFor example, given a /tmp/a such that:\n$ ls -FR /tmp/a\nb/ c/ d/\n\n/tmp/a/b:\nz/\n\n/tmp/a/b/z:\n\n/tmp/a/c:\nza zu\n\n/tmp/a/d:\n\nprint explore('/tmp/a') emits: {'c': ['za', 'zu'], 'b': {'z': []}, 'd': []}.\nIf this isn't exactly what you're after, maybe you can show us specifically what the differences are supposed to be? I suspect they can probably be easily fixed, if need be.\n", "There is a basic problem with the way you want to structure the data. If dir1/subdir1 contains subdirectories and files, should dict['dir1']['subdir1'] be a list or a dictionary? To access further subdirectories with ...['subdir2'] it needs to be a dictionary, but on the other hand dict['dir1']['subdir1'] should return a list of files.\nEither you have to build the tree from custom objects that combine these two aspects in some way, or you have to change the tree structure to treat files differently.\n", "I don't know why you would want to do this. You should be able to do your processing using os.path.walk, but in case you really need such a structure, you can do (untested):\nimport os\n\ndef dirfunc(fdict, dirname, fnames):\n tmpdict = fdict\n keys = dirname.split(os.sep)[:-1]\n for k in keys:\n tmpdict = tmpdict.setdefault(k, {})\n\n for f in fnames:\n if os.path.isdir(f):\n return\n\n tmpdict[dirname] = fnames\n\nmydict = {}\nos.walk(directory_to_search, dirfunc, mydict)\n\nAlso, you should not name your variable dict because it's a Python built-in. It is a very bad idea to rebind the name dict to something other than Python's dict type.\nEdit: edited to fix the \"double last key\" error and to use os.walk.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "directory", "os.walk", "path", "python", "subdirectory" ]
stackoverflow_0001878247_directory_os.walk_path_python_subdirectory.txt
Q: Order a list of files by size via python Example dump from the list of a directory: hello:3.1 GB world:1.2 MB foo:956.2 KB The above list is in the format of FILE:VALUE UNIT. How would one go about ordering each line above according to file size? I thought perhaps to parse each line for the unit via the pattern ":VALUE UNIT" (or somehow use the delimiter) then run it through the ConvertAll engine, receive the size off each value in bytes, hash it with the rest of the line (filenames), then order the resulting dictionary pairs via size. Trouble is, I have no idea about pattern matching. But I see that you can sort a dictionary If there is a better direction in which to solve this problem, please let me know. EDIT: The list that I had was actually in a file. Taking inspiration from answer of the (awesome) Alex Martelli, I've written up the following code that extracts from one file, orders it and writes to another. #!/usr/bin/env python sourceFile = open("SOURCE_FILE_HERE", "r") allLines = sourceFile.readlines() sourceFile.close() print "Reading the entire file into a list." cleanLines = [] for line in allLines: cleanLines.append(line.rstrip()) mult = dict(KB=2**10, MB=2**20, GB=2**30) def getsize(aline): fn, size = aline.split(':', 1) value, unit = size.split(' ') multiplier = mult[unit] return float(value) * multiplier print "Writing sorted list to file." cleanLines.sort(key=getsize) writeLines = open("WRITE_OUT_FILE_HERE",'a') for line in cleanLines: writeLines.write(line+"\n") writeLines.close() A: thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB'] mult = dict(KB=2**10, MB=2**20, GB=2**30) def getsize(aline): fn, size = aline.split(':', 1) value, unit = size.split(' ') multiplier = mult[unit] return float(value) * multiplier thelines.sort(key=getsize) print thelines emits ['foo:956.2 KB', 'world:1.2 MB', 'hello:3.1 GB'], as desired. You may have to add some entries to mult if KB, MB and GB don't exhaust your set of units of interest of course.
Order a list of files by size via python
Example dump from the list of a directory: hello:3.1 GB world:1.2 MB foo:956.2 KB The above list is in the format of FILE:VALUE UNIT. How would one go about ordering each line above according to file size? I thought perhaps to parse each line for the unit via the pattern ":VALUE UNIT" (or somehow use the delimiter) then run it through the ConvertAll engine, receive the size off each value in bytes, hash it with the rest of the line (filenames), then order the resulting dictionary pairs via size. Trouble is, I have no idea about pattern matching. But I see that you can sort a dictionary If there is a better direction in which to solve this problem, please let me know. EDIT: The list that I had was actually in a file. Taking inspiration from answer of the (awesome) Alex Martelli, I've written up the following code that extracts from one file, orders it and writes to another. #!/usr/bin/env python sourceFile = open("SOURCE_FILE_HERE", "r") allLines = sourceFile.readlines() sourceFile.close() print "Reading the entire file into a list." cleanLines = [] for line in allLines: cleanLines.append(line.rstrip()) mult = dict(KB=2**10, MB=2**20, GB=2**30) def getsize(aline): fn, size = aline.split(':', 1) value, unit = size.split(' ') multiplier = mult[unit] return float(value) * multiplier print "Writing sorted list to file." cleanLines.sort(key=getsize) writeLines = open("WRITE_OUT_FILE_HERE",'a') for line in cleanLines: writeLines.write(line+"\n") writeLines.close()
[ "thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB']\n\nmult = dict(KB=2**10, MB=2**20, GB=2**30)\n\ndef getsize(aline):\n fn, size = aline.split(':', 1)\n value, unit = size.split(' ')\n multiplier = mult[unit]\n return float(value) * multiplier\n\nthelines.sort(key=getsize)\nprint thelines\n\nemits ['foo:956.2 KB', 'world:1.2 MB', 'hello:3.1 GB'], as desired. You may have to add some entries to mult if KB, MB and GB don't exhaust your set of units of interest of course.\n" ]
[ 10 ]
[]
[]
[ "arrays", "dictionary", "hash", "python" ]
stackoverflow_0001879081_arrays_dictionary_hash_python.txt
Q: Count Parenthesis in a file with a Python program? I Wanna fix a function through it i can count how many times are used the:(,),[,] if the counts of ( are equal to those of ) and if the counts of [ are equal to those of ] then i have valid syntax! my first -dissapointed- try: filename=input("Give a file name:") def parenthesis(filename): try: f=open(filename,'r') except (IOError): print("The file",filename,"does not exist!False! Try again!") else: while True: for line in filename: line=f.readline() if line=='(': c1=line.count('(') elif line==')': c2=line.count(')') elif line=='[': c3=line.count('[') elif line==']': c4=line.count(']') elif line=='': break if c1==c2: print("Line: Valid Syntax") elif c1!=c2: print("Line: InValid Syntax") elif c3==c4: print("Line: Valid Syntax") elif c3!=c4: print("Line: InValid Syntax") finally: f.close() parenthesis(filename) A: Please excuse the length of this reply. If I understand you correctly, you want to do simple syntax checking of parentheses to make sure they are balanced correctly. In your question you specify a test based on simple counting, but as others have pointed out, this does not catch things like "([)]". I'd also like to offer some constructive criticism on other aspects of your code. To start with, it is better to get the filename from the command line, and not to prompt for it. This is so that you can easily run the program repeatedly, when developing it, without having to type in the filename all the time. This is your way: $ python foo.py Give a file name:data [some output] $ python foo.py Give a file name:data [some output] $ python foo.py Give a file name:data [some output] You need to type in the filename every time. You don't need to type in the command to run the program more than once. After the first time, you can use the arrow key to get it from the shell's command history. If you get the filename from the command line, you can do this instead: $ python foo.py testfile [some output] $ python foo.py testfile [some output] $ python foo.py testfile [some output] This way, when you test the second time, you don't need to type more than the up arrow and Enter keys. This is a small convenience, but it is important: when you're developing software, even small things can start annoying. It's like a large grain of sand under your foot when going on a long walk: you won't even notice it for the first couple of kilometers, but after a few more, you're bleeding. In Python, to access the command line arguments, you need the sys.argv list. The relevant changes to your program: import sys filename = sys.argv[1] If you do want to prompt, you should use something else than the built-in input function. It interprets whatever the user types as a Python expression, and that causes all sorts of problems. You could read using sys.stdin.readline. Anyway, we've now got the name of the file safely stored in the filename variable. It's time to do something with it. Your parentheses function does pretty much everything, and experience has shown that that's often not the best way of doing things. Every function should, instead, do just one thing, but do that well. I suggest that you should keep the parts of actually opening and closing a file separate from the actual counting. This will simplify the logic of the counting, since it does not need to worry about the rest. In code: import sys def check_parentheses(f): pass # we'll come to this later def main(): filename = sys.argv[1] try: f = file(filename) except IOError: sys.stderr.write('Error: Cannot open file %s' % filename) sys.exit(1) check_parentheses(f) f.close() main() I changed a couple of other things, too, in addition to rearranging things. First, I write the error message to the standard error output. This is the proper way to do it, and means fewer surprises to shell users to redirect the output. (If that doesn't make any sense to you, don't worry about it, just accept it as a given for now.) Second, if there's an error, I exit the program with sys.exit(1). This tells whoever started the program that it failed. In Unix shell, this lets you do things like the following: if python foo.py inputfile then echo "inputfile is OK!" else echo "inputfile is BAD!" fi The shell script might do something more interesting than just reporting success or failure, of course. It might, for example, remove all broken files, or e-mail whoever wrote them to ask them to fix them. The beauty is that you, who write the checker program, do not need to care. You just set the program exit code properly, and let whoever writes the shell script to worry about the rest. The next step is to actually read the contents of the file. This can be done in various ways. The easiest way is to do it line-by-line, like this: for line in f: # do something with the line We then need to look at each character in the line: for line in f: for c in line: # do something with the character We're now ready to actually start checking parentheses. As suggested by others, a stack is the appropriate data structure for this. A stack is basically a list (or array) where you add items to one end, and take them out in reverse order. Think of it as a stack of coins: you can add a coin to the top, and you can remove the topmost coin, but you can't remove one from the middle or bottom. (Well, you can, and it's a neat trick if you do, but computers are simple beasts and get upset by magic tricks.) We will use a Python list as a stack. To add an item, we use the list's append method, and to remove we use the pop method. An example: stack = list() stack.append('(') stack.append('[') stack.pop() # this will return '[' stack.pop() # this will return '(' To look at the topmost item in the stack, we use stack[-1] (in other words, the last item in the list). We use the stack as follows: when we find an opening parentheses ('('), bracket ('['), or brace ('{'), we put it on the stack. When we find a closing one, we check the topmost item on the stack, and make sure that it matches the closing one. If not, we print an error. Like this: def check_parentheses(f): stack = list() for line in f: for c in line: if c == '(' or c == '[' or c == '{': stack.append(c) elif c == ')': if stack[-1] != '(': print 'Error: unmatched )' else: stack.pop() elif c == ']': if stack[-1] != '[': print 'Error: unmatched ]' else: stack.pop() elif c == '}': if stack[-1] != '{': print 'Error: unmatched }' else: stack.pop() This now does find unmatched parentheses of various kinds. We can improve it a little bit by reporting the line and column where we find the problem. We need a line number and column number counter. def error(c, line_number, column_number): print 'Error: unmatched', c, 'line', line_number, 'column', column_number def check_parentheses(f): stack = list() line_number = 0 for line in f: line_number = line_number + 1 column_number = 0 for c in line: column_number = column_number + 1 if c == '(' or c == '[' or c == '{': stack.append(c) elif c == ')': if stack[-1] != '(': error(')', line_number, column_number) else: stack.pop() elif c == ']': if stack[-1] != '[': error(']', line_number, column_number) else: stack.pop() elif c == '}': if stack[-1] != '{': error('}', line_number, column_number) else: stack.pop() Note also how I added a helper function, error, to do the actual printing of the error message. If you want to change the error message, you now only need to do it in one place. Another thing to notice is that the cases for handling the closing symbols are all very similar. We could make that to a function, too. def check(stack, wanted, c, line_number, column_number): if stack[-1] != wanted: error(c, line_number, column_number) else: stack.pop() def check_parentheses(f): stack = list() line_number = 0 for line in f: line_number = line_number + 1 column_number = 0 for c in line: column_number = column_number + 1 if c == '(' or c == '[' or c == '{': stack.append(c) elif c == ')': check(stack, '(', ')', line_number, column_number) elif c == ']': check(stack, '[', ']', line_number, column_number) elif c == '}': check(stack, '{', '}', line_number, column_number) The program can be refined further, but this should suffice for now. I'll include the whole code at the end. Note that this program only cares about parentheses of various kinds. If you really want to check a whole Python program for syntactic correctness, you'll need to parse all of Python's syntax, and that is pretty complicated, and too much for one Stack Overflow answer. If that's what you really do want, please ask a followup question. The whole program: import sys def error(c, line_number, column_number): print 'Error: unmatched', c, 'line', line_number, 'column', column_number def check(stack, wanted, c, line_number, column_number): if stack[-1] != wanted: error(c, line_number, column_number) else: stack.pop() def check_parentheses(f): stack = list() line_number = 0 for line in f: line_number = line_number + 1 column_number = 0 for c in line: column_number = column_number + 1 if c == '(' or c == '[' or c == '{': stack.append(c) elif c == ')': check(stack, '(', ')', line_number, column_number) elif c == ']': check(stack, '[', ']', line_number, column_number) elif c == '}': check(stack, '{', '}', line_number, column_number) def main(): filename = sys.argv[1] try: f = file(filename) except IOError: sys.stderr.write('Error: Cannot open file %s' % filename) sys.exit(1) check_parentheses(f) f.close() main() A: I think if you change the: if line=='(': c1=line.count('(') elif line==')': c2=line.count(')') elif line=='[': c3=line.count('[') elif line==']': c4=line.count(']') elif line=='': break to something like: SearchFor = ['(', ')', '[', ']'] d = {} for itm in SearchFor: d[itm] = line.count(itm) # Then do the comparison if d['['] == d[']'] and d['('] == d[')']: print "Valid Syntax" else: print "Invalid Syntax" #You could look at each to find the exact cause. and the While True: as mentioned by others. I had missed that. :0) A: Remove the 'while True' line and this bit: elif line=='': break and then replace this: for line in filename: line=f.readline() with this: for line in f: Now you'll be looping over the lines in the file. Next, replace all of these sorts of things: if line=='(': c1=line.count('(') with: c1+=line.count('(') The if and elif lines are just preventing you from counting when you should. If the line doesn't have what you're looking for the count will be 0, which is fine. That should at least get you closer to a solution. A: I believe, You are looking for balanced symbol checker. It is better to use stack. Make an empty stack, For each symbol in the string: 2.1 If the symbol is an opening symbol, push it on the stack. 2.2 If it is a closing symbol, then 2.2.1 If the stack is empty, then it in false. 2.2.2 If the top of the stack does not match the closing symbol, return false. [check this step if you are checking for matched braces] 2.2.3 Pop the stack. Return true if the stack is empty, otherwise false. hth. A: Do you want to ensure that they parens & braces are matched? That "[(])" fails? If not, you're along the right path, except that you need to change your "=" to "+=". You're discarding the values of previous lines. A: My solution will try to help you understand a bit more precise way of doing this, and hopefully you'll learn a bit about data structures in the process. To properly do this, you're going to want to use a stack. You'll want to pull out all instances of (, ), [, and ] (perhaps using a regular expression... hint) and go through the array that that generates: Say your file is like this: (this [is] foobar) Your regular expression will yield this array: ['(', '[', ']', ')'] You will pop(0) off of this array into a stack. Algorithmically: 1) Put all tags {(,),[,]} in an array. 2) For each element in the array, pop(0) from it and push it onto your stack. Test it against the element before it. If it closes the element before it, then pop() twice from the array (eg, if you have '(' on the stack, and the next element to be pushed onto the stack is a ')', ')' closes '(', so you pop them both.) If it doesn't, continue. 3) If your array is empty and your stack is empty when this is over, then your file is well formed. If it's not, then you have a poorly formed file {something like (foo[bar)] }. Bonus: regular expression: REGEX = re.compile(r"\)\(\[\]"), REGEX.findall(your string to search). See more about regexes in Python here. A: All of these answers are wrong and will not work in all cases, so either use python parser e.g. tokenize etc or just use this count = min(text.count("("), text.count(")"))
Count Parenthesis in a file with a Python program?
I Wanna fix a function through it i can count how many times are used the:(,),[,] if the counts of ( are equal to those of ) and if the counts of [ are equal to those of ] then i have valid syntax! my first -dissapointed- try: filename=input("Give a file name:") def parenthesis(filename): try: f=open(filename,'r') except (IOError): print("The file",filename,"does not exist!False! Try again!") else: while True: for line in filename: line=f.readline() if line=='(': c1=line.count('(') elif line==')': c2=line.count(')') elif line=='[': c3=line.count('[') elif line==']': c4=line.count(']') elif line=='': break if c1==c2: print("Line: Valid Syntax") elif c1!=c2: print("Line: InValid Syntax") elif c3==c4: print("Line: Valid Syntax") elif c3!=c4: print("Line: InValid Syntax") finally: f.close() parenthesis(filename)
[ "Please excuse the length of this reply.\nIf I understand you correctly, you want to do simple syntax\nchecking of parentheses to make sure they are balanced correctly.\nIn your question you specify a test based on simple counting, but\nas others have pointed out, this does not catch things like\n\"([)]\".\nI'd also like to offer some constructive criticism on other\naspects of your code.\nTo start with, it is better to get the filename from the command\nline, and not to prompt for it. This is so that you can easily\nrun the program repeatedly, when developing it, without having\nto type in the filename all the time. This is your way:\n\n$ python foo.py\n Give a file name:data\n [some output]\n $ python foo.py\n Give a file name:data\n [some output]\n $ python foo.py\n Give a file name:data\n [some output] \n\nYou need to type in the filename every time. You don't need to type\nin the command to run the program more than once. After the first\ntime, you can use the arrow key to get it from the shell's command\nhistory. If you get the filename from the command line, you can do\nthis instead:\n\n$ python foo.py testfile\n [some output]\n $ python foo.py testfile\n [some output]\n $ python foo.py testfile\n [some output] \n\nThis way, when you test the second time, you don't need to type more\nthan the up arrow and Enter keys. This is a small convenience, but\nit is important: when you're developing software, even small \nthings can start annoying. It's like a large grain of sand under your\nfoot when going on a long walk: you won't even notice it for the first\ncouple of kilometers, but after a few more, you're bleeding.\nIn Python, to access the command line arguments, you need the\nsys.argv list. The relevant changes to your program:\nimport sys\nfilename = sys.argv[1]\n\nIf you do want to prompt, you should use something else than the\nbuilt-in input function. It interprets whatever the user types\nas a Python expression, and that causes all sorts of problems.\nYou could read using sys.stdin.readline.\nAnyway, we've now got the name of the file safely stored in\nthe filename variable. It's time to do something with it.\nYour parentheses function does pretty much everything, and\nexperience has shown that that's often not the best way of\ndoing things. Every function should, instead, do just one\nthing, but do that well.\nI suggest that you should keep the parts of actually opening\nand closing a file separate from the actual counting. This\nwill simplify the logic of the counting, since it does not\nneed to worry about the rest. In code:\nimport sys\n\ndef check_parentheses(f):\n pass # we'll come to this later\n\ndef main():\n filename = sys.argv[1]\n try:\n f = file(filename)\n except IOError:\n sys.stderr.write('Error: Cannot open file %s' % filename)\n sys.exit(1)\n check_parentheses(f)\n f.close()\n\nmain()\n\nI changed a couple of other things, too, in addition to rearranging\nthings. First, I write the error message to the standard error output.\nThis is the proper way to do it, and means fewer surprises to shell\nusers to redirect the output. (If that doesn't make any sense to you,\ndon't worry about it, just accept it as a given for now.)\nSecond, if there's an error, I exit the program with sys.exit(1).\nThis tells whoever started the program that it failed. In Unix\nshell, this lets you do things like the following:\nif python foo.py inputfile\nthen\n echo \"inputfile is OK!\"\nelse\n echo \"inputfile is BAD!\"\nfi\n\nThe shell script might do something more interesting than just reporting\nsuccess or failure, of course. It might, for example, remove all\nbroken files, or e-mail whoever wrote them to ask them to fix them.\nThe beauty is that you, who write the checker program, do not need\nto care. You just set the program exit code properly, and let whoever\nwrites the shell script to worry about the rest.\nThe next step is to actually read the contents of the file. This\ncan be done in various ways. The easiest way is to do it line-by-line,\nlike this:\nfor line in f:\n # do something with the line\n\nWe then need to look at each character in the line:\nfor line in f:\n for c in line:\n # do something with the character\n\nWe're now ready to actually start checking parentheses. As suggested\nby others, a stack is the appropriate data structure for this.\nA stack is basically a list (or array) where you add items to one\nend, and take them out in reverse order. Think of it as a stack of\ncoins: you can add a coin to the top, and you can remove the topmost\ncoin, but you can't remove one from the middle or bottom. \n(Well, you can, and it's a neat trick if you do, but computers are\nsimple beasts and get upset by magic tricks.)\nWe will use a Python list as a stack. To add an item, we use\nthe list's append method, and to remove we use the pop method.\nAn example:\nstack = list()\nstack.append('(')\nstack.append('[')\nstack.pop() # this will return '['\nstack.pop() # this will return '('\n\nTo look at the topmost item in the stack, we use stack[-1] (in\nother words, the last item in the list).\nWe use the stack as follows: when we find an opening parentheses ('('),\nbracket ('['), or brace ('{'), we put it on the stack. When we\nfind a closing one, we check the topmost item on the stack, and\nmake sure that it matches the closing one. If not, we print an\nerror. Like this:\ndef check_parentheses(f):\n stack = list()\n for line in f:\n for c in line:\n if c == '(' or c == '[' or c == '{':\n stack.append(c)\n elif c == ')':\n if stack[-1] != '(':\n print 'Error: unmatched )'\n else:\n stack.pop()\n elif c == ']':\n if stack[-1] != '[':\n print 'Error: unmatched ]'\n else:\n stack.pop()\n elif c == '}':\n if stack[-1] != '{':\n print 'Error: unmatched }'\n else:\n stack.pop()\n\nThis now does find unmatched parentheses of various kinds. We\ncan improve it a little bit by reporting the line and column \nwhere we find the problem. We need a line number and column number\ncounter.\ndef error(c, line_number, column_number):\n print 'Error: unmatched', c, 'line', line_number, 'column', column_number\n\ndef check_parentheses(f):\n stack = list()\n line_number = 0\n for line in f:\n line_number = line_number + 1\n column_number = 0\n for c in line:\n column_number = column_number + 1\n if c == '(' or c == '[' or c == '{':\n stack.append(c)\n elif c == ')':\n if stack[-1] != '(':\n error(')', line_number, column_number)\n else:\n stack.pop()\n elif c == ']':\n if stack[-1] != '[':\n error(']', line_number, column_number)\n else:\n stack.pop()\n elif c == '}':\n if stack[-1] != '{':\n error('}', line_number, column_number)\n else:\n stack.pop()\n\nNote also how I added a helper function, error, to do the actual\nprinting of the error message. If you want to change the error message,\nyou now only need to do it in one place.\nAnother thing to notice is that the cases for handling the closing\nsymbols are all very similar. We could make that to a function, too.\ndef check(stack, wanted, c, line_number, column_number):\n if stack[-1] != wanted:\n error(c, line_number, column_number)\n else:\n stack.pop()\n\ndef check_parentheses(f):\n stack = list()\n line_number = 0\n for line in f:\n line_number = line_number + 1\n column_number = 0\n for c in line:\n column_number = column_number + 1\n if c == '(' or c == '[' or c == '{':\n stack.append(c)\n elif c == ')':\n check(stack, '(', ')', line_number, column_number)\n elif c == ']':\n check(stack, '[', ']', line_number, column_number)\n elif c == '}':\n check(stack, '{', '}', line_number, column_number)\n\nThe program can be refined further, but this should suffice for now.\nI'll include the whole code at the end.\nNote that this program only cares about parentheses of various kinds.\nIf you really want to check a whole Python program for syntactic\ncorrectness, you'll need to parse all of Python's syntax, and that\nis pretty complicated, and too much for one Stack Overflow answer.\nIf that's what you really do want, please ask a followup question.\nThe whole program:\nimport sys\n\ndef error(c, line_number, column_number):\n print 'Error: unmatched', c, 'line', line_number, 'column', column_number\n\ndef check(stack, wanted, c, line_number, column_number):\n if stack[-1] != wanted:\n error(c, line_number, column_number)\n else:\n stack.pop()\n\ndef check_parentheses(f):\n stack = list()\n line_number = 0\n for line in f:\n line_number = line_number + 1\n column_number = 0\n for c in line:\n column_number = column_number + 1\n if c == '(' or c == '[' or c == '{':\n stack.append(c)\n elif c == ')':\n check(stack, '(', ')', line_number, column_number)\n elif c == ']':\n check(stack, '[', ']', line_number, column_number)\n elif c == '}':\n check(stack, '{', '}', line_number, column_number)\n\ndef main():\n filename = sys.argv[1]\n try:\n f = file(filename)\n except IOError:\n sys.stderr.write('Error: Cannot open file %s' % filename)\n sys.exit(1)\n check_parentheses(f)\n f.close()\n\nmain()\n\n", "I think if you change the:\n if line=='(':\n c1=line.count('(')\n elif line==')':\n c2=line.count(')')\n elif line=='[':\n c3=line.count('[')\n elif line==']':\n c4=line.count(']')\n elif line=='':\n break\n\nto something like:\nSearchFor = ['(', ')', '[', ']']\nd = {}\nfor itm in SearchFor:\n d[itm] = line.count(itm)\n\n\n# Then do the comparison\nif d['['] == d[']'] and d['('] == d[')']:\n print \"Valid Syntax\"\nelse:\n print \"Invalid Syntax\" #You could look at each to find the exact cause.\n\nand the While True: as mentioned by others. I had missed that. :0)\n", "Remove the 'while True' line and this bit:\nelif line=='':\n break\n\nand then replace this:\nfor line in filename:\n line=f.readline()\n\nwith this:\nfor line in f:\n\nNow you'll be looping over the lines in the file.\nNext, replace all of these sorts of things:\nif line=='(':\n c1=line.count('(')\n\nwith:\n c1+=line.count('(')\n\nThe if and elif lines are just preventing you from counting when you should. If the line doesn't have what you're looking for the count will be 0, which is fine.\nThat should at least get you closer to a solution.\n", "I believe, You are looking for balanced symbol checker. It is better to use stack.\n\nMake an empty stack,\nFor each symbol in the string:\n2.1 If the symbol is an opening symbol, push it on the stack.\n2.2 If it is a closing symbol, then\n2.2.1 If the stack is empty, then it in false.\n2.2.2 If the top of the stack does not match the closing symbol, return false. [check this step if you are checking for matched braces]\n2.2.3 Pop the stack.\nReturn true if the stack is empty, otherwise false.\n\nhth.\n", "Do you want to ensure that they parens & braces are matched? That \"[(])\" fails? If not, you're along the right path, except that you need to change your \"=\" to \"+=\". You're discarding the values of previous lines.\n", "My solution will try to help you understand a bit more precise way of doing this, and hopefully you'll learn a bit about data structures in the process.\nTo properly do this, you're going to want to use a stack. You'll want to pull out all instances of (, ), [, and ] (perhaps using a regular expression... hint) and go through the array that that generates:\nSay your file is like this: \n(this [is] foobar)\n\nYour regular expression will yield this array:\n['(', '[', ']', ')'] \n\nYou will pop(0) off of this array into a stack. \nAlgorithmically:\n1) Put all tags {(,),[,]} in an array.\n2) For each element in the array, pop(0) from it and push it onto your stack. Test it against the element before it. If it closes the element before it, then pop() twice from the array (eg, if you have '(' on the stack, and the next element to be pushed onto the stack is a ')', ')' closes '(', so you pop them both.) If it doesn't, continue. \n3) If your array is empty and your stack is empty when this is over, then your file is well formed. If it's not, then you have a poorly formed file {something like (foo[bar)] }.\nBonus: regular expression: REGEX = re.compile(r\"\\)\\(\\[\\]\"), REGEX.findall(your string to search). See more about regexes in Python here.\n", "All of these answers are wrong and will not work in all cases, so either use python parser e.g. tokenize etc or just use this\ncount = min(text.count(\"(\"), text.count(\")\"))\n" ]
[ 4, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "exception", "file", "parentheses", "python" ]
stackoverflow_0001878167_exception_file_parentheses_python.txt
Q: What signal can be connected to an initial dialog display in pyqt4 (qt) I have an application in which I would like to connect whatever signal is emitted when a pyqt4 dialog is displayed in order to do execute an initial method. I don't want the method to be called in the __init__ method for a number of reasons. I've spent quite some time searching but I have yet to find an answer. I'm sure there is a simple solution that because of my inexperience I am overlooking as I can do this in wxPython. Suggestions? A: There is no signal emitted on first display, instead, you will have to intercept the first resizeEvent or paintEvent by overloading these methods (as you don't want to initialize from the __init__ method). Another option would be to add your own showAndInit method, that initializes and then calls show.
What signal can be connected to an initial dialog display in pyqt4 (qt)
I have an application in which I would like to connect whatever signal is emitted when a pyqt4 dialog is displayed in order to do execute an initial method. I don't want the method to be called in the __init__ method for a number of reasons. I've spent quite some time searching but I have yet to find an answer. I'm sure there is a simple solution that because of my inexperience I am overlooking as I can do this in wxPython. Suggestions?
[ "There is no signal emitted on first display, instead, you will have to intercept the first resizeEvent or paintEvent by overloading these methods (as you don't want to initialize from the __init__ method).\nAnother option would be to add your own showAndInit method, that initializes and then calls show.\n" ]
[ 3 ]
[]
[]
[ "pyqt4", "python", "qt" ]
stackoverflow_0001878353_pyqt4_python_qt.txt
Q: Django & customising a legacy database I'm currently working on a project to implement a Django interface to an existing calendar application. The calendar application has MySQL as the backend DB. In our custom application we would like to modify/extend the data in one of the tables used by the existing calendar application e.g. # Auto-generated by inspectdb - table used by calendar application class CalendarEvent(models.Model:) name = models.CharField(max_length=80) start_time = models.DateTimeField() end_time = models.DateTimeField() # Manually created table class CustomCalendarEvent(models.Model:) code = models.CharField(max_length=80) # Mapped from name length = models.DateTimeField() # start_time - stop_time .... additional data .... We would also like our representation of the data to remain in sync with the existing calendar table i.e. when new entries are made in the calendar application these would automatically propagate to our custom table. I can think of a couple of obvious ways in which to do this (e.g. a synchronisation script initiated by cron or maybe MySQL triggers) but I don't feel that these solutions are particular elegant. One possibility is to use a Custom Manager for the CustomCalendarEvent and override the get_query_set functionality to also trigger a synchronisation function. Is this a legitimate use of Django CustomManagers? If not can anybody recommend an alternative approach to this problem? A: It appears that you are trying to extend CalendarEvent with more fields. First, I would make this change to CustomCalendarEvent: code = models.CharField(max_length=80) # Mapped from name calendar_event = models.ForeignKey(CalendarEvent) and if length is just calculating the difference in days between start_time and end_time I would remove it from CustomCalendarEvent and make it a callable in CalendarEvent instead (just a method that does the computation). You really don't want to be duplicating data between the two tables - which is what you get when you have name in CalendarEvent and code in CustomCalendarEvent. Updates to name will have to be synchronized to code and there is no reason for that if all that you want to do is extend the CalendarEvent table with more fields. Then you could override the save() and delete() methods for CalendarEvent to propagate the inserts/deletes change. Updates, I believe, do not matter in your case as CustomCalendarEvent is just an extension of CalendarEvent. Alternative approach: use a database insert trigger on CalendarEvent that propagates the entry to CustomCalendarEvent. I would still have the CustomCalendarEvent table have a foreign key into CalendarEvent instead of duplicating the data. EDIT: By the way, I would never use a custom manager to modify data like you are suggesting, even as a side effect of some read operation. Managers are about querying, not about modifying data. A: Why don't you use model inheritance? CustomCalendarEvent can inherit from CalendarEvent and add the new fields that way.
Django & customising a legacy database
I'm currently working on a project to implement a Django interface to an existing calendar application. The calendar application has MySQL as the backend DB. In our custom application we would like to modify/extend the data in one of the tables used by the existing calendar application e.g. # Auto-generated by inspectdb - table used by calendar application class CalendarEvent(models.Model:) name = models.CharField(max_length=80) start_time = models.DateTimeField() end_time = models.DateTimeField() # Manually created table class CustomCalendarEvent(models.Model:) code = models.CharField(max_length=80) # Mapped from name length = models.DateTimeField() # start_time - stop_time .... additional data .... We would also like our representation of the data to remain in sync with the existing calendar table i.e. when new entries are made in the calendar application these would automatically propagate to our custom table. I can think of a couple of obvious ways in which to do this (e.g. a synchronisation script initiated by cron or maybe MySQL triggers) but I don't feel that these solutions are particular elegant. One possibility is to use a Custom Manager for the CustomCalendarEvent and override the get_query_set functionality to also trigger a synchronisation function. Is this a legitimate use of Django CustomManagers? If not can anybody recommend an alternative approach to this problem?
[ "It appears that you are trying to extend CalendarEvent with more fields.\nFirst, I would make this change to CustomCalendarEvent:\ncode = models.CharField(max_length=80) # Mapped from name\ncalendar_event = models.ForeignKey(CalendarEvent)\nand if length is just calculating the difference in days between start_time and end_time I would remove it from CustomCalendarEvent and make it a callable in CalendarEvent instead (just a method that does the computation).\nYou really don't want to be duplicating data between the two tables - which is what you get when you have name in CalendarEvent and code in CustomCalendarEvent. Updates to name will have to be synchronized to code and there is no reason for that if all that you want to do is extend the CalendarEvent table with more fields.\nThen you could override the save() and delete() methods for CalendarEvent to propagate the inserts/deletes change. Updates, I believe, do not matter in your case as CustomCalendarEvent is just an extension of CalendarEvent.\nAlternative approach: use a database insert trigger on CalendarEvent that propagates the entry to CustomCalendarEvent. I would still have the CustomCalendarEvent table have a foreign key into CalendarEvent instead of duplicating the data.\n\nEDIT: By the way, I would never use a custom manager to modify data like you are suggesting, even as a side effect of some read operation. Managers are about querying, not about modifying data.\n", "Why don't you use model inheritance? CustomCalendarEvent can inherit from CalendarEvent and add the new fields that way.\n" ]
[ 2, 2 ]
[]
[]
[ "django", "legacy_database", "python" ]
stackoverflow_0001876163_django_legacy_database_python.txt
Q: Python Ascendance and descendance I apologize in advance for the basic level of my question. I would like to the print the: total number and identity of nodes that have 0 child, 1 child, 2 children, 3 children. total number of node that have 0 parent, 1 parent, 2 parents, 3 parents. here is my simple script. thanks. Vicinci search = [] search += search_nodes() node_father = [] node_child = [] for i in search: node_father += i.get_parents() node_child += i.get_children() print "Total of nodes", len(search) print "Total of parents", len(node_father) print "Total of children", len(node_child) A: You can either create a map and do it yourself or use itertools.groupBy 1) Do-it-yourself way: nodes_by_num_children={} for node in search: children=len(node.get_children()) if children not in nodes_by_num_children: nodes_by_num_children[children]=[] nodes_by_num_children[children].append(node) for num, nodes in nodes_by_num_children.iteritems(): print num for node in nodes: print node 2) Itertools way: import itertools search.sort(key=lambda x: len(x.get_children())) for num_children,nodes in itertools.groupBy(search,lambda x: len(x.get_children())): print num_children for node in nodes: print node A: from collections import defaultdict by_parents = defaultdict(list) by_children = defaultdict(list) for node in search_nodes(): parents = node.get_parents() by_parents[len(parents)].append(node) children = node.get_children() by_children[len(children)].append(node)
Python Ascendance and descendance
I apologize in advance for the basic level of my question. I would like to the print the: total number and identity of nodes that have 0 child, 1 child, 2 children, 3 children. total number of node that have 0 parent, 1 parent, 2 parents, 3 parents. here is my simple script. thanks. Vicinci search = [] search += search_nodes() node_father = [] node_child = [] for i in search: node_father += i.get_parents() node_child += i.get_children() print "Total of nodes", len(search) print "Total of parents", len(node_father) print "Total of children", len(node_child)
[ "You can either create a map and do it yourself or use itertools.groupBy\n1) Do-it-yourself way:\nnodes_by_num_children={}\nfor node in search:\n children=len(node.get_children())\n if children not in nodes_by_num_children:\n nodes_by_num_children[children]=[]\n nodes_by_num_children[children].append(node)\n\nfor num, nodes in nodes_by_num_children.iteritems():\n print num\n for node in nodes:\n print node\n\n2) Itertools way:\nimport itertools\nsearch.sort(key=lambda x: len(x.get_children()))\nfor num_children,nodes in itertools.groupBy(search,lambda x: len(x.get_children())):\n print num_children \n for node in nodes:\n print node\n\n", "from collections import defaultdict\n\nby_parents = defaultdict(list)\nby_children = defaultdict(list)\nfor node in search_nodes():\n parents = node.get_parents()\n by_parents[len(parents)].append(node)\n children = node.get_children()\n by_children[len(children)].append(node)\n\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001879851_python.txt
Q: How to run the program generated by pyuic4? I'm new to PyQt though I know python a bit.. I wanted to Qt designer for GUI programming since it'll make my job easier. I've taken a simple dialog in Qt designer and converted using pyuic4. from PyQt4 import QtCore, QtGui class Ui_Form1(object): def setupUi(self, Form1): Form1.setObjectName("Form1") Form1.resize(495, 364) self.listWidget = QtGui.QListWidget(Form1) self.listWidget.setGeometry(QtCore.QRect(60, 100, 221, 111)) self.listWidget.setObjectName("listWidget") self.lineEdit = QtGui.QLineEdit(Form1) self.lineEdit.setGeometry(QtCore.QRect(60, 250, 221, 26)) self.lineEdit.setObjectName("lineEdit") self.pushButton = QtGui.QPushButton(Form1) self.pushButton.setGeometry(QtCore.QRect(350, 170, 92, 28)) self.pushButton.setAutoDefault(False) self.pushButton.setObjectName("pushButton") self.retranslateUi(Form1) QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.listWidget.clear) QtCore.QMetaObject.connectSlotsByName(Form1) def retranslateUi(self, Form1): Form1.setWindowTitle(QtGui.QApplication.translate("Form1", "Form1", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("Form1", "X", None, QtGui.QApplication.UnicodeUTF8)) I want to run this program. How to run this program from this file by importing this? I know it's a very basic question. A: You may pass -x parameter to pyuic. It will generate addtional code to make the script executable. In real application you should better write a subclass of QMainWindow which could look like this: # Store this code in the file MyMainWindow.py from PyQt4.QtGui import * class MyMainWindow(QMainWindow): def __init__(self, ui_layout): QMainWindow.__init__(self) self.ui = ui_layout ui_layout.setupUi(self) And also create a main executable script in the same directory as MyMainWindow.py: from PyQt4.QtGui import * from MyMainWindow import * from Form1 import * # replace Form1 the name of your generated file import sys app = QApplication(sys.argv) window = MyMainWindow(Ui_Form1()) window.show() sys.exit(app.exec_()) Then run this last script to launch the program.
How to run the program generated by pyuic4?
I'm new to PyQt though I know python a bit.. I wanted to Qt designer for GUI programming since it'll make my job easier. I've taken a simple dialog in Qt designer and converted using pyuic4. from PyQt4 import QtCore, QtGui class Ui_Form1(object): def setupUi(self, Form1): Form1.setObjectName("Form1") Form1.resize(495, 364) self.listWidget = QtGui.QListWidget(Form1) self.listWidget.setGeometry(QtCore.QRect(60, 100, 221, 111)) self.listWidget.setObjectName("listWidget") self.lineEdit = QtGui.QLineEdit(Form1) self.lineEdit.setGeometry(QtCore.QRect(60, 250, 221, 26)) self.lineEdit.setObjectName("lineEdit") self.pushButton = QtGui.QPushButton(Form1) self.pushButton.setGeometry(QtCore.QRect(350, 170, 92, 28)) self.pushButton.setAutoDefault(False) self.pushButton.setObjectName("pushButton") self.retranslateUi(Form1) QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.listWidget.clear) QtCore.QMetaObject.connectSlotsByName(Form1) def retranslateUi(self, Form1): Form1.setWindowTitle(QtGui.QApplication.translate("Form1", "Form1", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("Form1", "X", None, QtGui.QApplication.UnicodeUTF8)) I want to run this program. How to run this program from this file by importing this? I know it's a very basic question.
[ "You may pass -x parameter to pyuic. It will generate addtional code to make the script executable.\n\nIn real application you should better write a subclass of QMainWindow which could look like this:\n# Store this code in the file MyMainWindow.py\nfrom PyQt4.QtGui import *\n\nclass MyMainWindow(QMainWindow):\n def __init__(self, ui_layout):\n QMainWindow.__init__(self)\n\n self.ui = ui_layout\n ui_layout.setupUi(self)\n\nAnd also create a main executable script in the same directory as MyMainWindow.py:\nfrom PyQt4.QtGui import *\nfrom MyMainWindow import *\nfrom Form1 import * # replace Form1 the name of your generated file\nimport sys\n\napp = QApplication(sys.argv)\n\nwindow = MyMainWindow(Ui_Form1())\nwindow.show()\n\nsys.exit(app.exec_())\n\nThen run this last script to launch the program.\n" ]
[ 6 ]
[]
[]
[ "pyqt", "python", "qt", "qt_designer" ]
stackoverflow_0001880039_pyqt_python_qt_qt_designer.txt
Q: Hashing Multiple Files Problem Specification: Given a directory, I want to iterate through the directory and its non-hidden sub-directories,  and add a whirlpool hash into the non-hidden file's names. If the script is re-run it would would replace an old hash with a new one. <filename>.<extension>   ==>  <filename>.<a-whirlpool-hash>.<extension> <filename>.<old-hash>.<extension>   ==>  <filename>.<new-hash>.<extension> Question: a) How would you do this? b) Out of the all methods available to you, what makes your method most suitable? Verdict: Thanks all, I have chosen SeigeX's answer for it's speed and portability. It is emprically quicker than the other bash variants,  and it worked without alteration on my Mac OS X machine. A: Updated to fix: 1. File names with '[' or ']' in their name (really, any character now. See comment) 2. Handling of md5sum when hashing a file with a backslash or newline in its name 3. Functionized hash-checking algo for modularity 4. Refactored hash-checking logic to remove double-negatives #!/bin/bash if (($# != 1)) || ! [[ -d "$1" ]]; then echo "Usage: $0 /path/to/directory" exit 1 fi is_hash() { md5=${1##*.} # strip prefix [[ "$md5" == *[^[:xdigit:]]* || ${#md5} -lt 32 ]] && echo "$1" || echo "${1%.*}" } while IFS= read -r -d $'\0' file; do read hash junk < <(md5sum "$file") basename="${file##*/}" dirname="${file%/*}" pre_ext="${basename%.*}" ext="${basename:${#pre_ext}}" # File already hashed? pre_ext=$(is_hash "$pre_ext") ext=$(is_hash "$ext") mv "$file" "${dirname}/${pre_ext}.${hash}${ext}" 2> /dev/null done < <(find "$1" -path "*/.*" -prune -o \( -type f -print0 \)) This code has the following benefits over other entries thus far It is fully compliant with Bash versions 2.0.2 and beyond No superfluous calls to other binaries like sed or grep; uses builtin parameter expansion instead Uses process substitution for 'find' instead of a pipe, no sub-shell is made this way Takes the directory to work on as an argument and does a sanity check on it Uses $() rather than `` notation for command substitution, the latter is deprecated Works with files with spaces Works with files with newlines Works with files with multiple extensions Works with files with no extension Does not traverse hidden directories Does NOT skip pre-hashed files, it will recalculate the hash as per the spec Test Tree $ tree -a a a |-- .hidden_dir | `-- foo |-- b | `-- c.d | |-- f | |-- g.5236b1ab46088005ed3554940390c8a7.ext | |-- h.d41d8cd98f00b204e9800998ecf8427e | |-- i.ext1.5236b1ab46088005ed3554940390c8a7.ext2 | `-- j.ext1.ext2 |-- c.ext^Mnewline | |-- f | `-- g.with[or].ext `-- f^Jnewline.ext 4 directories, 9 files Result $ tree -a a a |-- .hidden_dir | `-- foo |-- b | `-- c.d | |-- f.d41d8cd98f00b204e9800998ecf8427e | |-- g.d41d8cd98f00b204e9800998ecf8427e.ext | |-- h.d41d8cd98f00b204e9800998ecf8427e | |-- i.ext1.d41d8cd98f00b204e9800998ecf8427e.ext2 | `-- j.ext1.d41d8cd98f00b204e9800998ecf8427e.ext2 |-- c.ext^Mnewline | |-- f.d41d8cd98f00b204e9800998ecf8427e | `-- g.with[or].d41d8cd98f00b204e9800998ecf8427e.ext `-- f^Jnewline.d3b07384d113edec49eaa6238ad5ff00.ext 4 directories, 9 files A: #!/bin/bash find -type f -print0 | while read -d $'\0' file do md5sum=`md5sum "${file}" | sed -r 's/ .*//'` filename=`echo "${file}" | sed -r 's/\.[^./]*$//'` extension="${file:${#filename}}" filename=`echo "${filename}" | sed -r 's/\.md5sum-[^.]+//'` if [[ "${file}" != "${filename}.md5sum-${md5sum}${extension}" ]]; then echo "Handling file: ${file}" mv "${file}" "${filename}.md5sum-${md5sum}${extension}" fi done Tested on files containing spaces like 'a b' Tested on files containing multiple extensions like 'a.b.c' Tested with directories containing spaces and/or dots. Tested on files containing no extension inside directories containing dots, such as 'a.b/c' Updated: Now updates hashes if the file changes. Key points: Use of print0 piped to while read -d $'\0', to correctly handle spaces in file names. md5sum can be replaced with your favourite hash function. The sed removes the first space and everything after it from the output of md5sum. The base filename is extracted using a regular expression that finds the last period that isn't followed by another slash (so that periods in directory names aren't counted as part of the extension). The extension is found by using a substring with starting index as the length of the base filename. A: The logic of the requirements is complex enough to justify the use of Python instead of bash. It should provide a more readable, extensible, and maintainable solution. #!/usr/bin/env python import hashlib, os def ishash(h, size): """Whether `h` looks like hash's hex digest.""" if len(h) == size: try: int(h, 16) # whether h is a hex number return True except ValueError: return False for root, dirs, files in os.walk("."): dirs[:] = [d for d in dirs if not d.startswith(".")] # skip hidden dirs for path in (os.path.join(root, f) for f in files if not f.startswith(".")): suffix = hash_ = "." + hashlib.md5(open(path).read()).hexdigest() hashsize = len(hash_) - 1 # extract old hash from the name; add/replace the hash if needed barepath, ext = os.path.splitext(path) # ext may be empty if not ishash(ext[1:], hashsize): suffix += ext # add original extension barepath, oldhash = os.path.splitext(barepath) if not ishash(oldhash[1:], hashsize): suffix = oldhash + suffix # preserve 2nd (not a hash) extension else: # ext looks like a hash oldhash = ext if hash_ != oldhash: # replace old hash by new one os.rename(path, barepath+suffix) Here's a test directory tree. It contains: files without extension inside directories with a dot in their name filename which already has a hash in it (test on idempotency) filename with two extensions newlines in names $ tree a a |-- b | `-- c.d | |-- f | |-- f.ext1.ext2 | `-- g.d41d8cd98f00b204e9800998ecf8427e |-- c.ext^Mnewline | `-- f `-- f^Jnewline.ext1 7 directories, 5 files Result $ tree a a |-- b | `-- c.d | |-- f.0bee89b07a248e27c83fc3d5951213c1 | |-- f.ext1.614dd0e977becb4c6f7fa99e64549b12.ext2 | `-- g.d41d8cd98f00b204e9800998ecf8427e |-- c.ext^Mnewline | `-- f.0bee89b07a248e27c83fc3d5951213c1 `-- f^Jnewline.b6fe8bb902ca1b80aaa632b776d77f83.ext1 7 directories, 5 files The solution works correctly for all cases. Whirlpool hash is not in Python's stdlib, but there are both pure Python and C extensions that support it e.g., python-mhash. To install it: $ sudo apt-get install python-mhash To use it: import mhash print mhash.MHASH(mhash.MHASH_WHIRLPOOL, "text to hash here").hexdigest() Output: cbdca4520cc5c131fc3a86109dd23fee2d7ff7be56636d398180178378944a4f41480b938608ae98da7eccbf39a4c79b83a8590c4cb1bace5bc638fc92b3e653 Invoking whirlpooldeep in Python from subprocess import PIPE, STDOUT, Popen def getoutput(cmd): return Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate()[0] hash_ = getoutput(["whirlpooldeep", "-q", path]).rstrip() git can provide with leverage for the problems that need to track set of files based on their hashes. A: I wasn't really happy with my first answer, since as I said there, this problem looks like it's best solved with perl. You already said in one edit of your question that you have perl on the OS X machine you want to run this on, so I gave it a shot. It's hard to get it all right in bash, i.e. avoiding any quoting problems with odd filenames, and behaving nicely with corner-case filenames. So here it is in perl, a complete solution to your problem. It runs over all the files/directories listed on its command line. #!/usr/bin/perl -w # whirlpool-rename.pl # 2009 Peter Cordes <peter@cordes.ca>. Share and Enjoy! use Fcntl; # for O_BINARY use File::Find; use Digest::Whirlpool; # find callback, called once per directory entry # $_ is the base name of the file, and we are chdired to that directory. sub whirlpool_rename { print "find: $_\n"; # my @components = split /\.(?:[[:xdigit:]]{128})?/; # remove .hash while we're at it my @components = split /\.(?!\.|$)/, $_, -1; # -1 to not leave out trailing dots if (!$components[0] && $_ ne ".") { # hidden file/directory $File::Find::prune = 1; return; } # don't follow symlinks or process non-regular-files return if (-l $_ || ! -f _); my $digest; eval { sysopen(my $fh, $_, O_RDONLY | O_BINARY) or die "$!"; $digest = Digest->new( 'Whirlpool' )->addfile($fh); }; if ($@) { # exception-catching structure from whirlpoolsum, distributed with Digest::Whirlpool. warn "whirlpool: couldn't hash $_: $!\n"; return; } # strip old hashes from the name. not done during split only in the interests of readability @components = grep { !/^[[:xdigit:]]{128}$/ } @components; if ($#components == 0) { push @components, $digest->hexdigest; } else { my $ext = pop @components; push @components, $digest->hexdigest, $ext; } my $newname = join('.', @components); return if $_ eq $newname; print "rename $_ -> $newname\n"; if (-e $newname) { warn "whirlpool: clobbering $newname\n"; # maybe unlink $_ and return if $_ is older than $newname? # But you'd better check that $newname has the right contents then... } # This could be link instead of rename, but then you'd have to handle directories, and you can't make hardlinks across filesystems rename $_, $newname or warn "whirlpool: couldn't rename $_ -> $newname: $!\n"; } #main $ARGV[0] = "." if !@ARGV; # default to current directory find({wanted => \&whirlpool_rename, no_chdir => 0}, @ARGV ); Advantages: - actually uses whirlpool, so you can use this exact program directly. (after installing libperl-digest-whirlpool). Easy to change to any digest function you want, because instead of different programs with different output formats, you have the perl Digest common interface. implements all other requirements: ignore hidden files (and files under hidden directories). able to handle any possible filename without error or security problem. (Several people got this right in their shell scripts). follows best practices for traversing a directory tree, by chdiring down into each directory (like my previous answer, with find -execdir). This avoids problems with PATH_MAX, and with directories being renamed while you're running. clever handling of filenames that end with . foo..txt... -> foo..hash.txt... Handles old filenames containing hashes already without renaming them and then renaming them back. (It strips any sequence of 128 hex digits that's surrounded by "." characters.) In the everything-correct case, no disk write activity happens, just reads of every file. Your current solution runs mv twice in the already-correctly-named case, causing directory metadata writes. And being slower, because that's two processes that have to be execced. efficient. No programs are fork/execed, while most of the solutions that would actually work ended up having to sed something per-file. Digest::Whirlpool is implemented with a natively-compiled shared lib, so it's not slow pure-perl. This should be faster than running a program on every file, esp. for small files. Perl supports UTF-8 strings, so filenames with non-ascii characters shouldn't be a problem. (not sure if any multi-byte sequences in UTF-8 could include the byte that means ASCII '.' on its own. If that is possible, then you need UTF-8 aware string handling. sed doesn't know UTF-8. Bash's glob expressions may.) easily extensible. When you go to put this into a real program, and you want to handle more corner cases, you can do so quite easily. e.g. decide what to do when you want to rename a file but the hash-named filename already exists. good error reporting. Most shell scripts have this, though, by passing along errors from the progs they run. A: find . -type f -print | while read file do hash=`$hashcommand "$file"` filename=${file%.*} extension=${file##*.} mv $file "$filename.$hash.$extension" done A: You might want to store the results in one file, like in find . -type f -exec md5sum {} \; > MD5SUMS If you really want one file per hash: find . -type f | while read f; do g=`md5sum $f` > $f.md5; done or even find . -type f | while read f; do g=`md5sum $f | awk '{print $1}'`; echo "$g $f"> $f-$g.md5; done A: In sh or bash, two versions. One limits itself to files with extensions... hash () { #openssl md5 t.sh | sed -e 's/.* //' whirlpool "$f" } find . -type f -a -name '*.*' | while read f; do # remove the echo to run this for real echo mv "$f" "${f%.*}.whirlpool-`hash "$f"`.${f##*.}" done Testing... ... mv ./bash-4.0/signames.h ./bash-4.0/signames.whirlpool-d71b117a822394a5b273ea6c0e3f4dc045b1098326d39864564f1046ab7bd9296d5533894626288265a1f70638ee3ecce1f6a22739b389ff7cb1fa48c76fa166.h ... And this more complex version processes all plain files, with or without extensions, with or without spaces and odd characters, etc, etc... hash () { #openssl md5 t.sh | sed -e 's/.* //' whirlpool "$f" } find . -type f | while read f; do name=${f##*/} case "$name" in *.*) extension=".${name##*.}" ;; *) extension= ;; esac # remove the echo to run this for real echo mv "$f" "${f%/*}/${name%.*}.whirlpool-`hash "$f"`$extension" done A: Here's my take on it, in bash. Features: skips non-regular files; correctly deals with files with weird characters (i.e. spaces) in their names; deals with extensionless filenames; skips already-hashed files, so it can be run repeatedly (although if files are modified between runs, it adds the new hash rather than replacing the old one). I wrote it using md5 -q as the hash function; you should be able to replace this with anything else, as long as it only outputs the hash, not something like filename => hash. find -x . -type f -print0 | while IFS="" read -r -d $'\000' file; do hash="$(md5 -q "$file")" # replace with your favorite hash function [[ "$file" == *."$hash" ]] && continue # skip files that already end in their hash dirname="$(dirname "$file")" basename="$(basename "$file")" base="${basename%.*}" [[ "$base" == *."$hash" ]] && continue # skip files that already end in hash + extension if [[ "$basename" == "$base" ]]; then extension="" else extension=".${basename##*.}" fi mv "$file" "$dirname/$base.$hash$extension" done A: whirlpool isn't a very common hash. You'll probably have to install a program to compute it. e.g. Debian/Ubuntu include a "whirlpool" package. The program prints the hash of one file by itself. apt-cache search whirlpool shows that some other packages support it, including the interesting md5deep. Some of the earlier anwsers will fail on filenames with spaces in them. If this is the case, but your files don't have any newlines in the filename, then you can safely use \n as a delimiter. oldifs="$IFS" IFS=" " for i in $(find -type f); do echo "$i";done #output # ./base # ./base2 # ./normal.ext # ./trick.e "xt # ./foo bar.dir ext/trick' (name "- }$foo.ext{}.ext2 IFS="$oldifs" try without setting IFS to see why it matters. I was going to try something with IFS="."; find -print0 | while read -a array, to split on "." characters, but I normally never use array variables. There's no easy way that I see in the man page to insert the hash as the second-last array index, and push down the last element (the file extension, if it had one.) Any time bash array variables look interesting, I know it's time to do what I'm doing in perl instead! See the gotchas for using read: http://tldp.org/LDP/abs/html/gotchas.html#BADREAD0 I decided to use another technique I like: find -exec sh -c. It's the safest, since you're not parsing filenames. This should do the trick: find -regextype posix-extended -type f -not -regex '.*\.[a-fA-F0-9]{128}.*' \ -execdir bash -c 'for i in "${@#./}";do hash=$(whirlpool "$i"); ext=".${i##*.}"; base="${i%.*}"; [ "$base" = "$i" ] && ext=""; newname="$base.$hash$ext"; echo "ext:$ext $i -> $newname"; false mv --no-clobber "$i" "$newname";done' \ dummy {} + # take out the "false" before the mv, and optionally take out the echo. # false ignores its arguments, so it's there so you can # run this to see what will happen without actually renaming your files. -execdir bash -c 'cmd' dummy {} + has the dummy arg there because the first arg after the command becomes $0 in the shell's positional parameters, not part of "$@" that for loops over. I use execdir instead of exec so I don't have to deal with directory names (or the possibility of exceeding PATH_MAX for nested dirs with long names, when the actual filenames are all short enough.) -not -regex prevents this from being applied twice to the same file. Although whirlpool is an extremely long hash, and mv says File name too long if I run it twice without that check. (on an XFS filesystem.) Files with no extension get basename.hash. I had to check specially to avoid appending a trailing ., or getting the basename as the extension. ${@#./} strips out the leading ./ that find puts in front of every filename, so there is no "." in the whole string for files with no extension. mv --no-clobber may be a GNU extension. If you don't have GNU mv, do something else if you want to avoid deleting existing files (e.g. you run this once, some of the same file are added to the directory with their old names; you run it again.) OTOH, if you want that behaviour, just take it out. My solution should work even when filenames contain a newline (they can, you know!), or any other possible character. It would be faster and easier in perl, but you asked for shell. wallenborn's solution for making one file with all the checksums (instead of renaming the original) is pretty good, but inefficient. Don't run md5sum once per file, run it on as many files at once as will fit on its command line: find dir -type f -print0 | xargs -0 md5sum > dir.md5 or with GNU find, xargs is built in (note the + instead of ';') find dir -type f -exec md5sum {} + > dir.md5 if you just use find -print | xargs -d'\n', you will be screwed up by file names with quote marks in them, so be careful. If you don't know what files you might someday run this script on, always try to use print0 or -exec. This is esp. true if filenames are supplied by untrusted users (i.e. could be an attack vector on your server.) A: Hm, interesting problem. Try the following (the mktest function is just for testing -- TDD for bash! :) Edit: Added support for whirlpool hashes. code cleanup better quoting of filenames changed array-syntax for test part-- should now work with most korn-like shells. Note that pdksh does not support :-based parameter expansion (or rather it means something else) Note also that when in md5-mode it fails for filenames with whirlpool-like hashes, and possibly vice-versa. #!/usr/bin/env bash #Tested with: # GNU bash, version 4.0.28(1)-release (x86_64-pc-linux-gnu) # ksh (AT&T Research) 93s+ 2008-01-31 # mksh @(#)MIRBSD KSH R39 2009/08/01 Debian 39.1-4 # Does not work with pdksh, dash DEFAULT_SUM="md5" #Takes a parameter, as root path # as well as an optional parameter, the hash function to use (md5 or wp for whirlpool). main() { case $2 in "wp") export SUM="wp" ;; "md5") export SUM="md5" ;; *) export SUM=$DEFAULT_SUM ;; esac # For all visible files in all visible subfolders, move the file # to a name including the correct hash: find $1 -type f -not -regex '.*/\..*' -exec $0 hashmove '{}' \; } # Given a file named in $1 with full path, calculate it's hash. # Output the filname, with the hash inserted before the extention # (if any) -- or: replace an existing hash with the new one, # if a hash already exist. hashname_md5() { pathname="$1" full_hash=`md5sum "$pathname"` hash=${full_hash:0:32} filename=`basename "$pathname"` prefix=${filename%%.*} suffix=${filename#$prefix} #If the suffix starts with something that looks like an md5sum, #remove it: suffix=`echo $suffix|sed -r 's/\.[a-z0-9]{32}//'` echo "$prefix.$hash$suffix" } # Same as hashname_md5 -- but uses whirlpool hash. hashname_wp() { pathname="$1" hash=`whirlpool "$pathname"` filename=`basename "$pathname"` prefix=${filename%%.*} suffix=${filename#$prefix} #If the suffix starts with something that looks like an md5sum, #remove it: suffix=`echo $suffix|sed -r 's/\.[a-z0-9]{128}//'` echo "$prefix.$hash$suffix" } #Given a filepath $1, move/rename it to a name including the filehash. # Try to replace an existing hash, an not move a file if no update is # needed. hashmove() { pathname="$1" filename=`basename "$pathname"` path="${pathname%%/$filename}" case $SUM in "wp") hashname=`hashname_wp "$pathname"` ;; "md5") hashname=`hashname_md5 "$pathname"` ;; *) echo "Unknown hash requested" exit 1 ;; esac if [[ "$filename" != "$hashname" ]] then echo "renaming: $pathname => $path/$hashname" mv "$pathname" "$path/$hashname" else echo "$pathname up to date" fi } # Create som testdata under /tmp mktest() { root_dir=$(tempfile) rm "$root_dir" mkdir "$root_dir" i=0 test_files[$((i++))]='test' test_files[$((i++))]='testfile, no extention or spaces' test_files[$((i++))]='.hidden' test_files[$((i++))]='a hidden file' test_files[$((i++))]='test space' test_files[$((i++))]='testfile, no extention, spaces in name' test_files[$((i++))]='test.txt' test_files[$((i++))]='testfile, extention, no spaces in name' test_files[$((i++))]='test.ab8e460eac3599549cfaa23a848635aa.txt' test_files[$((i++))]='testfile, With (wrong) md5sum, no spaces in name' test_files[$((i++))]='test spaced.ab8e460eac3599549cfaa23a848635aa.txt' test_files[$((i++))]='testfile, With (wrong) md5sum, spaces in name' test_files[$((i++))]='test.8072ec03e95a26bb07d6e163c93593283fee032db7265a29e2430004eefda22ce096be3fa189e8988c6ad77a3154af76f582d7e84e3f319b798d369352a63c3d.txt' test_files[$((i++))]='testfile, With (wrong) whirlpoolhash, no spaces in name' test_files[$((i++))]='test spaced.8072ec03e95a26bb07d6e163c93593283fee032db7265a29e2430004eefda22ce096be3fa189e8988c6ad77a3154af76f582d7e84e3f319b798d369352a63c3d.txt'] test_files[$((i++))]='testfile, With (wrong) whirlpoolhash, spaces in name' test_files[$((i++))]='test space.txt' test_files[$((i++))]='testfile, extention, spaces in name' test_files[$((i++))]='test multi-space .txt' test_files[$((i++))]='testfile, extention, multiple consequtive spaces in name' test_files[$((i++))]='test space.h' test_files[$((i++))]='testfile, short extention, spaces in name' test_files[$((i++))]='test space.reallylong' test_files[$((i++))]='testfile, long extention, spaces in name' test_files[$((i++))]='test space.reallyreallyreallylong.tst' test_files[$((i++))]='testfile, long extention, double extention, might look like hash, spaces in name' test_files[$((i++))]='utf8test1 - æeiaæå.txt' test_files[$((i++))]='testfile, extention, utf8 characters, spaces in name' test_files[$((i++))]='utf8test1 - 漢字.txt' test_files[$((i++))]='testfile, extention, Japanese utf8 characters, spaces in name' for s in . sub1 sub2 sub1/sub3 .hidden_dir do #note -p not needed as we create dirs top-down #fails for "." -- but the hack allows us to use a single loop #for creating testdata in all dirs mkdir $root_dir/$s dir=$root_dir/$s i=0 while [[ $i -lt ${#test_files[*]} ]] do filename=${test_files[$((i++))]} echo ${test_files[$((i++))]} > "$dir/$filename" done done echo "$root_dir" } # Run test, given a hash-type as first argument runtest() { sum=$1 root_dir=$(mktest) echo "created dir: $root_dir" echo "Running first test with hashtype $sum:" echo main $root_dir $sum echo echo "Running second test:" echo main $root_dir $sum echo "Updating all files:" find $root_dir -type f | while read f do echo "more content" >> "$f" done echo echo "Running final test:" echo main $root_dir $sum #cleanup: rm -r $root_dir } # Test md5 and whirlpool hashes on generated data. runtests() { runtest md5 runtest wp } #For in order to be able to call the script recursively, without splitting off # functions to separate files: case "$1" in 'test') runtests ;; 'hashname') hashname "$2" ;; 'hashmove') hashmove "$2" ;; 'run') main "$2" "$3" ;; *) echo "Use with: $0 test - or if you just want to try it on a folder:" echo " $0 run path (implies md5)" echo " $0 run md5 path" echo " $0 run wp path" ;; esac A: In response to your updated question: If anyone can comment on how I can avoid looking in hidden directories with my BASH Script, it would be much appreciated. You can avoid hidden directories with find by using find -name '.?*' -prune -o \( -type f -print0 \) -name '.*' -prune will prune ".", and stop without doing anything. :/ I'd still recommend my Perl version, though. I updated it... You may still need to install Digest::Whirlpool from CPAN, though. A: using zsh: $ ls a.txt b.txt c.txt The magic: $ FILES=**/*(.) $ # */ stupid syntax coloring thinks this is a comment $ for f in $FILES; do hash=`md5sum $f | cut -f1 -d" "`; mv $f "$f:r.$hash.$f:e"; done $ ls a.60b725f10c9c85c70d97880dfe8191b3.txt b.3b5d5c3712955042212316173ccf37be.txt c.2cd6ee2c70b0bde53fbe6cac3c8b8bb1.txt Happy deconstruction! Edit: added files in subdirectories and quotes around mv argument A: Ruby: #!/usr/bin/env ruby require 'digest/md5' Dir.glob('**/*') do |f| next unless File.file? f next if /\.md5sum-[0-9a-f]{32}/ =~ f md5sum = Digest::MD5.file f newname = "%s/%s.md5sum-%s%s" % [File.dirname(f), File.basename(f,'.*'), md5sum, File.extname(f)] File.rename f, newname end Handles filenames that have spaces, no extension, and that have already been hashed. Ignores hidden files and directories — add File::FNM_DOTMATCH as the second argument of glob if that's desired.
Hashing Multiple Files
Problem Specification: Given a directory, I want to iterate through the directory and its non-hidden sub-directories,  and add a whirlpool hash into the non-hidden file's names. If the script is re-run it would would replace an old hash with a new one. <filename>.<extension>   ==>  <filename>.<a-whirlpool-hash>.<extension> <filename>.<old-hash>.<extension>   ==>  <filename>.<new-hash>.<extension> Question: a) How would you do this? b) Out of the all methods available to you, what makes your method most suitable? Verdict: Thanks all, I have chosen SeigeX's answer for it's speed and portability. It is emprically quicker than the other bash variants,  and it worked without alteration on my Mac OS X machine.
[ "Updated to fix:\n1. File names with '[' or ']' in their name (really, any character now. See comment)\n2. Handling of md5sum when hashing a file with a backslash or newline in its name\n3. Functionized hash-checking algo for modularity\n4. Refactored hash-checking logic to remove double-negatives\n#!/bin/bash\nif (($# != 1)) || ! [[ -d \"$1\" ]]; then\n echo \"Usage: $0 /path/to/directory\"\n exit 1\nfi\n\nis_hash() {\n md5=${1##*.} # strip prefix\n [[ \"$md5\" == *[^[:xdigit:]]* || ${#md5} -lt 32 ]] && echo \"$1\" || echo \"${1%.*}\"\n}\n\nwhile IFS= read -r -d $'\\0' file; do\n read hash junk < <(md5sum \"$file\")\n basename=\"${file##*/}\"\n dirname=\"${file%/*}\"\n pre_ext=\"${basename%.*}\"\n ext=\"${basename:${#pre_ext}}\"\n\n # File already hashed?\n pre_ext=$(is_hash \"$pre_ext\")\n ext=$(is_hash \"$ext\")\n\n mv \"$file\" \"${dirname}/${pre_ext}.${hash}${ext}\" 2> /dev/null\n\ndone < <(find \"$1\" -path \"*/.*\" -prune -o \\( -type f -print0 \\))\n\nThis code has the following benefits over other entries thus far\n\nIt is fully compliant with Bash versions 2.0.2 and beyond\nNo superfluous calls to other binaries like sed or grep; uses builtin parameter expansion instead\nUses process substitution for 'find' instead of a pipe, no sub-shell is made this way\nTakes the directory to work on as an argument and does a sanity check on it\nUses $() rather than `` notation for command substitution, the latter is deprecated\nWorks with files with spaces\nWorks with files with newlines\nWorks with files with multiple extensions\nWorks with files with no extension\nDoes not traverse hidden directories\nDoes NOT skip pre-hashed files, it will recalculate the hash as per the spec\n\nTest Tree\n\n$ tree -a a\na\n|-- .hidden_dir\n| `-- foo\n|-- b\n| `-- c.d\n| |-- f\n| |-- g.5236b1ab46088005ed3554940390c8a7.ext\n| |-- h.d41d8cd98f00b204e9800998ecf8427e\n| |-- i.ext1.5236b1ab46088005ed3554940390c8a7.ext2\n| `-- j.ext1.ext2\n|-- c.ext^Mnewline\n| |-- f\n| `-- g.with[or].ext\n`-- f^Jnewline.ext\n\n4 directories, 9 files \n\nResult\n\n$ tree -a a\na\n|-- .hidden_dir\n| `-- foo\n|-- b\n| `-- c.d\n| |-- f.d41d8cd98f00b204e9800998ecf8427e\n| |-- g.d41d8cd98f00b204e9800998ecf8427e.ext\n| |-- h.d41d8cd98f00b204e9800998ecf8427e\n| |-- i.ext1.d41d8cd98f00b204e9800998ecf8427e.ext2\n| `-- j.ext1.d41d8cd98f00b204e9800998ecf8427e.ext2\n|-- c.ext^Mnewline\n| |-- f.d41d8cd98f00b204e9800998ecf8427e\n| `-- g.with[or].d41d8cd98f00b204e9800998ecf8427e.ext\n`-- f^Jnewline.d3b07384d113edec49eaa6238ad5ff00.ext\n\n4 directories, 9 files\n\n", "#!/bin/bash\nfind -type f -print0 | while read -d $'\\0' file\ndo\n md5sum=`md5sum \"${file}\" | sed -r 's/ .*//'`\n filename=`echo \"${file}\" | sed -r 's/\\.[^./]*$//'`\n extension=\"${file:${#filename}}\"\n filename=`echo \"${filename}\" | sed -r 's/\\.md5sum-[^.]+//'`\n if [[ \"${file}\" != \"${filename}.md5sum-${md5sum}${extension}\" ]]; then\n echo \"Handling file: ${file}\"\n mv \"${file}\" \"${filename}.md5sum-${md5sum}${extension}\"\n fi\ndone\n\n\nTested on files containing spaces like 'a b'\nTested on files containing multiple extensions like 'a.b.c'\nTested with directories containing spaces and/or dots.\nTested on files containing no extension inside directories containing dots, such as 'a.b/c'\nUpdated: Now updates hashes if the file changes.\n\nKey points:\n\nUse of print0 piped to while read -d $'\\0', to correctly handle spaces in file names.\nmd5sum can be replaced with your favourite hash function. The sed removes the first space and everything after it from the output of md5sum.\nThe base filename is extracted using a regular expression that finds the last period that isn't followed by another slash (so that periods in directory names aren't counted as part of the extension).\nThe extension is found by using a substring with starting index as the length of the base filename.\n\n", "The logic of the requirements is complex enough to justify the use of Python instead of bash. It should provide a more readable, extensible, and maintainable solution.\n#!/usr/bin/env python\nimport hashlib, os\n\ndef ishash(h, size):\n \"\"\"Whether `h` looks like hash's hex digest.\"\"\"\n if len(h) == size: \n try:\n int(h, 16) # whether h is a hex number\n return True\n except ValueError:\n return False\n\nfor root, dirs, files in os.walk(\".\"):\n dirs[:] = [d for d in dirs if not d.startswith(\".\")] # skip hidden dirs\n for path in (os.path.join(root, f) for f in files if not f.startswith(\".\")):\n suffix = hash_ = \".\" + hashlib.md5(open(path).read()).hexdigest()\n hashsize = len(hash_) - 1\n # extract old hash from the name; add/replace the hash if needed\n barepath, ext = os.path.splitext(path) # ext may be empty\n if not ishash(ext[1:], hashsize):\n suffix += ext # add original extension\n barepath, oldhash = os.path.splitext(barepath) \n if not ishash(oldhash[1:], hashsize):\n suffix = oldhash + suffix # preserve 2nd (not a hash) extension\n else: # ext looks like a hash\n oldhash = ext\n if hash_ != oldhash: # replace old hash by new one\n os.rename(path, barepath+suffix)\n\nHere's a test directory tree. It contains:\n\nfiles without extension inside directories with a dot in their name\nfilename which already has a hash in it (test on idempotency)\nfilename with two extensions\nnewlines in names\n\n\n$ tree a\na\n|-- b\n| `-- c.d\n| |-- f\n| |-- f.ext1.ext2\n| `-- g.d41d8cd98f00b204e9800998ecf8427e\n|-- c.ext^Mnewline\n| `-- f\n`-- f^Jnewline.ext1\n\n7 directories, 5 files\n\nResult\n\n$ tree a\na\n|-- b\n| `-- c.d\n| |-- f.0bee89b07a248e27c83fc3d5951213c1\n| |-- f.ext1.614dd0e977becb4c6f7fa99e64549b12.ext2\n| `-- g.d41d8cd98f00b204e9800998ecf8427e\n|-- c.ext^Mnewline\n| `-- f.0bee89b07a248e27c83fc3d5951213c1\n`-- f^Jnewline.b6fe8bb902ca1b80aaa632b776d77f83.ext1\n\n7 directories, 5 files\n\nThe solution works correctly for all cases.\n\nWhirlpool hash is not in Python's stdlib, but there are both pure Python and C extensions that support it e.g., python-mhash.\nTo install it:\n$ sudo apt-get install python-mhash\n\nTo use it:\nimport mhash\n\nprint mhash.MHASH(mhash.MHASH_WHIRLPOOL, \"text to hash here\").hexdigest()\n\nOutput:\n cbdca4520cc5c131fc3a86109dd23fee2d7ff7be56636d398180178378944a4f41480b938608ae98da7eccbf39a4c79b83a8590c4cb1bace5bc638fc92b3e653\n\nInvoking whirlpooldeep in Python\nfrom subprocess import PIPE, STDOUT, Popen\n\ndef getoutput(cmd):\n return Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate()[0]\n\nhash_ = getoutput([\"whirlpooldeep\", \"-q\", path]).rstrip()\n\n\ngit can provide with leverage for the problems that need to track set of files based on their hashes. \n", "I wasn't really happy with my first answer, since as I said there, this problem looks like it's best solved with perl. You already said in one edit of your question that you have perl on the OS X machine you want to run this on, so I gave it a shot.\nIt's hard to get it all right in bash, i.e. avoiding any quoting problems with odd filenames, and behaving nicely with corner-case filenames.\nSo here it is in perl, a complete solution to your problem. It runs over all the files/directories listed on its command line.\n\n#!/usr/bin/perl -w\n# whirlpool-rename.pl\n# 2009 Peter Cordes <peter@cordes.ca>. Share and Enjoy!\n\nuse Fcntl; # for O_BINARY\nuse File::Find;\nuse Digest::Whirlpool;\n\n# find callback, called once per directory entry\n# $_ is the base name of the file, and we are chdired to that directory.\nsub whirlpool_rename {\n print \"find: $_\\n\";\n# my @components = split /\\.(?:[[:xdigit:]]{128})?/; # remove .hash while we're at it\n my @components = split /\\.(?!\\.|$)/, $_, -1; # -1 to not leave out trailing dots\n\n if (!$components[0] && $_ ne \".\") { # hidden file/directory\n $File::Find::prune = 1;\n return;\n }\n\n # don't follow symlinks or process non-regular-files\n return if (-l $_ || ! -f _);\n\n my $digest;\n eval {\n sysopen(my $fh, $_, O_RDONLY | O_BINARY) or die \"$!\";\n $digest = Digest->new( 'Whirlpool' )->addfile($fh);\n };\n if ($@) { # exception-catching structure from whirlpoolsum, distributed with Digest::Whirlpool.\n warn \"whirlpool: couldn't hash $_: $!\\n\";\n return;\n }\n\n # strip old hashes from the name. not done during split only in the interests of readability\n @components = grep { !/^[[:xdigit:]]{128}$/ } @components;\n if ($#components == 0) {\n push @components, $digest->hexdigest;\n } else {\n my $ext = pop @components;\n push @components, $digest->hexdigest, $ext;\n }\n\n my $newname = join('.', @components);\n return if $_ eq $newname;\n print \"rename $_ -> $newname\\n\";\n if (-e $newname) {\n warn \"whirlpool: clobbering $newname\\n\";\n # maybe unlink $_ and return if $_ is older than $newname?\n # But you'd better check that $newname has the right contents then...\n }\n # This could be link instead of rename, but then you'd have to handle directories, and you can't make hardlinks across filesystems\n rename $_, $newname or warn \"whirlpool: couldn't rename $_ -> $newname: $!\\n\";\n}\n\n\n#main\n$ARGV[0] = \".\" if !@ARGV; # default to current directory\nfind({wanted => \\&whirlpool_rename, no_chdir => 0}, @ARGV );\n\nAdvantages:\n- actually uses whirlpool, so you can use this exact program directly. (after installing libperl-digest-whirlpool). Easy to change to any digest function you want, because instead of different programs with different output formats, you have the perl Digest common interface.\n\nimplements all other requirements: ignore hidden files (and files under hidden directories).\nable to handle any possible filename without error or security problem. (Several people got this right in their shell scripts).\nfollows best practices for traversing a directory tree, by chdiring down into each directory (like my previous answer, with find -execdir). This avoids problems with PATH_MAX, and with directories being renamed while you're running.\nclever handling of filenames that end with . foo..txt... -> foo..hash.txt...\nHandles old filenames containing hashes already without renaming them and then renaming them back. (It strips any sequence of 128 hex digits that's surrounded by \".\" characters.) In the everything-correct case, no disk write activity happens, just reads of every file. Your current solution runs mv twice in the already-correctly-named case, causing directory metadata writes. And being slower, because that's two processes that have to be execced.\nefficient. No programs are fork/execed, while most of the solutions that would actually work ended up having to sed something per-file.\nDigest::Whirlpool is implemented with a natively-compiled shared lib, so it's not slow pure-perl. This should be faster than running a program on every file, esp. for small files.\nPerl supports UTF-8 strings, so filenames with non-ascii characters shouldn't be a problem. (not sure if any multi-byte sequences in UTF-8 could include the byte that means ASCII '.' on its own. If that is possible, then you need UTF-8 aware string handling. sed doesn't know UTF-8. Bash's glob expressions may.)\neasily extensible. When you go to put this into a real program, and you want to handle more corner cases, you can do so quite easily. e.g. decide what to do when you want to rename a file but the hash-named filename already exists.\ngood error reporting. Most shell scripts have this, though, by passing along errors from the progs they run.\n\n", "find . -type f -print | while read file\ndo\n hash=`$hashcommand \"$file\"`\n filename=${file%.*}\n extension=${file##*.}\n mv $file \"$filename.$hash.$extension\"\ndone\n\n", "You might want to store the results in one file, like in\nfind . -type f -exec md5sum {} \\; > MD5SUMS\n\nIf you really want one file per hash:\nfind . -type f | while read f; do g=`md5sum $f` > $f.md5; done\n\nor even\nfind . -type f | while read f; do g=`md5sum $f | awk '{print $1}'`; echo \"$g $f\"> $f-$g.md5; done\n\n", "In sh or bash, two versions. One limits itself to files with extensions...\nhash () {\n #openssl md5 t.sh | sed -e 's/.* //'\n whirlpool \"$f\"\n}\n\nfind . -type f -a -name '*.*' | while read f; do\n # remove the echo to run this for real\n echo mv \"$f\" \"${f%.*}.whirlpool-`hash \"$f\"`.${f##*.}\"\ndone\n\nTesting...\n...\nmv ./bash-4.0/signames.h ./bash-4.0/signames.whirlpool-d71b117a822394a5b273ea6c0e3f4dc045b1098326d39864564f1046ab7bd9296d5533894626288265a1f70638ee3ecce1f6a22739b389ff7cb1fa48c76fa166.h\n...\n\nAnd this more complex version processes all plain files, with or without extensions, with or without spaces and odd characters, etc, etc...\nhash () {\n #openssl md5 t.sh | sed -e 's/.* //'\n whirlpool \"$f\"\n}\n\nfind . -type f | while read f; do\n name=${f##*/}\n case \"$name\" in\n *.*) extension=\".${name##*.}\" ;;\n *) extension= ;;\n esac\n # remove the echo to run this for real\n echo mv \"$f\" \"${f%/*}/${name%.*}.whirlpool-`hash \"$f\"`$extension\"\ndone\n\n", "Here's my take on it, in bash. Features: skips non-regular files; correctly deals with files with weird characters (i.e. spaces) in their names; deals with extensionless filenames; skips already-hashed files, so it can be run repeatedly (although if files are modified between runs, it adds the new hash rather than replacing the old one). I wrote it using md5 -q as the hash function; you should be able to replace this with anything else, as long as it only outputs the hash, not something like filename => hash.\nfind -x . -type f -print0 | while IFS=\"\" read -r -d $'\\000' file; do\n hash=\"$(md5 -q \"$file\")\" # replace with your favorite hash function\n [[ \"$file\" == *.\"$hash\" ]] && continue # skip files that already end in their hash\n dirname=\"$(dirname \"$file\")\"\n basename=\"$(basename \"$file\")\"\n base=\"${basename%.*}\"\n [[ \"$base\" == *.\"$hash\" ]] && continue # skip files that already end in hash + extension\n if [[ \"$basename\" == \"$base\" ]]; then\n extension=\"\"\n else\n extension=\".${basename##*.}\"\n fi\n mv \"$file\" \"$dirname/$base.$hash$extension\"\ndone\n\n", "whirlpool isn't a very common hash. You'll probably have to install a program to compute it. e.g. Debian/Ubuntu include a \"whirlpool\" package. The program prints the hash of one file by itself. apt-cache search whirlpool shows that some other packages support it, including the interesting md5deep.\nSome of the earlier anwsers will fail on filenames with spaces in them. If this is the case, but your files don't have any newlines in the filename, then you can safely use \\n as a delimiter.\n\noldifs=\"$IFS\"\nIFS=\"\n\"\nfor i in $(find -type f); do echo \"$i\";done\n#output\n# ./base\n# ./base2\n# ./normal.ext\n# ./trick.e \"xt\n# ./foo bar.dir ext/trick' (name \"- }$foo.ext{}.ext2\nIFS=\"$oldifs\"\n\ntry without setting IFS to see why it matters.\nI was going to try something with IFS=\".\"; find -print0 | while read -a array, to split on \".\" characters, but I normally never use array variables. There's no easy way that I see in the man page to insert the hash as the second-last array index, and push down the last element (the file extension, if it had one.) Any time bash array variables look interesting, I know it's time to do what I'm doing in perl instead! See the gotchas for using read:\nhttp://tldp.org/LDP/abs/html/gotchas.html#BADREAD0\nI decided to use another technique I like: find -exec sh -c. It's the safest, since you're not parsing filenames.\nThis should do the trick:\n\nfind -regextype posix-extended -type f -not -regex '.*\\.[a-fA-F0-9]{128}.*' \\\n-execdir bash -c 'for i in \"${@#./}\";do \n hash=$(whirlpool \"$i\");\n ext=\".${i##*.}\"; base=\"${i%.*}\";\n [ \"$base\" = \"$i\" ] && ext=\"\";\n newname=\"$base.$hash$ext\";\n echo \"ext:$ext $i -> $newname\";\n false mv --no-clobber \"$i\" \"$newname\";done' \\\ndummy {} +\n# take out the \"false\" before the mv, and optionally take out the echo.\n# false ignores its arguments, so it's there so you can\n# run this to see what will happen without actually renaming your files.\n\n-execdir bash -c 'cmd' dummy {} + has the dummy arg there because the first arg after the command becomes $0 in the shell's positional parameters, not part of \"$@\" that for loops over. I use execdir instead of exec so I don't have to deal with directory names (or the possibility of exceeding PATH_MAX for nested dirs with long names, when the actual filenames are all short enough.)\n-not -regex prevents this from being applied twice to the same file. Although whirlpool is an extremely long hash, and mv says File name too long if I run it twice without that check. (on an XFS filesystem.)\nFiles with no extension get basename.hash. I had to check specially to avoid appending a trailing ., or getting the basename as the extension. ${@#./} strips out the leading ./ that find puts in front of every filename, so there is no \".\" in the whole string for files with no extension.\nmv --no-clobber may be a GNU extension. If you don't have GNU mv, do something else if you want to avoid deleting existing files (e.g. you run this once, some of the same file are added to the directory with their old names; you run it again.) OTOH, if you want that behaviour, just take it out.\nMy solution should work even when filenames contain a newline (they can, you know!), or any other possible character. It would be faster and easier in perl, but you asked for shell.\nwallenborn's solution for making one file with all the checksums (instead of renaming the original) is pretty good, but inefficient. Don't run md5sum once per file, run it on as many files at once as will fit on its command line:\nfind dir -type f -print0 | xargs -0 md5sum > dir.md5\nor with GNU find, xargs is built in (note the + instead of ';')\n find dir -type f -exec md5sum {} + > dir.md5\nif you just use find -print | xargs -d'\\n', you will be screwed up by file names with quote marks in them, so be careful. If you don't know what files you might someday run this script on, always try to use print0 or -exec. This is esp. true if filenames are supplied by untrusted users (i.e. could be an attack vector on your server.)\n", "Hm, interesting problem.\nTry the following (the mktest function is just for testing -- TDD for bash! :)\nEdit:\n\nAdded support for whirlpool hashes.\ncode cleanup\nbetter quoting of filenames\nchanged array-syntax for test part-- should now work with most korn-like shells. Note that pdksh does not support :-based parameter expansion (or rather\nit means something else)\n\nNote also that when in md5-mode it fails for filenames with whirlpool-like hashes, and\npossibly vice-versa.\n\n\n#!/usr/bin/env bash\n\n#Tested with:\n# GNU bash, version 4.0.28(1)-release (x86_64-pc-linux-gnu)\n# ksh (AT&T Research) 93s+ 2008-01-31\n# mksh @(#)MIRBSD KSH R39 2009/08/01 Debian 39.1-4\n# Does not work with pdksh, dash\n\nDEFAULT_SUM=\"md5\"\n\n#Takes a parameter, as root path\n# as well as an optional parameter, the hash function to use (md5 or wp for whirlpool).\nmain()\n{\n case $2 in\n \"wp\")\n export SUM=\"wp\"\n ;;\n \"md5\")\n export SUM=\"md5\"\n ;;\n *)\n export SUM=$DEFAULT_SUM\n ;;\n esac\n\n # For all visible files in all visible subfolders, move the file\n # to a name including the correct hash:\n find $1 -type f -not -regex '.*/\\..*' -exec $0 hashmove '{}' \\;\n}\n\n# Given a file named in $1 with full path, calculate it's hash.\n# Output the filname, with the hash inserted before the extention\n# (if any) -- or: replace an existing hash with the new one,\n# if a hash already exist.\nhashname_md5()\n{\n pathname=\"$1\"\n full_hash=`md5sum \"$pathname\"`\n hash=${full_hash:0:32}\n filename=`basename \"$pathname\"`\n prefix=${filename%%.*}\n suffix=${filename#$prefix}\n\n #If the suffix starts with something that looks like an md5sum,\n #remove it:\n suffix=`echo $suffix|sed -r 's/\\.[a-z0-9]{32}//'`\n\n echo \"$prefix.$hash$suffix\"\n}\n\n# Same as hashname_md5 -- but uses whirlpool hash.\nhashname_wp()\n{\n pathname=\"$1\"\n hash=`whirlpool \"$pathname\"`\n filename=`basename \"$pathname\"`\n prefix=${filename%%.*}\n suffix=${filename#$prefix}\n\n #If the suffix starts with something that looks like an md5sum,\n #remove it:\n suffix=`echo $suffix|sed -r 's/\\.[a-z0-9]{128}//'`\n\n echo \"$prefix.$hash$suffix\"\n}\n\n\n#Given a filepath $1, move/rename it to a name including the filehash.\n# Try to replace an existing hash, an not move a file if no update is\n# needed.\nhashmove()\n{\n pathname=\"$1\"\n filename=`basename \"$pathname\"`\n path=\"${pathname%%/$filename}\"\n\n case $SUM in\n \"wp\")\n hashname=`hashname_wp \"$pathname\"`\n ;;\n \"md5\")\n hashname=`hashname_md5 \"$pathname\"`\n ;;\n *)\n echo \"Unknown hash requested\"\n exit 1\n ;;\n esac\n\n if [[ \"$filename\" != \"$hashname\" ]]\n then\n echo \"renaming: $pathname => $path/$hashname\"\n mv \"$pathname\" \"$path/$hashname\"\n else\n echo \"$pathname up to date\"\n fi\n}\n\n# Create som testdata under /tmp\nmktest()\n{\n root_dir=$(tempfile)\n rm \"$root_dir\"\n mkdir \"$root_dir\"\n i=0\n test_files[$((i++))]='test'\n test_files[$((i++))]='testfile, no extention or spaces'\n\n test_files[$((i++))]='.hidden'\n test_files[$((i++))]='a hidden file'\n\n test_files[$((i++))]='test space'\n test_files[$((i++))]='testfile, no extention, spaces in name'\n\n test_files[$((i++))]='test.txt'\n test_files[$((i++))]='testfile, extention, no spaces in name'\n\n test_files[$((i++))]='test.ab8e460eac3599549cfaa23a848635aa.txt'\n test_files[$((i++))]='testfile, With (wrong) md5sum, no spaces in name'\n\n test_files[$((i++))]='test spaced.ab8e460eac3599549cfaa23a848635aa.txt'\n test_files[$((i++))]='testfile, With (wrong) md5sum, spaces in name'\n\n test_files[$((i++))]='test.8072ec03e95a26bb07d6e163c93593283fee032db7265a29e2430004eefda22ce096be3fa189e8988c6ad77a3154af76f582d7e84e3f319b798d369352a63c3d.txt'\n test_files[$((i++))]='testfile, With (wrong) whirlpoolhash, no spaces in name'\n\n test_files[$((i++))]='test spaced.8072ec03e95a26bb07d6e163c93593283fee032db7265a29e2430004eefda22ce096be3fa189e8988c6ad77a3154af76f582d7e84e3f319b798d369352a63c3d.txt']\n test_files[$((i++))]='testfile, With (wrong) whirlpoolhash, spaces in name'\n\n test_files[$((i++))]='test space.txt'\n test_files[$((i++))]='testfile, extention, spaces in name'\n\n test_files[$((i++))]='test multi-space .txt'\n test_files[$((i++))]='testfile, extention, multiple consequtive spaces in name'\n\n test_files[$((i++))]='test space.h'\n test_files[$((i++))]='testfile, short extention, spaces in name'\n\n test_files[$((i++))]='test space.reallylong'\n test_files[$((i++))]='testfile, long extention, spaces in name'\n\n test_files[$((i++))]='test space.reallyreallyreallylong.tst'\n test_files[$((i++))]='testfile, long extention, double extention,\n might look like hash, spaces in name'\n\n test_files[$((i++))]='utf8test1 - æeiaæå.txt'\n test_files[$((i++))]='testfile, extention, utf8 characters, spaces in name'\n\n test_files[$((i++))]='utf8test1 - 漢字.txt'\n test_files[$((i++))]='testfile, extention, Japanese utf8 characters, spaces in name'\n\n for s in . sub1 sub2 sub1/sub3 .hidden_dir\n do\n\n #note -p not needed as we create dirs top-down\n #fails for \".\" -- but the hack allows us to use a single loop\n #for creating testdata in all dirs\n mkdir $root_dir/$s\n dir=$root_dir/$s\n\n i=0\n while [[ $i -lt ${#test_files[*]} ]]\n do\n filename=${test_files[$((i++))]}\n echo ${test_files[$((i++))]} > \"$dir/$filename\"\n done\n done\n\n echo \"$root_dir\"\n}\n\n# Run test, given a hash-type as first argument\nruntest()\n{\n sum=$1\n\n root_dir=$(mktest)\n\n echo \"created dir: $root_dir\"\n echo \"Running first test with hashtype $sum:\"\n echo\n main $root_dir $sum\n echo\n echo \"Running second test:\"\n echo\n main $root_dir $sum\n echo \"Updating all files:\"\n\n find $root_dir -type f | while read f\n do\n echo \"more content\" >> \"$f\"\n done\n\n echo\n echo \"Running final test:\"\n echo\n main $root_dir $sum\n #cleanup:\n rm -r $root_dir\n}\n\n# Test md5 and whirlpool hashes on generated data.\nruntests()\n{\n runtest md5\n runtest wp\n}\n\n#For in order to be able to call the script recursively, without splitting off\n# functions to separate files:\ncase \"$1\" in\n 'test')\n runtests\n ;;\n 'hashname')\n hashname \"$2\"\n ;;\n 'hashmove')\n hashmove \"$2\"\n ;;\n 'run')\n main \"$2\" \"$3\"\n ;;\n *)\n echo \"Use with: $0 test - or if you just want to try it on a folder:\"\n echo \" $0 run path (implies md5)\"\n echo \" $0 run md5 path\"\n echo \" $0 run wp path\"\n ;;\nesac\n\n\n", "In response to your updated question:\n\nIf anyone can comment on how I can avoid looking in hidden directories with my BASH Script, it would be much appreciated.\n\nYou can avoid hidden directories with find by using\nfind -name '.?*' -prune -o \\( -type f -print0 \\)\n\n-name '.*' -prune will prune \".\", and stop without doing anything. :/\nI'd still recommend my Perl version, though. I updated it... You may still need to install Digest::Whirlpool from CPAN, though.\n", "using zsh:\n$ ls\na.txt\nb.txt\nc.txt\n\nThe magic:\n$ FILES=**/*(.) \n$ # */ stupid syntax coloring thinks this is a comment\n$ for f in $FILES; do hash=`md5sum $f | cut -f1 -d\" \"`; mv $f \"$f:r.$hash.$f:e\"; done\n$ ls\na.60b725f10c9c85c70d97880dfe8191b3.txt\nb.3b5d5c3712955042212316173ccf37be.txt\nc.2cd6ee2c70b0bde53fbe6cac3c8b8bb1.txt\n\nHappy deconstruction!\nEdit: added files in subdirectories and quotes around mv argument\n", "Ruby:\n#!/usr/bin/env ruby\nrequire 'digest/md5'\n\nDir.glob('**/*') do |f|\n next unless File.file? f\n next if /\\.md5sum-[0-9a-f]{32}/ =~ f\n md5sum = Digest::MD5.file f\n newname = \"%s/%s.md5sum-%s%s\" %\n [File.dirname(f), File.basename(f,'.*'), md5sum, File.extname(f)]\n File.rename f, newname\nend\n\nHandles filenames that have spaces, no extension, and that have already been hashed.\nIgnores hidden files and directories — add File::FNM_DOTMATCH as the second argument of glob if that's desired.\n" ]
[ 6, 4, 3, 3, 2, 1, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "bash", "batch_processing", "hash", "perl", "python" ]
stackoverflow_0001841737_bash_batch_processing_hash_perl_python.txt
Q: PKI verification across Java and Python I am trying to implement a PKI verification scheme, where a message string is signed with a private key on server, the signature is stored on the client along with the message string. The client then verifies the signature using a public key. The restrictions of my environment are, the server is Google App Engine and the client is a Java program. I have played with Java-only and Python-only solutions of PKI verification and got them to work, however when doing one operation in Python and another in Java is posing problem, mainly due to Key file format restrictions and my limited understanding of cryptography terminology. One of the biggest limitations is crypto support in GAE. The only library supported is PyCrypto and this library can't read public/private keys stored in PEM, DER or X509 formats. As far as I could find, only M2Crypto supports reading from these files, but it can't be used inside GAE because it's a wrapper around openssl, so not a pure python solution. Even if I could find a way to translate the public/private keys from PEM/DER/X509 to the format that PyCrypto understands, that will work for me. But I couldn't find any way to do it. Any ideas there? I found one possible solution in the form of tlslite. tlslite could read a private key from PEM file and create a signature. Here is the code. from tlslite.utils.cryptomath import bytesToBase64 from tlslite.utils.keyfactory import parsePEMKey s = open('private.pem').read() key = parsePEMKey(s) doc = 'Sample text' bytes = array('B') bytes.fromstring(doc) print bytesToBase64(key.sign(bytes)) The corresponding Java code I used to verify the signature is. String signAlgo = "SHA1WithRSAEncryption"; // read public key from public.der byte[] encodedKey = new byte[294]; // shortcut hardcoding getAssets().open("public.der").read(encodedKey); // create public key object X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(publicKeySpec); // read signature (created by python code above) byte[] encodedSig = new byte[345]; getAssets().open("signature.txt").read(encodedSig); byte[] decodedSig = Base64.decodeBase64(encodedSig); // Do verification Signature verifyalg = Signature.getInstance(signAlgo); verifyalg.initVerify(pk); verifyalg.update(message.getBytes()); Log.d(TAG, "Verif : "+verifyalg.verify(decodedSig)); The verification fails. I suspected if the tlslite is using different algorithm for signature creation than what the java code expects. So I tried to find that out. On python side print key.getSigningAlgorithm() gave me pkcs1-sha1 on Java side, I tried to find all supported algorithms with this code: Set<String> algos = java.security.Security.getAlgorithms("Signature"); for(String algo : algos) { Log.d(TAG, algo); } That gave me MD4WithRSAEncryption RSASSA-PSS SHA1withDSA SHA1withRSA/ISO9796-2 1.2.840.113549.1.1.10 SHA512withRSA/PSS MD5withRSA/ISO9796-2 DSA SHA512WithRSAEncryption SHA224withRSA/PSS NONEWITHDSA SHA256withRSA/PSS SHA224WithRSAEncryption SHA256WithRSAEncryption SHA1withRSA/PSS SHA1WithRSAEncryption SHA384withRSA/PSS SHA384WithRSAEncryption MD5WithRSAEncryption I tried all the SHA1 values on the Java side. But none helped to verify the signature generated by tlslite with pkcs1-sha1 algo. Any idea about this mapping? A: These are different operations. In Python, you need to use hashAndSign. The default happens to be SHA1 hash. A: Keyczar should work fine on App Engine, and is available in both Java and Python flavours.
PKI verification across Java and Python
I am trying to implement a PKI verification scheme, where a message string is signed with a private key on server, the signature is stored on the client along with the message string. The client then verifies the signature using a public key. The restrictions of my environment are, the server is Google App Engine and the client is a Java program. I have played with Java-only and Python-only solutions of PKI verification and got them to work, however when doing one operation in Python and another in Java is posing problem, mainly due to Key file format restrictions and my limited understanding of cryptography terminology. One of the biggest limitations is crypto support in GAE. The only library supported is PyCrypto and this library can't read public/private keys stored in PEM, DER or X509 formats. As far as I could find, only M2Crypto supports reading from these files, but it can't be used inside GAE because it's a wrapper around openssl, so not a pure python solution. Even if I could find a way to translate the public/private keys from PEM/DER/X509 to the format that PyCrypto understands, that will work for me. But I couldn't find any way to do it. Any ideas there? I found one possible solution in the form of tlslite. tlslite could read a private key from PEM file and create a signature. Here is the code. from tlslite.utils.cryptomath import bytesToBase64 from tlslite.utils.keyfactory import parsePEMKey s = open('private.pem').read() key = parsePEMKey(s) doc = 'Sample text' bytes = array('B') bytes.fromstring(doc) print bytesToBase64(key.sign(bytes)) The corresponding Java code I used to verify the signature is. String signAlgo = "SHA1WithRSAEncryption"; // read public key from public.der byte[] encodedKey = new byte[294]; // shortcut hardcoding getAssets().open("public.der").read(encodedKey); // create public key object X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(publicKeySpec); // read signature (created by python code above) byte[] encodedSig = new byte[345]; getAssets().open("signature.txt").read(encodedSig); byte[] decodedSig = Base64.decodeBase64(encodedSig); // Do verification Signature verifyalg = Signature.getInstance(signAlgo); verifyalg.initVerify(pk); verifyalg.update(message.getBytes()); Log.d(TAG, "Verif : "+verifyalg.verify(decodedSig)); The verification fails. I suspected if the tlslite is using different algorithm for signature creation than what the java code expects. So I tried to find that out. On python side print key.getSigningAlgorithm() gave me pkcs1-sha1 on Java side, I tried to find all supported algorithms with this code: Set<String> algos = java.security.Security.getAlgorithms("Signature"); for(String algo : algos) { Log.d(TAG, algo); } That gave me MD4WithRSAEncryption RSASSA-PSS SHA1withDSA SHA1withRSA/ISO9796-2 1.2.840.113549.1.1.10 SHA512withRSA/PSS MD5withRSA/ISO9796-2 DSA SHA512WithRSAEncryption SHA224withRSA/PSS NONEWITHDSA SHA256withRSA/PSS SHA224WithRSAEncryption SHA256WithRSAEncryption SHA1withRSA/PSS SHA1WithRSAEncryption SHA384withRSA/PSS SHA384WithRSAEncryption MD5WithRSAEncryption I tried all the SHA1 values on the Java side. But none helped to verify the signature generated by tlslite with pkcs1-sha1 algo. Any idea about this mapping?
[ "These are different operations. In Python, you need to use hashAndSign. The default happens to be SHA1 hash.\n", "Keyczar should work fine on App Engine, and is available in both Java and Python flavours.\n" ]
[ 1, 1 ]
[]
[]
[ "cryptography", "google_app_engine", "java", "python" ]
stackoverflow_0001867355_cryptography_google_app_engine_java_python.txt
Q: Use Python to insert xml markup around the difference of two strings I have an oldstring: 'foobarba <span class="foo">z</span>' and a newstring: 'foodbar ba<span class="foo">z</span>' a string is given for a classname, it could be "foo" again, let's say "bar". Given newstring, oldstring and bar, I want to end up with: 'foo<span class="bar">d</span> ba<span class="foo">z</span>' I want to diff the two strings. If the new string is shorter, maybe check for empty tags and through them out .. but for now we can do nothing. But, if the new string is longer (it will be longer by probably 1 character, maybe more, but few), I want to find the new character(s), check whether it is wrapped by an appropriate span (one with the given bar) and, if not wrapped, wrap it. If the oldstring is now: 'foo<span class="bar">d</span> ba<span class="foo">z</span>' given foo again as the classname, and the newstring: 'foo<span class="bar">dz</span> ba<span class="foo">z</span>' I would like to sense the new z character and come out with 'foo<span class="bar">d</span><span class="foo">z</span> ba<span class="foo">z</span>' OR 'foo<span class="bar">d<span class="foo">z</span></span> ba<span class="foo">z</span>' Suggestions for good python modules or even perhaps a quick trick from the stdlib would be great. idk, I'm tired; might wake up with the answer tomorrow. A: Use difflib from the stdlib to find differences between your strings, then just insert your span tags around the diffs.
Use Python to insert xml markup around the difference of two strings
I have an oldstring: 'foobarba <span class="foo">z</span>' and a newstring: 'foodbar ba<span class="foo">z</span>' a string is given for a classname, it could be "foo" again, let's say "bar". Given newstring, oldstring and bar, I want to end up with: 'foo<span class="bar">d</span> ba<span class="foo">z</span>' I want to diff the two strings. If the new string is shorter, maybe check for empty tags and through them out .. but for now we can do nothing. But, if the new string is longer (it will be longer by probably 1 character, maybe more, but few), I want to find the new character(s), check whether it is wrapped by an appropriate span (one with the given bar) and, if not wrapped, wrap it. If the oldstring is now: 'foo<span class="bar">d</span> ba<span class="foo">z</span>' given foo again as the classname, and the newstring: 'foo<span class="bar">dz</span> ba<span class="foo">z</span>' I would like to sense the new z character and come out with 'foo<span class="bar">d</span><span class="foo">z</span> ba<span class="foo">z</span>' OR 'foo<span class="bar">d<span class="foo">z</span></span> ba<span class="foo">z</span>' Suggestions for good python modules or even perhaps a quick trick from the stdlib would be great. idk, I'm tired; might wake up with the answer tomorrow.
[ "Use difflib from the stdlib to find differences between your strings, then just insert your span tags around the diffs.\n" ]
[ 1 ]
[]
[]
[ "html", "parsing", "python", "string" ]
stackoverflow_0001880356_html_parsing_python_string.txt
Q: pythonic way to explode a list of tuples I need to do the opposite of this Multiple Tuple to Two-Pair Tuple in Python? Namely, I have a list of tuples [(1,2), (3,4), (5,6)] and need to produce this [1,2,3,4,5,6] I would personally do this >>> tot = [] >>> for i in [(1,2), (3,4), (5,6)]: ... tot.extend(list(i)) but I'd like to see something fancier. A: The most efficient way to do it is this: tuples = [(1,2), (3,4), (5,6)] [item for t in tuples for item in t] output [1, 2, 3, 4, 5, 6] Here is the comparison I did for various way to do it in a duplicate question. I know someone is going to suggest this solution sum(tuples, ()) But don't use it, it will create a new intermediate result list for each step! unless you don't care about performance and just want a compact solution. For more details check Alex's answer In summary: sum is faster for small lists, but the performance degrades significantly with larger lists. A: >>> import itertools >>> tp = [(1,2),(3,4),(5,6)] >>> lst = list(itertools.chain(*tp)) >>> lst [1, 2, 3, 4, 5, 6] Of course, if you don't need a list but an iterator, you can drop the list() conversion call. A: l = [(1,2), (3,4), (5,6)] reduce (lambda x,y: x+list(y), l, [])
pythonic way to explode a list of tuples
I need to do the opposite of this Multiple Tuple to Two-Pair Tuple in Python? Namely, I have a list of tuples [(1,2), (3,4), (5,6)] and need to produce this [1,2,3,4,5,6] I would personally do this >>> tot = [] >>> for i in [(1,2), (3,4), (5,6)]: ... tot.extend(list(i)) but I'd like to see something fancier.
[ "The most efficient way to do it is this:\ntuples = [(1,2), (3,4), (5,6)]\n[item for t in tuples for item in t]\n\noutput\n[1, 2, 3, 4, 5, 6]\n\nHere is the comparison I did for various way to do it in a duplicate question.\nI know someone is going to suggest this solution\nsum(tuples, ())\n\nBut don't use it, it will create a new intermediate result list for each step! unless you don't care about performance and just want a compact solution.\nFor more details check Alex's answer\nIn summary: sum is faster for small lists, but the performance degrades significantly with larger lists.\n", ">>> import itertools\n>>> tp = [(1,2),(3,4),(5,6)]\n>>> lst = list(itertools.chain(*tp))\n>>> lst\n[1, 2, 3, 4, 5, 6]\n\nOf course, if you don't need a list but an iterator, you can drop the list() conversion call.\n", "l = [(1,2), (3,4), (5,6)]\nreduce (lambda x,y: x+list(y), l, [])\n\n" ]
[ 21, 6, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001880683_list_python.txt
Q: Does 'p' have a special meaning in Django? Why are p and p8 different in the following code? The beginning of a view function (in file views.py in a Django app named "proteinSearch" with a model named "Protein" that has a field named "description"): def searchForProteins2(request, searchStr): p8 = Protein.objects.filter( description__icontains=searchStr) #Why doesn't this work????? p = Protein.objects.filter( description__icontains=searchStr) import pdb; pdb.set_trace() Interactively in pdb: (Pdb) searchStr u'centr' (Pdb) p8 [<Protein: IPI00657962.1>, <Protein: IPI00479143.2>, <Protein: IPI00477050.4>, <Protein: IPI00220625.1>, 95.2>] (Pdb) p *** SyntaxError: SyntaxError('unexpected EOF while parsing', ('<string>', 0, 0, '')) A: When you are in Debugging mode (pdb or ipdb REPL), 'p' is meant for a specific functionality, i.e. evaluating an expression expr. Like, ipdb> x = 1 ipdb> p x 1 ipdb> p x==True True ipdb> p x==1 True In Django, 'p' will simply means a variable. If you want to print value of 'p' variable, try, ipdb> p p :)
Does 'p' have a special meaning in Django?
Why are p and p8 different in the following code? The beginning of a view function (in file views.py in a Django app named "proteinSearch" with a model named "Protein" that has a field named "description"): def searchForProteins2(request, searchStr): p8 = Protein.objects.filter( description__icontains=searchStr) #Why doesn't this work????? p = Protein.objects.filter( description__icontains=searchStr) import pdb; pdb.set_trace() Interactively in pdb: (Pdb) searchStr u'centr' (Pdb) p8 [<Protein: IPI00657962.1>, <Protein: IPI00479143.2>, <Protein: IPI00477050.4>, <Protein: IPI00220625.1>, 95.2>] (Pdb) p *** SyntaxError: SyntaxError('unexpected EOF while parsing', ('<string>', 0, 0, ''))
[ "When you are in Debugging mode (pdb or ipdb REPL), 'p' is meant for a specific functionality, i.e. evaluating an expression expr.\nLike, \nipdb> x = 1\nipdb> p x\n1\nipdb> p x==True\nTrue\nipdb> p x==1\nTrue\n\nIn Django, 'p' will simply means a variable.\nIf you want to print value of 'p' variable, try,\nipdb> p p\n\n:)\n" ]
[ 13 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001880753_django_python.txt
Q: Decoding packed data into a structure What would the best way of unpacking a python string into fields I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function It has the following format uint8 - header uint8 - length uint32 - typeID uint16 -param1 uint16 -param2 uint16 -param3 uint16 -param4 char[24] - name string uint32 - checksum uint8 - footer (I also need to unpack other packets with different formats to the above) How do I unpack these? I am new to python, have done a bit of 'C'. If I was using 'C' I would probably use a structure, would this be the way to go with Python? Regards X A: The struct module is designed to unpack heterogeneous data to a tuple based on a format string. It makes more sense to unpack the whole struct at once rather than trying to pull out one field at a time. Here is an example: fields = struct.unpack('!BBI4H20sIB', data) Then you can access a given field, for example the first field: fields[0] You could also use the tuple to initialize a NamedTuple; look at the documentation for struct for an example. NamedTuples are only available in Python 2.6+, but they behave more like Python structures in that you can access elements as attributes, e.g. fields.header. Of course, you could also accomplish this with a little more work by writing a class to encapsulate the information from the tuple... again, if you care. You can always just index into fields directly, as I showed above. A: use struct module A: This is an answer to your question-as-an-answer: It certainly can't be the best way, because it DOESN'T WORK. struct.unpack() always returns a tuple. To pluck out the single item in that tuple, you need to do either field1 = struct.unpack('B',data[0])[0] or field1, = struct.unpack('B',data[0]). Even with that fix, it's not a good way: too much typing, error proneness of unnecessary [start:end], inefficiency of 10 function calls instead of one. As you have names, you can use them instead of field1 or field[0] ... like this: (header, length, typeID, param1, param2, param3, param4, name_string, checksum, footer, ) = struct.unpack("!2B I 4H 24s I B", data) A: Is this the best way of doing this or is there a better way It is likely that there will be strings with other formats which will require a different unpacking scheme field1 = struct.unpack('B',data[0]) field2 = struct.unpack('B',data[1]) field3 = struct.unpack('!I',data[2:6]) field4 = struct.unpack('!H',data[6:8]) field5 = struct.unpack('!H',data[8:10]) field6 = struct.unpack('!H',data[10:12]) field7 = struct.unpack('!H',data[12:14]) field8 = struct.unpack('20s',data[14:38]) field9 = struct.unpack('!I',data[38:42]) field10 = struct.unpack('B',data[42]) Regards A: Take a look at the module 'struct'.
Decoding packed data into a structure
What would the best way of unpacking a python string into fields I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function It has the following format uint8 - header uint8 - length uint32 - typeID uint16 -param1 uint16 -param2 uint16 -param3 uint16 -param4 char[24] - name string uint32 - checksum uint8 - footer (I also need to unpack other packets with different formats to the above) How do I unpack these? I am new to python, have done a bit of 'C'. If I was using 'C' I would probably use a structure, would this be the way to go with Python? Regards X
[ "The struct module is designed to unpack heterogeneous data to a tuple based on a format string. It makes more sense to unpack the whole struct at once rather than trying to pull out one field at a time. Here is an example:\nfields = struct.unpack('!BBI4H20sIB', data)\n\nThen you can access a given field, for example the first field:\nfields[0]\n\nYou could also use the tuple to initialize a NamedTuple; look at the documentation for struct for an example. NamedTuples are only available in Python 2.6+, but they behave more like Python structures in that you can access elements as attributes, e.g. fields.header. Of course, you could also accomplish this with a little more work by writing a class to encapsulate the information from the tuple... again, if you care. You can always just index into fields directly, as I showed above.\n", "use struct module\n", "This is an answer to your question-as-an-answer:\nIt certainly can't be the best way, because it DOESN'T WORK. struct.unpack() always returns a tuple. To pluck out the single item in that tuple, you need to do either field1 = struct.unpack('B',data[0])[0] or field1, = struct.unpack('B',data[0]).\nEven with that fix, it's not a good way: too much typing, error proneness of unnecessary [start:end], inefficiency of 10 function calls instead of one.\nAs you have names, you can use them instead of field1 or field[0] ... like this:\n(header, length, typeID, param1, param2,\nparam3, param4, name_string, checksum, footer,\n) = struct.unpack(\"!2B I 4H 24s I B\", data)\n\n", "Is this the best way of doing this or is there a better way\nIt is likely that there will be strings with other formats which will require a different unpacking scheme\nfield1 = struct.unpack('B',data[0])\nfield2 = struct.unpack('B',data[1])\nfield3 = struct.unpack('!I',data[2:6])\nfield4 = struct.unpack('!H',data[6:8])\nfield5 = struct.unpack('!H',data[8:10])\nfield6 = struct.unpack('!H',data[10:12])\nfield7 = struct.unpack('!H',data[12:14])\nfield8 = struct.unpack('20s',data[14:38])\nfield9 = struct.unpack('!I',data[38:42])\nfield10 = struct.unpack('B',data[42]) \nRegards\n", "Take a look at the module 'struct'.\n" ]
[ 7, 4, 4, 1, 0 ]
[]
[]
[ "python", "string", "unpack" ]
stackoverflow_0001879914_python_string_unpack.txt
Q: Retrieve the source of a dynamic website using python (bypassing onclick) I wish to retrieve the source of a website, that is dynamically generated upon clicking a link. The link itself is as below: <a onclick="function(); return false" href="#">Link</a> This stops me from directly querying for a URL that would allow me to get the dynamically generated website (urllib/2). How would one retrieve the source of the website, which was generated with the above function (in HTML) via python? Is there a method to bypass the return false" href="#"? Or the onclick entirely, and get the actual URL? If there is another way to generate the website from the abstract link above, so that one can get it from urllib in python, please refer me to it. EDIT: I generalized the code seen above - however I've been told that one has to reverse engineer the specific javascript to be able to use it. Link to .js - http://a.quizlet.com/j/english/create_setku80j8.js Link to site with link: <a onclick="importText(); return false" href="#">Bulk-import data</a> Actual URL of site: http://quizlet.com/create_set/ Beautified JS of relevant .js above: http://pastie.org/737042 A: You will probably have to reverse engineer the JavaScript to work out what is going on. Can you provide the site and the link in question? A: I don't immediately see any content-generation or link-following code in that script; all importText does is toggle whether a few divs are shown. If you want to study the calls the webapp makes to do a particular action, in order to reproduce them from a bot, you're probably best off looking at the HTTP requests (form submissions and AJAX calls) that the browser makes whilst performing that action. You can use Firebug's ‘Net’ panel to study this for Firefox, or Fiddler for IE.
Retrieve the source of a dynamic website using python (bypassing onclick)
I wish to retrieve the source of a website, that is dynamically generated upon clicking a link. The link itself is as below: <a onclick="function(); return false" href="#">Link</a> This stops me from directly querying for a URL that would allow me to get the dynamically generated website (urllib/2). How would one retrieve the source of the website, which was generated with the above function (in HTML) via python? Is there a method to bypass the return false" href="#"? Or the onclick entirely, and get the actual URL? If there is another way to generate the website from the abstract link above, so that one can get it from urllib in python, please refer me to it. EDIT: I generalized the code seen above - however I've been told that one has to reverse engineer the specific javascript to be able to use it. Link to .js - http://a.quizlet.com/j/english/create_setku80j8.js Link to site with link: <a onclick="importText(); return false" href="#">Bulk-import data</a> Actual URL of site: http://quizlet.com/create_set/ Beautified JS of relevant .js above: http://pastie.org/737042
[ "You will probably have to reverse engineer the JavaScript to work out what is going on.\nCan you provide the site and the link in question?\n", "I don't immediately see any content-generation or link-following code in that script; all importText does is toggle whether a few divs are shown.\nIf you want to study the calls the webapp makes to do a particular action, in order to reproduce them from a bot, you're probably best off looking at the HTTP requests (form submissions and AJAX calls) that the browser makes whilst performing that action. You can use Firebug's ‘Net’ panel to study this for Firefox, or Fiddler for IE.\n" ]
[ 2, 1 ]
[]
[]
[ "javascript", "onclick", "python", "urllib", "urllib2" ]
stackoverflow_0001879876_javascript_onclick_python_urllib_urllib2.txt
Q: Best XMPP Library for Python Web Application I want to learn how to use XMPP and to create a simple web application with real collaboration features. I am writing the application with Python(WSGI), and the application will require javascript enabled because I am going to use jQuery or Dojo. I have downloaded Openfire for the server and which lib to choose? SleekXMPP making trouble with tlslite module(python 2.5 and I need only python 2.6). What is your suggestion? A: I think the Python way to go is to use Twisted along with Words. Good luck! A: Along with what Julien mentioned, also check out the excellent Strophe XMPP javascript client library, as well as the Twisted based XMPP toolkit called Wokkel. A: I have found a lot of issues with Openfire and TLS are not with the xmpp lib :( -- SleekXMPP in the trunk has been converted to Python 3.0 and the branch is maintained for Python 2.5 Unlike Julien, I would only go with Twisted Words if you really need the power of Twisted or if you are already using Twisted. IMO SleekXMPP offers the closest match to the current XEP's in use today.
Best XMPP Library for Python Web Application
I want to learn how to use XMPP and to create a simple web application with real collaboration features. I am writing the application with Python(WSGI), and the application will require javascript enabled because I am going to use jQuery or Dojo. I have downloaded Openfire for the server and which lib to choose? SleekXMPP making trouble with tlslite module(python 2.5 and I need only python 2.6). What is your suggestion?
[ "I think the Python way to go is to use Twisted along with Words.\nGood luck!\n", "Along with what Julien mentioned, also check out the excellent Strophe XMPP javascript client library, as well as the Twisted based XMPP toolkit called Wokkel.\n", "I have found a lot of issues with Openfire and TLS are not with the xmpp lib :( -- SleekXMPP in the trunk has been converted to Python 3.0 and the branch is maintained for Python 2.5\nUnlike Julien, I would only go with Twisted Words if you really need the power of Twisted or if you are already using Twisted. IMO SleekXMPP offers the closest match to the current XEP's in use today.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "javascript", "python", "wsgi", "xmpp" ]
stackoverflow_0001847120_javascript_python_wsgi_xmpp.txt
Q: Large functionality change based on variables I'm in a situation where I've got a project that has a large number of Django views across quite a few different apps. The same codebase and database is being used by a large number of clients. There are a few site-specific use-cases that are coming in and this requires quite a bit of custom code to be written. I'd like to come up with a strategy where we can have the default functionality and then replace django views based on user parameters and so on. Ideally I'd have a central codebase and a project or app per site but due to the current deployment strategy I don't see how this is possible without a massive refactor. I don't like this idea but it might demonstrate the problem better, basically having some way to dynamically load up another module and replace the those in views.py would do the job. Or something like a function decorator that checked for a replacement for that function and it calls that or calls the default if it can't find it. Dynamic loading could be done with something like this The problem I have here is the code base is really large and I need to retain the current API of course and maintain as much backwards compatibility as possible. Basically I'm looking for suggestions for the most pythonic and clear way to do this. A: The most pythonic way would be to use classes for your views and then use inheritance to override specific parts of each view. In your description you describe something which sounds exactly like inheritance. There are two relevant SO questions you might want to look at class views in django and django class view with decorator and sessions Inheritance will give you the tools to do this fine grained overloading that you want to do I think. This would of course require a bit of API change, but it is better to do it now than wait until the project is twice the size!
Large functionality change based on variables
I'm in a situation where I've got a project that has a large number of Django views across quite a few different apps. The same codebase and database is being used by a large number of clients. There are a few site-specific use-cases that are coming in and this requires quite a bit of custom code to be written. I'd like to come up with a strategy where we can have the default functionality and then replace django views based on user parameters and so on. Ideally I'd have a central codebase and a project or app per site but due to the current deployment strategy I don't see how this is possible without a massive refactor. I don't like this idea but it might demonstrate the problem better, basically having some way to dynamically load up another module and replace the those in views.py would do the job. Or something like a function decorator that checked for a replacement for that function and it calls that or calls the default if it can't find it. Dynamic loading could be done with something like this The problem I have here is the code base is really large and I need to retain the current API of course and maintain as much backwards compatibility as possible. Basically I'm looking for suggestions for the most pythonic and clear way to do this.
[ "The most pythonic way would be to use classes for your views and then use inheritance to override specific parts of each view. In your description you describe something which sounds exactly like inheritance.\nThere are two relevant SO questions you might want to look at class views in django and django class view with decorator and sessions\nInheritance will give you the tools to do this fine grained overloading that you want to do I think.\nThis would of course require a bit of API change, but it is better to do it now than wait until the project is twice the size!\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001880619_django_python.txt
Q: Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model? I've got a couple django models that look like this: from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name I'm having all kinds of fun trying to get the limit_choices_to working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible? A: Yes. You need to override the form that admin uses for the Gallery model, then limit the queryset of the photos field in that form: class GalleryAdminForm(django.forms.ModelForm): class Meta: model = Gallery def __init__(self, *args, **kwargs): super(GalleryAdminForm, self).__init__(*args, **kwargs) self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site) class GalleryAdmin(django.contrib.admin.ModelAdmin): form = GalleryAdminForm django.contrib.admin.site.register(Gallery, GalleryAdmin) A: I would delete site field on my Photo model and add a ForeignKey to Gallery. I would remove limit_choices_to from photos fields on Gallery model. Because you are using ForeignKeys to Sites, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless. class Photo(models.Model): title = models.CharField(max_length=100) gallery = models.ForeignKey(Gallery, related_name='photos') file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) def __unicode__(self): return self.name Once you set the site on a gallery all its photos will inherit this property. And the site will be accessible as photo_instance.gallery.site: @property def site(self): return self.gallery.site This should work as if you had a site field. But I haven't tested it. Things change or course, if you decide that a gallery or a photo can appear in multiple sites.
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
I've got a couple django models that look like this: from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name I'm having all kinds of fun trying to get the limit_choices_to working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?
[ "Yes. You need to override the form that admin uses for the Gallery model, then limit the queryset of the photos field in that form:\nclass GalleryAdminForm(django.forms.ModelForm):\n\n class Meta:\n model = Gallery\n\n def __init__(self, *args, **kwargs):\n super(GalleryAdminForm, self).__init__(*args, **kwargs)\n self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site)\n\n\nclass GalleryAdmin(django.contrib.admin.ModelAdmin):\n form = GalleryAdminForm\n\ndjango.contrib.admin.site.register(Gallery, GalleryAdmin)\n\n", "I would delete site field on my Photo model and add a ForeignKey to Gallery. I would remove limit_choices_to from photos fields on Gallery model.\nBecause you are using ForeignKeys to Sites, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless.\nclass Photo(models.Model):\n title = models.CharField(max_length=100)\n gallery = models.ForeignKey(Gallery, related_name='photos')\n file = models.ImageField(upload_to=get_site_profile_path) \n\n def __unicode__(self):\n return self.title\n\n\nclass Gallery(models.Model): \n name = models.CharField(max_length=40)\n site = models.ForeignKey(Site)\n\n def __unicode__(self):\n return self.name\n\nOnce you set the site on a gallery all its photos will inherit this property. And the site will be accessible as photo_instance.gallery.site:\n@property\ndef site(self):\n return self.gallery.site\n\nThis should work as if you had a site field. But I haven't tested it.\nThings change or course, if you decide that a gallery or a photo can appear in multiple sites.\n" ]
[ 6, 2 ]
[ "According to the docs, \"limit_choices_to has no effect when used on a ManyToManyField with an intermediate table\". By my reading, that means it has no effect at all, because ManyToManyFields use intermediate tables...\nI haven't tried to make it work in the Admin site, but from your own views, you can create a form and override the queryset used to populate the list of choices:\nform.fields[\"photos\"].queryset = request.user.photo_set.all()\n\n" ]
[ -1 ]
[ "django", "foreign_keys", "limit_choices_to", "manytomanyfield", "python" ]
stackoverflow_0000345401_django_foreign_keys_limit_choices_to_manytomanyfield_python.txt
Q: How to get the absolute path of a file using tkFileDialog? I am using: file = tkFileDialog.askopenfile(parent=root, mode='rb', filetypes=[('Subrip Subtitle File','*.srt')], title='Choose a subtitle file') to get a file object specified by the user. Is there any way I can get the absolute path of this file from the file object? A: file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file') abs_path = os.path.abspath(file.name) A: os.path.abspath should do what you want, if I understand your question correctly.
How to get the absolute path of a file using tkFileDialog?
I am using: file = tkFileDialog.askopenfile(parent=root, mode='rb', filetypes=[('Subrip Subtitle File','*.srt')], title='Choose a subtitle file') to get a file object specified by the user. Is there any way I can get the absolute path of this file from the file object?
[ "file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')\nabs_path = os.path.abspath(file.name)\n\n", "os.path.abspath should do what you want, if I understand your question correctly.\n" ]
[ 13, 3 ]
[]
[]
[ "dialog", "file", "python", "tkinter" ]
stackoverflow_0001881202_dialog_file_python_tkinter.txt
Q: How to upgrade the version of Python used by Apache? On a Red hat box, I upgraded Python from 2.3 to 2.6.4 and changed the symlink to python so when I type in python the 2.6.4 interpreter comes up. However my .py file works from the command-line, but not in the browser. It seemed like a sys.path issue so I opened the file in a browser and printed out sys.path. Surprisingly, my sys.path is different when called from a browser than when called from a command-line. Because the paths are all referring to 2.3, I believe Apache is picking up Python 2.3 rather than the new 2.6.4 version I installed. How do I make Apache use Python 2.6.4? A: If you're using mod_python or mod_wsgi, you should reinstall them as they've probably been built to the python version you had when they were first installed on the system (which in your case appears to be Python 2.3). A: Apache isn't calling python directly, so the path is irrelevant. You will probably want to build yourself a new mod_wsgi to link against python 2.6.4. A: On RH box Apache probably runs as root user. Login as root and see which version of python root sees. HIH ..richie
How to upgrade the version of Python used by Apache?
On a Red hat box, I upgraded Python from 2.3 to 2.6.4 and changed the symlink to python so when I type in python the 2.6.4 interpreter comes up. However my .py file works from the command-line, but not in the browser. It seemed like a sys.path issue so I opened the file in a browser and printed out sys.path. Surprisingly, my sys.path is different when called from a browser than when called from a command-line. Because the paths are all referring to 2.3, I believe Apache is picking up Python 2.3 rather than the new 2.6.4 version I installed. How do I make Apache use Python 2.6.4?
[ "If you're using mod_python or mod_wsgi, you should reinstall them as they've probably been built to the python version you had when they were first installed on the system (which in your case appears to be Python 2.3).\n", "Apache isn't calling python directly, so the path is irrelevant. You will probably want to build yourself a new mod_wsgi to link against python 2.6.4.\n", "On RH box Apache probably runs as root user. Login as root and see which version of python root sees.\nHIH\n..richie\n" ]
[ 2, 1, 0 ]
[]
[]
[ "apache", "python", "sys.path", "upgrade" ]
stackoverflow_0001880746_apache_python_sys.path_upgrade.txt
Q: How to unpickle from C code I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code. I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshalling data, but nothing about unpickling from C. Edit : Commenters Peter H asked if I was working with numpy arrays. The answer is yes. A: You might want to use something more standardized, like JSON. You have a JSON module in Python 2.6. There are 6 different JSON modules for C. You might want to use something more C-like, like the Python struct module. It can build a C-compatible object directly, saving you from pickling and unpickling. http://docs.python.org/library/struct.html A: If it's just a matrix, you could just write it out as a CSV file. Look at the Python csv module for this. http://docs.python.org/library/csv.html A: Protocol Buffers are an interesting approach to serialize information in a cross-language way that's also quite compact and fast (support for C, as opposed to C++, isn't part of the protobuf package as released, but linking in some C++ code may be acceptable in some C projects, or there may be third-party implementations such as protobuf-c -- see here for a list of other third-party add-ons). A: Check out the chapter on Serializing Data in Mark Pilgrim's Dive Into Python. He states there that "The pickle protocol is Python-specific; there is no guarantee of cross-language compatibility. You probably couldn’t take the [...] pickle file you just created and do anything useful with it in Perl, PHP, Java, or any other language." Perhaps JSON is a better alternative, also explained in that chapter. A: If you absolutely must use pickling, you can embed Python in your C program and unpickle in C via Python. A quick example from Linux Journal Python Docs How do you call Python code from C code? A: take a look at module struct ? A: Besides JSON, there are also the Google Protocol Buffers which have 'native' support (from Google) for Python, C++ and Java -- and a number of third-party bindings to other languages including C.
How to unpickle from C code
I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code. I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshalling data, but nothing about unpickling from C. Edit : Commenters Peter H asked if I was working with numpy arrays. The answer is yes.
[ "You might want to use something more standardized, like JSON. You have a JSON module in Python 2.6. There are 6 different JSON modules for C. \nYou might want to use something more C-like, like the Python struct module. It can build a C-compatible object directly, saving you from pickling and unpickling. http://docs.python.org/library/struct.html\n", "If it's just a matrix, you could just write it out as a CSV file. Look at the Python csv module for this.\nhttp://docs.python.org/library/csv.html\n", "Protocol Buffers are an interesting approach to serialize information in a cross-language way that's also quite compact and fast (support for C, as opposed to C++, isn't part of the protobuf package as released, but linking in some C++ code may be acceptable in some C projects, or there may be third-party implementations such as protobuf-c -- see here for a list of other third-party add-ons).\n", "Check out the chapter on Serializing Data in Mark Pilgrim's Dive Into Python. He states there that \"The pickle protocol is Python-specific; there is no guarantee of cross-language compatibility. You probably couldn’t take the [...] pickle file you just created and do anything useful with it in Perl, PHP, Java, or any other language.\"\nPerhaps JSON is a better alternative, also explained in that chapter.\n", "If you absolutely must use pickling, you can embed Python in your C program and unpickle in C via Python.\n\nA quick example from Linux Journal\nPython Docs\nHow do you call Python code from C code?\n\n", "take a look at module struct ?\n", "Besides JSON, there are also the Google Protocol Buffers which have 'native' support (from Google) for Python, C++ and Java -- and a number of third-party bindings to other languages including C.\n" ]
[ 5, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0001881851_c_python.txt
Q: Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend) It's likely that this is just a general Python Tkinter question, not necessarily a matplotlib one. So I'm in the midst of developing a rather large suite of plotting functionality on top of matplotlib using the Matplotlib "TkAgg" backend (Agg rendering to a Tk canvas using TkInter). I'm using some of the default zooming functionality provided by matplotlib out of the box...specifically the "Zoom to box" button on the default matplotlib toolbar. I am creating my own toolbar by subclassing the existing "matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg" class. Pretty much, the issue here is that I hate the default icon that "Zoom to box" uses (the Tkinter "tcross"). I've figured out how to use a different Tkinter built-in cursor (e.g. this changes the cursor to "plus" instead of "tcross"): import matplotlib matplotlib.use('TkAgg') import matplotlib.backend_bases import matplotlib.backends.backend_tk_agg matplotlib.backends.backend_tkagg.cursord[matplotlib.backend_bases.cursors.SELECT_REGION] = "plus" And in general, I know that to change the current mouse cursor to one of the built-in Tkinter ones from the toolbar class, I can just call: self.window.configure(cursor="cursor_name") So what I would really, really like is to be able to use a magnifying glass icon for when the user is in "zoom mode". I already have a .ppm of the magnifying glass icon I'd like to use and everything, but I can't figure out for the life of me how to use my magnifying glass as the mouse cursor icon. Is it possible to use a custom image as a mouse cursor in Python Tkinter? Help! Platform note: This needs to be workable on Mac OS X 10.5+, RedHat Enterprise Linux 5, and possibly Solaris 10, so a platform-specific solution is undesirable. A: Something like this works with unix X11 XBM files: import Tkinter t = Tkinter.Tk() t.configure(cursor=('@/usr/include/X11/bitmaps/star', '/usr/include/X11/bitmaps/starMask', 'black', 'white')) t.mainloop() As for the Macs, from the man page for "Tk_GetCursorFromData": The Macintosh version of Tk supports all of the X cursors and will also accept any of the standard Mac cursors including ibeam, crosshair, watch, plus, and arrow. In addition, Tk will load Macintosh cursor resources of the types crsr (color) and CURS (black and white) by the name of the of the resource. The application and all its open dynamic library's resource files will be searched for the named cursor. If there are conflicts color cursors will always be loaded in preference to black and white cursors.
Is it possible to make a custom mouse cursor with Python Tkinter? (Using matplotlib with the TkAgg backend)
It's likely that this is just a general Python Tkinter question, not necessarily a matplotlib one. So I'm in the midst of developing a rather large suite of plotting functionality on top of matplotlib using the Matplotlib "TkAgg" backend (Agg rendering to a Tk canvas using TkInter). I'm using some of the default zooming functionality provided by matplotlib out of the box...specifically the "Zoom to box" button on the default matplotlib toolbar. I am creating my own toolbar by subclassing the existing "matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg" class. Pretty much, the issue here is that I hate the default icon that "Zoom to box" uses (the Tkinter "tcross"). I've figured out how to use a different Tkinter built-in cursor (e.g. this changes the cursor to "plus" instead of "tcross"): import matplotlib matplotlib.use('TkAgg') import matplotlib.backend_bases import matplotlib.backends.backend_tk_agg matplotlib.backends.backend_tkagg.cursord[matplotlib.backend_bases.cursors.SELECT_REGION] = "plus" And in general, I know that to change the current mouse cursor to one of the built-in Tkinter ones from the toolbar class, I can just call: self.window.configure(cursor="cursor_name") So what I would really, really like is to be able to use a magnifying glass icon for when the user is in "zoom mode". I already have a .ppm of the magnifying glass icon I'd like to use and everything, but I can't figure out for the life of me how to use my magnifying glass as the mouse cursor icon. Is it possible to use a custom image as a mouse cursor in Python Tkinter? Help! Platform note: This needs to be workable on Mac OS X 10.5+, RedHat Enterprise Linux 5, and possibly Solaris 10, so a platform-specific solution is undesirable.
[ "Something like this works with unix X11 XBM files:\nimport Tkinter\nt = Tkinter.Tk()\nt.configure(cursor=('@/usr/include/X11/bitmaps/star', '/usr/include/X11/bitmaps/starMask', 'black', 'white'))\nt.mainloop()\n\nAs for the Macs, from the man page for \"Tk_GetCursorFromData\":\n\nThe Macintosh version of Tk supports all of the X cursors \n and\n will also accept any of the standard Mac cursors\n including\n ibeam, crosshair, watch, plus, and arrow. In addition, Tk \n will\n load Macintosh cursor resources of the types crsr (color)\n and\n CURS (black and white) by the name of the of the resource.\n The\n application and all its open dynamic library's resource\n files\n will be searched for the named cursor. If there are \n conflicts\n color cursors will always be loaded in preference to\n black and\n white cursors.\n\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "mouse_cursor", "python", "tkinter" ]
stackoverflow_0001877360_matplotlib_mouse_cursor_python_tkinter.txt
Q: How do I transfer data in .csv file into my sqlite database in django? This is my models.py from django.db import models class School(models.Model): school = models.CharField(max_length=300) def __unicode__(self): return self.school class Lawyer(models.Model): firm_url = models.URLField('Bio', max_length=200) firm_name = models.CharField('Firm', max_length=100) first = models.CharField('First Name', max_length=50) last = models.CharField('Last Name', max_length=50) year_graduated = models.IntegerField('Year graduated') school = models.CharField(max_length=300) school = models.ForeignKey(School) class Meta: ordering = ('?',) def __unicode__(self): return self.first And 2 sample rows from the csv file: "http://www.graychase.com/aabbas,Gray & Chase LLP, Amr A ,Abbas,The George Washington University Law School, 2005" "http://www.graychase.com/kadam,Gray & Chase LLP, Karin ,Adam,Ernst Moritz Arndt University Greifswald, 2004" Thank you. EDIT Can you give a bit more detailed info about this script? Some questions: My app is in C:.../Documents/PROJECTS/Django/sw2/wkw2. This path is already in PYTHONPATH do I still need this line? If so, do I enter it like this? sys.path.append('C:\\sw2') what does os.environ do? I tried to read the documentation but I didn't understand. os.environ['DJANGO_SETTINGS_MODULE'] = 'sw2.settings' from django.core.management import setup_environ from sw2 import settings from sw2.wkw2.models import * import csv dataReader = csv.reader(open('csvtest1.csv'), delimiter=',', quotechar='"') for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer.school=row[4] lawyer.year_graduated=row[5] lawyer.save() Thanks! Edit in response to celopes' answer: celopes: I saw your answer a little late. I've been trying to update the database in the shell with >>> p1 = Lawyer(school = "The George Washington University Law School", last = "Babbas", firm_url = "http://www.graychase.com/babbas", year_graduated = 2005, firm_name= "Gray & Chase", first= "Amr A") but I kept getting the integer error. Finally, I realized that school needed to be the school_id, that is, in the form, >>> p1 = Lawyer(school_id = 1, last = "Babbas", firm_url = "http://www.graychase.com/babbas", year_graduated = 2005, firm_name= "Gray & Chase", first= "Amr A") From this I realized that, I needed to know the school id of each school to update the Lawyer table. Since that was not possible, I decided to remove the ForeignKey because I didn't know how to fix this. (I am new to both Python and Django.) And this morning I saw your answer. Now I changed my model in the dev server and I have only 1 table: Lawyer. I think this is what I will be using. My apologies again for not seeing your answer earlier. Edit 12/14/09: celopes: Thanks again for this script. It solved my problem. It's good that I don't need to convert the csv to json or another format before saving to the db. I have made a few changes. First as mentioned before, I changed the model to just Lawyer. Also, you fixed the duplicate school by using "name." But I have list_display, list_filter and search_fields in admin.py and changing fields names caused too many errors. class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), #('School', {'fields': ['school', 'year_graduated']}), ] list_display = ('last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated') list_filter = ['school', 'year_graduated'] search_fields = ['last', 'school', 'firm_name'] #search_fields = ['school__school'] #search_fields = ['school__lawyer__last'] With the new models.py the simplified script worked well. This is what I am using: csv_filepathname="C:/Users/A/Documents/Projects/Django/sw2/wkw2/fixtures/data1.csv" your_djangoproject_home="C:/Users/A/Documents/PROJECTS/Django/" import sys,os sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] ='sw2.settings' from sw2.wkw2.models import Lawyer import csv dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer.school=row[4] lawyer.year_graduated=row[5] lawyer.save() Also I removed the quotes around each row. I noticed that if I put the the year in quotes, I got the integer error, without quotes works fine. How did you make it work with quotes? Thanks again, this has been very helpful. Now I have to make it work in the production server. A: I created a complete script using this data as a test: "http://www.graychase.com/aabbas","Gray & Chase LLP","Amr A","Abbas","The George Washington University Law School","2005" "http://www.graychase.com/kadam","Gray & Chase LLP","Karin","Adam","Ernst Moritz Arndt University Greifswald","2004" Please mind that your CSV file as you exemplify above IS WRONG. The csv file reader will read the entire line as an entry because the entire line is in quotes. Either remove the beginning and trailing quotes from every line in the csv file or - like I did - enclose each distinct value in the line in quotes. Here are your models that will work with the script below: from django.db import models class School(models.Model): name = models.CharField(max_length=300, unique=True) def __unicode__(self): return self.name class Lawyer(models.Model): firm_url = models.URLField('Bio', max_length=200, unique=True) firm_name = models.CharField('Firm', max_length=100) first = models.CharField('First Name', max_length=50) last = models.CharField('Last Name', max_length=50) year_graduated = models.IntegerField('Year graduated') school = models.ForeignKey(School) def __unicode__(self): return self.first Here is the script that will read your CSV file (unless I got the name of you project sw2 and application wkw2 wrong, then fix those references): ############ All you need to modify is below ############ # Full path and name to your csv file csv_filepathname="C:/Users/A/Documents/Projects/Django/sw2/wkw2/fixtures/data.csv" # Full path to the directory immediately above your django project directory your_djangoproject_home="C:.../Documents/PROJECTS/Django/" ############ All you need to modify is above ############ import sys,os sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] ='sw2.settings' from sw2.wkw2.models import School, Lawyer import csv dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') old_school = None for row in dataReader: if old_school != row[4]: old_school = row[4] school = School() school.name = old_school school.save() dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer_school=School.objects.get(name=row[4]) lawyer.school=lawyer_school lawyer.year_graduated=row[5] lawyer.save() The script is first creating every single possible school from the available schools in the CSV file. Then it runs through the CSV again and create every single lawyer. I ran this script with the test data. It works just fine and loads all the CSV data.
How do I transfer data in .csv file into my sqlite database in django?
This is my models.py from django.db import models class School(models.Model): school = models.CharField(max_length=300) def __unicode__(self): return self.school class Lawyer(models.Model): firm_url = models.URLField('Bio', max_length=200) firm_name = models.CharField('Firm', max_length=100) first = models.CharField('First Name', max_length=50) last = models.CharField('Last Name', max_length=50) year_graduated = models.IntegerField('Year graduated') school = models.CharField(max_length=300) school = models.ForeignKey(School) class Meta: ordering = ('?',) def __unicode__(self): return self.first And 2 sample rows from the csv file: "http://www.graychase.com/aabbas,Gray & Chase LLP, Amr A ,Abbas,The George Washington University Law School, 2005" "http://www.graychase.com/kadam,Gray & Chase LLP, Karin ,Adam,Ernst Moritz Arndt University Greifswald, 2004" Thank you. EDIT Can you give a bit more detailed info about this script? Some questions: My app is in C:.../Documents/PROJECTS/Django/sw2/wkw2. This path is already in PYTHONPATH do I still need this line? If so, do I enter it like this? sys.path.append('C:\\sw2') what does os.environ do? I tried to read the documentation but I didn't understand. os.environ['DJANGO_SETTINGS_MODULE'] = 'sw2.settings' from django.core.management import setup_environ from sw2 import settings from sw2.wkw2.models import * import csv dataReader = csv.reader(open('csvtest1.csv'), delimiter=',', quotechar='"') for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer.school=row[4] lawyer.year_graduated=row[5] lawyer.save() Thanks! Edit in response to celopes' answer: celopes: I saw your answer a little late. I've been trying to update the database in the shell with >>> p1 = Lawyer(school = "The George Washington University Law School", last = "Babbas", firm_url = "http://www.graychase.com/babbas", year_graduated = 2005, firm_name= "Gray & Chase", first= "Amr A") but I kept getting the integer error. Finally, I realized that school needed to be the school_id, that is, in the form, >>> p1 = Lawyer(school_id = 1, last = "Babbas", firm_url = "http://www.graychase.com/babbas", year_graduated = 2005, firm_name= "Gray & Chase", first= "Amr A") From this I realized that, I needed to know the school id of each school to update the Lawyer table. Since that was not possible, I decided to remove the ForeignKey because I didn't know how to fix this. (I am new to both Python and Django.) And this morning I saw your answer. Now I changed my model in the dev server and I have only 1 table: Lawyer. I think this is what I will be using. My apologies again for not seeing your answer earlier. Edit 12/14/09: celopes: Thanks again for this script. It solved my problem. It's good that I don't need to convert the csv to json or another format before saving to the db. I have made a few changes. First as mentioned before, I changed the model to just Lawyer. Also, you fixed the duplicate school by using "name." But I have list_display, list_filter and search_fields in admin.py and changing fields names caused too many errors. class LawyerAdmin(admin.ModelAdmin): fieldsets = [ ('Name', {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}), #('School', {'fields': ['school', 'year_graduated']}), ] list_display = ('last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated') list_filter = ['school', 'year_graduated'] search_fields = ['last', 'school', 'firm_name'] #search_fields = ['school__school'] #search_fields = ['school__lawyer__last'] With the new models.py the simplified script worked well. This is what I am using: csv_filepathname="C:/Users/A/Documents/Projects/Django/sw2/wkw2/fixtures/data1.csv" your_djangoproject_home="C:/Users/A/Documents/PROJECTS/Django/" import sys,os sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] ='sw2.settings' from sw2.wkw2.models import Lawyer import csv dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer.school=row[4] lawyer.year_graduated=row[5] lawyer.save() Also I removed the quotes around each row. I noticed that if I put the the year in quotes, I got the integer error, without quotes works fine. How did you make it work with quotes? Thanks again, this has been very helpful. Now I have to make it work in the production server.
[ "I created a complete script using this data as a test:\n\"http://www.graychase.com/aabbas\",\"Gray & Chase LLP\",\"Amr A\",\"Abbas\",\"The George Washington University Law School\",\"2005\"\n\"http://www.graychase.com/kadam\",\"Gray & Chase LLP\",\"Karin\",\"Adam\",\"Ernst Moritz Arndt University Greifswald\",\"2004\"\n\nPlease mind that your CSV file as you exemplify above IS WRONG. The csv file reader will read the entire line as an entry because the entire line is in quotes. Either remove the beginning and trailing quotes from every line in the csv file or - like I did - enclose each distinct value in the line in quotes.\nHere are your models that will work with the script below:\nfrom django.db import models\n\nclass School(models.Model): \n name = models.CharField(max_length=300, unique=True)\n\n def __unicode__(self):\n return self.name\n\nclass Lawyer(models.Model):\n firm_url = models.URLField('Bio', max_length=200, unique=True)\n firm_name = models.CharField('Firm', max_length=100)\n first = models.CharField('First Name', max_length=50)\n last = models.CharField('Last Name', max_length=50)\n year_graduated = models.IntegerField('Year graduated')\n school = models.ForeignKey(School)\n\n def __unicode__(self):\n return self.first\n\nHere is the script that will read your CSV file (unless I got the name of you project sw2 and application wkw2 wrong, then fix those references):\n############ All you need to modify is below ############\n# Full path and name to your csv file\ncsv_filepathname=\"C:/Users/A/Documents/Projects/Django/sw2/wkw2/fixtures/data.csv\"\n# Full path to the directory immediately above your django project directory\nyour_djangoproject_home=\"C:.../Documents/PROJECTS/Django/\"\n############ All you need to modify is above ############\n\nimport sys,os\nsys.path.append(your_djangoproject_home)\nos.environ['DJANGO_SETTINGS_MODULE'] ='sw2.settings'\n\nfrom sw2.wkw2.models import School, Lawyer\n\nimport csv\ndataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='\"')\n\nold_school = None\nfor row in dataReader:\n if old_school != row[4]:\n old_school = row[4]\n school = School()\n school.name = old_school\n school.save()\n\ndataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='\"')\n\nfor row in dataReader:\n lawyer=Lawyer()\n lawyer.firm_url=row[0]\n lawyer.firm_name=row[1]\n lawyer.first=row[2]\n lawyer.last=row[3]\n\n lawyer_school=School.objects.get(name=row[4])\n lawyer.school=lawyer_school\n\n lawyer.year_graduated=row[5]\n lawyer.save()\n\nThe script is first creating every single possible school from the available schools in the CSV file. Then it runs through the CSV again and create every single lawyer.\nI ran this script with the test data. It works just fine and loads all the CSV data.\n" ]
[ 8 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0001882469_csv_django_python.txt
Q: WMD Preview Doesn't Match Output I am using WMD in a google app situation whereby the site administrator can update the pages of the site and the users see the information. The preview function is working fine and I can see the text the way I want it to appear, but when I am in the users section, the markdown is being returned without the formatting - how can i fix this? This is the code i am using {% block content-left %} {% if is_admin %} <div id="content-bodyleft" class="wmd-preview"></div> <form action="/admin/content/" method="post"> <textarea id="markdown" name="markdown" style="width: 400px; height: 200px;" >{{ page_content.html }}</textarea> <input name="page" type="hidden" value="{{ request.path }}" /> <input type="submit" name="Save" /> </form> <div class="wmd-output"></div> <script type="text/javascript"> // to set WMD's options programatically, define a "wmd_options" // object with whatever settings // you want to override. Here are the defaults: wmd_options = { // format sent to the server. Use "Markdown" to return the markdown source. output: "Markdown", // line wrapping length for lists, blockquotes, etc. lineLength: 40, // toolbar buttons. Undo and redo get appended automatically. buttons: "bold italic | link blockquote code image | ol ul heading hr", // option to automatically add WMD to the first textarea found. // See apiExample.html for usage. autostart: true }; </script> <div class="wmd-output"></div> <script type="text/javascript" src="/static/wmd/wmd.js"></script> {% else %} {{ page_content.html|markdown }} {% endif %} A: The reason this is happening is because the Django Form is only seeing the value of the <textarea> tag that represents WMD editor. That value is the actual markdown, not the rendered HTML that you see in the preview. There are several ways to fix this, on either the client or the server... When the form is saved, convert the markdown to HTML on the server using a python markdown module, like this one When the form is submitted on the client, have javascript replace the value of the WMD <textarea> tag to the actual HTML Option #1 is probably the easiest. Here's some sample code... import markdown class MyModel(models.Model): text = models.TextField() def save(self, force_insert=False, force_update=False): if self.text: self.text = markdown.markdown(self.text) super(MyModel, self).save(force_insert, force_update) A: This doesn't appear to have anything to do with WMD.js, which is an editor and has nothing to do with displaying the content. You don't post your models, but it looks like you are entering content into the "markdown" field, but displaying a different field, "html". I presume you have something in your models - maybe on save - that populates that html field with the converted markup? Also are you sure you're seeing raw markdown, or are you seeing raw HTML? I would assume you would need to unescape the html output: {{ page_content.html|safe }} A: This is my models.py file # models.py from google.appengine.ext import db class GoogleToken(db.Model): session_token = db.StringProperty() scope_url = db.StringProperty() added_on = db.DateTimeProperty(auto_now_add=True) class PageContent(db.Model): html = db.TextProperty() page = db.StringProperty() class PageMedia(db.Model): name = db.StringProperty() type = db.StringProperty() content = db.BlobProperty(default=None) class Announcement(db.Model): title = db.StringProperty() content = db.TextProperty() added_on = db.DateTimeProperty(auto_now_add=True) and this is from views.py def content(request): html = request.POST.get('markdown', None) page = request.POST.get('page', None) logging.debug(html) logging.debug('Page: %s' % page) query = PageContent.all().filter('page =', page) page_content = query.get() if page_content == None: page_content = PageContent(html=html,page=page) else: page_content.html = html To help you understand what is happening, for example I am typing Title ---- *Subtitle* Text text text and seeing Title Subtitle Text text text in preview, but on output i am seeing Title----*Subtitle*Text text text Thanks, I do appreciate your help with this.
WMD Preview Doesn't Match Output
I am using WMD in a google app situation whereby the site administrator can update the pages of the site and the users see the information. The preview function is working fine and I can see the text the way I want it to appear, but when I am in the users section, the markdown is being returned without the formatting - how can i fix this? This is the code i am using {% block content-left %} {% if is_admin %} <div id="content-bodyleft" class="wmd-preview"></div> <form action="/admin/content/" method="post"> <textarea id="markdown" name="markdown" style="width: 400px; height: 200px;" >{{ page_content.html }}</textarea> <input name="page" type="hidden" value="{{ request.path }}" /> <input type="submit" name="Save" /> </form> <div class="wmd-output"></div> <script type="text/javascript"> // to set WMD's options programatically, define a "wmd_options" // object with whatever settings // you want to override. Here are the defaults: wmd_options = { // format sent to the server. Use "Markdown" to return the markdown source. output: "Markdown", // line wrapping length for lists, blockquotes, etc. lineLength: 40, // toolbar buttons. Undo and redo get appended automatically. buttons: "bold italic | link blockquote code image | ol ul heading hr", // option to automatically add WMD to the first textarea found. // See apiExample.html for usage. autostart: true }; </script> <div class="wmd-output"></div> <script type="text/javascript" src="/static/wmd/wmd.js"></script> {% else %} {{ page_content.html|markdown }} {% endif %}
[ "The reason this is happening is because the Django Form is only seeing the value of the <textarea> tag that represents WMD editor. That value is the actual markdown, not the rendered HTML that you see in the preview.\nThere are several ways to fix this, on either the client or the server...\n\nWhen the form is saved, convert the markdown to HTML on the server using a python markdown module, like this one\nWhen the form is submitted on the client, have javascript replace the value of the WMD <textarea> tag to the actual HTML\n\nOption #1 is probably the easiest. Here's some sample code...\nimport markdown\n\nclass MyModel(models.Model):\n text = models.TextField()\n\n def save(self, force_insert=False, force_update=False):\n if self.text:\n self.text = markdown.markdown(self.text)\n\n super(MyModel, self).save(force_insert, force_update)\n\n", "This doesn't appear to have anything to do with WMD.js, which is an editor and has nothing to do with displaying the content.\nYou don't post your models, but it looks like you are entering content into the \"markdown\" field, but displaying a different field, \"html\". I presume you have something in your models - maybe on save - that populates that html field with the converted markup? \nAlso are you sure you're seeing raw markdown, or are you seeing raw HTML? I would assume you would need to unescape the html output:\n{{ page_content.html|safe }}\n\n", "This is my models.py file \n# models.py\nfrom google.appengine.ext import db\n\nclass GoogleToken(db.Model):\n session_token = db.StringProperty()\n scope_url = db.StringProperty()\n added_on = db.DateTimeProperty(auto_now_add=True)\n\nclass PageContent(db.Model):\n html = db.TextProperty()\n page = db.StringProperty()\n\nclass PageMedia(db.Model):\n name = db.StringProperty()\n type = db.StringProperty()\n content = db.BlobProperty(default=None)\n\nclass Announcement(db.Model):\n title = db.StringProperty()\n content = db.TextProperty()\n added_on = db.DateTimeProperty(auto_now_add=True)\n\nand this is from views.py \ndef content(request):\n html = request.POST.get('markdown', None)\n page = request.POST.get('page', None)\n\n logging.debug(html)\n logging.debug('Page: %s' % page)\n\n query = PageContent.all().filter('page =', page)\n page_content = query.get()\n if page_content == None:\n page_content = PageContent(html=html,page=page)\n else:\n page_content.html = html\n\nTo help you understand what is happening, for example I am typing\nTitle\n----\n*Subtitle*\n\nText text text \n\nand seeing \nTitle\nSubtitle\nText text text \nin preview, but on output i am seeing\nTitle----*Subtitle*Text text text \n\nThanks, I do appreciate your help with this. \n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "markdown", "python", "wmd" ]
stackoverflow_0001864081_django_google_app_engine_markdown_python_wmd.txt
Q: SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record. I am using the Declarative Base approach. I setup the parent child relationship using the FKs and the relation function. What I'm trying to achieve is to get something like a pseudo autoincrement function that will lookup the max CategoryID value within the Category unique name group and increment it up one. I've tried using various default functions but the problem I run into is the inability to specify the CategoryUniqueName at the time of insertion. I can't find a way to pass the current value of CategoryItems.CategoryUniqueName so that the lookup query has the correct filter applied when trying to select something like func.max(CategoryItems.CategoryID). If I hardcode a query it works just fine. This is what I'm thinking should work but, again, I can't find a way to specify the unique value for the filter. unique_group='my_group' result=con.query(func.max(CategoryItems.CategoryID)).filter(and_( CategoryItems.CategoryUniqueName==unique_group, )).one() The classes are shown below. Much appreciate some guidance on how to accomplish this inside standard SQL Alchemy. I know I could always lookup the value and simply specify it directly within the same transaction but I'm trying to come up with a stand-alone SQL Alchemy approach that does not require additional logic elsewhere. class Category(Base): __tablename__ = 'parent_table' __table_args__ = {'mysql_engine':'InnoDB', 'useexisting':True} CategoryUniqueName = Column(Unicode(255), primary_key=True) CategoryGroupName = Column(Unicode(255), nullable=False) CategoryGroupMemo = Column(UnicodeText) SortOrder = Column(Integer, index=True) IsLocked = Column(Boolean, default=0) class CategoryItems(Base): __tablename__ = 'child_table' __table_args__ = {'mysql_engine':'InnoDB', 'useexisting':True} CategoryUniqueName = Column(Unicode(255), ForeignKey(Category.CategoryUniqueName), primary_key=True) CategoryID = Column(Integer, primary_key=True, autoincrement=False) CategoryName = Column(Unicode(255), nullable=False, index=True) CategoryMemo = Column(UnicodeText) CategoryImage = Column(Unicode(255)) CategoryFlex1 = Column(Unicode(255), index=True) CategoryFlex2 = Column(Unicode(255), index=True) CategoryFlex3 = Column(Unicode(255), index=True) SortOrder = Column(Integer, index=True) category_group = relation( Category, backref=backref( 'items', order_by=SortOrder, collection_class=ordering_list('SortOrder'), cascade="all, delete, delete-orphan" )) A: I see 3 ways to go: The most obvious and well documented. Create a mapper extension with before_insert() hook replacing inserted parameter. Pass function as default argument. This function is called with context parameter with all data you need: context.compiled_parameters[0]['CategoryUniqueName'], context.connection. Pass FetchedValue() in server_default parameter and use trigger to do the job server side. All these solutions have race condition mentioned by ddaa. In case of race condition your code won't break database state, but will fail with exception when primary key is defined properly (it's not true for your code!). It might be acceptable for some application to fail (show 500 page in web application) in some rare cases. Note, that you have defined a CategoryID as primary key. This won't allow reuse of the same number for different values of CategoryUniqueName column. You have to change it to composite primary index for 2 columns. A: Thanks for the insight Denis, you are spot on. I played with both options 1 and 2 and they work very nicely. The context parameter was the key for option 2. I didn't realize it was being passed automatically. One thing I did note was option 1 would introduce a race condition even in the context of a single user submit of multiple records. I think this has something to do with the flush and save timing. However option 2 works brilliantly. This is the little function that gets called from the default parameter now: def getNextId(context): unique_name=context.compiled_parameters[0]['CategoryUniqueName'] sql = """ SELECT MAX(CategoryID) FROM child_table WHERE CategoryUniqueName='%s'""" % (unique_name, ) result = context.connection.execute(sql).fetchone()[0] if result > 0: return result + 1 else: return 1 A: So, what you're trying to achieve is have each set of CategoryItems with a different CategoryUniqueName have their CategoryId auto-incremented separately? If that's right, your current approach (get the current max of CategoryId in the subset of CategoryItems you're adding to) is broken. It has an intrinsic race condition: concurrent insertions will use the same CategoryId. Do you really need your CategoryId incremented separately? Why not just use the normal auto-increment feature. The sequence CategoryId's for a given CategoryUniqueName will have holes, but is that really a problem? If you require successive sequence numbers, you will need to prevent race condition using some manual locking.
SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records
I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record. I am using the Declarative Base approach. I setup the parent child relationship using the FKs and the relation function. What I'm trying to achieve is to get something like a pseudo autoincrement function that will lookup the max CategoryID value within the Category unique name group and increment it up one. I've tried using various default functions but the problem I run into is the inability to specify the CategoryUniqueName at the time of insertion. I can't find a way to pass the current value of CategoryItems.CategoryUniqueName so that the lookup query has the correct filter applied when trying to select something like func.max(CategoryItems.CategoryID). If I hardcode a query it works just fine. This is what I'm thinking should work but, again, I can't find a way to specify the unique value for the filter. unique_group='my_group' result=con.query(func.max(CategoryItems.CategoryID)).filter(and_( CategoryItems.CategoryUniqueName==unique_group, )).one() The classes are shown below. Much appreciate some guidance on how to accomplish this inside standard SQL Alchemy. I know I could always lookup the value and simply specify it directly within the same transaction but I'm trying to come up with a stand-alone SQL Alchemy approach that does not require additional logic elsewhere. class Category(Base): __tablename__ = 'parent_table' __table_args__ = {'mysql_engine':'InnoDB', 'useexisting':True} CategoryUniqueName = Column(Unicode(255), primary_key=True) CategoryGroupName = Column(Unicode(255), nullable=False) CategoryGroupMemo = Column(UnicodeText) SortOrder = Column(Integer, index=True) IsLocked = Column(Boolean, default=0) class CategoryItems(Base): __tablename__ = 'child_table' __table_args__ = {'mysql_engine':'InnoDB', 'useexisting':True} CategoryUniqueName = Column(Unicode(255), ForeignKey(Category.CategoryUniqueName), primary_key=True) CategoryID = Column(Integer, primary_key=True, autoincrement=False) CategoryName = Column(Unicode(255), nullable=False, index=True) CategoryMemo = Column(UnicodeText) CategoryImage = Column(Unicode(255)) CategoryFlex1 = Column(Unicode(255), index=True) CategoryFlex2 = Column(Unicode(255), index=True) CategoryFlex3 = Column(Unicode(255), index=True) SortOrder = Column(Integer, index=True) category_group = relation( Category, backref=backref( 'items', order_by=SortOrder, collection_class=ordering_list('SortOrder'), cascade="all, delete, delete-orphan" ))
[ "I see 3 ways to go:\n\nThe most obvious and well documented. Create a mapper extension with before_insert() hook replacing inserted parameter.\nPass function as default argument. This function is called with context parameter with all data you need: context.compiled_parameters[0]['CategoryUniqueName'], context.connection.\nPass FetchedValue() in server_default parameter and use trigger to do the job server side.\n\nAll these solutions have race condition mentioned by ddaa. In case of race condition your code won't break database state, but will fail with exception when primary key is defined properly (it's not true for your code!). It might be acceptable for some application to fail (show 500 page in web application) in some rare cases.\nNote, that you have defined a CategoryID as primary key. This won't allow reuse of the same number for different values of CategoryUniqueName column. You have to change it to composite primary index for 2 columns.\n", "Thanks for the insight Denis, you are spot on. I played with both options 1 and 2 and they work very nicely. The context parameter was the key for option 2. I didn't realize it was being passed automatically. One thing I did note was option 1 would introduce a race condition even in the context of a single user submit of multiple records. I think this has something to do with the flush and save timing. However option 2 works brilliantly.\nThis is the little function that gets called from the default parameter now:\ndef getNextId(context):\n unique_name=context.compiled_parameters[0]['CategoryUniqueName']\n sql = \"\"\"\n SELECT MAX(CategoryID)\n FROM child_table\n WHERE CategoryUniqueName='%s'\"\"\" % (unique_name, )\n\n result = context.connection.execute(sql).fetchone()[0]\n if result > 0:\n return result + 1\n else:\n return 1 \n\n", "So, what you're trying to achieve is have each set of CategoryItems with a different CategoryUniqueName have their CategoryId auto-incremented separately?\nIf that's right, your current approach (get the current max of CategoryId in the subset of CategoryItems you're adding to) is broken. It has an intrinsic race condition: concurrent insertions will use the same CategoryId.\nDo you really need your CategoryId incremented separately? Why not just use the normal auto-increment feature. The sequence CategoryId's for a given CategoryUniqueName will have holes, but is that really a problem?\nIf you require successive sequence numbers, you will need to prevent race condition using some manual locking.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "auto_increment", "declarative", "primary_key", "python", "sqlalchemy" ]
stackoverflow_0001870364_auto_increment_declarative_primary_key_python_sqlalchemy.txt
Q: How does Smalltalk (Pharo for example) compare to Python? I've seen some comparisons between Smalltalk and Ruby on the one hand and Ruby and Python on the other, but not between Python and Smalltalk. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct? A: For example Python does not seem to have Metaclasses. It sure does -- it just doesn't implicitly generate a new metaclass for every class: it uses the same metaclass as the parent class, or type by default. Python's design philosophy, aka "The Zen of Python", can be perused by doing import this at an interactive interpreter's prompt; the applicable point here is the second one, "Explicit is better than implicit." In Python 2.X, you specify a custom metaclass with the following syntax: class sic: __metaclass__ = mymeta ... In Python 3.X, more elegantly, you use named-argument syntax: class sify(metaclass=mymeta): ... Smalltalk has no concept of generators. Python's generators are first-class (typically standalone) functions, and Smalltalk doesn't have the concept of "standalone" functions -- it has methods inside classes. But it certainly does have iterators -- as classes, of course: iterator := aCollection iterator. [iterator hasNext] whileTrue: [iterator next doSomething]. Since Smalltalk has first-class "code blocks" (Ruby took them from it), you accomplish iteration, just like other "control structures", by sending a code block to a suitable method, and if you wish you can do that directly with the collection (think select:): aCollection select: [:item | item doSomething]. So in Smalltalk (and Ruby) you send the code block to the iteration; Python does things the other way round, the iteration sends values out to the surrounding "calling" code. Looks very different, but not "deeply" different in the end. First-class code blocks mean that Smalltalk doesn't need nor have "control structure" statements and keywords such as if or while: they can be accomplished by sending code blocks as arguments of appropriate methods (e.g. ifTrue: method of booleans). (Ruby chooses to have the keywords/statements in addition to the first-class code blocks; I would say that Python [[explicitly]] and Smalltalk [[implicitly]] both try, like C, to "offer a single way to perform an operation", while Ruby's more in the Perl-ish school of "there are many ways to do it"). And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct? No, absolutely incorrect -- Python intensely does dynamic method dispatch, to extremes. Consider for example: for i in range(10): myobject.bah() By Python semantics, this performs 10 lookups for method bah in myobject -- just in case the previous execution of the method had caused myobject to entirely restructure itself internally so that its current bah method is completely different from the previous one (might be a pretty insane thing for the programmer to rely on such furious dynamism, but Python supports it). This is the reason that makes: themethod = myobject.bah for i in range(10): themethod() a common hand-optimization in Python code -- does one dynamic lookup before the loop instead of 10 inside the loop, one per leg (it's a case of "constant hoisting", since the compiler is forbidden from doing the "constant folding" itself by Python's extreme rules for dynamic lookups -- unless it can prove that it's guaranteed to be innocuous, and in practice such proof is too hard so Python implementations typically don't bother). Python uses unified namespaces: methods are attributes of an object just like any other, except that they're callable. This is why extracting the method without calling it (known as a "bound method"), setting a reference to it in a variable (or stashing it into a list or other container, returning it from a function, whatever) is a plain and simple operation like in the above constant-hoisting example. Smalltalk and Ruby have separate namespaces for methods and other attributes (in Smalltalk, non-methods attributes are not visible outside the object's own methods), so "extracting a method" and "calling the resulting object" require more introspective ceremony (but the common case of dispatching may be thereby made marginally simpler in certain cases -- in particular, "just mentioning" an argument-less method implicitly calls it, while in Python, like in C, calling is explicitly performed by appending parentheses, while "just mentioning", well... "just mentions" it, making it available for any sort of explicit operation including calling;-). A: Python certainly does have metaclasses. Smalltalk has some unusual features: Has a rather simple syntax and only about 6 (!) keywords. Everything else (including defining new classes) is accomplished by calling methods (sending messages in Smalltalk). This allows you to create some DSL within the language. In Smalltalk, you don't store source files, but instead have one big memory image and you modify it on the fly. You can also modify most of the Smalltalk itself (and possibly break it ;) A: I've been reading coders at work which is a really nice book full of interviews with top programmers. Anyhow, one of them is the inventor of smalltalk and he talks in length on his language and how it relates to python (he likes python quite a bit as well). The only problem he had with python was it's slow code... he really wanted to have the smalltalk jit compiler as a backend for python, but unfortunately due to the software belonging to the company he worked for, this was not possible. anyhow... maybe not a point by point comparison, but really a good read anyway this book. A: Smalltalk has no concept of generators. True, but they can be implemented in most Smalltalk dialects from within the language. GNU Smalltalk comes with Generators as part of its stream library. A: According to Wikipedia's page on dynamic method dispatch: Smalltalk Implementation Smalltalk uses a type based message dispatcher. Each instance has a single type whose definition contains the methods. When an instance receives a message, the dispatcher looks up the corresponding method in the message-to-method map for the type and then invokes the method. [...] Many other dynamically typed languages, including Python, Ruby, Objective-C and Groovy use similar approaches. Emphasis added, and one paragraph snipped. So, at least that part seems to be similar between the two languages.
How does Smalltalk (Pharo for example) compare to Python?
I've seen some comparisons between Smalltalk and Ruby on the one hand and Ruby and Python on the other, but not between Python and Smalltalk. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?
[ "\nFor example Python does not seem to\n have Metaclasses.\n\nIt sure does -- it just doesn't implicitly generate a new metaclass for every class: it uses the same metaclass as the parent class, or type by default. Python's design philosophy, aka \"The Zen of Python\", can be perused by doing import this at an interactive interpreter's prompt; the applicable point here is the second one, \"Explicit is better than implicit.\"\nIn Python 2.X, you specify a custom metaclass with the following syntax:\nclass sic:\n __metaclass__ = mymeta\n ...\n\nIn Python 3.X, more elegantly, you use named-argument syntax:\nclass sify(metaclass=mymeta):\n ...\n\n\nSmalltalk has no\n concept of generators.\n\nPython's generators are first-class (typically standalone) functions, and Smalltalk doesn't have the concept of \"standalone\" functions -- it has methods inside classes. But it certainly does have iterators -- as classes, of course:\niterator := aCollection iterator.\n[iterator hasNext] whileTrue: [iterator next doSomething]. \n\nSince Smalltalk has first-class \"code blocks\" (Ruby took them from it), you accomplish iteration, just like other \"control structures\", by sending a code block to a suitable method, and if you wish you can do that directly with the collection (think select:):\naCollection select: [:item | item doSomething].\n\nSo in Smalltalk (and Ruby) you send the code block to the iteration; Python does things the other way round, the iteration sends values out to the surrounding \"calling\" code. Looks very different, but not \"deeply\" different in the end.\nFirst-class code blocks mean that Smalltalk doesn't need nor have \"control structure\" statements and keywords such as if or while: they can be accomplished by sending code blocks as arguments of appropriate methods (e.g. ifTrue: method of booleans). (Ruby chooses to have the keywords/statements in addition to the first-class code blocks; I would say that Python [[explicitly]] and Smalltalk [[implicitly]] both try, like C, to \"offer a single way to perform an operation\", while Ruby's more in the Perl-ish school of \"there are many ways to do it\").\n\nAnd although\n both are said to be dynamicly typed, I\n believe that Python does not do\n dynamic method dispatch. Is this\n correct?\n\nNo, absolutely incorrect -- Python intensely does dynamic method dispatch, to extremes. Consider for example:\nfor i in range(10):\n myobject.bah()\n\nBy Python semantics, this performs 10 lookups for method bah in myobject -- just in case the previous execution of the method had caused myobject to entirely restructure itself internally so that its current bah method is completely different from the previous one (might be a pretty insane thing for the programmer to rely on such furious dynamism, but Python supports it). This is the reason that makes:\nthemethod = myobject.bah\nfor i in range(10):\n themethod()\n\na common hand-optimization in Python code -- does one dynamic lookup before the loop instead of 10 inside the loop, one per leg (it's a case of \"constant hoisting\", since the compiler is forbidden from doing the \"constant folding\" itself by Python's extreme rules for dynamic lookups -- unless it can prove that it's guaranteed to be innocuous, and in practice such proof is too hard so Python implementations typically don't bother).\nPython uses unified namespaces: methods are attributes of an object just like any other, except that they're callable. This is why extracting the method without calling it (known as a \"bound method\"), setting a reference to it in a variable (or stashing it into a list or other container, returning it from a function, whatever) is a plain and simple operation like in the above constant-hoisting example.\nSmalltalk and Ruby have separate namespaces for methods and other attributes (in Smalltalk, non-methods attributes are not visible outside the object's own methods), so \"extracting a method\" and \"calling the resulting object\" require more introspective ceremony (but the common case of dispatching may be thereby made marginally simpler in certain cases -- in particular, \"just mentioning\" an argument-less method implicitly calls it, while in Python, like in C, calling is explicitly performed by appending parentheses, while \"just mentioning\", well... \"just mentions\" it, making it available for any sort of explicit operation including calling;-).\n", "Python certainly does have metaclasses.\nSmalltalk has some unusual features:\n\nHas a rather simple syntax and only about 6 (!) keywords. Everything else (including defining new classes) is accomplished by calling methods (sending messages in Smalltalk). This allows you to create some DSL within the language.\nIn Smalltalk, you don't store source files, but instead have one big memory image and you modify it on the fly. You can also modify most of the Smalltalk itself (and possibly break it ;)\n\n", "I've been reading coders at work which is a really nice book full of interviews with top programmers. Anyhow, one of them is the inventor of smalltalk and he talks in length on his language and how it relates to python (he likes python quite a bit as well). The only problem he had with python was it's slow code... he really wanted to have the smalltalk jit compiler as a backend for python, but unfortunately due to the software belonging to the company he worked for, this was not possible.\nanyhow... maybe not a point by point comparison, but really a good read anyway this book.\n", "\nSmalltalk has no concept of\n generators.\n\nTrue, but they can be implemented in most Smalltalk dialects from within the language. GNU Smalltalk comes with Generators as part of its stream library.\n", "According to Wikipedia's page on dynamic method dispatch:\n\nSmalltalk Implementation\nSmalltalk uses a type based message\n dispatcher. Each instance has a single\n type whose definition contains the\n methods. When an instance receives a\n message, the dispatcher looks up the\n corresponding method in the\n message-to-method map for the type and\n then invokes the method. [...]\nMany other dynamically typed\n languages, including Python, Ruby,\n Objective-C and Groovy use similar\n approaches.\n\nEmphasis added, and one paragraph snipped. So, at least that part seems to be similar between the two languages.\n" ]
[ 9, 7, 2, 2, 1 ]
[]
[]
[ "comparison", "language_comparisons", "language_features", "python", "smalltalk" ]
stackoverflow_0001508256_comparison_language_comparisons_language_features_python_smalltalk.txt
Q: DJANGO : Update div with AJAX I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine. Now I need to retrieve the latest chat message from the table and append the list on the chat page. I am new to Django, so please go slow. So how do I get data from the chat table back to the chat page? Thanks in advance! A: My favorite technique for this kind of thing is to use an inclusion tag basically you make a separate template for rendering the individual objects in the page template page template: {% load message_tags %} <h3>Messages</h3> <div class="message_list"> {% for message in messages %} {% render_message message %} {% endfor %} </div> templatetags/message_tags.py: from django import template register = template.Library() @register.inclusion_tag('individual_message.html') def render_message(message): context_for_rendering_inclusion_tag = {'message': message} return context_for_rendering_inclusion_tag now you can use the same template to render the the additional messages you want to add to the message_list div in a separate view which you can call from your ajax code def ajax_retrieve_latest_message(request): # ... Get the lastest message render_to_response('individual_message.html', ... And your jQuery will look something like... $.post(url_of_ajax_view, request_data, function(data, status) { if (status == 'success') { $(".message_list").append(data); } }); For completeness, your individual_message.html file would contain all the markup for displaying the actual message on the page... Hope this all helps :) A: Since you're already using an AJAX post, why don't you return the data from that and insert it into the div? The view that accepts the post can return a rendered template or JSON, and your javascript can insert it in the callback. A: There's a lot going on in order to make this process work... The client regularly polls the server for new chat entries The server checks for and only replies with the newest The client receives the newest entries and appends them to the DOM This can be confusing when you're first starting because it's not always clear what the client does and what the server does, but if the large problem is broken down I think you'll find it's a simple process. If the client is going to regularly poll the server for new chat entries, then the server (django) needs to have some type of API to do so. Your biggest decision will be what data type the server returns. You can choose from: rendered HTML, XML, YAML, or JSON. The lightest weight is JSON, and it's supported by most of the major javascript frameworks (and django includes a JSON serializer since it's that awesome). # Your model I'm assuming is something to the effect of... class ChatLine(models.Model): screenname = model.ChatField(max_length=40) value = models.CharField(max_length=100) created = models.DateTimeField(default=datetime.now()) # A url pattern to match our API... url(r'^api/latest-chat/(?P<seconds_old>\d+)/$',get_latest_chat), # A view to answer that URL def get_latest_chat(request, seconds_old): # Query comments since the past X seconds chat_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old) chat = Chat.objects.filter(created__gte=comments_since) # Return serialized data or whatever you're doing with it return HttpResponse(simplejson.dumps(chat),mimetype='application/json') So whenever we poll our API, we should get back something like this.. [ { 'value':'Hello World', 'created':'2009-12-10 14:56:11', 'screenname':'tstone' }, { 'value':'And more cool Django-ness', 'created':'2009-12-10 14:58:49', 'screenname':'leethax0r1337' }, ] On our actual page, we have a <div> tag which we'll call <div id="chatbox"> which will hold whatever the incoming chat messages are. Our javascript simple needs to poll the server API that we created, check if there is a response, and then if there are items, append them to the chat box. <!-- I'm assuming you're using jQuery --> <script type="text/javascript"> LATEST_CHAT_URL = '{% url get_latest_chat 5 %}'; // On page start... $(function() { // Start a timer that will call our API at regular intervals // The 2nd value is the time in milliseconds, so 5000 = 5 seconds setTimeout(updateChat, 5000) }); function updateChat() { $.getJSON(LATEST_CHAT_URL, function(data){ // Enumerate JSON objects $.each(data.items, function(i,item){ var newChatLine = $('<span class="chat"></span>'); newChatLine.append('<span class="user">' + item.screenname + '</span>'); newChatLine.append('<span class="text">' + item.text + '</span>'); $('#chatbox').append(newChatLine); }); }); } </script> <div id="chatbox"> </div> Now of course I haven't tested any of this, but I hope that gives you an idea about how the whole goes together.
DJANGO : Update div with AJAX
I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine. Now I need to retrieve the latest chat message from the table and append the list on the chat page. I am new to Django, so please go slow. So how do I get data from the chat table back to the chat page? Thanks in advance!
[ "My favorite technique for this kind of thing is to use an inclusion tag\nbasically you make a separate template for rendering the individual objects in the page template\npage template:\n{% load message_tags %} \n\n<h3>Messages</h3>\n<div class=\"message_list\">\n {% for message in messages %}\n {% render_message message %}\n {% endfor %}\n</div>\n\ntemplatetags/message_tags.py:\nfrom django import template\n\nregister = template.Library()\n\n@register.inclusion_tag('individual_message.html')\ndef render_message(message):\n context_for_rendering_inclusion_tag = {'message': message}\n return context_for_rendering_inclusion_tag\n\nnow you can use the same template to render the the additional messages you want to add to the message_list div in a separate view which you can call from your ajax code\ndef ajax_retrieve_latest_message(request):\n # ... Get the lastest message\n render_to_response('individual_message.html', ... \n\nAnd your jQuery will look something like...\n$.post(url_of_ajax_view, request_data, function(data, status) {\n if (status == 'success') {\n $(\".message_list\").append(data);\n }\n});\n\nFor completeness, your individual_message.html file would contain all the markup for displaying the actual message on the page...\nHope this all helps :)\n", "Since you're already using an AJAX post, why don't you return the data from that and insert it into the div? The view that accepts the post can return a rendered template or JSON, and your javascript can insert it in the callback.\n", "There's a lot going on in order to make this process work...\n\nThe client regularly polls the server for new chat entries\nThe server checks for and only replies with the newest \nThe client receives the newest entries and appends them to the DOM\n\nThis can be confusing when you're first starting because it's not always clear what the client does and what the server does, but if the large problem is broken down I think you'll find it's a simple process.\nIf the client is going to regularly poll the server for new chat entries, then the server (django) needs to have some type of API to do so. Your biggest decision will be what data type the server returns. You can choose from: rendered HTML, XML, YAML, or JSON. The lightest weight is JSON, and it's supported by most of the major javascript frameworks (and django includes a JSON serializer since it's that awesome).\n# Your model I'm assuming is something to the effect of...\nclass ChatLine(models.Model):\n screenname = model.ChatField(max_length=40)\n value = models.CharField(max_length=100)\n created = models.DateTimeField(default=datetime.now())\n\n# A url pattern to match our API...\nurl(r'^api/latest-chat/(?P<seconds_old>\\d+)/$',get_latest_chat),\n\n# A view to answer that URL\ndef get_latest_chat(request, seconds_old):\n # Query comments since the past X seconds\n chat_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old)\n chat = Chat.objects.filter(created__gte=comments_since)\n\n # Return serialized data or whatever you're doing with it\n return HttpResponse(simplejson.dumps(chat),mimetype='application/json')\n\nSo whenever we poll our API, we should get back something like this..\n[\n {\n 'value':'Hello World',\n 'created':'2009-12-10 14:56:11',\n 'screenname':'tstone'\n },\n {\n 'value':'And more cool Django-ness',\n 'created':'2009-12-10 14:58:49',\n 'screenname':'leethax0r1337'\n },\n]\n\nOn our actual page, we have a <div> tag which we'll call <div id=\"chatbox\"> which will hold whatever the incoming chat messages are. Our javascript simple needs to poll the server API that we created, check if there is a response, and then if there are items, append them to the chat box.\n<!-- I'm assuming you're using jQuery -->\n<script type=\"text/javascript\">\n\n LATEST_CHAT_URL = '{% url get_latest_chat 5 %}';\n\n // On page start...\n $(function() {\n // Start a timer that will call our API at regular intervals\n // The 2nd value is the time in milliseconds, so 5000 = 5 seconds\n setTimeout(updateChat, 5000)\n });\n\n function updateChat() {\n $.getJSON(LATEST_CHAT_URL, function(data){\n // Enumerate JSON objects\n $.each(data.items, function(i,item){\n var newChatLine = $('<span class=\"chat\"></span>');\n newChatLine.append('<span class=\"user\">' + item.screenname + '</span>');\n newChatLine.append('<span class=\"text\">' + item.text + '</span>');\n $('#chatbox').append(newChatLine);\n });\n });\n }\n\n</script>\n\n<div id=\"chatbox\">\n</div>\n\nNow of course I haven't tested any of this, but I hope that gives you an idea about how the whole goes together.\n" ]
[ 14, 2, 2 ]
[]
[]
[ "ajax", "django", "django_templates", "jquery", "python" ]
stackoverflow_0001879872_ajax_django_django_templates_jquery_python.txt
Q: Python stacktrace help I have this stack trace error when I try view some data in my Python website, could some one clue me up as to what the problem is I am so lost Environment: Request Method: GET Request URL: http://mywesbite.genericdomain.co.uk/admin/shop/passwordresetrequest/4/ Django Version: 1.1.1 Python Version: 2.5.2 Installed Applications: ['django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mywebsite.news', 'mywebsite.store_locator', 'mywebsite.css_switch', 'mywebsite.professional', 'mywebsite.contact', 'mywebsite.shop', 'tinymce', 'captcha'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Template error: In template /usr/lib/python2.5/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 20 Caught an exception while rendering: 'PasswordResetRequest' object has no attribute 'date' 10 : 11 : {% block coltype %}{% if ordered_objects %}colMS{% else %}colM{% endif %}{% endblock %} 12 : 13 : {% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %} 14 : 15 : {% block breadcrumbs %}{% if not is_popup %} 16 : <div class="breadcrumbs"> 17 : <a href="../../../">{% trans "Home" %}</a> &rsaquo; 18 : <a href="../../">{{ app_label|capfirst|escape }}</a> &rsaquo; 19 : {% if has_change_permission %}<a href="../">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %} &rsaquo; 20 : {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %} {{ original|truncatewords:"18" }} {% endif %} 21 : </div> 22 : {% endif %}{% endblock %} 23 : 24 : {% block content %}<div id="content-main"> 25 : {% block object-tools %} 26 : {% if change %}{% if not is_popup %} 27 : <ul class="object-tools"><li><a href="history/" class="historylink">{% trans "History" %}</a></li> 28 : {% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%} 29 : </ul> 30 : {% endif %}{% endif %} Traceback: File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in root 490. return self.model_page(request, *url.split('/', 2)) File "/usr/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in model_page 509. return admin_obj(request, rest_of_url) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in __call__ 1098. return self.change_view(request, unquote(url)) File "/usr/lib/python2.5/site-packages/django/db/transaction.py" in _commit_on_success 240. res = func(*args, **kw) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in change_view 873. return self.render_change_form(request, context, change=True, obj=obj) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in render_change_form 590. ], context, context_instance=context_instance) File "/usr/lib/python2.5/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/python2.5/site-packages/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 97. return compiled_parent.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 97. return compiled_parent.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 243. return self.nodelist_true.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 24. result = self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 243. return self.nodelist_true.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 244. return self.nodelist_false.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /admin/shop/passwordresetrequest/4/ Exception Value: Caught an exception while rendering: 'PasswordResetRequest' object has no attribute 'date' Original Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 71, in render_node result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 87, in render output = force_unicode(self.filter_expression.resolve(context)) File "/usr/lib/python2.5/site-packages/django/template/__init__.py", line 572, in resolve new_obj = func(obj, *arg_vals) File "/usr/lib/python2.5/site-packages/django/template/defaultfilters.py", line 37, in _dec args[0] = force_unicode(args[0]) File "/usr/lib/python2.5/site-packages/django/utils/encoding.py", line 71, in force_unicode s = unicode(s) File "/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py", line 1105, in __unicode__ return ", ".join((str(self.account),self.date.strftime("%b. %d, %Y, %H:%M %p"))) AttributeError: 'PasswordResetRequest' object has no attribute 'date' My model class Account(BaseAccount): """ The account is an extension of the Django user and serves as the profile object in user.get_profile() for shop purchases and sessions """ telephone = models.CharField(max_length=32) default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True) security_question = models.ForeignKey(SecurityQuestion) security_answer = models.CharField(max_length=200) how_heard = models.CharField("How did you hear about us?", max_length=100) feedback = models.TextField(blank=True) opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name) temporary = models.BooleanField() def has_placed_orders(self): """ Returns True if the user has placed at least one order, False otherwise """ return self.order_set.count() > 0 def get_last_order(self): """ Returns the latest order that this customer has placed. If no orders have been placed, then None is returned """ try: return self.order_set.all().order_by('-date')[0] except IndexError: return None def get_currency(self): """ Get the currency for this customer. If global currencies are enabled (settings.ENABLE_GLOBAL_CURRENCIES) then this function will return the currency related to their default address, otherwise, it returns the site default """ if settings.ENABLE_GLOBAL_CURRENCIES: return self.default_address.country.currency return Currency.get_default_currency() currency = property(get_currency) def get_gateway_currency(self): """ Get the currency that an order will be put through protx with. If protx currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the currency will be the same returned by get_currency, otherwise, the site default is used """ if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES: return self.currency return Currency.get_default_currency() gateway_currency = property(get_gateway_currency) def password_reset_presave(sender, **kwargs): """ This pre-save is responsible for generating a unique key for the request before it is saved to DB. """ instance = kwargs['instance'] if not instance.key: instance.generate_key() class PasswordResetRequest(models.Model): """ Stores a history of all of the password reset requests that have been issued across the site. It is also used to validate resets against a given URL given the key. """ account = models.ForeignKey(Account) key = models.CharField(max_length=100, unique=True) issued = models.DateTimeField(auto_now_add=True) used = models.BooleanField() def is_valid(self): """ Is this password reset request still valid? Returns true if it hasn't yet been successfully used, and was issued any time within the last seven days """ return not self.used and datetime.datetime.now() < self.issued + datetime.timedelta(days=7) def __unicode__(self): """ The unicode representation of this password reset request. It is build using the unicode representation of the customers account, plus the date and time the request was made, in string form """ return ", ".join((str(self.account),self.issued.strftime("%b. %d, %Y, %H:%M %p"))) def generate_key(self): """ Generate a uuid4 key and assign it to this objects key attribute """ from uuid import uuid4 self.key = uuid4() class Meta: """ Django meta options verbose_name = "Password Reset Request" verbose_name_plural = "Password Reset Requests" """ verbose_name = "Password Reset Request" verbose_name_plural = "Password Reset Requests" pre_save.connect(password_reset_presave, sender=PasswordResetRequest) A: The significant piece is in the last few lines (remember that the most recent call, ie: the one that cause the error, is always printed last in a stacktrace): File "/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py", line 1105, in __unicode__ return ", ".join((str(self.account),self.date.strftime("%b. %d, %Y, %H:%M %p"))) AttributeError: 'PasswordResetRequest' object has no attribute 'date' What this means is that, in the file mywebsite/shop/models.py on line 1105 (which is in your def __unicode__(self): method), you are calling self.date.strftime(), but the model has no property called date. A: Look at the last line: In /var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py in the __unicode__ method you have a line: return ", ".join((str(self.account),self.date.strftime("%b. %d, %Y, %H:%M %p"))) and that self don't know about the date attribute. Maybe there is none defined. If you're unsure, change this particular return statement to return something meaningless but correct for the moment and see, if it was the only error. A: Well the problem is in the unicode method of the PasswordResetRequest model defined in shop/models.py. You try to access self.date on this object and it doesn't have a date attribute. Maybe if you paste your model I could help more... A: there was no reference of date is should of been issued
Python stacktrace help
I have this stack trace error when I try view some data in my Python website, could some one clue me up as to what the problem is I am so lost Environment: Request Method: GET Request URL: http://mywesbite.genericdomain.co.uk/admin/shop/passwordresetrequest/4/ Django Version: 1.1.1 Python Version: 2.5.2 Installed Applications: ['django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mywebsite.news', 'mywebsite.store_locator', 'mywebsite.css_switch', 'mywebsite.professional', 'mywebsite.contact', 'mywebsite.shop', 'tinymce', 'captcha'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Template error: In template /usr/lib/python2.5/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 20 Caught an exception while rendering: 'PasswordResetRequest' object has no attribute 'date' 10 : 11 : {% block coltype %}{% if ordered_objects %}colMS{% else %}colM{% endif %}{% endblock %} 12 : 13 : {% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %} 14 : 15 : {% block breadcrumbs %}{% if not is_popup %} 16 : <div class="breadcrumbs"> 17 : <a href="../../../">{% trans "Home" %}</a> &rsaquo; 18 : <a href="../../">{{ app_label|capfirst|escape }}</a> &rsaquo; 19 : {% if has_change_permission %}<a href="../">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %} &rsaquo; 20 : {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %} {{ original|truncatewords:"18" }} {% endif %} 21 : </div> 22 : {% endif %}{% endblock %} 23 : 24 : {% block content %}<div id="content-main"> 25 : {% block object-tools %} 26 : {% if change %}{% if not is_popup %} 27 : <ul class="object-tools"><li><a href="history/" class="historylink">{% trans "History" %}</a></li> 28 : {% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%} 29 : </ul> 30 : {% endif %}{% endif %} Traceback: File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in root 490. return self.model_page(request, *url.split('/', 2)) File "/usr/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in model_page 509. return admin_obj(request, rest_of_url) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in __call__ 1098. return self.change_view(request, unquote(url)) File "/usr/lib/python2.5/site-packages/django/db/transaction.py" in _commit_on_success 240. res = func(*args, **kw) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in change_view 873. return self.render_change_form(request, context, change=True, obj=obj) File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in render_change_form 590. ], context, context_instance=context_instance) File "/usr/lib/python2.5/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/python2.5/site-packages/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 97. return compiled_parent.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 97. return compiled_parent.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 243. return self.nodelist_true.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render 24. result = self.nodelist.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 243. return self.nodelist_true.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render 244. return self.nodelist_false.render(context) File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /admin/shop/passwordresetrequest/4/ Exception Value: Caught an exception while rendering: 'PasswordResetRequest' object has no attribute 'date' Original Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 71, in render_node result = node.render(context) File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 87, in render output = force_unicode(self.filter_expression.resolve(context)) File "/usr/lib/python2.5/site-packages/django/template/__init__.py", line 572, in resolve new_obj = func(obj, *arg_vals) File "/usr/lib/python2.5/site-packages/django/template/defaultfilters.py", line 37, in _dec args[0] = force_unicode(args[0]) File "/usr/lib/python2.5/site-packages/django/utils/encoding.py", line 71, in force_unicode s = unicode(s) File "/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py", line 1105, in __unicode__ return ", ".join((str(self.account),self.date.strftime("%b. %d, %Y, %H:%M %p"))) AttributeError: 'PasswordResetRequest' object has no attribute 'date' My model class Account(BaseAccount): """ The account is an extension of the Django user and serves as the profile object in user.get_profile() for shop purchases and sessions """ telephone = models.CharField(max_length=32) default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True) security_question = models.ForeignKey(SecurityQuestion) security_answer = models.CharField(max_length=200) how_heard = models.CharField("How did you hear about us?", max_length=100) feedback = models.TextField(blank=True) opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name) temporary = models.BooleanField() def has_placed_orders(self): """ Returns True if the user has placed at least one order, False otherwise """ return self.order_set.count() > 0 def get_last_order(self): """ Returns the latest order that this customer has placed. If no orders have been placed, then None is returned """ try: return self.order_set.all().order_by('-date')[0] except IndexError: return None def get_currency(self): """ Get the currency for this customer. If global currencies are enabled (settings.ENABLE_GLOBAL_CURRENCIES) then this function will return the currency related to their default address, otherwise, it returns the site default """ if settings.ENABLE_GLOBAL_CURRENCIES: return self.default_address.country.currency return Currency.get_default_currency() currency = property(get_currency) def get_gateway_currency(self): """ Get the currency that an order will be put through protx with. If protx currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the currency will be the same returned by get_currency, otherwise, the site default is used """ if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES: return self.currency return Currency.get_default_currency() gateway_currency = property(get_gateway_currency) def password_reset_presave(sender, **kwargs): """ This pre-save is responsible for generating a unique key for the request before it is saved to DB. """ instance = kwargs['instance'] if not instance.key: instance.generate_key() class PasswordResetRequest(models.Model): """ Stores a history of all of the password reset requests that have been issued across the site. It is also used to validate resets against a given URL given the key. """ account = models.ForeignKey(Account) key = models.CharField(max_length=100, unique=True) issued = models.DateTimeField(auto_now_add=True) used = models.BooleanField() def is_valid(self): """ Is this password reset request still valid? Returns true if it hasn't yet been successfully used, and was issued any time within the last seven days """ return not self.used and datetime.datetime.now() < self.issued + datetime.timedelta(days=7) def __unicode__(self): """ The unicode representation of this password reset request. It is build using the unicode representation of the customers account, plus the date and time the request was made, in string form """ return ", ".join((str(self.account),self.issued.strftime("%b. %d, %Y, %H:%M %p"))) def generate_key(self): """ Generate a uuid4 key and assign it to this objects key attribute """ from uuid import uuid4 self.key = uuid4() class Meta: """ Django meta options verbose_name = "Password Reset Request" verbose_name_plural = "Password Reset Requests" """ verbose_name = "Password Reset Request" verbose_name_plural = "Password Reset Requests" pre_save.connect(password_reset_presave, sender=PasswordResetRequest)
[ "The significant piece is in the last few lines (remember that the most recent call, ie: the one that cause the error, is always printed last in a stacktrace):\n File \"/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py\", line 1105, in \n __unicode__\n return \", \".join((str(self.account),self.date.strftime(\"%b. %d, %Y, %H:%M %p\")))\n AttributeError: 'PasswordResetRequest' object has no attribute 'date'\n\nWhat this means is that, in the file mywebsite/shop/models.py on line 1105 (which is in your def __unicode__(self): method), you are calling self.date.strftime(), but the model has no property called date.\n", "Look at the last line:\nIn\n/var/www/mywesbite/src/mywebsite/../mywesbite/shop/models.py\n\nin the __unicode__ method you have a line:\nreturn \", \".join((str(self.account),self.date.strftime(\"%b. %d, %Y, %H:%M %p\")))\n\nand that self don't know about the date attribute. Maybe there is none defined.\nIf you're unsure, change this particular return statement to return something meaningless but correct for the moment and see, if it was the only error.\n", "Well the problem is in the unicode method of the PasswordResetRequest model defined in shop/models.py. You try to access self.date on this object and it doesn't have a date attribute.\nMaybe if you paste your model I could help more...\n", "there was no reference of date is should of been issued\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "python", "stack_trace" ]
stackoverflow_0001881485_django_python_stack_trace.txt
Q: Where should django manager code live? This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports? A question may be asked as to why models.py is so huge, but let's just assume it's size and breadth of utility is justified. A: I prefer to keep my models in models.py and managers in managers.py (forms in forms.py) all within the same app. For more generic managers, I prefer to keep them in core.managers if they can be re-used for other apps. In some of our larger apps with models/modelname.py that will contains a manager and the model code which doesn't seem bad. A: Your best bet with a large set of models is to use django modules to your advantage, and simply create a folder named models. Move your old models.py into this models folder, and rename it __init__.py. This will allow you to then separate each model into more specific files inside of this model folder. You would then only need to import each model into your __init__.py's namespace. So, for instance, you might want to separate it into: yourapp/ models/ __init__.py # This file should import anything from your other files in this directory basic.py # Just an example name morespecificmodels.py # Just an example name managers.py # Might want to separate your manager into this Then your __init__.py can just be: from basic import * # You should replace * with each models name, most likely. from managers import YourManager # Whatever your manager is called. This is the structure that I use when my model files get huge, however I try to separate things into more pluggable apps as often as possible - so this is rarely used by me. Hope this helps. A: I always place mine in managers.py. If you have a circular import issue remember that a) You can reference the model class for a manager at self.model, and b) You can do imports inside of functions. A: What I did when building Django apps was to create a [modelname].py file with just the specific model code, manager code and sometimes form code and used an __init__.py file to import then all in the models directory. This helped me atleast in keeping it managable.
Where should django manager code live?
This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports? A question may be asked as to why models.py is so huge, but let's just assume it's size and breadth of utility is justified.
[ "I prefer to keep my models in models.py and managers in managers.py (forms in forms.py) all within the same app. For more generic managers, I prefer to keep them in core.managers if they can be re-used for other apps. In some of our larger apps with models/modelname.py that will contains a manager and the model code which doesn't seem bad.\n", "Your best bet with a large set of models is to use django modules to your advantage, and simply create a folder named models. Move your old models.py into this models folder, and rename it __init__.py. This will allow you to then separate each model into more specific files inside of this model folder.\nYou would then only need to import each model into your __init__.py's namespace.\nSo, for instance, you might want to separate it into:\nyourapp/\n models/\n __init__.py # This file should import anything from your other files in this directory\n basic.py # Just an example name\n morespecificmodels.py # Just an example name\n managers.py # Might want to separate your manager into this\n\nThen your __init__.py can just be:\nfrom basic import * # You should replace * with each models name, most likely.\nfrom managers import YourManager # Whatever your manager is called.\n\nThis is the structure that I use when my model files get huge, however I try to separate things into more pluggable apps as often as possible - so this is rarely used by me.\nHope this helps.\n", "I always place mine in managers.py. If you have a circular import issue remember that a) You can reference the model class for a manager at self.model, and b) You can do imports inside of functions.\n", "What I did when building Django apps was to create a [modelname].py file with just the specific model code, manager code and sometimes form code and used an __init__.py file to import then all in the models directory. This helped me atleast in keeping it managable.\n" ]
[ 32, 12, 9, 4 ]
[]
[]
[ "design_patterns", "django", "django_managers", "django_models", "python" ]
stackoverflow_0001883322_design_patterns_django_django_managers_django_models_python.txt
Q: Linting Python: what is good? Are there any good modules that you can run against your code to catch coding errors? I expected pylint to catch mistakes in the use of default arguments to functions like this: >>> def spam(eggs=[]): ... eggs.append("spam") ... return eggs but was disappointed to find them unreported. I am looking for something beyond PEP8 formatting. A: I tried the first example and PyLint 0.18.1 gave me the warning: W: 1:spam: Dangerous default value [] as argument A: That is not an error in your code if that is what you want to do. However, as specified in the accepted answer, an empty list is a "dangerous" default value in that it is easy to introduce hard-to-find problems.
Linting Python: what is good?
Are there any good modules that you can run against your code to catch coding errors? I expected pylint to catch mistakes in the use of default arguments to functions like this: >>> def spam(eggs=[]): ... eggs.append("spam") ... return eggs but was disappointed to find them unreported. I am looking for something beyond PEP8 formatting.
[ "I tried the first example and PyLint 0.18.1 gave me the warning:\nW: 1:spam: Dangerous default value [] as argument\n\n", "That is not an error in your code if that is what you want to do. However, as specified in the accepted answer, an empty list is a \"dangerous\" default value in that it is easy to introduce hard-to-find problems.\n" ]
[ 5, 1 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0001883725_pylint_python.txt