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: Django: separate template dir for model What's the point of using template structure like this: templates/ app/ article_view.html # or view_article.html category_view.html vs templates/ app/ article/ view.html category/ view.html It's easier to find particular template with second approach, but I almost don't see any apps using it. Why? A: This depends on the scale of the project; a small-scale thingie could be more easy to handle with the first approach, while a project with several hundred template files could use a better folder structure, i.e. the second approach A: Generally speaking, templates are associated with views rather than models. A view pulls in one or more models as needed, then renders the appropriate template. Since an app usually consolidates views in one file, the template to app correspondence works well enough.
Django: separate template dir for model
What's the point of using template structure like this: templates/ app/ article_view.html # or view_article.html category_view.html vs templates/ app/ article/ view.html category/ view.html It's easier to find particular template with second approach, but I almost don't see any apps using it. Why?
[ "This depends on the scale of the project; a small-scale thingie could be more easy to handle with the first approach, while a project with several hundred template files could use a better folder structure, i.e. the second approach\n", "Generally speaking, templates are associated with views rather than models. ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003945233_django_python.txt
Q: The dateutil.parser.parse() of distance strings? Anyone know a python package that's the dateutil of distance strings? It would be great if something was out there that worked something like the following: >>> from awesome_dist_module import Distance >>> d = Distance("100 ft") >>> d.meters 30.48 >>> d = Distance("100 feet") >>> d.meters 30.48 >>> d.miles 0.0189393939 The key thing isn't the conversions so much as being able to pass in a string that represents some kind of measurement and get back a float for another measurement of you're choosing without knowing what measurement is in the string. Anything? A: I wrote this for you, but you can expand it as you like: class Distance(object): METER = 1 FOOT = 0.3048 MILE = 1609.344 INCH = 0.0254 UNITS = {'meters': METER, 'mts': METER, 'mt': METER, 'feet': FOOT, 'foot': FOOT, 'ft': FOOT, 'miles': MILE, 'mls': MILE, 'ml': MILE, 'inch': INCH, } def __init__(self, s): self.number, unit = s.split() self._convert(unit) def _convert(self, unit): self.number = float(self.number) if self.UNITS[unit] != 1: self.number *= self.UNITS[unit] @ property def meters(self): return self.number @ meters.setter def meters(self, v): self.number = float(v) @ property def miles(self): return self.number / self.MILE @ miles.setter def miles(self, v): self.number = v self._convert('miles') @ property def feet(self): return self.number / self.FOOT @ feet.setter def feet(self, v): self.number = v self._convert('feet') @ property def inch(self): return self.number / self.INCH @ inch.setter def inch(self, v): self.number = v self._convert('inch') Some examples: >>> d = Distance('1302.09029321 mts') >>> d.meters 1302.09029321 >>> d.feet 4271.949780872703 >>> d.inch 51263.39737047244 >>> d.miles 0.8090813978925575 >>> d.miles = 1 >>> d.meters 1609.344 >>> d.feet 5280.0 >>> d.inch = .0002 >>> d.inch 0.00019999999999999998 >>> d.feet 1.6666666666666664e-05 >>> d.meters 5.08e-06 >>> d.miles 3.156565656565656e-09 >>> d.feet = 1 >>> d.meters 0.3048 >>> d.miles 0.0001893939393939394 EDIT: Added setters A: If you know which units you'll need (and don't need to look up hundreds of different units) you can implement this yourself fairly easily. Here's an example: class Distance(): METER = 1 FOOT = 0.3048 UNITS = { "feet" : FOOT, "ft" : FOOT, "foot" : FOOT, "meters" : METER, "mts" : METER, "meter" : METER, "mt" : METER } def __init__(self, string): number, unit = string.split() number = long(number) self.value = number * Distance.UNITS[unit] if __name__ == "__main__": d = Distance("1500 ft") print d.value That takes care of the string reading for you. You can then use any unit conversion library. A: Is one of the following modules close to your needs? units >>> from units import unit >>> metre = unit('m') >>> second = unit('s') >>> print(metre(10) / second(2)) 5 m / s >>> print(metre(10) ** 3) 1000 m * m * m magnitude >>> from magnitude import mg >>> print mg(10, 'm/s') ** 2 100.0000 m2 / s2 >>> print (mg(10, 'm') * 2 / (10, 'm/s2')).sqrt() 1.4142 s >>> tsq = mg(10, 'm') * 2 / (10, 'm/s2') >>> print tsq ** 0.5 1.4142 s >>> print mg(1, "lightyear") / mg(1, "c") >>> 31557600.0000 s >>> y = mg(1, "lightyear") / (1, "c") >>> print y.ounit("year") 1.0000 year >>> print y.ounit('day') >>> print yd 365.2500 day >>> power = mg(100, 'kg') * (2, 'gravity') * (5, 'km/h') >>> print power 2724.0694 m2 kg / s3 >>> print power.ounit('mW') 2724069.4444 mW >>> print power.ounit('kW') 2.7241 kW Unum (documentation in the source) quantities (documentation)
The dateutil.parser.parse() of distance strings?
Anyone know a python package that's the dateutil of distance strings? It would be great if something was out there that worked something like the following: >>> from awesome_dist_module import Distance >>> d = Distance("100 ft") >>> d.meters 30.48 >>> d = Distance("100 feet") >>> d.meters 30.48 >>> d.miles 0.0189393939 The key thing isn't the conversions so much as being able to pass in a string that represents some kind of measurement and get back a float for another measurement of you're choosing without knowing what measurement is in the string. Anything?
[ "I wrote this for you, but you can expand it as you like:\nclass Distance(object):\n\n METER = 1\n FOOT = 0.3048\n MILE = 1609.344\n INCH = 0.0254\n UNITS = {'meters': METER,\n 'mts': METER,\n 'mt': METER,\n 'feet': FOOT,\n 'foot': FOOT,\n 'ft': FOOT,\n ...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003943752_python.txt
Q: Reading and interpreting data from a binary file in Python I want to read a file byte by byte and check if the last bit of each byte is set: #!/usr/bin/python def main(): fh = open('/tmp/test.txt', 'rb') try: byte = fh.read(1) while byte != "": if (int(byte,16) & 0x01) is 0x01: print 1 else: print 0 byte = fh.read(1) finally: fh.close fh.close() if __name__ == "__main__": main() The error I get is: Traceback (most recent call last): File "./mini_01.py", line 21, in <module> main() File "./mini_01.py", line 10, in main if (int(byte,16) & 0x01) is 0x01: ValueError: invalid literal for int() with base 16: '\xaf' Anyone an idea? I didn't succeed using the struct and the binascii modules. A: Try using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just: ba = bytearray(fh.read()) for byte in ba: print byte & 1 or to create a list of results: low_bit_list = [byte & 1 for byte in bytearray(fh.read())] This works because when you index a bytearray you just get back an integer (0-255), whereas if you just read a byte from the file you get back a single character string and so need to use ord to convert it to an integer. If your file is too big to comfortably hold in memory (though I'm guessing it isn't) then an mmap could be used to create the bytearray from a buffer: import mmap m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) ba = bytearray(m) A: You want to use ord instead of int: if (ord(byte) & 0x01) == 0x01: A: One way: import array filebytes= array.array('B') filebytes.fromfile(open("/tmp/test.txt", "rb")) if all(i & 1 for i in filebytes): # all file bytes are odd Another way: fobj= open("/tmp/test.txt", "rb") try: import functools except ImportError: bytereader= lambda: fobj.read(1) else: bytereader= functools.partial(fobj.read, 1) if all(ord(byte) & 1 for byte in iter(bytereader, '')): # all bytes are odd fobj.close()
Reading and interpreting data from a binary file in Python
I want to read a file byte by byte and check if the last bit of each byte is set: #!/usr/bin/python def main(): fh = open('/tmp/test.txt', 'rb') try: byte = fh.read(1) while byte != "": if (int(byte,16) & 0x01) is 0x01: print 1 else: print 0 byte = fh.read(1) finally: fh.close fh.close() if __name__ == "__main__": main() The error I get is: Traceback (most recent call last): File "./mini_01.py", line 21, in <module> main() File "./mini_01.py", line 10, in main if (int(byte,16) & 0x01) is 0x01: ValueError: invalid literal for int() with base 16: '\xaf' Anyone an idea? I didn't succeed using the struct and the binascii modules.
[ "Try using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just:\nba = bytearray(fh.read())\nfor byte in ba:\n print byte & 1\n\nor to create a list of results:\nlow_bit_list = [byte & 1 for byte in bytearray(fh.read())]\n\nThis works because ...
[ 51, 9, 4 ]
[]
[]
[ "binary", "bitwise_operators", "python" ]
stackoverflow_0003943149_binary_bitwise_operators_python.txt
Q: Undefined variable from import when using wxPython in pydev I just downloaded wxPython, and was running some of the sample programs from here. However, on every line that uses a variable from wx.*, I get a "Undefined variable from import error" For example, the following program generates five errors on lines 1,4,8, and two on line 5: import wx class MyFrame(wx.Frame): """ We simply derive a new class of Frame. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.Show(True) app = wx.App(False) frame = MyFrame(None, 'Small editor') app.MainLoop() The program, however, compiles and runs perfectly. I haven't made any significant modifications to pydev or eclipse, and the wxPython install is fresh. A: This happened to me. I had installed PyDev and configured it and went on my merry way. A few months later, I installed wxPython and had this same problem. An easy way to fix is in eclipse: Window -> Preferences -> Pydev -> Interpreter - Python Just remove the default interpreter and add a new one (it can be the same one you had before). Pydev/Eclipse searches through your Python Installation directory and adds the correct paths to your PYTHONPATH. I restarted and all was well. I noticed it added C:\Python26\lib\site-packages\wx-2.8-msw-unicode So you could probably just add that to the PYTHONPATH instead of going through all the above, assuming that path is where this directory is installed. By the way, I am using: Eclipse Helios Pydev 1.6.2.2010090812 Python 2.6 wxPython2.8-win32-unicode-2.8.11.0-py26 But I think this should be a pretty general solution to the problem. A: PyDev finds the references when you setup the interpreter in Window -> Preferences -> Pydev -> Interpreter - Python If wxPython was not in your site-packages directory when you first setup the interpreter, then the references to the wx objects and names will not be known to the editor lookup function. To fix this, remove the interpreter from Window -> Preferences -> Pydev -> Interpreter - Python and then select new. Re-add the python installation again and press apply. At this time, Pydev will import all of the site-package objects again and should populate the lookup dictionary. You'll want to restart Eclipse for changes to take place. A: Some of the newer versions of pydev (circa January 2010) have a hard time tracking down imported names. It's probably nothing. If this is still occurring, report the bug to aptana appcelerator, though no doubt they already know about it. I get this problem when working with packages I've just recently downloaded, and eventually the errors go away. My most recent problem was after downloading pygame (circa January 2010). Edit I've amended my answer above since people are downvoting it, and I'm assuming it's because the information is stale, or because appcelerator bought aptana. I have not used pydev with Eclipse for nearly 2 years and the situation may be different now. A: Use CTRL+1 key combination on error text and add #@UndefinedVariable or #@UnresolvedImport in the end of corresponding lines with errors, it will remove these warnings temporary. See this answer: How do I fix PyDev "Undefined variable from import" errors? A: Try wx = wx Don't ask why. This approach (that I found when trying to break the problem in smaller parts) just seems to remove the wx undefined variables problem. A: #import wx from wx import wx #@UnresolvedImport will fix.
Undefined variable from import when using wxPython in pydev
I just downloaded wxPython, and was running some of the sample programs from here. However, on every line that uses a variable from wx.*, I get a "Undefined variable from import error" For example, the following program generates five errors on lines 1,4,8, and two on line 5: import wx class MyFrame(wx.Frame): """ We simply derive a new class of Frame. """ def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,100)) self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.Show(True) app = wx.App(False) frame = MyFrame(None, 'Small editor') app.MainLoop() The program, however, compiles and runs perfectly. I haven't made any significant modifications to pydev or eclipse, and the wxPython install is fresh.
[ "This happened to me. I had installed PyDev and configured it and went on my merry way. A few months later, I installed wxPython and had this same problem. An easy way to fix is in eclipse:\nWindow -> Preferences -> Pydev -> Interpreter - Python\nJust remove the default interpreter and add a new one (it can be t...
[ 40, 7, 3, 3, 3, 3 ]
[]
[]
[ "eclipse", "pydev", "python", "wxpython" ]
stackoverflow_0002143549_eclipse_pydev_python_wxpython.txt
Q: Can't scroll to the end of TreeView PyGTK / GTK When I try to scroll down to the end of my TreeView, which is inside a ScrolledWindow, it doesn't scroll where it should but one or two lines before. I tried several methods and they all provide the same behavior : self.wTree.get_widget("tree_last_log").scroll_to_cell((self.number_results-1,)) # or self.wTree.get_widget("tree_last_log").set_cursor((self.number_results-1,)) # or adj = self.wTree.get_widget("scrolledwindow1").get_vadjustment() adj.set_value(adj.get_property('upper')) self.wTree.get_widget("scrolledwindow1").set_vadjustment(adj) # or self.wTree.get_widget("scrolledwindow1").emit('scroll-child', gtk.SCROLL_END, False) Where is the problem ? A: The C API docs may be helpful: http://library.gnome.org/devel/gtk/stable/GtkTreeView.html#gtk-tree-view-scroll-to-cell You can see there are arguments there that would mess things up, depending on how pygtk defaults them. You might try specifying explicitly all the args. One trick to TreeView and TextView is that they do asynchronous layout so the "upper" on the adjustment may well just be zero if row heights haven't been computed yet. if messing with the adjustment, there's no need to set it back, though it should be harmless. 'scroll-child' signal is not what you want, that's a keybinding signal used to bind keys to.
Can't scroll to the end of TreeView PyGTK / GTK
When I try to scroll down to the end of my TreeView, which is inside a ScrolledWindow, it doesn't scroll where it should but one or two lines before. I tried several methods and they all provide the same behavior : self.wTree.get_widget("tree_last_log").scroll_to_cell((self.number_results-1,)) # or self.wTree.get_widget("tree_last_log").set_cursor((self.number_results-1,)) # or adj = self.wTree.get_widget("scrolledwindow1").get_vadjustment() adj.set_value(adj.get_property('upper')) self.wTree.get_widget("scrolledwindow1").set_vadjustment(adj) # or self.wTree.get_widget("scrolledwindow1").emit('scroll-child', gtk.SCROLL_END, False) Where is the problem ?
[ "The C API docs may be helpful:\nhttp://library.gnome.org/devel/gtk/stable/GtkTreeView.html#gtk-tree-view-scroll-to-cell\nYou can see there are arguments there that would mess things up, depending on how pygtk defaults them. You might try specifying explicitly all the args.\nOne trick to TreeView and TextView is th...
[ 1 ]
[]
[]
[ "gtk", "gtk2", "pygtk", "python" ]
stackoverflow_0003510705_gtk_gtk2_pygtk_python.txt
Q: What does this code do in Python? I'm learning Python and ran into some code that has this line... self.clear() I am curious as to what it would do and why would someone need to do this? A: That line calls the clear method on the current object. What the clear method actually does depends on what class this code is inside. A: If you found it inside the function, that looked like: def __parse(self,filename): then you will probably find something similar to this: def clear(self): If you find it, there's the code, that will be executed within self.clear()
What does this code do in Python?
I'm learning Python and ran into some code that has this line... self.clear() I am curious as to what it would do and why would someone need to do this?
[ "That line calls the clear method on the current object. What the clear method actually does depends on what class this code is inside.\n", "If you found it inside the function, that looked like:\ndef __parse(self,filename):\n\nthen you will probably find something similar to this:\ndef clear(self):\n\nIf you fin...
[ 5, 1 ]
[ "sorry if it wasnt clear but i just found the code for clear() ... all it did was clear the UserDict object before assigning new values to it....i misunderstood the code and thought the writer was actually deleting the current object....anyway answer found....thanks for the help guys....i will be more careful in th...
[ -1 ]
[ "python" ]
stackoverflow_0003945554_python.txt
Q: Python - Iterate through 2 lists at the same time Possible Duplicate: How to iterate through two lists in parallel? I have 2 lists: l = ["a", "b", "c"] m = ["x", "y", "z"] And I want to iterate through both at the same time, something like this: for e, f in l, m: print e, f Must show: a x b y c z The thing is that is totally illegal. How can I do something like this? (In a Pythonic way) A: Look at itertools izip. It'll look like this for i,j in izip( mylistA, mylistB ): print i + j The zip function will also work but izip creates an iterator which does not force the creation of a third list.
Python - Iterate through 2 lists at the same time
Possible Duplicate: How to iterate through two lists in parallel? I have 2 lists: l = ["a", "b", "c"] m = ["x", "y", "z"] And I want to iterate through both at the same time, something like this: for e, f in l, m: print e, f Must show: a x b y c z The thing is that is totally illegal. How can I do something like this? (In a Pythonic way)
[ "Look at itertools izip. It'll look like this\nfor i,j in izip( mylistA, mylistB ):\n print i + j\n\nThe zip function will also work but izip creates an iterator which does not force the creation of a third list.\n" ]
[ 6 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003945809_list_loops_python.txt
Q: Searching a normal query in an inverted index I have a full inverted index in form of nested python dictionary. Its structure is : {word : { doc_name : [location_list] } } For example let the dictionary be called index, then for a word " spam ", entry would look like : { spam : { doc1.txt : [102,300,399], doc5.txt : [200,587] } } so that, the documents containing any word can be given by index[word].keys() , and frequency in that document by len(index[word][document]) Now my question is, how do I implement a normal query search in this index. i.e. given a query containing lets say 4 words, find documents containing all four matches (ranked by total frequency of occurrence ), then docs containing 3 matches and so on .... ** Added this code, using S. Lott's answer. This is the code I have written. Its working exactly as I want, ( just some formatting of output is needed ) but I know it could be improved. ** from collections import defaultdict from operator import itemgetter # Take input query = input(" Enter the query : ") # Some preprocessing query = query.lower() query = query.strip() # now real work wordlist = query.split() search_words = [ x for x in wordlist if x in index ] # list of words that are present in index. print "\nsearching for words ... : ", search_words, "\n" doc_has_word = [ (index[word].keys(),word) for word in search_words ] doc_words = defaultdict(list) for d, w in doc_has_word: for p in d: doc_words[p].append(w) # create a dictionary identifying matches for each document result_set = {} for i in doc_words.keys(): count = 0 matches = len(doc_words[i]) # number of matches for w in doc_words[i]: count += len(index[w][i]) # count total occurances result_set[i] = (matches,count) # Now print in sorted order print " Document \t\t Words matched \t\t Total Frequency " print '-'*40 for doc, (matches, count)) in sorted(result_set.items(), key = itemgetter(1), reverse = True): print doc, "\t",doc_words[doc],"\t",count Pls comment .... Thanx. A: Here's a start: doc_has_word = [ (index[word].keys(),word) for word in wordlist ] This will build an list of (word,document) pairs. You can't easily make a dictionary out of that, since each document occurs many times. But from collections import defaultdict doc_words = defaultdict(list) for d, w in doc_has_word: doc_words[tuple(d.items())].append(w) Might be helpful. A: import itertools index = {...} def query(*args): result = [] doc_count = [(doc, len(index[word][doc])) for word in args for doc in index[word]] doc_group = itertools.groupby(doc_count, key=lambda doc: doc[0]) for doc, group in doc_group: result.append((doc, sum([elem[1] for elem in group]))) return sorted(result, key=lambda x:x[1])[::-1] A: Here is a solution for finding the similar documents (the hardest part): wordList = ['spam','eggs','toast'] # our list of words to query for wordMatches = [index.get(word, {}) for word in wordList] similarDocs = reduce(set.intersection, [set(docMatch.keys()) for docMatch in wordMatches]) wordMatches gets a list where each element is a dictionary of the document matches for one of the words being matched. similarDocs is a set of the documents that contain all of the words being queried for. This is found by taking just the document names out of each of the dictionaries in the wordMatches list, representing these lists of document names as sets, and then intersecting the sets to find the common document names. Once you have found the documents that are similar, you should be able to use a defaultdict (as shown in S. Lott's answer) to append all of the lists of matches together for each word and each document. Related links: This answer demonstrates defaultdict(int). defaultdict(list) works pretty much the same way. set.intersection example
Searching a normal query in an inverted index
I have a full inverted index in form of nested python dictionary. Its structure is : {word : { doc_name : [location_list] } } For example let the dictionary be called index, then for a word " spam ", entry would look like : { spam : { doc1.txt : [102,300,399], doc5.txt : [200,587] } } so that, the documents containing any word can be given by index[word].keys() , and frequency in that document by len(index[word][document]) Now my question is, how do I implement a normal query search in this index. i.e. given a query containing lets say 4 words, find documents containing all four matches (ranked by total frequency of occurrence ), then docs containing 3 matches and so on .... ** Added this code, using S. Lott's answer. This is the code I have written. Its working exactly as I want, ( just some formatting of output is needed ) but I know it could be improved. ** from collections import defaultdict from operator import itemgetter # Take input query = input(" Enter the query : ") # Some preprocessing query = query.lower() query = query.strip() # now real work wordlist = query.split() search_words = [ x for x in wordlist if x in index ] # list of words that are present in index. print "\nsearching for words ... : ", search_words, "\n" doc_has_word = [ (index[word].keys(),word) for word in search_words ] doc_words = defaultdict(list) for d, w in doc_has_word: for p in d: doc_words[p].append(w) # create a dictionary identifying matches for each document result_set = {} for i in doc_words.keys(): count = 0 matches = len(doc_words[i]) # number of matches for w in doc_words[i]: count += len(index[w][i]) # count total occurances result_set[i] = (matches,count) # Now print in sorted order print " Document \t\t Words matched \t\t Total Frequency " print '-'*40 for doc, (matches, count)) in sorted(result_set.items(), key = itemgetter(1), reverse = True): print doc, "\t",doc_words[doc],"\t",count Pls comment .... Thanx.
[ "Here's a start:\ndoc_has_word = [ (index[word].keys(),word) for word in wordlist ]\n\nThis will build an list of (word,document) pairs. You can't easily make a dictionary out of that, since each document occurs many times.\nBut\nfrom collections import defaultdict\ndoc_words = defaultdict(list)\nfor d, w in doc_h...
[ 3, 0, 0 ]
[]
[]
[ "information_retrieval", "inverted_index", "python" ]
stackoverflow_0003944910_information_retrieval_inverted_index_python.txt
Q: Passing self into a constructor in python I recently was working on a little python project and came to a situation where I wanted to pass self into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't remember ever having to do this with python. Is passing references to self to new objects something that isn't considered pythonic? I don't think I've seen any python programs explicitly passing self references around. Have I just happen to not have a need for it until now? Or am I fighting python style? A: Yes it is legal, and yes it is pythonic. I find myself using this pattern when you have an object and a container object where the contained objects need to know about their parent. A: Just pass it like a parameter. Of course, it won't be called self in the other initializer... class A: def __init__(self, num, target): self.num = num self.target = target class B: def __init__(self, num): self.a = A(num, self) a = A(1) b = B(2) print b.a.num # prints 2
Passing self into a constructor in python
I recently was working on a little python project and came to a situation where I wanted to pass self into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't remember ever having to do this with python. Is passing references to self to new objects something that isn't considered pythonic? I don't think I've seen any python programs explicitly passing self references around. Have I just happen to not have a need for it until now? Or am I fighting python style?
[ "Yes it is legal, and yes it is pythonic.\nI find myself using this pattern when you have an object and a container object where the contained objects need to know about their parent.\n", "Just pass it like a parameter. Of course, it won't be called self in the other initializer...\nclass A:\n def __init__(se...
[ 18, 4 ]
[]
[]
[ "python", "self", "this" ]
stackoverflow_0003945924_python_self_this.txt
Q: Encoding JSON in Mako? Im having trouble with json in mako. I do this: ${ to_json( dict( a = 1, b = 2 ) ) } where to_json is: <%! import simplejson as json def to_json( d ): return json.dumps( d ) %> however, instead of giving me {"a": "1", "b": "2"} its giving me {&quot;a&quot;: 1, &quot;b&quot;: 2} so mako changes the " to " somewhere what should i be doing instead? in contrast, heres a test script import simplejson as json print json.dumps( dict( a=1,b=2 ) ) output {"a": 1, "b": 2} edit i changed my function to <%! import simplejson as json def to_json( d ): return "{\"a\": 1}" %> and it changes the " to &quot;, so its an issue with mako, it seems. A: seems like theres an auto filter somewhere, so when i changed ${ to_json( dict( a = 1, b = 2 ) ) } to ${ to_json( dict( a = 1, b = 2 ) ) | n } to turn off filters, it is okay, thanks
Encoding JSON in Mako?
Im having trouble with json in mako. I do this: ${ to_json( dict( a = 1, b = 2 ) ) } where to_json is: <%! import simplejson as json def to_json( d ): return json.dumps( d ) %> however, instead of giving me {"a": "1", "b": "2"} its giving me {&quot;a&quot;: 1, &quot;b&quot;: 2} so mako changes the " to " somewhere what should i be doing instead? in contrast, heres a test script import simplejson as json print json.dumps( dict( a=1,b=2 ) ) output {"a": 1, "b": 2} edit i changed my function to <%! import simplejson as json def to_json( d ): return "{\"a\": 1}" %> and it changes the " to &quot;, so its an issue with mako, it seems.
[ "seems like theres an auto filter somewhere, so when i changed \n${ to_json( dict( a = 1, b = 2 ) ) }\n\nto\n${ to_json( dict( a = 1, b = 2 ) ) | n }\n\nto turn off filters, it is okay, thanks\n" ]
[ 2 ]
[]
[]
[ "json", "mako", "python" ]
stackoverflow_0003945820_json_mako_python.txt
Q: Converting string to tuple and adding to tuple I have a config file like this. [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like ((2,2,10,10), (12,8,2,10)) A: Instead of using a regex or int/string functions, you could also use the ast module's literal_eval function, which only evaluates strings that are valid Python literals. This function is safe (according to the docs). http://docs.python.org/library/ast.html#ast.literal_eval import ast ast.literal_eval("(1,2,3,4)") # (1,2,3,4) And, like others have said, ConfigParser works for parsing the INI file. A: To turn the strings into tuples of ints (which is, I assume, what you want), you can use a regex like this: x = "(1,2,3)" t = tuple(int(v) for v in re.findall("[0-9]+", x)) And you can use, say, configparser to parse the config file. A: Considering that cp is the ConfigParser object for the cfg file having the config. [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) >> import ast >> tuple(ast.literal_eval(v[1]) for v in cp.items('rects')) ((2,2,10,10), (12,8,2,10)) Edit : Changed eval() to a safer version literal_eval() From python docs - literal_eval() does following : Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None A: You can simply make a tuple of tuples like new_tuple = (rect1,rect2) # ((2,2,10,10), (12,8,2,10)) If you want to loop through values for i in rect1+rect2: print i If you want to regroup the numbers you could do tuple_regrouped = zip(rect1,rect2) #((2,12),(2,8),(10,2), (10,10)) EDIT: Didn't notice the string part. If you have lines in strings, like from reading a config file, you can do something like # line = "rect1 = (1,2,3,4)" config_dict = {} var_name, tuple_as_str = line.replace(" ","").split("=") config_dict[var_name] = tuple([int(i) for i in tuple_as_str[1:-1].split(',')]) # and now you'd have config_dict['rect1'] = (1,2,3,4) A: The easiest way to do this would be to use Michael Foord's ConfigObject library. It has an unrepr mode, which'll directly convert the string into a tuple for you.
Converting string to tuple and adding to tuple
I have a config file like this. [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like ((2,2,10,10), (12,8,2,10))
[ "Instead of using a regex or int/string functions, you could also use the ast module's literal_eval function, which only evaluates strings that are valid Python literals. This function is safe (according to the docs).\nhttp://docs.python.org/library/ast.html#ast.literal_eval\nimport ast\nast.literal_eval(\"(1,2,3,4...
[ 11, 9, 3, 2, 2 ]
[]
[]
[ "python", "string", "tuples" ]
stackoverflow_0003945856_python_string_tuples.txt
Q: How do I update an instance of a Django Model with request.POST if POST is a nested array? I have a form that submits the following data: question[priority] = "3" question[effort] = "5" question[question] = "A question" That data is submitted to the URL /questions/1/save where 1 is the question.id. What I'd love to do is get question #1 and update it based on the POST data. I've got some of it working, but I don't know how to push the POST into the instance. question = get_object_or_404(Question, pk=id) question <<< request.POST['question'] # This obviously doesn't work, but is what I'm trying to achieve. question.save() So, is there anyway to push the QueryDict into the model instance and update each of the fields with my form data? Of course, I could loop over the POST and set each value individually, but that seems overly complex for such a beautiful language. A: You can use a ModelForm to accomplish this. First define the ModelForm: from django import forms class QuestionForm(forms.ModelForm): class Meta: model = Question Then, in your view: question = Question.objects.get(pk=id) if request.method == 'POST': form = QuestionForm(request.POST, instance=question) form.save()
How do I update an instance of a Django Model with request.POST if POST is a nested array?
I have a form that submits the following data: question[priority] = "3" question[effort] = "5" question[question] = "A question" That data is submitted to the URL /questions/1/save where 1 is the question.id. What I'd love to do is get question #1 and update it based on the POST data. I've got some of it working, but I don't know how to push the POST into the instance. question = get_object_or_404(Question, pk=id) question <<< request.POST['question'] # This obviously doesn't work, but is what I'm trying to achieve. question.save() So, is there anyway to push the QueryDict into the model instance and update each of the fields with my form data? Of course, I could loop over the POST and set each value individually, but that seems overly complex for such a beautiful language.
[ "You can use a ModelForm to accomplish this. First define the ModelForm:\nfrom django import forms\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model = Question\n\nThen, in your view:\nquestion = Question.objects.get(pk=id)\nif request.method == 'POST':\n form = QuestionForm(request.POST, i...
[ 43 ]
[]
[]
[ "django", "django_models", "post", "python", "request" ]
stackoverflow_0003946036_django_django_models_post_python_request.txt
Q: What are the implications of using mutable types as default arguments in Python? Possible Duplicates: Why the “mutable default argument fix” syntax is so ugly, asks python newbie least astonishment in python: the mutable default argument Here is an example. def list_as_default(arg = []): pass A: From: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L
What are the implications of using mutable types as default arguments in Python?
Possible Duplicates: Why the “mutable default argument fix” syntax is so ugly, asks python newbie least astonishment in python: the mutable default argument Here is an example. def list_as_default(arg = []): pass
[ "From: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html\nThe default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on...
[ 2 ]
[]
[]
[ "least_astonishment", "python" ]
stackoverflow_0003946235_least_astonishment_python.txt
Q: A little help needed in code translation (Python to C#) Good night everyone, This question leaves me a little embarassed because, of couse, I know I should be able to get the answer alone. However, my knowledge about Python is just a little bit more than nothing, so I need help from someone more experienced with it than me... The following code comes from Norvig's "Natural Language Corpus Data" chapter in a recently edited book, and it's about transforming a sentence "likethisone" into "[like, this, one]" (that means, segmenting the word correctly)... I have ported all of the code to C# (in fact, re-wrote the program by myself) except for the function segment, which I am having a lot of trouble even trying to understand it's syntax. Can someone please help me translating it to a more readable form in C#? Thank you very much in advance. ################ Word Segmentation (p. 223) @memo def segment(text): "Return a list of words that is the best segmentation of text." if not text: return [] candidates = ([first]+segment(rem) for first,rem in splits(text)) return max(candidates, key=Pwords) def splits(text, L=20): "Return a list of all possible (first, rem) pairs, len(first)<=L." return [(text[:i+1], text[i+1:]) for i in range(min(len(text), L))] def Pwords(words): "The Naive Bayes probability of a sequence of words." return product(Pw(w) for w in words) #### Support functions (p. 224) def product(nums): "Return the product of a sequence of numbers." return reduce(operator.mul, nums, 1) class Pdist(dict): "A probability distribution estimated from counts in datafile." def __init__(self, data=[], N=None, missingfn=None): for key,count in data: self[key] = self.get(key, 0) + int(count) self.N = float(N or sum(self.itervalues())) self.missingfn = missingfn or (lambda k, N: 1./N) def __call__(self, key): if key in self: return self[key]/self.N else: return self.missingfn(key, self.N) def datafile(name, sep='\t'): "Read key,value pairs from file." for line in file(name): yield line.split(sep) def avoid_long_words(key, N): "Estimate the probability of an unknown word." return 10./(N * 10**len(key)) N = 1024908267229 ## Number of tokens Pw = Pdist(datafile('count_1w.txt'), N, avoid_long_words) A: Let's tackle the first function first: def segment(text): "Return a list of words that is the best segmentation of text." if not text: return [] candidates = ([first]+segment(rem) for first,rem in splits(text)) return max(candidates, key=Pwords) It takes a word and returns the most likely list of words that it could be, so its signature will be static IEnumerable<string> segment(string text). Obviously if text is an empty string, its result should be an empty list. Otherwise, it creates a recursive list comprehension defining the possible candidate lists of words and returns the maximum based on its probability. static IEnumerable<string> segment(string text) { if (text == "") return new string[0]; // C# idiom for empty list of strings var candidates = from pair in splits(text) select new[] {pair.Item1}.Concat(segment(pair.Item2)); return candidates.OrderBy(Pwords).First(); } Of course, now we have to translate the splits function. Its job is to return a list of all possible tuples of the beginning and end of a word. It's fairly straightforward to translate: static IEnumerable<Tuple<string, string>> splits(string text, int L = 20) { return from i in Enumerable.Range(1, Math.Min(text.Length, L)) select Tuple.Create(text.Substring(0, i), text.Substring(i)); } Next is Pwords, which just calls the product function on the result of Pw on each word in its input list: static double Pwords(IEnumerable<string> words) { return product(from w in words select Pw(w)); } And product is pretty simple: static double product(IEnumerable<double> nums) { return nums.Aggregate((a, b) => a * b); } ADDENDUM: Looking at the full source code, it is apparent that Norvig intends the results of the segment function to be memoized for speed. Here's a version that provides this speed-up: static Dictionary<string, IEnumerable<string>> segmentTable = new Dictionary<string, IEnumerable<string>>(); static IEnumerable<string> segment(string text) { if (text == "") return new string[0]; // C# idiom for empty list of strings if (!segmentTable.ContainsKey(text)) { var candidates = from pair in splits(text) select new[] {pair.Item1}.Concat(segment(pair.Item2)); segmentTable[text] = candidates.OrderBy(Pwords).First().ToList(); } return segmentTable[text]; } A: I don't know C# at all, but I can explain how the Python code works. @memo def segment(text): "Return a list of words that is the best segmentation of text." if not text: return [] candidates = ([first]+segment(rem) for first,rem in splits(text)) return max(candidates, key=Pwords) The first line, @memo is a decorator. This causes the function, as defined in the subsequent lines, to be wrapped in another function. Decorators are commonly used to filter inputs and outputs. In this case, based on the name and the role of the function it's wrapping, I gather that this function memoizes calls to segment. Next: def segment(text): "Return a list of words that is the best segmentation of text." if not text: return [] Declares the function proper, gives a docstring, and sets the termination condition for this function's recursion. Next is the most complicated line, and probably the one that gave you trouble: candidates = ([first]+segment(rem) for first,rem in splits(text)) The outer parentheses, combined with the for..in construct, create a generator expression. This is an efficient way of iterating over a sequence, in this case splits(text). Generator expressions are sort of a compact for-loop that yields values. In this case, the values become the elements of the iteration candidates. "Genexps" are similar to list comprehensions, but achieve greater memory efficiency by not retaining each value that they produce. So for each value in the iteration returned by splits(text), a list is produced by the generator expression. Each of the values from splits(text) is a (first, rem) pair. Each produced list starts with the object first; this is expressed by putting first inside a list literal, i.e. [first]. Then another list is added to it; that second list is determined by a recursive call to segment. Adding lists in Python concatenates them, i.e. [1, 2] + [3, 4] gives [1, 2, 3, 4]. Finally, in return max(candidates, key=Pwords) the recursively-determined list iteration and a key function are passed to max. The key function is called on each value in the iteration to get the value used to determine whether or not that list has the highest value in the iteration.
A little help needed in code translation (Python to C#)
Good night everyone, This question leaves me a little embarassed because, of couse, I know I should be able to get the answer alone. However, my knowledge about Python is just a little bit more than nothing, so I need help from someone more experienced with it than me... The following code comes from Norvig's "Natural Language Corpus Data" chapter in a recently edited book, and it's about transforming a sentence "likethisone" into "[like, this, one]" (that means, segmenting the word correctly)... I have ported all of the code to C# (in fact, re-wrote the program by myself) except for the function segment, which I am having a lot of trouble even trying to understand it's syntax. Can someone please help me translating it to a more readable form in C#? Thank you very much in advance. ################ Word Segmentation (p. 223) @memo def segment(text): "Return a list of words that is the best segmentation of text." if not text: return [] candidates = ([first]+segment(rem) for first,rem in splits(text)) return max(candidates, key=Pwords) def splits(text, L=20): "Return a list of all possible (first, rem) pairs, len(first)<=L." return [(text[:i+1], text[i+1:]) for i in range(min(len(text), L))] def Pwords(words): "The Naive Bayes probability of a sequence of words." return product(Pw(w) for w in words) #### Support functions (p. 224) def product(nums): "Return the product of a sequence of numbers." return reduce(operator.mul, nums, 1) class Pdist(dict): "A probability distribution estimated from counts in datafile." def __init__(self, data=[], N=None, missingfn=None): for key,count in data: self[key] = self.get(key, 0) + int(count) self.N = float(N or sum(self.itervalues())) self.missingfn = missingfn or (lambda k, N: 1./N) def __call__(self, key): if key in self: return self[key]/self.N else: return self.missingfn(key, self.N) def datafile(name, sep='\t'): "Read key,value pairs from file." for line in file(name): yield line.split(sep) def avoid_long_words(key, N): "Estimate the probability of an unknown word." return 10./(N * 10**len(key)) N = 1024908267229 ## Number of tokens Pw = Pdist(datafile('count_1w.txt'), N, avoid_long_words)
[ "Let's tackle the first function first:\ndef segment(text): \n \"Return a list of words that is the best segmentation of text.\" \n if not text: return [] \n candidates = ([first]+segment(rem) for first,rem in splits(text)) \n return max(candidates, key=Pwords) \n\nIt takes a word and returns the most l...
[ 2, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0003946265_c#_python.txt
Q: Matplotlib how to draw on figure on PIL image I've got a new problem here, I wish to inputs a PIL image object, and then draw the figure that generated from matplotlib, and then return the PIL image object. How could I achieve this? A: Why don't you create the image in matplotlib, save it and then import it into pil? xdata = pylab.arange(1961, 2031, 1) pylab.figure(num=None, figsize=(20.48, 10.24), dpi=100, facecolor='w', edgecolor='k') pylab.plot(xdata, ydata, linewidth=3.0) pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.title(title) pylab.grid(True) ram = cStringIO.StringIO() pylab.savefig(ram, format='png') import Image im = Image.open(ram.read())
Matplotlib how to draw on figure on PIL image
I've got a new problem here, I wish to inputs a PIL image object, and then draw the figure that generated from matplotlib, and then return the PIL image object. How could I achieve this?
[ "Why don't you create the image in matplotlib, save it and then import it into pil?\nxdata = pylab.arange(1961, 2031, 1)\npylab.figure(num=None, figsize=(20.48, 10.24), dpi=100, facecolor='w', edgecolor='k')\npylab.plot(xdata, ydata, linewidth=3.0)\npylab.xlabel(xlabel)\npylab.ylabel(ylabel)\npylab.title(title)\npy...
[ 3 ]
[]
[]
[ "matplotlib", "python", "python_imaging_library" ]
stackoverflow_0003939217_matplotlib_python_python_imaging_library.txt
Q: Appengine - Can a user import Yaml or Json file to update datastore with new values? Imagine this scenario: I made a small application in Python for Google App Engine for general use. Users can login to my app, update their profile, change address and change the picture among many other things. A user can export the models to PDF, YAML and JSON, save the file on his computer. You can download any available format of your personal information. My question is: Is It Possible for a user to upload files and update the datastore with new values? A: Yes. Your users will be able to upload data in any file type your application can process. You will, of course, need to write handlers to process the files and perform the updates. There are also some size restrictions with uploading, downloading, and processing data. You will want to keep those in mind.
Appengine - Can a user import Yaml or Json file to update datastore with new values?
Imagine this scenario: I made a small application in Python for Google App Engine for general use. Users can login to my app, update their profile, change address and change the picture among many other things. A user can export the models to PDF, YAML and JSON, save the file on his computer. You can download any available format of your personal information. My question is: Is It Possible for a user to upload files and update the datastore with new values?
[ "Yes. Your users will be able to upload data in any file type your application can process. You will, of course, need to write handlers to process the files and perform the updates.\nThere are also some size restrictions with uploading, downloading, and processing data. You will want to keep those in mind.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003946401_google_app_engine_google_cloud_datastore_python.txt
Q: Function declaration in python to have a readable and clean code? Is it possible to declare functions in python and define them later or in a separate file? I have some code like: class tata: def method1(self): def func1(): # This local function will be only used in method1, so there is no use to # define it outside. # Some code for func1. # Some code for method1. The problem is that the code becomes messy and difficult to read. So I wonder if it's possible for instance to declare func1 inside method1 and define it later? A: Sure, no problem: foo.py: def func1(): pass script.py: import foo class tata: def method1(self): func1=foo.func1 A: I think what you want is to import the function within method1, e.g. def method1(...): from module_where_func1_is_defined import func1 # do stuff something = func1(stuff, more_stuff) # do more stuff Python modules are basically just files; as long as the file module_where_func1_is_defined.py is in the same directory as your script, method1 will be able to import it. If you want to be able to customize the way method1 works, and also make it even more clear that it uses func1, you can pass func1 to method1 as a default parameter: import other_module # various codes def method1(other_args, func=other_module.func1) # do stuff something = func(stuff, more_stuff) # do more stuff A: The inner definition creates a separate name in the inner scope. It will shadow anything you define later on with the same name. If you want to define the function later on, then just do so. The name will only be checked for when it is actually used. def foo(): print 'foo' bar() def bar(): print 'bar' foo() A: If func1() needs to handle anything contained in the scope of method1() you're best leaving func1()'s definition there. You'll have to have func1() receive any pertinent data as parameters if it's not defined within the scope of method1() A: You can create methods afterwards class Something(object): def test1(self): pass def dummy(self): print "ok", self Something.test1 = dummy However it's not possible to have an anonymous function (well, there are lambda expressions but you cannot have statements there), so you have to provide a temporary name You might want to use decorators in order to make it more readable: def define(cls, name): def decor(f): setattr(cls, name, f) return decor class Something(object): def test1(self): pass @define(Something, "test1") def dummy(self): print "ok", self This code should be more readable. It will still pollute dummy but initialize it with null.
Function declaration in python to have a readable and clean code?
Is it possible to declare functions in python and define them later or in a separate file? I have some code like: class tata: def method1(self): def func1(): # This local function will be only used in method1, so there is no use to # define it outside. # Some code for func1. # Some code for method1. The problem is that the code becomes messy and difficult to read. So I wonder if it's possible for instance to declare func1 inside method1 and define it later?
[ "Sure, no problem:\nfoo.py:\ndef func1():\n pass\n\nscript.py:\nimport foo\nclass tata:\n def method1(self):\n func1=foo.func1\n\n", "I think what you want is to import the function within method1, e.g.\ndef method1(...):\n from module_where_func1_is_defined import func1\n # do stuff\n somethin...
[ 6, 3, 2, 2, 0 ]
[]
[]
[ "declaration", "python", "syntax" ]
stackoverflow_0003946628_declaration_python_syntax.txt
Q: Randomise order of if-else execution in Python This might sound like a strange question, but bear with me... I have a dictionary in Python with values like so: 'B': 23.6 'D': 0.6 'F': 35.9 'H': 35.9 I need to do an if-else with these values to do different things depending which one is > 30. The code I have at the moment is along the lines of: if angles['B'] > 30: # Do stuff elif angles['D'] > 30: # Do other stuff elif angles['F'] > 30: # Do different stuf elif angles['H'] > 30: # Do even more different stuff Now the problem comes when I have two or more values the same (like in the example data above). In this case I want to randomly pick one of these to use. The question is: how do I do that in Python? Bear in mind that regardless of the values of the dictionary either nothing (if they're all < 30) or only one thing should be done. A: You can make a sequence of key/value pairs: pairs = angles.iteritems() Filter it to remove elements <= 30: filtered = [(name, value) for name, value in pairs if value > 30] check to see if there are any options if filtered: and then pick one: from random import choice name, value = choice(filtered) update: added the following... As Aaron mentions in the comments, this only gets you halfway there. You still need to codify the action you're going to take based on name. Aaron suggests using a dictionary containing functions. Basically, you would define some functions to do something with your name/value pairs def thing1(name, value): # do stuff... def thing2(name, value): # do different stuff... set up a dictionary mapping names to function calls routes = {'A': thing1, 'B': thing2, 'C': thing1} and define a routing function that dispatches to the appropriate function: def route(pair): name, value = pair return routes[name](name, value) Then you can just call route with the name/value pair you get from choice, e.g. result = route(choice(filtered)) A more structured approach could instead involve creating a class to handle all of this or just the routing aspects. A: from random import choice while angles: x = choice(angles.keys()) if angles.pop(x)>30: if x == 'B': # Do stuff elif x == 'D': # Do other stuff elif x == 'F': # Do different stuf elif x == 'H': # Do even more different stuff break A: Write a function to scan through the dictionary... def has_gt_30(d): for key, value in d.items(): if value > 30: return key return False angle = has_gt_30(angles_dict) if angle: do_stuff(angle) This won't pick one randomly, but it will pick one arbitrarily. If you really want a random one, replace the "return key" with an aggregation of keys that fit the criteria and return that. Then use random.choice. A: you can do also: import random angles = {'B':23, 'D': 2.6, 'F': 35.9, 'H':35.9 } keys = angles.keys() random.shuffle(keys) # shuffle the list of dictionary keys for key in keys: if angles[key] > 30: # ... break
Randomise order of if-else execution in Python
This might sound like a strange question, but bear with me... I have a dictionary in Python with values like so: 'B': 23.6 'D': 0.6 'F': 35.9 'H': 35.9 I need to do an if-else with these values to do different things depending which one is > 30. The code I have at the moment is along the lines of: if angles['B'] > 30: # Do stuff elif angles['D'] > 30: # Do other stuff elif angles['F'] > 30: # Do different stuf elif angles['H'] > 30: # Do even more different stuff Now the problem comes when I have two or more values the same (like in the example data above). In this case I want to randomly pick one of these to use. The question is: how do I do that in Python? Bear in mind that regardless of the values of the dictionary either nothing (if they're all < 30) or only one thing should be done.
[ "You can make a sequence of key/value pairs:\npairs = angles.iteritems()\n\nFilter it to remove elements <= 30:\nfiltered = [(name, value) for name, value in pairs if value > 30]\n\ncheck to see if there are any options\nif filtered:\n\nand then pick one:\n from random import choice\n name, value = choice(fil...
[ 11, 2, 1, 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003946488_python_random.txt
Q: What to consider before subclassing list? I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true? I'm asking if list is generally bad to subclass and if so, what are the reasons. Alternately, what should I consider before subclassing list in Python? A: The abstract base classes provided in the collections module, particularly MutableSequence, can be useful when implementing list-like classes. These are available in Python 2.6 and later. With ABCs you can implement the "core" functionality of your class and it will provide the methods which logically depend on what you've defined. For example, implementing __getitem__ in a collections.Sequence-derived class will be enough to provide your class with __contains__, __iter__, and other methods. You may still want to use a contained list object to do the heavy lifting. A: There are no benefits to subclassing list. None of the methods will use any methods you override, so you can have unexpected bugs. Further, it's very often confusing doing things like self.append instead of self.foos.append or especially self[4] rather than self.foos[4] to access your data. You can make something that works exactly like a list or (better) howevermuch like a list you really want while just subclassing object. A: I think the first question I'd ask myself is, "Is my new object really a list?". Does it walk like a list, talk like a list? Or is is something else? If it is a list, then all the standard list methods should all make sense. If the standard list methods don't make sense, then your object should contain a list, not be a list. In old python (2.2?) sub-classing list was a bad idea for various technical reasons, but in a modern python it is fine. A: Nick is correct. Also, while I can't speak to Python, in other OO languages (Java, Smalltalk) subclassing a list is a bad idea. Inheritance in general should be avoided and delegation-composition used instead. Rather, you make a container class and delegate calls to the list. The container class has a reference to the list and you can even expose the calls and returns of the list in your own methods. This adds flexibility and allows you to change the implementation (a different list type or data structure) later w/o breaking any code. If you want your list to do different listy-type things then your container can do this and use the plain list as a simple data structure. Imagine if you had 47 different uses of lists. Do you really want to maintain 47 different subclasses? Instead you could do this via the container and interfaces. One class to maintain and allow people to call your new and improved methods via the interface(s) with the implementation remaining hidden.
What to consider before subclassing list?
I was recently going over a coding problem I was having and someone looking at the code said that subclassing list was bad (my problem was unrelated to that class). He said that you shouldn't do it and that it came with a bunch of bad side effects. Is this true? I'm asking if list is generally bad to subclass and if so, what are the reasons. Alternately, what should I consider before subclassing list in Python?
[ "The abstract base classes provided in the collections module, particularly MutableSequence, can be useful when implementing list-like classes. These are available in Python 2.6 and later.\nWith ABCs you can implement the \"core\" functionality of your class and it will provide the methods which logically depend o...
[ 18, 15, 11, 6 ]
[]
[]
[ "list", "python", "subclassing" ]
stackoverflow_0003945940_list_python_subclassing.txt
Q: Append element with SAX in python I know how to parse xml with sax in python, but how would I go about inserting elements into the document i'm parsing? Do I have to create a separate file? Could someone provide a simple example or alter the one I've put below. Thanks. from xml.sax.handler import ContentHandler from xml.sax import make_parser import sys class aHandler(ContentHandler): def startElement(self, name, attrs): print "<",name,">" def characters(self, content): print content def endElement(self,name): print "</",name,">" handler = aHandler() saxparser = make_parser() saxparser.setContentHandler(handler) datasource = open("settings.xml","r") saxparser.parse(datasource) <?xml version="1.0"?> <names> <name> <first>First1</first> <second>Second1</second> </name> <name> <first>First2</first> <second>Second2</second> </name> <name> <first>First3</first> <second>Second3</second> </name> </names> A: With DOM, you have the entire xml structure in memory. With SAX, you don't have a DOM available, so you don't have anything to append an element to. The main reason for using SAX is if the xml structure is really, really huge-- if it would be a serious performance hit to place the DOM in memory. If that isn't the case (as it appears to be from your small sample xml file), I would always use DOM vs. SAX. If you go the DOM route, (which seems to be the only option to me), look into lxml. It's one of the best python xml libraries around.
Append element with SAX in python
I know how to parse xml with sax in python, but how would I go about inserting elements into the document i'm parsing? Do I have to create a separate file? Could someone provide a simple example or alter the one I've put below. Thanks. from xml.sax.handler import ContentHandler from xml.sax import make_parser import sys class aHandler(ContentHandler): def startElement(self, name, attrs): print "<",name,">" def characters(self, content): print content def endElement(self,name): print "</",name,">" handler = aHandler() saxparser = make_parser() saxparser.setContentHandler(handler) datasource = open("settings.xml","r") saxparser.parse(datasource) <?xml version="1.0"?> <names> <name> <first>First1</first> <second>Second1</second> </name> <name> <first>First2</first> <second>Second2</second> </name> <name> <first>First3</first> <second>Second3</second> </name> </names>
[ "With DOM, you have the entire xml structure in memory.\nWith SAX, you don't have a DOM available, so you don't have anything to append an element to.\nThe main reason for using SAX is if the xml structure is really, really huge-- if it would be a serious performance hit to place the DOM in memory. If that isn't th...
[ 0 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0003946743_python_sax_xml.txt
Q: Running a Python program on a web server I have a Python script which accepts a XML file as input and then processes it and creates another file. Now the way I have to run this program in terminal (mac) is: ttx myfile.xml And it does the job. Now I am trying to install this program on a web server. I have all the necessary files installed as Modules under my Python installation. My problem is, How can I pass a file to this Python script on a web server? Should I be using File Upload method? or urllib2? or something else? Thanks a lot A: Passing the data would be easiest with HTTP POST. As to integrating Python script w/ Apache, the way I know would be to create a simple Django app to wrap the main Python function in your script, but I believe there must be some more direct way. A: There is a "minimal http-upload cgi-script"-recipe, which can be used for that. A: You could create a simple CGI script: http://wiki.python.org/moin/CgiScripts using the python cgi module. Either as a wrapper around your python script, or update the existing one - put a text area box for pasting the contents or otherwise you need to upload the file and pass it on to your program. Then print the content header and the results to stdout; and they should show up in the browser. A: The best interface from Python to a web server is probably WSGI. It's what Django recommends for its interface to Apache. WSGI is defined in PEP 333. WSGI works by passing Apache's requests to your Python code as function calls. An example from the PEP uses the following Python code for a simple application: def simple_app(environ, start_response): """Simplest possible application object""" status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return ['Hello world!\n'] On apache, install mod_wsgi (available as a package in several distros), and then put this somewhere in your Apache configuration: WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.wsgi <Directory /usr/local/www/wsgi-scripts> Order allow, deny Allow from all </Directory> One of the really nice things about WSGI is that your Python code doesn't have to live in the document tree, and therefore isn't available for download and inspection.
Running a Python program on a web server
I have a Python script which accepts a XML file as input and then processes it and creates another file. Now the way I have to run this program in terminal (mac) is: ttx myfile.xml And it does the job. Now I am trying to install this program on a web server. I have all the necessary files installed as Modules under my Python installation. My problem is, How can I pass a file to this Python script on a web server? Should I be using File Upload method? or urllib2? or something else? Thanks a lot
[ "Passing the data would be easiest with HTTP POST. As to integrating Python script w/ Apache, the way I know would be to create a simple Django app to wrap the main Python function in your script, but I believe there must be some more direct way.\n", "There is a \"minimal http-upload cgi-script\"-recipe, which ca...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003247591_python.txt
Q: How to make NSLog work with Python's logging module when using PyObjC? I'm writing a Django-based webapp that imports a Cocoa framework via PyObjC. The Cocoa framework has NSLog() littered all through it and while I can see them when running the Django server in non-daemon mode, as soon as I go to daemon I simply lose all this useful NSLog() output. Is there any easy way to get NSLog stuff to bubble up into the Python logging module's world so it can be merged in with the log messages being emitted by the actual Python code? Did a little Googling and it seems like you might have to redirect stderr and somehow suck it back into Python in order to achieve this, which would be kind of a bummer ... Any help much appreciated. A: According to this page, NSLog basically works like fprintf(stderr, format_string, args ...); so you do need to capture / redirect the standard error output. I wrote a post some time ago which might help for Python-only programs, but I would guess that the Cocoa code accesses the process-level file descriptor 2 (stderr) under the covers. So you'll need to do some low-level fiddling around with the process' stderr. Here's an example: old_stderr = os.dup(sys.stderr.fileno()) # keep a copy fd = os.open('path/to/mylog', os.O_CREAT | os.O_WRONLY) os.dup2(fd, sys.stderr.fileno()) # Now, stderr output, including NSLog output, should go to 'path/to/mylog' ... os.dup2(old_stderr, sys.stderr.fileno()) #stderr restored to its old state Once you have fd, you can create a file-like object out of it and pass it to StreamHandler, for example, as a means to merging the output from Python code and Cocoa code.
How to make NSLog work with Python's logging module when using PyObjC?
I'm writing a Django-based webapp that imports a Cocoa framework via PyObjC. The Cocoa framework has NSLog() littered all through it and while I can see them when running the Django server in non-daemon mode, as soon as I go to daemon I simply lose all this useful NSLog() output. Is there any easy way to get NSLog stuff to bubble up into the Python logging module's world so it can be merged in with the log messages being emitted by the actual Python code? Did a little Googling and it seems like you might have to redirect stderr and somehow suck it back into Python in order to achieve this, which would be kind of a bummer ... Any help much appreciated.
[ "According to this page, NSLog basically works like\nfprintf(stderr, format_string, args ...);\n\nso you do need to capture / redirect the standard error output. I wrote a post some time ago which might help for Python-only programs, but I would guess that the Cocoa code accesses the process-level file descriptor 2...
[ 3 ]
[]
[]
[ "django", "logging", "nslog", "pyobjc", "python" ]
stackoverflow_0003910541_django_logging_nslog_pyobjc_python.txt
Q: Setting up a python screen scraper that could work on Google App engine I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that could run on Google App engine. A: Beautifulsoup runs fine on App Engine (just make sure to use 3.0.8, not the iffy 3.1.0). The main alternative, I think, would be html5lib -- I haven't tries it on App Engine but I believe it does run there (quite slowly -- if that's a problem I think you need to stick with BeautifulSoup), e.g. this service runs on App Engine and is based on html5lib. A: I have had good (although slow) results using mechanize and BeautifulSoup. In fact, to save code space on Google App Engine, I use the (old) version of BeautifulSoup included in mechanize. I have mechanize in a zip file, mechanize.zip. The index of this zip file looks like: mechanize/ mechanize/__init__.py mechanize/_auth.py mechanize/_beautifulsoup.py mechanize/_clientcookie.py ... etc Then in my Python code, import sys sys.path.insert(0, 'mechanize.zip') import mechanize from mechanize._beautifulsoup import BeautifulSoup A: The other choice is lxml, but it uses C code and so does not work on GAE. A: I have used BeautifulSoup with great success parsing HTML. Problem is that's all BeautifulSoup does, is parse the HTML. I ended up writing all the http interactions using urlfetch. To web-scrape my target I need a full fledged code driven browser that can execute javascript on my target site's pages. I think I'm having to dump the python app and go java so I can use HTMLUnit - prototyping underway. - mattb
Setting up a python screen scraper that could work on Google App engine
I am looking to setup a automated screen scraper that will run on Google app engine using python. I want it to scrape the site and put the specified results into a Entity in app engine. I am looking for some directions on what to use. I have seen beautifulsoup but wonder if people could recommend anything else that could run on Google App engine.
[ "Beautifulsoup runs fine on App Engine (just make sure to use 3.0.8, not the iffy 3.1.0). The main alternative, I think, would be html5lib -- I haven't tries it on App Engine but I believe it does run there (quite slowly -- if that's a problem I think you need to stick with BeautifulSoup), e.g. this service runs on...
[ 4, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "screen_scraping" ]
stackoverflow_0002406082_google_app_engine_python_screen_scraping.txt
Q: Getting the entire output from subprocess.Popen I'm getting a slightly weird result from calling subprocess.Popen that I suspect has a lot to do with me being brand-new to Python. args = [ 'cscript', '%USERPROFILE%\\tools\\jslint.js','%USERPROFILE%\\tools\\jslint.js' ] p = Popen(args, stdout=PIPE, shell=True).communicate()[0] Results in output like the following (the trailing double \r\n is there in case it's important) Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n If I run that command from an interactive Python shell it looks like this >>> args = ['cscript', '%USERPROFILE%\\tools\\jslint.js', '%USERPROFILE%\\tools\jslint.js'] >>> p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True).communicate()[0] Lint at line 5631 character 17: Unexpected /*member 'OpenTextFile'. f = fso.OpenTextFile(WScript.Arguments(0), 1), ... Lint at line 5649 character 17: Unexpected /*member 'Quit'. WScript.Quit(1); So there's all the output I really care about, but if I dump the value of the "p" variable I just set up... >>> p 'Microsoft (R) Windows Script Host Version 5.8\r\nCopyright (C) Microsoft Corpor ation. All rights reserved.\r\n\r\n' >>> Where'd all that data I want end up going? It definitely didn't end up in "p". Looks like it's going to stdout, but I didn't I explictly tell it not to do that? I'm running this on Windows 7 x64 with Python 2.6.6 A: Is it going to stderr? Try redirecting: p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()[0] A: It's probably going to stderr, as SimonJ suggested. Also, the docs say not to use shell=True in Windows for your case: The executable argument specifies the program to execute. It is very seldom needed: Usually, the program to execute is defined by the args argument. If shell=True, the executable argument specifies which shell to use. On Unix, the default shell is /bin/sh. On Windows, the default shell is specified by the COMSPEC environment variable. The only reason you would need to specify shell=True on Windows is where the command you wish to execute is actually built in to the shell, eg dir, copy. You don’t need shell=True to run a batch file, nor to run a console-based executable. Later: oh wait. Are you using the shell to get those environment variables expanded? Okay, I take it back: you do need the shell=True.
Getting the entire output from subprocess.Popen
I'm getting a slightly weird result from calling subprocess.Popen that I suspect has a lot to do with me being brand-new to Python. args = [ 'cscript', '%USERPROFILE%\\tools\\jslint.js','%USERPROFILE%\\tools\\jslint.js' ] p = Popen(args, stdout=PIPE, shell=True).communicate()[0] Results in output like the following (the trailing double \r\n is there in case it's important) Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n If I run that command from an interactive Python shell it looks like this >>> args = ['cscript', '%USERPROFILE%\\tools\\jslint.js', '%USERPROFILE%\\tools\jslint.js'] >>> p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True).communicate()[0] Lint at line 5631 character 17: Unexpected /*member 'OpenTextFile'. f = fso.OpenTextFile(WScript.Arguments(0), 1), ... Lint at line 5649 character 17: Unexpected /*member 'Quit'. WScript.Quit(1); So there's all the output I really care about, but if I dump the value of the "p" variable I just set up... >>> p 'Microsoft (R) Windows Script Host Version 5.8\r\nCopyright (C) Microsoft Corpor ation. All rights reserved.\r\n\r\n' >>> Where'd all that data I want end up going? It definitely didn't end up in "p". Looks like it's going to stdout, but I didn't I explictly tell it not to do that? I'm running this on Windows 7 x64 with Python 2.6.6
[ "Is it going to stderr? Try redirecting:\np = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()[0]\n\n", "It's probably going to stderr, as SimonJ suggested.\nAlso, the docs say not to use shell=True in Windows for your case:\n\nThe executable argument specifies th...
[ 7, 3 ]
[]
[]
[ "python", "stdout", "subprocess" ]
stackoverflow_0003947191_python_stdout_subprocess.txt
Q: List of substrings I have big string, it can have a few thousands lines. I would like to to get all sub-strings like: [tag] here can be everything [/tag] in a list. How can I do this? My regex is not working (or I'm doing something wrong). A: The function find_all_tags returns a list of all occurences of tag tag in text: import re def find_all_tags(text, tag): return re.findall(r"(?s)\[" + tag + r"\].*?\[/" + tag + r"\]", text) >>> text="""this is [b]bold text[/b] and some[b] that spans a line[/b] some [i]italics[/i] and some [b][i]bold italics[/i][/b]""" >>> find_all_tags(text, "b") ['[b]bold text[/b]', '[b]\nthat spans a line[/b]', '[b][i]bold italics[/i][/b]'] Tell me if you need something different (e.g a generator instead of a list of the substrings) A: You can just use string splits for item in my_big_string.split("]"): if "[" in item: print item.split("[")[-1] eg >>> text="""this is [b]bold text[/b] and some[b] ... that spans a line[/b] some [i]italics[/i] and some ... [b][i]bold italics[/i][/b]""" >>> for item in text.split("]"): ... if "[" in item: ... print item.split("[")[-1], ... b /b b /b i /i b i /i /b >>>
List of substrings
I have big string, it can have a few thousands lines. I would like to to get all sub-strings like: [tag] here can be everything [/tag] in a list. How can I do this? My regex is not working (or I'm doing something wrong).
[ "The function find_all_tags returns a list of all occurences of tag tag in text:\nimport re\ndef find_all_tags(text, tag):\n return re.findall(r\"(?s)\\[\" + tag + r\"\\].*?\\[/\" + tag + r\"\\]\", text)\n\n>>> text=\"\"\"this is [b]bold text[/b] and some[b]\nthat spans a line[/b] some [i]italics[/i] and some\n[...
[ 0, 0 ]
[]
[]
[ "list", "python", "regex", "string", "tags" ]
stackoverflow_0003944856_list_python_regex_string_tags.txt
Q: Call a function in a module after setup.py installation I've got a program/joke that needs a reasonably large data structure to operate, (a dictionary that takes a few seconds to construct) and I would like to create and pickle it into the installation dir when running python setup.py install. setup() in distutils.core looks like it shouldn't exit, so I thought that I could just import my module and call the function after calling setup() in setup.py, but it doesn't seem to be working, even though installation does work. This is what my setup.py looks like right now: from distutils.core import setup setup(... ) from phoneoops import utils utils.get_hashed_dictionary(save=True) A: I created a dummy setup.py as: from distutils.core import setup setup() print 'after' and my print statement prints just fine after running python setup.py install. I tried an invalid command like python setup.py xx, and the after print didn't get called. Are you sure it didn't raise an Exception or SystemExit? When I modified this simple example to: try: setup() except SystemExit as e: print e print 'after' and ran python setup.py xx, the after statement ran fine. Edit: Agreed, @AndiDog, this is better (unless for some reason you want to swallow the exception): try: setup() finally: print 'after'
Call a function in a module after setup.py installation
I've got a program/joke that needs a reasonably large data structure to operate, (a dictionary that takes a few seconds to construct) and I would like to create and pickle it into the installation dir when running python setup.py install. setup() in distutils.core looks like it shouldn't exit, so I thought that I could just import my module and call the function after calling setup() in setup.py, but it doesn't seem to be working, even though installation does work. This is what my setup.py looks like right now: from distutils.core import setup setup(... ) from phoneoops import utils utils.get_hashed_dictionary(save=True)
[ "I created a dummy setup.py as:\nfrom distutils.core import setup\nsetup()\nprint 'after'\n\nand my print statement prints just fine after running python setup.py install.\nI tried an invalid command like python setup.py xx, and the after print didn't get called.\nAre you sure it didn't raise an Exception or System...
[ 1 ]
[]
[]
[ "distutils", "python", "setup.py" ]
stackoverflow_0003947041_distutils_python_setup.py.txt
Q: First Python Tkinter window works, but the rest are blank I think I'm missing something basic about Tkinter. What would be the correct way to create several windows with the same hidden root window? I can get one window to open, but once it's closed subsequent ones show up blank, without any widgets in them. I've also noticed if I leave the root window visible, it disappears when I close the first "real" window. I would post code, but I haven't been able to figure out what causes the behavior, and my actual code is fairly complicated, and has to run inside another (even more complicated) program. I've tried using .quit() or .destroy() to close windows, and put mainloop()s and wait_window() loops in different places, but everything either still has the error or something worse goes wrong. I guess what I'm looking for is just a different perspective. My problem seems similar to the one here, but I haven't been able to gain anything new from the answer. Any ideas? I know this is a little vague. Thanks SOLVED: This probably won't help anyone, but I figured out the problem. I have several classes of windows, each derived from Tkinter.Toplevel. In my base Window class I made a close() function that calls self.destroy(). Then in its subclasses I added custom code to store their geometry etc, and finally called Window.close(self). Something about that doesn't work, because if I just use self.quit() instead of invoking the superclass's close(), everything is fine. A: Your question is too vague to know for certain what the problem is. Rest assured, when you use it right it's quite easy to create multiple windows, and to hide and show them at will. You ask what the correct way to create multiple windows is; the answer to that is to call Toplevel() for each window, nothing more, nothing less. It is then up to you to place widgets inside of that window. There's no secret, no hidden options, no extra commands. Just make sure that the parent for each child widget is set appropriately. Here's a simple example: import Tkinter as tk import sys def exit(): sys.exit(0) root = tk.Tk() root.wm_withdraw() for i in range (10): top = tk.Toplevel(root) top.title("Window %s" % i) label = tk.Label(top, text="This is toplevel #%s" % i) button = tk.Button(top, text="exit", command=exit) label.pack() button.pack() root.mainloop()
First Python Tkinter window works, but the rest are blank
I think I'm missing something basic about Tkinter. What would be the correct way to create several windows with the same hidden root window? I can get one window to open, but once it's closed subsequent ones show up blank, without any widgets in them. I've also noticed if I leave the root window visible, it disappears when I close the first "real" window. I would post code, but I haven't been able to figure out what causes the behavior, and my actual code is fairly complicated, and has to run inside another (even more complicated) program. I've tried using .quit() or .destroy() to close windows, and put mainloop()s and wait_window() loops in different places, but everything either still has the error or something worse goes wrong. I guess what I'm looking for is just a different perspective. My problem seems similar to the one here, but I haven't been able to gain anything new from the answer. Any ideas? I know this is a little vague. Thanks SOLVED: This probably won't help anyone, but I figured out the problem. I have several classes of windows, each derived from Tkinter.Toplevel. In my base Window class I made a close() function that calls self.destroy(). Then in its subclasses I added custom code to store their geometry etc, and finally called Window.close(self). Something about that doesn't work, because if I just use self.quit() instead of invoking the superclass's close(), everything is fine.
[ "Your question is too vague to know for certain what the problem is. Rest assured, when you use it right it's quite easy to create multiple windows, and to hide and show them at will.\nYou ask what the correct way to create multiple windows is; the answer to that is to call Toplevel() for each window, nothing more,...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003945585_python_tkinter.txt
Q: Recursive directory list/analyze function doesn't seem to recurse right I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this: OTUS-ASIO:face fish$ sufs >>> /Users/fish/Dropbox/ost2/face (total 194) === 1 1 - === css 16 ----- === gif 14 ----- === html 12 ---- === icc 87 -------------------------- === jpg 3 - === js 46 -------------- === png 3 - === zip 2 - ... which would be great, if those values were correct. They are not. Here's what happens when I run it in a subdirectory of the directory I listed above: OTUS-ASIO:face fish$ cd images/ OTUS-ASIO:images fish$ sufs >>> /Users/fish/Dropbox/ost2/face/images (total 1016) === JPG 3 - === gif 17 - === ico 1 - === jpeg 1 - === jpg 901 -------------------------- === png 87 --- ... It only seems to go one directory level down. Running the script one level up didn't pick up on the 'jpeg' suffix at all, and seemed to miss a good 898 jpg files. The script in question is here: #!/usr/bin/env python # encoding: utf-8 """ getfilesuffixes.py Created by FI$H 2000 on 2010-10-15. Copyright (c) 2010 OST, LLC. All rights reserved. """ import sys, os, getopt help_message = ''' Prints a list of all the file suffixes found in each DIR, with counts. Defaults to the current directory wth no args. $ %s DIR [DIR DIR etc ...] ''' % os.path.basename(__file__) dirs = dict() skips = ('DS_Store','hgignore') class Usage(Exception): def __init__(self, msg): self.msg = msg def getmesomesuffixes(rootdir, thisdir=None): if not thisdir: thisdir = rootdir for thing in [os.path.abspath(h) for h in os.listdir(thisdir)]: if os.path.isdir(thing): getmesomesuffixes(rootdir), thing) else: if thing.rfind('.') > -1: suf = thing.rsplit('.').pop() dirs[rootdir][suf] = dirs[rootdir].get(suf, 0) + 1 return def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "h", ["help",]) except getopt.error, msg: raise Usage(msg) for option, value in opts: if option == "-v": verbose = True if option in ("-h", "--help"): raise Usage(help_message) if len(args) == 0: args.append(os.getcwd()) for durr in [os.path.abspath(arg) for arg in args]: if os.path.isdir(durr): dirs[durr] = dict() for k, v in dirs.items(): getmesomesuffixes(k) print "" for k, v in dirs.items(): sufs = v.items() sufs.sort() maxcount = reduce(lambda fs, ns: fs > ns and fs or ns, map(lambda t: t[1], sufs), 1) mincount = reduce(lambda fs, ns: fs < ns and fs or ns, map(lambda t: t[1], sufs), 1) total = reduce(lambda fs, ns: fs + ns, map(lambda t: t[1], sufs), 0) print ">>>\t\t\t%s (total %s)" % (k, total) for suf, sufcount in sufs: try: skips.index(suf) except ValueError: print "===\t\t\t%12s\t %3s\t %s" % (suf, sufcount, "-" * (int(float(float(sufcount) / float(maxcount)) * 25) + 1)) print "" except Usage, err: print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg) print >> sys.stderr, "\t for help use --help" return 2 if __name__ == "__main__": sys.exit(main()) It seems that getmesomesuffixes() is subtly not doing what I want it to. I hate to ask such an annoying question, but if anyone can spot whatever amateur-hour error I am making with a quick once-over, it would save me some serious frustration. A: Yeah, Won't you be better off if you used os.walk for root, dirs, files in os.walk(basedir): ... do you stuff .. See the example at http://docs.python.org/library/os.html Also look at os.path.splitext(path), a finer way to find the type of your file. >>> os.path.splitext('/d/c/as.jpeg') ('/d/c/as', '.jpeg') >>> Both of these together should simplify your code. A: import os import os.path from collections import defaultdict def foo(dir='.'): d = defaultdict(int) for _, _, files in os.walk(dir): for f in files: d[os.path.splitext(f)[1]] += 1 return d if __name__ == '__main__': d = foo() for k, v in sorted(d.items()): print k, v
Recursive directory list/analyze function doesn't seem to recurse right
I wrote what I thought was a straightforward Python script to traverse a given directory and tabulate all the file suffixes it finds. The output looks like this: OTUS-ASIO:face fish$ sufs >>> /Users/fish/Dropbox/ost2/face (total 194) === 1 1 - === css 16 ----- === gif 14 ----- === html 12 ---- === icc 87 -------------------------- === jpg 3 - === js 46 -------------- === png 3 - === zip 2 - ... which would be great, if those values were correct. They are not. Here's what happens when I run it in a subdirectory of the directory I listed above: OTUS-ASIO:face fish$ cd images/ OTUS-ASIO:images fish$ sufs >>> /Users/fish/Dropbox/ost2/face/images (total 1016) === JPG 3 - === gif 17 - === ico 1 - === jpeg 1 - === jpg 901 -------------------------- === png 87 --- ... It only seems to go one directory level down. Running the script one level up didn't pick up on the 'jpeg' suffix at all, and seemed to miss a good 898 jpg files. The script in question is here: #!/usr/bin/env python # encoding: utf-8 """ getfilesuffixes.py Created by FI$H 2000 on 2010-10-15. Copyright (c) 2010 OST, LLC. All rights reserved. """ import sys, os, getopt help_message = ''' Prints a list of all the file suffixes found in each DIR, with counts. Defaults to the current directory wth no args. $ %s DIR [DIR DIR etc ...] ''' % os.path.basename(__file__) dirs = dict() skips = ('DS_Store','hgignore') class Usage(Exception): def __init__(self, msg): self.msg = msg def getmesomesuffixes(rootdir, thisdir=None): if not thisdir: thisdir = rootdir for thing in [os.path.abspath(h) for h in os.listdir(thisdir)]: if os.path.isdir(thing): getmesomesuffixes(rootdir), thing) else: if thing.rfind('.') > -1: suf = thing.rsplit('.').pop() dirs[rootdir][suf] = dirs[rootdir].get(suf, 0) + 1 return def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "h", ["help",]) except getopt.error, msg: raise Usage(msg) for option, value in opts: if option == "-v": verbose = True if option in ("-h", "--help"): raise Usage(help_message) if len(args) == 0: args.append(os.getcwd()) for durr in [os.path.abspath(arg) for arg in args]: if os.path.isdir(durr): dirs[durr] = dict() for k, v in dirs.items(): getmesomesuffixes(k) print "" for k, v in dirs.items(): sufs = v.items() sufs.sort() maxcount = reduce(lambda fs, ns: fs > ns and fs or ns, map(lambda t: t[1], sufs), 1) mincount = reduce(lambda fs, ns: fs < ns and fs or ns, map(lambda t: t[1], sufs), 1) total = reduce(lambda fs, ns: fs + ns, map(lambda t: t[1], sufs), 0) print ">>>\t\t\t%s (total %s)" % (k, total) for suf, sufcount in sufs: try: skips.index(suf) except ValueError: print "===\t\t\t%12s\t %3s\t %s" % (suf, sufcount, "-" * (int(float(float(sufcount) / float(maxcount)) * 25) + 1)) print "" except Usage, err: print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg) print >> sys.stderr, "\t for help use --help" return 2 if __name__ == "__main__": sys.exit(main()) It seems that getmesomesuffixes() is subtly not doing what I want it to. I hate to ask such an annoying question, but if anyone can spot whatever amateur-hour error I am making with a quick once-over, it would save me some serious frustration.
[ "Yeah, Won't you be better off if you used os.walk\nfor root, dirs, files in os.walk(basedir):\n ... do you stuff ..\n\nSee the example at \n\nhttp://docs.python.org/library/os.html\n\nAlso look at os.path.splitext(path), a finer way to find the type of your file.\n>>> os.path.splitext('/d/c/as.jpeg')\n('/d/c/as...
[ 3, 1 ]
[]
[]
[ "command_line", "directory_structure", "filesystems", "python", "recursion" ]
stackoverflow_0003946439_command_line_directory_structure_filesystems_python_recursion.txt
Q: Sorting csv columns in bash, reading bash output into python variables Hi I have a ton of data in multiple csv files and filter out a data set using grep: user@machine:~/$ cat data.csv | grep -a "63[789]\...;" 637.05;1450.2 637.32;1448.7 637.60;1447.7 637.87;1451.5 638.14;1454.2 638.41;1448.6 638.69;1445.8 638.96;1440.0 639.23;1431.9 639.50;1428.8 639.77;1427.3 I want to figure out the data set which has the highest count, the column right of the ; and then know the corresponding value (left of the ;). In this case the set I'm looking for would be 638.14;1454.2 I tried different things and ended up using a combination of bash and python, which works, but isn't very pretty: os.system('ls | grep csv > filelist') files = open("filelist") files = files.read() files = files.split("\n") for filename in files[0:-1]: os.system('cat ' + filename + ' | grep -a "63[6789]\...;" > filtered.csv') filtered = csv.reader(open('filtered.csv'), delimiter=';') sortedlist = sorted(filtered_file, key=operator.itemgetter(1), reverse=True) dataset = sortedlist[0][0] + ';' + sortedlist[0][1] + '\n' I would love to have a bash only solution (cut, awk, arrays?!?) but couldn't figure it out. Also I don't like the work around writing the bash commands into files and then reading them into python variables. Can I read them into variables directly or are there better solutions to this problem? (probably perl etc... but I am really interested in a bash solution..) Thank you very much!! A: A quick one-liner would be: grep -a "63[789]\...;" data.csv | sort -n -r -t ';' -k 2 | head --lines=1 This simply sorts the file numerically based on the second column and then prints out the first row. Hope that helps. A: If you are going to use Python, then use Python. Why are you intermixing bash commands together? It makes your code not portable/dependent on a bash environment. import os import glob import operator os.chdir("/mypath") for file in glob.glob("*.csv"): data=open(file).readlines() data=[i.strip().split(";") for i in data if i[:3] in ["637","638","639"]] # data=[i.strip().split(";") for i in data if i[:3] in ["637","638","639"] and isinstance(float(i[:6]),float) ] sortedlist = sorted(data, key=operator.itemgetter(1), reverse=True) print "Highest for file %s: %s" % (file,sortedlist[0]) OR, if you are more interested in a bash+tools solution find . -type f -name '*.csv' |while read -r FILE do grep -a "63[789]\...;" "$FILE" | sort -n -r -t ';' -k 2 | head -1 >> output.txt done A: $ cat data.csv | grep -a "63[789]\...;" | awk 'BEGIN {FS=";"} $2>max{max=$2; val=$1} END {print "max " max " at " val}' max 1454.2 at 638.14 A: If you have a ton of data then you don't want to store all that data into memory and then sort it to get the max value. This approach is inefficient regarding both computing time complexity and memory. You can simply parse the files and compute the desired values on-the-fly instead. A fast pure Python approach to deal with your problem: import os, re os.chdir('/path/to/csvdir') for f in os.listdir('.'): dataset, count = 0.0, 0.0 for line in open(f): if re.search(r'63[6789]\...', line): d, c = map(float, line.strip().split(';')) if count < c: dataset, count = d, c print f, dataset This approach can also be used to show a list of max values (if there can be more than one dataset with highest counts) by modifying the appropriate lines: dataset, count = [], 0.0 ... if count < c: dataset, count = [d], c elif count == c: dataset.append(d) Edit: the script assumes that your csvdir is populated only with files containing the parsing format. If you want to filter them by name, you can use either glob (with limited regexp capabilities in name filtering): for f in glob.glob('*.csv'): or apply a filter to os.listdir: for f in filter(lambda f: re.match('.*\.csv', f), os.listdir('.')): A: Here is code I wrote to sort csv files using python. It allows you to specify multiple columns and to sort in reverse order by using a minus sign. #!/usr/bin/env python # Usage: # (1) sort ctb_consolidated_test_id.csv by Academic Year, Test ID, Period, and Test Name, with Test ID in descending order # sort_csv.py -c "Academic Year" -c "-Test ID" -c "Period" -c "Test Name" ctb_consolidated_test_id.csv from __future__ import with_statement from __future__ import print_function import sys def multikeysort(items, columns): from operator import itemgetter import re num_re = re.compile(r'^\d+$') comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns ] def number_comparable(val1, val2): return len(val1) != len(val2) and num_re.match(val1) and num_re.match(val2) def column_comparer(left, right): for fn, mult in comparers: val1, val2 = fn(left), fn(right) if number_comparable(val1, val2): val1, val2 = int(val1), int(val2) result = cmp(val1, val2) if result: return mult * result return 0 return sorted(items, cmp=column_comparer) def sort_csv(filename, columns): import csv with open(filename, "r") as f: reader = csv.DictReader(f) writer = csv.DictWriter(sys.stdout, reader.fieldnames) writer.writerow(dict(zip(reader.fieldnames, reader.fieldnames))) writer.writerows(multikeysort(reader, columns)) if __name__ == '__main__': from glob import glob from optparse import OptionParser, make_option option_list = [ make_option('-c', '--column', dest='columns', action='append', metavar='COLUMN NAME'), ] parser = OptionParser(option_list=option_list) (options, args) = parser.parse_args() filenames = (filename for arg in args for filename in glob(arg)) for filename in filenames: sort_csv(filename, options.columns) A: nice, thanks a lot, Hakop Palyan !! Now is there a trick on how to get this data set out of all the csv files and collect it somewhere as a new file? something like find . -name '*.csv' -print0 | xargs -0 grep -a "63[789]\...;" | sort -n -r -t ';' -k 2 | head --lines=1 this one prints only the first line, I would need to iterate over the individual files and collect the datasets ... A: I know you are looking for a bash based solution but I could not help offering something using the csv module. import os import csv import re target_re = re.compile(r'^63[789]\.\d\d$') csv_filenames = [f for f in os.listdir('.') if f.endwith('.csv')] largest_in_each_file = [] for f in csv_filenames: largest = (None, 0) for a,b in csv.reader(open(f, 'rb'), delimiter=';'): if target_re.match(a) and b > largest[1]: largest = (a, b) largest_in_each_file.append(largest) largest_overall = largest_in_each_file[0] for largest in largest_in_each_file: print "%s;%s in %s" % largest if largest[1] > largest_overall[1]: largest_overall = largest print "-" * 10 print "%s;%s in %s is the largest record in all files" % largest_overall
Sorting csv columns in bash, reading bash output into python variables
Hi I have a ton of data in multiple csv files and filter out a data set using grep: user@machine:~/$ cat data.csv | grep -a "63[789]\...;" 637.05;1450.2 637.32;1448.7 637.60;1447.7 637.87;1451.5 638.14;1454.2 638.41;1448.6 638.69;1445.8 638.96;1440.0 639.23;1431.9 639.50;1428.8 639.77;1427.3 I want to figure out the data set which has the highest count, the column right of the ; and then know the corresponding value (left of the ;). In this case the set I'm looking for would be 638.14;1454.2 I tried different things and ended up using a combination of bash and python, which works, but isn't very pretty: os.system('ls | grep csv > filelist') files = open("filelist") files = files.read() files = files.split("\n") for filename in files[0:-1]: os.system('cat ' + filename + ' | grep -a "63[6789]\...;" > filtered.csv') filtered = csv.reader(open('filtered.csv'), delimiter=';') sortedlist = sorted(filtered_file, key=operator.itemgetter(1), reverse=True) dataset = sortedlist[0][0] + ';' + sortedlist[0][1] + '\n' I would love to have a bash only solution (cut, awk, arrays?!?) but couldn't figure it out. Also I don't like the work around writing the bash commands into files and then reading them into python variables. Can I read them into variables directly or are there better solutions to this problem? (probably perl etc... but I am really interested in a bash solution..) Thank you very much!!
[ "A quick one-liner would be:\ngrep -a \"63[789]\\...;\" data.csv | sort -n -r -t ';' -k 2 | head --lines=1\n\nThis simply sorts the file numerically based on the second column and then prints out the first row. Hope that helps.\n", "If you are going to use Python, then use Python. Why are you intermixing bash com...
[ 6, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0003946898_bash_python_shell.txt
Q: Change Form Validation for Admin Login in Django I use a custom auth backend in my django application that allows users to login with ther emails. But when I try to login in the admin I get the message: "usernames cant contain the '@' char" I suppose this error is raised before it reaches the auth backend, so its a form issue, right ? A: Unfortunately no, this error is raised just if the authentication fails and there is no User with the given email. The bad thing is that this validation is hard-coded [1]. There is an open ticket for this [2]. Since version 1.2 django allows emails as User.username, if you're using this version maybe you won't even need a custom auth backend. But the bug [2] persists! The only solution I can see to remove this validation is create a custom AdminSite and override the login() method, which is bad... [1] http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/sites.py#L323 [2] http://code.djangoproject.com/ticket/13928
Change Form Validation for Admin Login in Django
I use a custom auth backend in my django application that allows users to login with ther emails. But when I try to login in the admin I get the message: "usernames cant contain the '@' char" I suppose this error is raised before it reaches the auth backend, so its a form issue, right ?
[ "Unfortunately no, this error is raised just if the authentication fails and there is no User with the given email. The bad thing is that this validation is hard-coded [1].\nThere is an open ticket for this [2].\nSince version 1.2 django allows emails as User.username, if you're using this version maybe you won't e...
[ 1 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0003947102_django_django_admin_django_forms_python.txt
Q: Splitting a long tuple into smaller tuples I have a long tuple like (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) and i am trying to split it into a tuple of tuples like ((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10)) I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)r lists. My friend said i should split it but i just cant get it -_- I need to split the tuple into tuples with 4 elements that i will later use a rectangles to draw to a image with PIL. A: Well there is a certain idiom for that: def grouper(n, iterable): args = [iter(iterable)] * n return zip(*args) t = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) print grouper(4, t) But its kind of complicated to explain. A slightly more general version of this is listed in the itertools receipes. You can also slice the tuple yourself parts = (t[0:4], t[4:8], t[8:12], t[12:16]) # or as a function def grouper2(n, lst): return [t[i:i+n] for i in range(0, len(t), n)] which is probably what your friend meant. A: >>> atup (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) >>> [ atup[n:n+4] for n,i in enumerate(atup) if n%4==0 ] [(2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10)] A: Another possible answer (using a generator): oldTuple = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) newTuple = tuple(oldTuple[x:x+4] for x in range(0, len(oldTuple), 4)) A: I had written such a function as gist some time back, available at http://gist.github.com/616853 def split(input_list,num_fractions=None,subset_length=None): ''' Given a list/tuple split original list based on either one of two parameters given but NOT both, Returns generator num_fractions : Number of subsets original list has to be divided into, of same size to the extent possible. In case equilength subsets can't be generated, all but the last subset will have the same number of elements. subset_length : Split on every subset_length elements till the list is exhausted. ''' if not input_list: yield input_list #For some reason I can't just return from here : return not allowed in generator expression elif not bool(num_fractions) ^ bool(subset_length): #Will check for both the invalid cases, '0' and 'None'.. Oh Python :) raise Exception("Only one of the params : num_fractions,subset_length to be provided") else: if num_fractions: #calcluate subset_length in this case subset_length = max(len(input_list)/num_fractions,1) for start in xrange(0,len(input_list),subset_length): yield input_list[start:start+subset_length] >> list(list_split.split((2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10),subset_length=4)) [(2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10)] The code is longer than the solutions given above, but covers all possible sequence split conditions.
Splitting a long tuple into smaller tuples
I have a long tuple like (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10) and i am trying to split it into a tuple of tuples like ((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10)) I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)r lists. My friend said i should split it but i just cant get it -_- I need to split the tuple into tuples with 4 elements that i will later use a rectangles to draw to a image with PIL.
[ "Well there is a certain idiom for that:\ndef grouper(n, iterable):\n args = [iter(iterable)] * n\n return zip(*args)\n\nt = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)\nprint grouper(4, t)\n\nBut its kind of complicated to explain. A slightly more general version of this is listed in the ite...
[ 10, 4, 0, 0 ]
[]
[]
[ "list", "python", "split", "tuples" ]
stackoverflow_0003947337_list_python_split_tuples.txt
Q: How to develop and then parse a data structure I'm designing a weather program where I need to keep track of certain things and allow the user to add data which will be saved and subsequently read later. My fields are City State Zip Metar I might have more I want to do with this configuration file later, so I would like it to have something like this: [LOCATIONS] Phoenix:AZ:85001:KPHX Dallas:TX:75201:KDFW [USER CONFIGS] for later Setting up to write the file shouldn't be very hard, just create the file object to write to, write the [Locations] followed by the data that I plan on keeping together in lists and just join the lists with the colon. However, I'm a little stumped on how to read it back in. I know I can read the line in one at a time and check if line == '[LOCATIONS]' for example, and read the lines after until I come to a blank line, but what if there is an extra blank line. Or should I do a startswith('[') and just not add blank lines. Tried to do some googling online because this looks like it would be a fairly frequent problem for new programers, but I have come up empty (except some learning about the CVS module, which I don't think can help me here). A formal database using sqlite would be overkill. At most there will likely be 20-50 entries for each user, most would be less. Also in the program, each item of data (except state) entered in the GUI can result in all the others being updated with the correct values. Since almost every data item can act as a lead, I'm not sure how I should set this up for easy searching. Should I make a dictionary for City that would include a structure like {'Dallas':('TX', '75201', 'KDFW')} to help with lookup one for Metars {'KDFW': ('Dallas', 'TX', '75201')} and Zips {'75201': ('DALLAS', 'TX', 'KDFW')}? This seems a little better than iterating over each line to check for a match, but seems a bit of a waste considering the original structure will be a list like ['Dallas', 'TX', '75201', 'KDFW']. What would be nice as a dictionary-like object that could have each item in it act like a key returning the other values in the association. Various thoughts and ideas are appreciated. A: To store data, you may use XML. Then read it off using any XML parser, SAX or DOM which are included with python. Since the size of data is very less (only around 20-25 entries per user), you can take the approach of first knowing about the search term, whether its state name or whether its pin code etc. (Ask user to enter this in GUI). Assuming that data is stored as [City State Pin Mater], you can then search in the respective column. e.g if the user enters 12345, and you know it's a pin, you only need to search in the 3rd index of the list-data and then return the list. For state name you would search in the 2nd column. And this approach works even if the number of records is large, say a couple of hundreds. A: In case of syntax you've proposed there is a ConfigParser module thus you can parse the file easily, getting all the strings grouped by sections or whatever you want. But later it will lead to other troubles - just think about massive updates to the file. So I'd recommend to use sqlite too. It's a standard module and it's tiny, so no overhead or extra dependencies. A: You can use sqlite , or any other kind of databases like Mysql, etc.. to store you data. A: I would not recommend using an ini-formatted file like you've posted. I think you have two general options: * Use a database, such as sqlite as @ghostdog74 suggests * Use a flat file using a common, easily-parsable data structure For flat file, XML or JSON is probably the best bet. There are built-in parsers to both in most languages now. JSON is a bit more efficient, but XML is a bit more readable and structured. The downside to this of course is that you basically have to parse/read the entire file in order to do a lookup. The upside is it should be a trivial amount of code. You are talking about creating your own indexes, effectively, so you can easily lookup by ZIP or metar, etc. I'd suggest it's unnecessary. If you REALLY wanted to, you could use a hash-table in memory to store references to the objects, but unless you're reading the file once and then doing multiple lookups, the overhead of building the hashtables will likely be way more than just looping through to find what you need. I get the impression this is a web app where you read the file, do one or two lookups, and spit out a web page. If your data is at the point where the act of looping through all records is causing a noticeable performance impact, then you're into the territory where you should be using a real database, such as sqlite, mysql, postgresql, etc. Anything less, and you'll just be re-inventing what they've already done with indexing and file storage in a not-as-good way. A: As far as the data structure, I taught myself how to use xml.dom. It turns out, I really like it. I see now why programmers are using it more for config files, etc. I decided to develop my own class that acts sort of like a dictionary but can have multiple keys. Unlike a dictionary, it can have more then one key with the same value (but I designed the key() method will return only unique values). Here is the code: #! /usr/bin/python2.6 # -*- coding: utf-8 -*- '''makes a new dictionary-type class This class allows for multiple keys unlike the dictionary type. The keys are past first as a list or tuple. Then, the data is to be passed in a tuple or list of tuples or lists with the exact number of data items per list/tuple. Example: >>> from superdict import SuperDict >>> keynames = ['fname', 'lname', 'street', 'city', 'state', 'zip'] >>> names = [ ... ['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'], ... ['Rachel', 'West', '456 Bossom Rd', 'St Louis', 'MO', '62482'] ... ] >>> dictionary = SuperDict(keynames, names) There is a SuperDict.keys method that shows all the keys for a given keyname to be accessed as in: >>> print dictionary.keys('city') ['Topeka', 'St Louis'] The add method is used to pass a list/tuple but must have the same number of 'fields'. >>> dictionary.add(['John', 'Richards', '6 Tulip Ln', 'New Orleans', 'LA', '69231']) The extend method is used to pass a multiple lists/tuples inside a list/tuple as above. >>> new_names = [ ['Randy', 'Young', '54 Palm Tree Cr', 'Honolulu', 'HA', '98352'], ['Scott', 'People', '31932 5th Ave', 'New York', 'NY', '03152'] ] >>> dictonary.extend(new_names) The data attribute can be used to access the raw data as in: >>> dictionary.data [['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'], ['Rachel', 'West', '456 Bossom Rd', 'St Louis', 'MO', '62482'], ['Randy', 'Young', '54 Palm Tree Cr', 'Honolulu', 'HA', '98352'], ['Scott', 'People', '31932 5th Ave', 'New York', 'NY', '03152']] The data item is retrieved with the find method as below: >>> dictionary.find('city', 'Topeka') ['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'] What if there are more than one? Use the extended options of find to find a second field as in: >>> dictionary.find('city', 'Topeka', 'state', 'KS') ['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'] To find all the fields that match, use findall (second keyname is available for this just as in the find method): >>> dictionary.find('city', 'Topeka') [['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'], ['Ralph', 'Johnson', '513 Willow Way', 'Topeka', 'KS', '73189']] The delete method allows one to remove data, if needed: >>> dictionary.delete(new_names[0]) >>> dictionary.data [['Jim', 'Smith', '123 Cherry St', 'Topeka', 'KS', '73135'], ['Rachel', 'West', '456 Bossom Rd', 'St Louis', 'MO', '62482'], ['Scott', 'People', '31932 5th Ave', 'New York', 'NY', '03152']] maintainer: <signupnarnie@gmail.com> LICENSE: GPL version 2 Copywrite 2010 ''' __version__ = 0.4 indexnames = ['city','state','zip','metar'] datasample = [ ['Pawhuska', 'OK', '74056', 'KBVO'], ['Temple', 'TX', '76504', 'KTPL'] ] class SuperDict(object): ''' superdict = SuperDict(keynames, data) Keynames are a list/tuple of the entry names Data is a list/tuple of lists/tuples containing the data1 All should be of the same length See module doc string for more information ''' def __init__(self, indexnames, data=None): self.keydict = dict() if data: self.data = data for index, name in enumerate(indexnames): self.keydict[name.lower()] = index def keys(self, index, sort=False): ''' SuperDict.keys(keyname, sort=False) Returns all the "keys" for the keyname(field name) but duplicates are removed. If sort=True, then the keys are sorted ''' index = index.lower() keynames = [] for item in self.data: key = item[self.keydict[index]] if key: keynames.append(key) keynames = list(set(keynames)) if sort: keynames = sorted(keynames) return keynames def add(self, data): ''' SuperDict.add(list/tuple) adds another another entry into the dataset ''' if self.data: if not len(data) == len(self.data[0]): print 'data length mismatch' return self.data.append(data) def extend(self, data): ''' SuperDict([list1, list2]) SuperDict((tuple1, tuple2)) Extends the dataset by more than one field at a time ''' for datum in data: self.add(datum) def delete(self, data): ''' SuperDict.delete(list/tuple) Deletes an entry matching the list or tuple passed to the method ''' # question for later: should I return true or false if something delete or not for index, item in enumerate(self.data): if data == item: del self.data[index] def find(self, keyname1, data1, keyname2=None, data2=None): ''' SuperDict(keyname1, data1, keyname2=None, data2=None) Look for the first entry based on the value of a keyname(s). ''' keyname1 = keyname1.lower() if keyname2: keyname2 = keyname2.lower() for item in self.data: if data1 == item[self.keydict[keyname1]]: if not data2: return item elif data2 == item[self.keydict[keyname2]]: return item def findall(self, keyname1, data1, keyname2=None, data2=None): ''' SuperDict.findall(keyname1, data1, keyname2=None, data2=None) ''' keyname1 = keyname1.lower() if keyname2: keyname2 = keyname2.lower() items = [] for item in self.data1: if data1 == item[self.keydict[keyname1]]: if not data2: items.append(item) elif data2 == item[self.keydict[keyname2]]: items.append(item) return items
How to develop and then parse a data structure
I'm designing a weather program where I need to keep track of certain things and allow the user to add data which will be saved and subsequently read later. My fields are City State Zip Metar I might have more I want to do with this configuration file later, so I would like it to have something like this: [LOCATIONS] Phoenix:AZ:85001:KPHX Dallas:TX:75201:KDFW [USER CONFIGS] for later Setting up to write the file shouldn't be very hard, just create the file object to write to, write the [Locations] followed by the data that I plan on keeping together in lists and just join the lists with the colon. However, I'm a little stumped on how to read it back in. I know I can read the line in one at a time and check if line == '[LOCATIONS]' for example, and read the lines after until I come to a blank line, but what if there is an extra blank line. Or should I do a startswith('[') and just not add blank lines. Tried to do some googling online because this looks like it would be a fairly frequent problem for new programers, but I have come up empty (except some learning about the CVS module, which I don't think can help me here). A formal database using sqlite would be overkill. At most there will likely be 20-50 entries for each user, most would be less. Also in the program, each item of data (except state) entered in the GUI can result in all the others being updated with the correct values. Since almost every data item can act as a lead, I'm not sure how I should set this up for easy searching. Should I make a dictionary for City that would include a structure like {'Dallas':('TX', '75201', 'KDFW')} to help with lookup one for Metars {'KDFW': ('Dallas', 'TX', '75201')} and Zips {'75201': ('DALLAS', 'TX', 'KDFW')}? This seems a little better than iterating over each line to check for a match, but seems a bit of a waste considering the original structure will be a list like ['Dallas', 'TX', '75201', 'KDFW']. What would be nice as a dictionary-like object that could have each item in it act like a key returning the other values in the association. Various thoughts and ideas are appreciated.
[ "To store data, you may use XML. Then read it off using any XML parser, SAX or DOM which are included with python. \nSince the size of data is very less (only around 20-25 entries per user), you can take the approach of first knowing about the search term, whether its state name or whether its pin code etc. (Ask us...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "data_structures", "file_io", "parsing", "python" ]
stackoverflow_0003920681_data_structures_file_io_parsing_python.txt
Q: Python - removing items from lists # I have 3 lists: L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] # I want to create another that is L1 minus L2's memebers and L3's memebers, so: L4 = (L1 - L2) - L3 # Of course this isn't going to work I'm wondering, what is the "correct" way to do this. I can do it many different ways, but Python's style guide says there should be only 1 correct way of doing each thing. I've never known what this was. A: Here are some tries: L4 = [ n for n in L1 if (n not in L2) and (n not in L3) ] # parens for clarity tmpset = set( L2 + L3 ) L4 = [ n for n in L1 if n not in tmpset ] Now that I have had a moment to think, I realize that the L2 + L3 thing creates a temporary list that immediately gets thrown away. So an even better way is: tmpset = set(L2) tmpset.update(L3) L4 = [ n for n in L1 if n not in tmpset ] Update: I see some extravagant claims being thrown around about performance, and I want to assert that my solution was already as fast as possible. Creating intermediate results, whether they be intermediate lists or intermediate iterators that then have to be called into repeatedly, will be slower, always, than simply giving L2 and L3 for the set to iterate over directly like I have done here. $ python -m timeit \ -s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2)' \ 'ts = set(L2); ts.update(L3); L4 = [ n for n in L1 if n not in ts ]' 10000 loops, best of 3: 39.7 usec per loop All other alternatives (that I can think of) will necessarily be slower than this. Doing the loops ourselves, for example, rather than letting the set() constructor do them, adds expense: $ python -m timeit \ -s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2)' \ 'unwanted = frozenset(item for lst in (L2, L3) for item in lst); L4 = [ n for n in L1 if n not in unwanted ]' 10000 loops, best of 3: 46.4 usec per loop Using iterators, will all of the state-saving and callbacks they involve, will obviously be even more expensive: $ python -m timeit \ -s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2);from itertools import ifilterfalse, chain' \ 'L4 = list(ifilterfalse(frozenset(chain(L2, L3)).__contains__, L1))' 10000 loops, best of 3: 47.1 usec per loop So I believe that the answer I gave last night is still far and away (for values of "far and away" greater than around 5µsec, obviously) the best, unless the questioner will have duplicates in L1 and wants them removed once each for every time the duplicate appears in one of the other lists. A: update::: post contains a reference to false allegations of inferior performance of sets compared to frozensets. I maintain that it's still sensible to use a frozenset in this instance, even though there's no need to hash the set itself, just because it's more correct semantically. Though, in practice, I might not bother typing the extra 6 characters. I'm not feeling motivated to go through and edit the post, so just be advised that the "allegations" link links to some incorrectly run tests. The gory details are hashed out in the comments. :::update The second chunk of code posted by Brandon Craig Rhodes is quite good, but as he didn't respond to my suggestion about using a frozenset (well, not when I started writing this, anyway), I'm going to go ahead and post it myself. The whole basis of the undertaking at hand is to check if each of a series of values (L1) are in another set of values; that set of values is the contents of L2 and L3. The use of the word "set" in that sentence is telling: even though L2 and L3 are lists, we don't really care about their list-like properties, like the order that their values are in or how many of each they contain. We just care about the set (there it is again) of values they collectively contain. If that set of values is stored as a list, you have to go through the list elements one by one, checking each one. It's relatively time-consuming, and it's bad semantics: again, it's a "set" of values, not a list. So Python has these neat set types that hold a bunch of unique values, and can quickly tell you if some value is in them or not. This works in pretty much the same way that python's dict types work when you're looking up a key. The difference between sets and frozensets is that sets are mutable, meaning that they can be modified after creation. Documentation on both types is here. Since the set we need to create, the union of the values stored in L2 and L3, is not going to be modified once created, it's semantically appropriate to use an immutable data type. This also allegedly has some performance benefits. Well, it makes sense that it would have some advantage; otherwise, why would Python have frozenset as a builtin? update... Brandon has answered this question: the real advantage of frozen sets is that their immutability makes it possible for them to be hashable, allowing them to be dictionary keys or members of other sets. I ran some informal timing tests comparing the speed for creation of and lookup on relatively large (3000-element) frozen and mutable sets; there wasn't much difference. This conflicts with the above link, but supports what Brandon says about them being identical but for the aspect of mutability. ...update Now, because frozensets are immutable, they don't have an update method. Brandon used the set.update method to avoid creating and then discarding a temporary list en route to set creation; I'm going to take a different approach. items = (item for lst in (L2, L3) for item in lst) This generator expression makes items an iterator over, consecutively, the contents of L2 and L3. Not only that, but it does it without creating a whole list-full of intermediate objects. Using nested for expressions in generators is a bit confusing, but I manage to keep it sorted out by remembering that they nest in the same order that they would if you wrote actual for loops, e.g. def get_items(lists): for lst in lists: for item in lst: yield item That generator function is equivalent to the generator expression that we assigned to items. Well, except that it's a parametrized function definition instead of a direct assignment to a variable. Anyway, enough digression. The big deal with generators is that they don't actually do anything. Well, at least not right away: they just set up work to be done later, when the generator expression is iterated. This is formally referred to as being lazy. We're going to do that (well, I am, anyway) by passing items to the frozenset function, which iterates over it and returns a frosty cold frozenset. unwanted = frozenset(items) You could actually combine the last two lines, by putting the generator expression right inside the call to frozenset: unwanted = frozenset(item for lst in (L2, L3) for item in lst) This neat syntactical trick works as long as the iterator created by the generator expression is the only parameter to the function you're calling. Otherwise you have to write it in its usual separate set of parentheses, just like you were passing a tuple as an argument to the function. Now we can build a new list in the same way that Brandon did, with a list comprehension. These use the same syntax as generator expressions, and do basically the same thing, except that they are eager instead of lazy (again, these are actual technical terms), so they get right to work iterating over the items and creating a list from them. L4 = [item for item in L1 if item not in unwanted] This is equivalent to passing a generator expression to list, e.g. L4 = list(item for item in L1 if item not in unwanted) but more idiomatic. So this will create the list L4, containing the elements of L1 which weren't in either L2 or L3, maintaining the order that they were originally in and the number of them that there were. If you just want to know which values are in L1 but not in L2 or L3, it's much easier: you just create that set: L1_unique_values = set(L1) - unwanted You can make a list out of it, as does st0le, but that might not really be what you want. If you really do want the set of values that are only found in L1, you might have a very good reason to keep that set as a set, or indeed a frozenset: L1_unique_values = frozenset(L1) - unwanted ...Annnnd, now for something completely different: from itertools import ifilterfalse, chain L4 = list(ifilterfalse(frozenset(chain(L2, L3)).__contains__, L1)) A: Assuming your individual lists won't contain duplicates....Use Set and Difference L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] print(list(set(L1) - set(L2) - set(L3))) A: Doing such operations in Lists can hamper your program's performance very soon. What happens is with each remove, List operations do a fresh malloc & move elements around. This can be expensive if you have a very huge list or otherwise. So I would suggest this - I am assuming your list has unique elements. Otherwise you need to maintain a list in your dict having duplicate values. Anyway for the data your provided, here it is- METHOD 1 d = dict() for x in L1: d[x] = True # Check if L2 data is in 'd' for x in L2: if x in d: d[x] = False for x in L3: if x in d: d[x] = False # Finally retrieve all keys with value as True. final_list = [x for x in d if d[x]] METHOD 2 If all that looks like too much code. Then you could try using set. But this way your list will loose all duplicate elements. final_set = set.difference(set(L1),set(L2),set(L3)) final_list = list(final_set) A: This may be less pythonesque than the list-comprehension answer, but has a simpler look to it: l1 = [ ... ] l2 = [ ... ] diff = list(l1) # this copies the list for element in l2: diff.remove(element) The advantage here is that we preserve order of the list, and if there are duplicate elements, we remove only one for each time it appears in l2. A: I think intuited's answer is way too long for such a simple problem, and Python already has a builtin function to chain two lists as a generator. The procedure is as follows: Use itertools.chain to chain L2 and L3 without creating a memory-consuming copy Create a set from that (in this case, a frozenset will do because we don't change it after creation) Use list comprehension to filter out elements that are in L1 and also in L2 or L3. As set/frozenset lookup (x in someset) is O(1), this will be very fast. And now the code: L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] from itertools import chain tmp = frozenset(chain(L2, L3)) L4 = [x for x in L1 if x not in tmp] # [1, 3, 6] This should be one of the fastest, simplest and least memory-consuming solution.
Python - removing items from lists
# I have 3 lists: L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] L2 = [4, 7, 8] L3 = [5, 2, 9] # I want to create another that is L1 minus L2's memebers and L3's memebers, so: L4 = (L1 - L2) - L3 # Of course this isn't going to work I'm wondering, what is the "correct" way to do this. I can do it many different ways, but Python's style guide says there should be only 1 correct way of doing each thing. I've never known what this was.
[ "Here are some tries:\nL4 = [ n for n in L1 if (n not in L2) and (n not in L3) ] # parens for clarity\n\ntmpset = set( L2 + L3 )\nL4 = [ n for n in L1 if n not in tmpset ]\n\nNow that I have had a moment to think, I realize that the L2 + L3 thing creates a temporary list that immediately gets thrown away. So an e...
[ 10, 6, 0, 0, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003947654_list_comprehension_python.txt
Q: How to parse e.g. 2010-04-24T07:47:00.007+02:00 with Python strptime Does anyone know how to parse the format as described in the title using Pythons strptime method? I have something similar to this: import datetime date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z') I can't seem to figure out what kind of timeformat this is. By the way, I'm a newbie at the Python language (I'm used to C#). UPDATE This is how I changed the code based on the advise (answers) below: from dateutil.parser import * from datetime import * date = parse(entry.published.text) A: That date is in ISO 8601, or more specifically RFC 3339, format. Such dates can't be parsed with strptime. There's a Python issue that discusses this. dateutil.parser.parse can handle a wide variety of dates, including the one in your example. If you're using an external module for XML or RSS parsing, there is probably a routine in there to parse that date. A: Here's a good way to find the answer: using strftime, construct a format string that will emit what you see. That string will, by definition, be the string needed to PARSE the time with strptime. A: If you are trying to parse RSS or Atom feeds then use Universal Feed Parser. It supports many date/time formats. >>> import feedparser # parse feed >>> d = feedparser.parse("http://stackoverflow.com/feeds/question/3946689") >>> t = d.entries[0].published_parsed # get date of the first entry as a time tuple >>> import datetime >>> datetime.datetime(*t[:6]) # convert time tuple to datetime object datetime.datetime(2010, 10, 15, 22, 46, 56)
How to parse e.g. 2010-04-24T07:47:00.007+02:00 with Python strptime
Does anyone know how to parse the format as described in the title using Pythons strptime method? I have something similar to this: import datetime date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z') I can't seem to figure out what kind of timeformat this is. By the way, I'm a newbie at the Python language (I'm used to C#). UPDATE This is how I changed the code based on the advise (answers) below: from dateutil.parser import * from datetime import * date = parse(entry.published.text)
[ "That date is in ISO 8601, or more specifically RFC 3339, format.\nSuch dates can't be parsed with strptime. There's a Python issue that discusses this.\ndateutil.parser.parse can handle a wide variety of dates, including the one in your example.\nIf you're using an external module for XML or RSS parsing, there is...
[ 5, 0, 0 ]
[ "That's the standard XML datetime format, ISO 8601. If you're already using an XML library, most of them have datetime parsers built in. xml.utils.iso8601 works reasonably well.\nimport xml.utils.iso8601\ndate = xml.utils.iso8601.parse(entry.published.text)\n\nYou can look at a bunch of other ways to deal with that...
[ -1 ]
[ "date", "python", "rfc3339", "strptime" ]
stackoverflow_0003946689_date_python_rfc3339_strptime.txt
Q: how to find out whether website is using cookies or http based authentication I am trying to automate files download via a webserver. I plan on using wget or curl or python urllib / urllib2. Most solutions use wget and urllib and urllib2. They all talk of HHTP based authentication and cookie based authentication. My problem is I dont know which one is used in the website that stores my data. Here is the interaction with the site: Normally I login to site http://www.anysite.com/index.cgi? I get a form with a login and password. I type in both and hit return. The url stays as http://www.anysite.com/index.cgi? during the entire interaction. But now I have a list of folders and files If I click on a folder or file the URL changes to http://shamrockstructures.com/cgi-bin/index.cgi?page=download&file=%2Fhome%2Fjanysite%2Fpublic_html%2Fuser_data%2Fuserareas%2Ffile.tar.bz2 And the browser offers me a chance to save the file I want to know how to figure out whether the site is using HTTP or cookie based authentication. After which I am assuming I can use cookielib or urllib2 in python to connect to it, get the list of files and folders and recursively download everything while staying connected. p.S: I have tried the cookie cutter ways to connect via wget and wget --http-user "uname" --http-password "passwd" http://www.anysite.com/index.cgi? , but they only return the web form back to me. A: If you log in using a Web page, the site is probably using cookie-based authentication. (It could technically use HTTP basic auth, by embedding your credentials in the URI, but this would be a dumb thing to do in most cases.) If you get a separate, smallish dialog with a user name and password field (like this one), it is using HTTP basic authentication. If you try to log in using HTTP basic auth, and get back the login page, as is happening to you, this is a certain indication that the site is not using HTTP basic auth. Most sites use cookie-based authentication these days. To do this with an HTTP cilent such as urllib2, you will need to do an HTTP POST of the fields in the login form. (You may need to actually request the login form first, as a site could include a cookie that you need to even log in, but usually this is not necessary.) This should return a "successfully logged in" page that you can test for. Save the cookies you get back from this request. When making the next request, include these cookies. Each request you make may respond with cookies, and you need to save those and send them again with the next request. urllib2 has a function called a "cookie jar" which will automatically handle the cookies for you as you send requests and receive Web pages. That's what you want. A: You can use pycurl like this: import pycurl COOKIE_JAR = 'cookiejar' # file to store the cookies LOGIN_URL = 'http://www.yoursite.com/login.cgi' USER_FIELD = 'user' # Name of the element in the HTML form USER = 'joe' PASSWD_FIELD = 'passwd' # Name of the element in the HTML form PASSWD = 'MySecretPassword' def read(html): """Read the body of the response, with posible future html parsing and re-requesting""" print html com = pycurl.Curl() com.setopt(pycurl.WRITEFUNCTION, read) com.setopt(pycurl.COOKIEJAR, COOKIE_JAR) com.setopt(pycurl.FOLLOWLOCATION, 1) # follow redirects com.setopt(pycurl.POST, 1) com.setopt(pycurl.POSTFIELDS, '%s=%s;%s=%s'%(USER_FIELD, USER, PASSWD_FIELD, PASSWD)) com.setopt(pycurl.URL, LOGIN_URL ) com.perform() Plain pycurl it may seam very "primitive" (with the limited setopt approach), but it gets the job done, and handle pretty well the cookies with the cookie jar option. A: AFAIK cookie based authentication is only used once you have logged in successfully atleast ONCE. You can try disabling storing cookies from that domain by changing your browser settings, if you are still able to download files that it should be a HTTP based authentication. Try doing a equivalent GET request for the (possibly POST) login request that is probably happening right now for login. Use firebug or fiddler to see the login request that is sent. Also note if there is some javascript code which is returning you a different output, based on your useragent string or some other parameter. See if httplib, mechanize helps.
how to find out whether website is using cookies or http based authentication
I am trying to automate files download via a webserver. I plan on using wget or curl or python urllib / urllib2. Most solutions use wget and urllib and urllib2. They all talk of HHTP based authentication and cookie based authentication. My problem is I dont know which one is used in the website that stores my data. Here is the interaction with the site: Normally I login to site http://www.anysite.com/index.cgi? I get a form with a login and password. I type in both and hit return. The url stays as http://www.anysite.com/index.cgi? during the entire interaction. But now I have a list of folders and files If I click on a folder or file the URL changes to http://shamrockstructures.com/cgi-bin/index.cgi?page=download&file=%2Fhome%2Fjanysite%2Fpublic_html%2Fuser_data%2Fuserareas%2Ffile.tar.bz2 And the browser offers me a chance to save the file I want to know how to figure out whether the site is using HTTP or cookie based authentication. After which I am assuming I can use cookielib or urllib2 in python to connect to it, get the list of files and folders and recursively download everything while staying connected. p.S: I have tried the cookie cutter ways to connect via wget and wget --http-user "uname" --http-password "passwd" http://www.anysite.com/index.cgi? , but they only return the web form back to me.
[ "If you log in using a Web page, the site is probably using cookie-based authentication. (It could technically use HTTP basic auth, by embedding your credentials in the URI, but this would be a dumb thing to do in most cases.) If you get a separate, smallish dialog with a user name and password field (like this one...
[ 2, 1, 0 ]
[]
[]
[ "cgi", "python", "session_cookies", "urllib2", "wget" ]
stackoverflow_0003944624_cgi_python_session_cookies_urllib2_wget.txt
Q: Get the coords and height/width of a svg group into python Hi I want to load the groups of a svg-file into several gtk pixbuffs/subpixbufs therefore I need the coordinates and width and height of them I'm currently just using rsvg and gtk is it possible to get those information with that modules ? Or do I need another module to read out that data from the svg-file? thanks alot A: I found out to simply use RSVG::Handle::get_dimensions_sub(id)
Get the coords and height/width of a svg group into python
Hi I want to load the groups of a svg-file into several gtk pixbuffs/subpixbufs therefore I need the coordinates and width and height of them I'm currently just using rsvg and gtk is it possible to get those information with that modules ? Or do I need another module to read out that data from the svg-file? thanks alot
[ "I found out to simply use RSVG::Handle::get_dimensions_sub(id)\n" ]
[ 1 ]
[]
[]
[ "gtk", "python", "rsvg", "svg" ]
stackoverflow_0003268600_gtk_python_rsvg_svg.txt
Q: What is the correct way to form MySQL queries in python? I am new to python, I come here from the land of PHP. I constructed a SQL query like this in python based on my PHP knowledge and I get warnings and errors cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid)) # rowcount here is int What is the right way to form queries? Also, how do I escape strings to form SQL safe ones? like if I want to escape -, ', " etc, I used to use addslashes. How do we do it in python? Thanks A: First of all, it's high time to learn to pass variables to the queries safely, using the method Matus expressed. Clearer, tuple = (foovar, barvar) cursor.execute("QUERY WHERE foo = ? AND bar = ?", tuple) If you only need to pass one variable, you must still make it a tuple: insert comma at the end to tell Python to treat it as a one-tuple: tuple = (onevar,) Your example would be of form: cursor_.execute("update posts set comment_count = comment_count + ? where id = ?", (cursor_.rowcount, postid)) You can also use named parameters like this: cursor_.execute("update posts set comment_count = comment_count + :count where id = :id", {"count": cursor_.rowcount, "id": postid}) This time the parameters aren't a tuple, but a dictionary that is formed in pairs of "key": value. A: from python manual: t = (symbol,) c.execute( 'select * from stocks where symbol=?', t ) this way you prevent SQL injection ( suppose this is the SQL safe you refer to ) and also have formatting solved
What is the correct way to form MySQL queries in python?
I am new to python, I come here from the land of PHP. I constructed a SQL query like this in python based on my PHP knowledge and I get warnings and errors cursor_.execute("update posts set comment_count = comment_count + "+str(cursor_.rowcount)+" where ID = " + str(postid)) # rowcount here is int What is the right way to form queries? Also, how do I escape strings to form SQL safe ones? like if I want to escape -, ', " etc, I used to use addslashes. How do we do it in python? Thanks
[ "First of all, it's high time to learn to pass variables to the queries safely, using the method Matus expressed. Clearer,\ntuple = (foovar, barvar)\ncursor.execute(\"QUERY WHERE foo = ? AND bar = ?\", tuple)\n\nIf you only need to pass one variable, you must still make it a tuple: insert comma at the end to tell P...
[ 3, 2 ]
[]
[]
[ "mysql", "python", "sql" ]
stackoverflow_0003948309_mysql_python_sql.txt
Q: Pythonic equivalent of ./foo.py < bar.png I've got a Python program that reads from sys.stdin, so I can call it with ./foo.py < bar.png. How do I test this code from within another Python module? That is, how do I set stdin to point to the contents of a file while running the test script? I don't want to do something like ./test.py < test.png. I don't think I can use fileinput, because the input is binary, and I only want to handle a single file. The file is opened using Image.open(sys.stdin) from PIL. A: You should generalise your script so that it can be invoked from the test script, in addition to being used as a standalone program. Here's an example script that does this: #! /usr/bin/python import sys def read_input_from(file): print file.read(), if __name__ == "__main__": if len(sys.argv) > 1: # filename supplied, so read input from that filename = sys.argv[1] file = open(filename) else: # no filename supplied, so read from stdin file = sys.stdin read_input_from(file) If this is called with a filename, the contents of that file will be displayed. Otherwise, input read from stdin will be displayed. (Being able to pass a filename on the command line might be a useful improvement for your foo.py script.) In the test script you can now invoke the function in foo.py with a file, for example: #! /usr/bin/python import foo file = open("testfile", "rb") foo.read_input_from(file) A: Your function or class should accept a stream instead of choosing which stream to use. Your main function will choose sys.stdin. Your test method will probably choose a StringIO instance or a test file. The program: # foo.py import sys from PIL import Image def foo(stream): im = Image.open(stream) # ... def main(): foo(sys.stdin) if __name__ == "__main__": main() The test: # test.py import StringIO, unittest import foo class FooTest(unittest.TestCase): def test_foo(self): input_data = "...." input_stream = StringIO.StringIO(input_data) # can use a test file instead: # input_stream = open("test_file", "rb") result = foo.foo(input_stream) # asserts on result if __name__ == "__main__": unittest.main() A: A comp.lang.python post showed the way: Substitute a StringIO() object for sys.stdout, and then get the output with getvalue(): def setUp(self): """Set stdin and stdout.""" self.stdin_backup = sys.stdin self.stdout_backup = sys.stdout self.output_stream = StringIO() sys.stdout = self.output_stream self.output_file = None def test_standard_file(self): sys.stdin = open(EXAMPLE_PATH) foo.main() self.assertNotEqual( self.output_stream.getvalue(), '') def tearDown(self): """Restore stdin and stdout.""" sys.stdin = self.stdin_backup sys.stdout = self.stdout_backup A: You can always monkey patch Your stdin. But it is quite ugly way. So better is to generalize Your script as Richard suggested. import sys import StringIO mockin = StringIO.StringIO() mockin.write("foo") mockin.flush() mockin.seek(0) setattr(sys, 'stdin', mockin) def read_stdin(): f = sys.stdin result = f.read() f.close() return result print read_stdin() Also, do not forget to restore stdin when tearing down your test.
Pythonic equivalent of ./foo.py < bar.png
I've got a Python program that reads from sys.stdin, so I can call it with ./foo.py < bar.png. How do I test this code from within another Python module? That is, how do I set stdin to point to the contents of a file while running the test script? I don't want to do something like ./test.py < test.png. I don't think I can use fileinput, because the input is binary, and I only want to handle a single file. The file is opened using Image.open(sys.stdin) from PIL.
[ "You should generalise your script so that it can be invoked from the test script, in addition to being used as a standalone program. Here's an example script that does this:\n#! /usr/bin/python\n\nimport sys\n\ndef read_input_from(file):\n print file.read(),\n\nif __name__ == \"__main__\":\n if len(sys.argv)...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003948247_python_unit_testing.txt
Q: Python. Transform str('+') to mathematical operation How transform str('+') to mathematical operation? For example: a = [0,1,2] # or a = ['0','1','2'] b = ['+','-','*'] c = int(a[0]+b[0]+a[1]) In other words, how transform str('-1*2') to int(), without for i in c: if i == '+': ... Thanks. A: You can also use the operator module: import operator as op #Create a mapping between the string and the operator: ops = {'+': op.add, '-': op.sub, '*': op.mul} a = [0,1,2] b = ['+','-','*'] #use the mapping c = ops[b[0]](a[0], a[1]) A: i thin you're looking for eval(), but i advice to use something else... however, >>> eval('-1*2') -2 eval 'executes' the string you pass to it, like code. so it's quite dangerous for security, especially if the parameters are user input... in this case i suggest to use parsing library, such as ply http://www.dabeaz.com/ply/ that for such thing is really simple to use and very effective :) A: If your math expressions will fit Python syntax but you are skeered of eval (you should be) you can look into python's ast module (docs). It will parse the expression into an abstract syntax tree you can iterate over. You can evaluate a limited subset of Python and throw errors if you encounter anything outside your expression grammar. A: Use eval like everyone else is saying but filter it first. >>> s = '1 + 12 / 2 - 12*31' >>> allowed = set(' 1234567890()+-/*\\') >>> if allowed.issuperset(s): ... eval(s) ... -365 A: You can read about http://en.wikipedia.org/wiki/Reverse_Polish_notation A: Use eval: > eval(str('-1*2')) > -2 A: Dett, A Simple eval on the whole string... However be aware that if the user inputs the string, eval is risky, unless you do some parsing first x = '-1*2' y = eval(x) y will then be the integer value.
Python. Transform str('+') to mathematical operation
How transform str('+') to mathematical operation? For example: a = [0,1,2] # or a = ['0','1','2'] b = ['+','-','*'] c = int(a[0]+b[0]+a[1]) In other words, how transform str('-1*2') to int(), without for i in c: if i == '+': ... Thanks.
[ "You can also use the operator module:\nimport operator as op\n#Create a mapping between the string and the operator:\nops = {'+': op.add, '-': op.sub, '*': op.mul}\n\na = [0,1,2]\nb = ['+','-','*']\n\n#use the mapping\nc = ops[b[0]](a[0], a[1])\n\n", "i thin you're looking for eval(), but i advice to use somethi...
[ 4, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0003948244_eval_python.txt
Q: Python unittests almost never check types I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites. Java being statically-typed and Python being dynamically-typed, should'nt the reverse be the case? A: In dynamically-typed languages, developers often follow the duck typing principle -- "if it looks like a duck and walks like a duck, it is a duck". As long as the object does what all the tests require, does it really matter what kind of object it is? Duck typing says no. A: Python unit tests do check types. All the time. In fact, that's the only thing they are doing. Python is duck-typed. Duck typing means that the type of an object is defined by its behavior. Unit tests test behavior. Ergo, they test types. A: in addition to seconding what everyone is saying about duck typing here, I'd also like to point you in the direction of the types module: http://docs.python.org/library/types.html ... whose collection of types correspond to many builtins and other commonly used types, so that you may easily explicitly assert for whatever type you want, in your unit tests.
Python unittests almost never check types
I was going through a few tests written in Java using JUnit and I could'nt help noticing the emphasis which is laid on checking the "type" of objects. This is something I have never seen in Python test-suites. Java being statically-typed and Python being dynamically-typed, should'nt the reverse be the case?
[ "In dynamically-typed languages, developers often follow the duck typing principle -- \"if it looks like a duck and walks like a duck, it is a duck\". As long as the object does what all the tests require, does it really matter what kind of object it is? Duck typing says no.\n", "Python unit tests do check type...
[ 15, 5, 0 ]
[]
[]
[ "java", "python", "unit_testing" ]
stackoverflow_0003943808_java_python_unit_testing.txt
Q: How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...? Is there a standard body or a specific normative way how time-related things should be implemented in practice (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete implementation which could serve as a example for how time-related things should be handled? Which existing library would you consider as a bad, a decent or a good example? A: I'll try to give an answer to the second and third question using the Java library which might become part of Java 7. javax.time.* (JSR 310) These classes are a complete rewrite of JodaTime trying to fix the design flaws of util.Date/util.Time as well as JodaTime. JSR 310 tries to provide a comprehensive model for date and time, which is type-safe and self-documenting. It is interoperable with existing classes, but also considers XML- and DBMS-based use-cases. The classes are final, immutable, thread-safe and cannot be modified after construction. Instances are created via a rich set of Factory methods which can cache things in the background. LocalDate dateToday = LocalDate.of(2010, 9, 14); LocalDate oneMonthLater = dateToday.with(OCTOBER); LocalDate oneYearLater = dateToday.withYear(2011); The API has some "machine-oriented" classes and some "human-oriented" classes: Machine-oriented Instant For a point of time comparable to an Unix or Java timestamp. Actually there are Instant, TAIInstant and UTCInstant which enable people to exactly choose which definition of time they need i. e. "day-based", "linear, without leap seconds" etc. Duration A time range not necessarily associated with a specific Date or Calendar. Human-oriented There is a rich collection of classes handling different use-cases like Date-only, Time-only, Time and Date, with and without Timezones, with and without DST. DateProvider OffsetDate, LocalDate (, java.sql.Date compatibility) TimeProvider OffsetTime, LocalTime (, java.sql.Time compatibility) DateTimeProvider ZonedDateTime, OffsetDateTime, LocalDateTime (, java.util.GregorianCalendar compatibility) InstantProvider Instant, ZonedDateTime, OffsetDateTime (, java.util.Date compatibility) Period Periods represent a time span like "5 days" that can be added and subtracted from a date/time. Matcher Matchers enable queries like "is this date in the year 2006?" or "is this day the last day of this year". Adjuster Adjusters come to the rescue if you have want to make more complex changes, like "Give me the last day of the month!" or "The second Tuesday after Christmas, please!". Resolver Resolvers allow users to define what should happen if a certain date is not valid, like February 31st 2010: DateResolver previous = DateResolvers.previousValid(); LocalDate date = date(2010, 2, 30, previous); // date = 2010-02-28 Working with Timezone and DST data It is possible to serialize these classes and deserialize them using either the current timezone data or the timezone data when they were serialized. Additionally, rules from different timezones can be compared: It is possible to find out if DST rules have changed, e. g. between version 2010e and 2010f for Dates in London or Moscow and decide what should be done if a Time is in a gap or overlap. Calendar systems Although everything is based on ISO-8601, simple calendars for Hebrew, Hijrah, Japanese, ThaiBuddist, etc. time systems are provided. Formatting and Parsing toString() returns ISO8601 and patterns like those in SimpleDateFormat and more advanced are supported. Integration Databases JodaTime Legacy JDK classes (java.util.*) XML References: https://jsr-310.dev.java.net/nonav/doc-2010-06-22/index.html JavaZone 2010 - Stephen Colebourne: Time to fix it! - JSR-310 Date and Time API A: I don't think there's a single standard to such things at the moment, however there are multiple standards which such things may conform to: ISO 8601 for example. ICU's own date/time handling is a cross-language (C/C++ and Java) and multi-platform library. It handles dates and times internally, typically, using for a single time a UDate (C/C++) or a java.util.Date/long (Java), as number of milliseconds since 1-1-1970, or a Calendar object which is specific to the type of calendar (Gregorian vs Hijri, etc). Durations are available for formatting. Leap years are calculated as part of calendar systems, and leap seconds are assumed to be handled by the underlying operating system. DST/Timezone data is kept up to date with 'the tz database' sometimes referred to by its author's surname, Olson. Hope this has answered your question some as regards ICU. A: There are time(s) and there are dates (calendars) The first problem is that dates are not linked to time but to astronomical position of Earh, Moon, etc. + regularity/periodicity of human activity. The time is also subjective and relative or even relativistic and measured either astronomically or or atomically. The time bodies and the date/calendar bodies The International Standartization Organization (ISO) [4] has issued "ISO 8601 Data elements and interchange formats — Information interchange — Representation of dates and times" [4a] which, like other international standards, is recommendation and is based on already established practices. It is (subjectively) based only on Gregorian Calendar [5] and on proleptic one (projected backwards to well before it was actually invented so is of limited use in dealing with historic dates) [5a]. The World Calendar Association [1d] initiated the introduction of new World Calendar since 2012 [1b-1d] which would make useless already existing date libraries. Again, the same main problem, see on it further on. The most covering, I ever saw, date-time-related comparison in IT systems is [2] between BIG8 DBMS (IBM DB2, Informix, Ingres, InterBase, Microsoft SQL Server, MySQL, Oracle, and Sybase). This and all other surveys show that the processing of the same, for ex., Gregorian calendar time/dates are different between all systems as well as inside the same platforms (between different products and versions of the same product), see for ex., [3]. THE MAIN PROBLEM with all date/time libraries in all-all systems, frameworks is that their date/time datatypes do not permit to include geographical and calendar information in date/time datatypes. Without which they are mainly half- useless - what is the sense of milliseconds in SQL Server datetime2 values in 7th century? At that time there was even no clocks measuring time with accuracy of minutes (Galileo Galilei used, for ex., his heart beats to measure intervals of time in his experiments) as well as Gregorian Calendar was not even invented. So, plenty of datetime type space is misused failing to give the most important flexibility of working with dates by linking and including with them to geography and/or calendar info. Just fast illustrations: Modern Russia uses Gregorian calendar and the Russian Orthodox Church uses Julian calendar by which many state holidays in Russia are determined (for example, Christmas in Russia is on 7th of January and Old New Year is on 14th of January by Gregorian Calendar while the dates of other religious holidays are floating relatively to Gregorian Calendar). In pre-1917 Russia, Poland as its part, used Gregorian Calendar while all the rest Russia used Julian Calendar (with floating difference of 13-18 days at the "same" time zone) [5b]; Double-click on clock in MS Windows (or open Control Panel --> Date and Time) --> Time Zone tab --> view time zones in combobox. You will see that there are 25 hours from GMT-12:00 to GMT+13:00 over a hundred of time zones with fractions of hour like GMT+5:00, GMT+5:30, GMT+5:45, etc. ==== Cited: [1] New World Calendar [1a]Update: Sorry, do not read [1a], author confused calendars and wrote wrong info in this news brief World Calendar 2012: 35 days in a month http://www.panorama.am/en/society/2010/01/29/newcalendar [1b] http://en.wikipedia.org/wiki/World_Calendar [1c] http://www.theworldcalendarin2012.org/Index2.htm [1d] http://www.theworldcalendar.org/TWCA.htm [2] Peter Gulutzan,Trudy Pelzer. SQL Performance Tuning: Dates in SQL http://www.informit.com/articles/printerfriendly.aspx?p=30939 [3] SqlDateTime.MinValue != C# DateTime.MinValue, why? SqlDateTime.MinValue != DateTime.MinValue, why? [4] International Organization for Standardization http://en.wikipedia.org/wiki/International_Organization_for_Standardization [4a] ISO 8601 Data elements and interchange formats — Information interchange — Representation of dates and times http://en.wikipedia.org/wiki/ISO_8601 [5] Gregorian Calendar http://en.wikipedia.org/wiki/Gregorian_calendar [5a] Proleptic Gregorian calendar http://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar [5b] Gregorian Calendar Adoption http://en.wikipedia.org/wiki/Gregorian_calendar#Adoption [6] http://en.wikipedia.org/wiki/Galileo_Galilei A: I haven't used it in a while, but from past experience I'd say that Boost.Date_Time is a pretty good example. While probably not the first choice for many fast paced projects today, the expressive power of C++ still seems to be a very good match for a complex problem domain like date/time, so combined with the high quality peer review process to pass for becoming an official Boost C++ library I'd hope that the library at hand could serve as a example for how time-related things should be handled, albeit not as a complete implementation, see below. Boost Date Time The library is documented very well, so I could probably assemble the entire answer from quotes, but I'll try to extract some fragments according to the template suggested by soc's answer instead - nonetheless I'm going to start with an entire quote: Motivation The motivation for this library comes from working with and helping build several date-time libraries on several projects. [...] Programming with dates and times should be almost as simple and natural as programming with strings and integers. Applications with lots of temporal logic can be radically simplified by having a robust set of operators and calculation capabilities. Classes should provide the ability to compare dates and times, add lengths or time durations, retrieve dates and times from clocks, and work naturally with date and time intervals. Domain Concepts The library supports 3 basic temporal types: Time Point - Specifier for a location in the time continuum. Time Duration - A length of time unattached to any point on the time continuum. Time Interval - A duration of time attached to a specific point in the time continuum. Also known as a time period. Calculations You can get a pretty intuitive overview on how the domain concepts relate to each other in section Details - Calculations. Constraints An important part of my original decision to evaluate the library has been the available documentation of design goals and necessary tradeoffs in light of the complex problem domain, which seems to outline the real world expertise that has been put into the library - you can read more about it in the following two sections: Design Goals Tradeoffs: Stability, Predictability, and Approximations Working with Timezone and DST data There is full support for all kind of calculations and conversions one could think of, as far as I'm concerned - see the headings in section Examples for an initial impression. Calendar/Time systems This is definitely the weak spot concerning your specification, despite the library being specifically designed with extensibility in mind: A large part of the genesis of this library has been the observation that few date-time libraries are built in a fashion that allows customization and extension. A typical example, the calendar logic is built directly into the date class. Or the clock retrieval functions are built directly into the time class. These design decisions usually make it impossible to extend or change the library behavior. At a more fundamental level, there are usually assumptions about the resolution of time representation or the gregorian calendar. However, I'm not aware of any implementations of other calendar/time systems than the ones included, see Library Reference for the current implementations of: Date Time Gregorian Posix Time Local Time Formatting and Parsing This is fully supported and one of the strong points of the library due to the respective power of the underlying C++ I/O system, see Date Time Input/Output - the stream oriented C++ I/O has both merit and issues depending on your needs and expectations, but this topic is discussed elsewhere on this site. Integration This is provided as well via compatibility with Boost Serialization, which is archive oriented though, usually meaning a file of binary data, text data, XML or so; i.e. databases are not explicitly supported as in your JSR 310 example. A: To answer your "Good Example" question, take a look at Noda Time - Jon Skeet's port of the Joda-Time libraries for Java to .Net A: You mention Python in an earlier comment. Python's builtin datetime support (docs) is pretty practical, but you have to use a third-party timezone database such as pytz (docs) to make it close to complete. And, as the pytz docs mention, you may still have problems with adding deltas to times right around DST transitions if you aren't careful. It was once the case that eGenix's mx.DateTime was the way to go if datetime didn't do it for your application, particularly for string to timestamp conversions, but dateutil seems to be popular these days (I haven't used it though).
How do libraries in different programming languages handle Date & Time, Timestamps & Durations, Leapseconds & -years, DSTs & Timezones, ...?
Is there a standard body or a specific normative way how time-related things should be implemented in practice (like ICU for Unicode-related tasks) or is this currently a "best-effort", depending on how much effort, time and money language and library implementers want to spend? Is there a specific and complete implementation which could serve as a example for how time-related things should be handled? Which existing library would you consider as a bad, a decent or a good example?
[ "I'll try to give an answer to the second and third question using the Java library which might become part of Java 7.\njavax.time.* (JSR 310)\nThese classes are a complete rewrite of JodaTime trying to fix the design flaws of util.Date/util.Time as well as JodaTime.\nJSR 310 tries to provide a comprehensive model ...
[ 17, 11, 11, 7, 4, 4 ]
[]
[]
[ "c#", "date", "language_agnostic", "python", "time" ]
stackoverflow_0003709870_c#_date_language_agnostic_python_time.txt
Q: Python replacement for PHP's header How to send a raw http header in python just like header() in PHP ? A: Pass a list of two-tuples containing the header name and header value to the start_response() function. A: In Django, you'd be like: def someview(request): # ... etc ... out = HttpResponse(outputstring, mimetype="text/html", status_code="302", ) out['Content-Disposition'] = "attachment; filename=download.html" # fill in all your favorite HTTP headers here return out ... for cache-control and friends, you need to import a bunch of decorators and wrap your view functions accordingly (I forget which) -- this is because django has a caching system with which many sub-rosa bits of the framework are integrated. I find the cache stuff confusing, but also nice. non-cache HTTP headers are E-Z.
Python replacement for PHP's header
How to send a raw http header in python just like header() in PHP ?
[ "Pass a list of two-tuples containing the header name and header value to the start_response() function.\n", "In Django, you'd be like:\ndef someview(request):\n # ... etc ...\n out = HttpResponse(outputstring,\n mimetype=\"text/html\",\n status_code=\"302\",\n )\n out['Content-Dispo...
[ 1, 1 ]
[]
[]
[ "header", "php", "python" ]
stackoverflow_0003948690_header_php_python.txt
Q: twisted on centos missing mail.smtp? I'm trying to get buildbot running on centos5, and getting the following error: File "/usr/lib/python2.4/site-packages/buildbot/status/mail.py", line 14, in ? from twisted.mail.smtp import sendmail, ESMTPSenderFactory ImportError: No module named mail.smtp I have the following twisted packages installed (and don't see anything else relevant to install): $ rpm -qa | grep twisted python-twisted-web-0.7.0-1.el5 python-twisted-core-2.5.0-4.el5 python-twisted-words-0.5.0-3.el5 I'm more familiar with debian where I can do: $ apt-file find twisted/mail/smtp python-twisted-mail: /usr/share/pyshared/twisted/mail/smtp.py Two questions: Is there something I can pull from yum that will provide this file or do I need to resort to manual tactics for this part of twisted? Is there anything analogous to the apt-file command above for rpm/yum-based systems? Thanks. (I considered superuser, but this seems so tightly coupled to programming that I expect better answers here...) A: The equivalent of apt-file in redhat is "yum whatprovides". But I did try this for the smtp package you are looking for and it did return any matching package :( [vc@vc ~]$ yum whatprovides */twisted/mail/smtp.py Loaded plugins: downloadonly, fastestmirror Excluding Packages in global exclude list Finished addons/filelists | 195 B 00:00 base/filelists_db | 3.4 MB 00:01 extras/filelists_db | 197 kB 00:00 updates/filelists_db | 2.9 MB 00:01 No Matches found This link has a comparison about different package managers, hope it helps
twisted on centos missing mail.smtp?
I'm trying to get buildbot running on centos5, and getting the following error: File "/usr/lib/python2.4/site-packages/buildbot/status/mail.py", line 14, in ? from twisted.mail.smtp import sendmail, ESMTPSenderFactory ImportError: No module named mail.smtp I have the following twisted packages installed (and don't see anything else relevant to install): $ rpm -qa | grep twisted python-twisted-web-0.7.0-1.el5 python-twisted-core-2.5.0-4.el5 python-twisted-words-0.5.0-3.el5 I'm more familiar with debian where I can do: $ apt-file find twisted/mail/smtp python-twisted-mail: /usr/share/pyshared/twisted/mail/smtp.py Two questions: Is there something I can pull from yum that will provide this file or do I need to resort to manual tactics for this part of twisted? Is there anything analogous to the apt-file command above for rpm/yum-based systems? Thanks. (I considered superuser, but this seems so tightly coupled to programming that I expect better answers here...)
[ "The equivalent of apt-file in redhat is \"yum whatprovides\". But I did try this for the smtp package you are looking for and it did return any matching package :(\n[vc@vc ~]$ yum whatprovides */twisted/mail/smtp.py \nLoaded plugins: downloadonly, fastestmirror \nExcluding Packages in global exclude list \nFinishe...
[ 1 ]
[]
[]
[ "centos", "python", "rpm", "twisted" ]
stackoverflow_0003937164_centos_python_rpm_twisted.txt
Q: Python indentation when adding looping statements to existing code In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere? I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces and be done with it. Go to every single line and add tabs/spaces. What if you were adding nested loops/if/then statements to existing code? Am I missing some shortcut? A: I think every serious editor or IDE supports the option to select multiple lines and press tab to indent or Shift-Tab to unindent all that lines. A: in IDLE, the standard python IDE, select the code, go on 'format' and you can chooose indent region, dedent region and so on A: You have to use an editor command to re-indent. Keep in mind: Beautiful is better than ugly. ... and the rest of "The Zen of Python, by Tim Peters" # python -c "import this" A: edit: rewrote to accomodate fileinput's "eccentricities"* def indent_code(filename, startline, endline): from fileinput import input from itertools import izip, count all_remaining = count() def print_lines(lines, prefix='', range=all_remaining): for _, line in izip(range, lines): print prefix + line, lines = input(filename, inplace=1) print_lines(lines, range=xrange(1, startline)) # 1-based line numbers print_lines(lines, ' ', xrange(startline, endline + 1)) # inclusive print_lines(lines) def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('filename') parser.add_argument('startline', type=int) parser.add_argument('endline', type=int) ns = parser.parse_args() indent_code(ns.filename, ns.startline, ns.endline) if __name__ == '__main__': main() Well, either that or >}. *: I originally wrote this using a nice, concise combination of stdout.writelines and some generator expressions. Unfortunately, that code didn't work. The iterator returned by fileinput.input() doesn't actually open a file until you call its next method. It works its sketchy output-redirection magic on sys.stdout at the same time. This means that if you call sys.stdout.writelines and pass it the fileinput.input iterator, your call, and the output, goes to the original standard out rather than the one remapped by fileinput to the file "currently" being processed. So you end up with the lines that are supposed to replace the contents of the file being instead just printed to the terminal. It's possible to work around this issue by calling next on the fileinput iterator before calling stdout.writelines, but this causes other problems: reaching the end of the input file causes its handle to be closed from the iterator's next method when called within file.writelines. Under Python 2.6, this segfaults because there's no check made (in the C code which implements writelines) to see if the file is still open, and the file handle non-zero, after getting the next value from the iterator. I think under 2.7 it just throws an exception, so this strategy might work there. The above code actually does test correctly. A: textmate (and maybe e?): select then apple-] bbedit: also select then apple-] emacs: select then M-x 'indent-region' bpython: don't know, autoindenting is so easy in bpython, you'd have to work to break it xcode: don't do python in xcode that's generally all I need to know. also yeah it's easy to slap a brace above or below a poorly indented block, but you know it's just going to confuse the shit out of you a week later when you haven't been staring at it for like a day. srsly u guys.
Python indentation when adding looping statements to existing code
In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere? I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces and be done with it. Go to every single line and add tabs/spaces. What if you were adding nested loops/if/then statements to existing code? Am I missing some shortcut?
[ "I think every serious editor or IDE supports the option to select multiple lines and press tab to indent or Shift-Tab to unindent all that lines.\n", "in IDLE, the standard python IDE, select the code, go on 'format' and you can chooose indent region, dedent region and so on\n", "You have to use an editor comm...
[ 11, 3, 1, 1, 0 ]
[]
[]
[ "indentation", "python", "python_idle" ]
stackoverflow_0003948257_indentation_python_python_idle.txt
Q: Copying a list of paths/files to a directory I'm just doing an exercise where I have a list of files (given as absolute paths), which should be copied to a given directory if some sort of flag is set. This is my function to copy the files: def copy_to(paths, dst): if not os.path.exists(dst): os.makedirs(dst) for path in paths: shutil.copy(path, dst) However, the given solution looks different: def copy_to(paths, dst): if not os.path.exists(dst): os.makedirs(dst) for path in paths: basename = os.path.basename(path) shutil.copy(path, os.path.join(dst, basename)) Is getting the basename of the path and joining it with the path where to copy to really needed here? A: As per the current manual, it is not needed: shutil.copy(src, dst) Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings. It says that, if dst is a directory, copy() places a file with the same basename of src on dst A: It isn't needed. The documentation says: Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. The given solution does this explicitly, rather than letting shutil.copy do it implicitly. That's the only difference. A: already answered but a few points I noticed. Use of dir here is shadowing the builtin dir. Also, what is os.path.makedirs? On my python (2.6) this gives >>> os.path.makedirs Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'makedirs' Do you mean os.makedirs?
Copying a list of paths/files to a directory
I'm just doing an exercise where I have a list of files (given as absolute paths), which should be copied to a given directory if some sort of flag is set. This is my function to copy the files: def copy_to(paths, dst): if not os.path.exists(dst): os.makedirs(dst) for path in paths: shutil.copy(path, dst) However, the given solution looks different: def copy_to(paths, dst): if not os.path.exists(dst): os.makedirs(dst) for path in paths: basename = os.path.basename(path) shutil.copy(path, os.path.join(dst, basename)) Is getting the basename of the path and joining it with the path where to copy to really needed here?
[ "As per the current manual, it is not needed:\n\nshutil.copy(src, dst) Copy the file\n src to the file or directory dst. If\n dst is a directory, a file with the\n same basename as src is created (or\n overwritten) in the directory\n specified. Permission bits are copied.\n src and dst are path names given as...
[ 3, 1, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003948805_file_io_python.txt
Q: How can I put a wx.ScrolledWindow inside a wx.SplitterWindow? I wouldn't have thought this would be so tricky. I'm trying to get something like this: X | X Where both Xs are ScrolledWindows that will ultimately contain lots of text and '|' is a "splitter" dividing the two. I want something about like most visual diffs give you. I can't seem to get this to work, though. My big problem now is that I'm violating some assertions. When I run it in straight up python, it actually draws approximately what I'd expect, minus some refinement of the appropriate sizes despite the constraint violations. My project uses pybliographer, though, which exits on the constraint violations. Am I doing this wrong? Is there an easier way to do this? I've included a simple modification of the splitterwindow example code to use scrolledwindows. I first fit the panels inside the scrolledwindows and then use that to set the scrollbars as in the second example in the wxpython wiki(http://wiki.wxpython.org/ScrolledWindows, sorry new user can't make two hyperlinks). import wx class Splitterwindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(350, 300)) quote = '''Whether you think that you can, or that you can't, you are usually right''' splitter = wx.SplitterWindow(self, -1) scroll1 = wx.ScrolledWindow(splitter,-1) panel1 = wx.Panel(scroll1, -1) wx.StaticText(panel1, -1, quote, (100, 100), style=wx.ALIGN_CENTRE) panel1.SetBackgroundColour(wx.LIGHT_GREY) panel1.SetAutoLayout(True) panel1.Layout() panel1.Fit() scroll_unit = 50 width,height = panel1.GetSizeTuple() scroll1.SetScrollbars(scroll_unit,scroll_unit,width/scroll_unit,height/scroll_unit) scroll2 = wx.ScrolledWindow(splitter,-1) panel2 = wx.Panel(scroll2, -1) wx.StaticText(panel2, -1, quote, (100, 100), style=wx.ALIGN_CENTRE) panel2.SetBackgroundColour(wx.WHITE) panel2.SetAutoLayout(True) panel2.Layout() panel2.Fit() scroll_unit = 50 width,height = panel2.GetSizeTuple() scroll2.SetScrollbars(scroll_unit,scroll_unit,width/scroll_unit,height/scroll_unit) splitter.SplitVertically(scroll1, scroll2) self.Centre() self.Show(True) app = wx.App() tmp = Splitterwindow(None, -1, 'splitterwindow.py') app.MainLoop() A: What's wrong with the example? For me it works as expected.
How can I put a wx.ScrolledWindow inside a wx.SplitterWindow?
I wouldn't have thought this would be so tricky. I'm trying to get something like this: X | X Where both Xs are ScrolledWindows that will ultimately contain lots of text and '|' is a "splitter" dividing the two. I want something about like most visual diffs give you. I can't seem to get this to work, though. My big problem now is that I'm violating some assertions. When I run it in straight up python, it actually draws approximately what I'd expect, minus some refinement of the appropriate sizes despite the constraint violations. My project uses pybliographer, though, which exits on the constraint violations. Am I doing this wrong? Is there an easier way to do this? I've included a simple modification of the splitterwindow example code to use scrolledwindows. I first fit the panels inside the scrolledwindows and then use that to set the scrollbars as in the second example in the wxpython wiki(http://wiki.wxpython.org/ScrolledWindows, sorry new user can't make two hyperlinks). import wx class Splitterwindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(350, 300)) quote = '''Whether you think that you can, or that you can't, you are usually right''' splitter = wx.SplitterWindow(self, -1) scroll1 = wx.ScrolledWindow(splitter,-1) panel1 = wx.Panel(scroll1, -1) wx.StaticText(panel1, -1, quote, (100, 100), style=wx.ALIGN_CENTRE) panel1.SetBackgroundColour(wx.LIGHT_GREY) panel1.SetAutoLayout(True) panel1.Layout() panel1.Fit() scroll_unit = 50 width,height = panel1.GetSizeTuple() scroll1.SetScrollbars(scroll_unit,scroll_unit,width/scroll_unit,height/scroll_unit) scroll2 = wx.ScrolledWindow(splitter,-1) panel2 = wx.Panel(scroll2, -1) wx.StaticText(panel2, -1, quote, (100, 100), style=wx.ALIGN_CENTRE) panel2.SetBackgroundColour(wx.WHITE) panel2.SetAutoLayout(True) panel2.Layout() panel2.Fit() scroll_unit = 50 width,height = panel2.GetSizeTuple() scroll2.SetScrollbars(scroll_unit,scroll_unit,width/scroll_unit,height/scroll_unit) splitter.SplitVertically(scroll1, scroll2) self.Centre() self.Show(True) app = wx.App() tmp = Splitterwindow(None, -1, 'splitterwindow.py') app.MainLoop()
[ "What's wrong with the example? For me it works as expected.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003861148_python_wxpython.txt
Q: In Python, how can I prohibit class inheritance? Possible Duplicate: Final classes in Python 3.x- something Guido isn't telling me? I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java as an example, where there's the 'final' keyword for prohibiting subclassing. Is it possible to prohibit subclassing in Python? If yes, it'd be great to see an example... Thanks. A: There is no Python keyword for this - it is not Pythonic. Whether a class can be subclassed is determined by a flag called Py_TPFLAGS_BASETYPE which can be set via the C API. This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java). You can however emulate the behaviour using only Python code if you wish: class Final(type): def __new__(cls, name, bases, classdict): for b in bases: if isinstance(b, Final): raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) return type.__new__(cls, name, bases, dict(classdict)) class C(metaclass=Final): pass class D(C): pass Source A: In my opinion, classes should generally not have any subclassing restrictions at all. I would like to suggest the third option: Add a comment in your class' documentation that states that the class is not meant to be subclassed.
In Python, how can I prohibit class inheritance?
Possible Duplicate: Final classes in Python 3.x- something Guido isn't telling me? I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java as an example, where there's the 'final' keyword for prohibiting subclassing. Is it possible to prohibit subclassing in Python? If yes, it'd be great to see an example... Thanks.
[ "There is no Python keyword for this - it is not Pythonic.\nWhether a class can be subclassed is determined by a flag called Py_TPFLAGS_BASETYPE which can be set via the C API.\n\nThis bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar t...
[ 18, 12 ]
[]
[]
[ "python" ]
stackoverflow_0003948964_python.txt
Q: Override reversed(...) in Python 2.5 I need a custom __reverse__ function for my class that I am deploying on App Engine, so it needs to work with Python 2.5. Is there a __future__ import or a workaround I could use? Subclassing list won't work, as I need my class to be a subclass of dict. EDIT: Using OrderedDict will not solve the problems, because the dict keys are not the same the same as the list items. This is the object I'm trying to create: My object needs to provide the same attributes as a list, i.e. support iter(obj) and reverse(obj). The elements must be instances of a special third party class. Each elements is associated with a key. Internally, need to access these objects using their keys. That's why I'd put them in a mapping. I've revised my implementation to be a list subclass instead of a dict subclass, so here's what I have now: class Foo(list): pat = {} def __init__(self): for app in APPS: # these are strings obj = SpecialClass(app) self.append(obj) self.pat[app] = obj def __getitem__(self, item): # Use object as a list if isinstance(item, int): return super(Foo, self).__getitem__(item) # Use object as a dict if item not in self.pat: # Never raise a KeyError self.pat[item] = SpecialClass(None) return self.pat[item] def __setitem__(self, item, value): if isinstance(item, int): return self.pat.__setitem__(item, value) return super(Foo).__setitem__(item, value) EDIT 2: Now that my class is a subclass of list, my problem is resolved. A: __reversed__ isn't supported in 2.5, so your only option if you really need to customize the reversed order of your collection, is to modify the places that you call reversed to use something else. But I'm curious: if you are subclassing dict, then the order of items is arbitrary anyway, so what does reversed mean in this case? A: Creating a custom __reversed__ is only possible since 2.6, so you can't simply implement that and have reversed working in 2.5. In 2.5 and below, you can however make your custom class still working with reversed by implementing the sequence protocol (i.e. implement both __len__ and __getitem__). A different possibility would be to replace the built-in function reversed with a custom function that treats your custom class differently. This could work like this: originalReversed = reversed def myReversed ( seq ): if isinstance( seq, MyCustomClass ): # do something special else: return originalReversed( seq ) reversed = myReversed However, I wouldn't recommend that as it changes the normal behaviour of built-in functions (obviously) and might confuse other users.. So you should rather implement the sequnce protocol to make reversed working.
Override reversed(...) in Python 2.5
I need a custom __reverse__ function for my class that I am deploying on App Engine, so it needs to work with Python 2.5. Is there a __future__ import or a workaround I could use? Subclassing list won't work, as I need my class to be a subclass of dict. EDIT: Using OrderedDict will not solve the problems, because the dict keys are not the same the same as the list items. This is the object I'm trying to create: My object needs to provide the same attributes as a list, i.e. support iter(obj) and reverse(obj). The elements must be instances of a special third party class. Each elements is associated with a key. Internally, need to access these objects using their keys. That's why I'd put them in a mapping. I've revised my implementation to be a list subclass instead of a dict subclass, so here's what I have now: class Foo(list): pat = {} def __init__(self): for app in APPS: # these are strings obj = SpecialClass(app) self.append(obj) self.pat[app] = obj def __getitem__(self, item): # Use object as a list if isinstance(item, int): return super(Foo, self).__getitem__(item) # Use object as a dict if item not in self.pat: # Never raise a KeyError self.pat[item] = SpecialClass(None) return self.pat[item] def __setitem__(self, item, value): if isinstance(item, int): return self.pat.__setitem__(item, value) return super(Foo).__setitem__(item, value) EDIT 2: Now that my class is a subclass of list, my problem is resolved.
[ "__reversed__ isn't supported in 2.5, so your only option if you really need to customize the reversed order of your collection, is to modify the places that you call reversed to use something else.\nBut I'm curious: if you are subclassing dict, then the order of items is arbitrary anyway, so what does reversed mea...
[ 2, 1 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0003949172_python_python_2.5.txt
Q: Turn a hex string into a percent encoded string in Python I have a string. It looks like s = 'e6b693e6a0abe699ab'. I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'. What's a good way of writing percentEncode(s)? (Note, I don't care that unreserved characters aren't converted into ASCII.) I can think of big verbose ways of doing this, but I want something nice and simple, and while I'm fairly new to Python, I'd be suprised if Python can't do this nicely. A: >>> ''.join( "%"+i+s[n+1] for n,i in enumerate(s) if n%2==0 ) '%e6%b6%93%e6%a0%ab%e6%99%ab' Or using re >>> import re >>> re.sub("(..)","%\\1",s) '%e6%b6%93%e6%a0%ab%e6%99%ab' A: Oh, you mean: ''.join(["%%%s" % pair for pair in [s[i:i+2] for i in range(0,len(s),2)]]) Though probably if you're doing this for url escaping or some such, there's a library function more appropriate to your use. Edited to add -- since everyone loves a cute itertools solution: >>> from itertools import izip, cycle >>> its = iter(s) >>> tups = izip(cycle('%'), its, its) >>> ''.join(''.join(t) for t in tups) '%e6%b6%93%e6%a0%ab%e6%99%ab' A: On the off chance that you are doing URL-encoding manually, you might want to read this blog post. It explains how to do this using the standard library's urllib module's quote_plus function. A: use a Regex to the effect of /([0-9a-f]{2})/ig and replace with %\1 A: Just to be academic. Trying to use as many iterators as possible. s = 'e6b693e6a0abe699ab' from itertools import islice, izip, cycle, chain def percentEncode(s): percentChars = cycle('%') firstChars = islice(s,0,None, 2) secondChars = islice(s,1,None, 2) return ''.join(chain.from_iterable(izip(percentChars, firstChars, secondChars))) if __name__ == '__main__': print percentEncode(s) Thanks to @tcarobruce for the reminder to reuse the string iter. s = 'e6b693e6a0abe699ab' from itertools import islice, izip, cycle, chain def percentEncode(s): iter_s = iter(s) return ''.join(chain.from_iterable(izip(cycle('%'), iter_s, iter_s))) if __name__ == '__main__': print percentEncode(s) A: Based on a comment of yours in the initial question, if starting from the initial string initial_s before its encoding into hex, you can have the result as: def percent_encode(initial_s): return ''.join('%%%02x' % ord(c) for c in initial_s) >>> percent_encode('hello') '%68%65%6c%6c%6f'
Turn a hex string into a percent encoded string in Python
I have a string. It looks like s = 'e6b693e6a0abe699ab'. I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'. What's a good way of writing percentEncode(s)? (Note, I don't care that unreserved characters aren't converted into ASCII.) I can think of big verbose ways of doing this, but I want something nice and simple, and while I'm fairly new to Python, I'd be suprised if Python can't do this nicely.
[ ">>> ''.join( \"%\"+i+s[n+1] for n,i in enumerate(s) if n%2==0 )\n'%e6%b6%93%e6%a0%ab%e6%99%ab'\n\nOr using re\n>>> import re\n>>> re.sub(\"(..)\",\"%\\\\1\",s)\n'%e6%b6%93%e6%a0%ab%e6%99%ab'\n\n", "Oh, you mean:\n''.join([\"%%%s\" % pair for pair in [s[i:i+2] for i in range(0,len(s),2)]])\n\nThough probably if ...
[ 3, 2, 2, 1, 1, 1 ]
[]
[]
[ "percent_encoding", "python" ]
stackoverflow_0003938801_percent_encoding_python.txt
Q: How can you manually render a form field with its initial value set? I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source. ie. Instead of declaring form fields like this... {{ form.first_name }} .. I actually do ... <label for="id_first_name">Your name:</label> <input type="text" value="{{ form.first_name.somehow_get_initial_value_here }}" name="first_name" id="id_first_name" class="blabla" maxlength="30" > {% if form.first_name.errors %}<span>*** {{ form.first_name.errors|join:", " }}</span>{% endif %} Problem is that there seems to be no way to get the initial value of the field in the second method. {{ form.first_name }} statement does render the input element with the proper initial value but somehow there is nothing like {{ form.first_name.initial_value }} field when you want to render the form manually. A: There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need: http://code.djangoproject.com/ticket/10427 A: <input value="{{form.name.data|default_if_none:'my_defaut_value'}}" ... /> You will have to use default_if_none because the implicit value of a bound field will not be stored in data. More details here
How can you manually render a form field with its initial value set?
I'm trying to render a form's fields manually so that my designer colleagues could manipulate the input elements within the HTML instead of struggling in Python source. ie. Instead of declaring form fields like this... {{ form.first_name }} .. I actually do ... <label for="id_first_name">Your name:</label> <input type="text" value="{{ form.first_name.somehow_get_initial_value_here }}" name="first_name" id="id_first_name" class="blabla" maxlength="30" > {% if form.first_name.errors %}<span>*** {{ form.first_name.errors|join:", " }}</span>{% endif %} Problem is that there seems to be no way to get the initial value of the field in the second method. {{ form.first_name }} statement does render the input element with the proper initial value but somehow there is nothing like {{ form.first_name.initial_value }} field when you want to render the form manually.
[ "There is an interesting long standing ticket about this very issue. There is sample code to implement a template filter in the comments that should do what you need:\nhttp://code.djangoproject.com/ticket/10427\n", "<input value=\"{{form.name.data|default_if_none:'my_defaut_value'}}\" ... />\n\nYou will have to u...
[ 4, 0 ]
[]
[]
[ "django", "django_forms", "form_fields", "python" ]
stackoverflow_0003929903_django_django_forms_form_fields_python.txt
Q: Python save as/open hello there i am making a text editor in Tkinter (python) and so i made a menu and wanted to know how i can call a function that will display the windows Save-as or open boxes that every program uses. For example in notepad you can click file-save and then it opens the windows save box. I already have the menu but how can i open the save box. Thanks a lot. A: Here is an example from http://www.daniweb.com/forums/thread39327.html: import tkFileDialog def open_it(): filename = tkFileDialog.askopenfilename() print filename # test def save_it(): filename = tkFileDialog.askopenfilename() print filename # test def save_as(): filename = tkFileDialog.asksaveasfilename() print filename # test
Python save as/open
hello there i am making a text editor in Tkinter (python) and so i made a menu and wanted to know how i can call a function that will display the windows Save-as or open boxes that every program uses. For example in notepad you can click file-save and then it opens the windows save box. I already have the menu but how can i open the save box. Thanks a lot.
[ "Here is an example from http://www.daniweb.com/forums/thread39327.html:\n\n\nimport tkFileDialog\n\ndef open_it():\n filename = tkFileDialog.askopenfilename()\n print filename # test\n\ndef save_it():\n filename = tkFileDialog.askopenfilename()\n print filename # test\n\ndef save_as():\n filename ...
[ 2 ]
[]
[]
[ "python", "tkinter", "windows" ]
stackoverflow_0003950034_python_tkinter_windows.txt
Q: Generate RGB colors as different as possible I have been using the random function to generate color values xi = [a, b, c] where a, b, and c can be any number from 0 to 255. I need ideas to write a function that generate x values as different as possible for the human eye. One of the problems I am having is that I don't know the number of x elements that will be generated. So my previous functions attempts are generating values that end up quickly converging as more and more values are generated. Ideas? A: Using a different colour model can help here - for example, you could use HSV, and then cycle through the hue while maintaining a consistent saturation and value. HSV also makes it easier to generate colours which complement each other, for example, you could take 2 colours with hues 120 or 180 degrees apart. See also convert RGB values to equivalent HSV values using python hex <-> RGB <-> HSV Color space conversion with Python
Generate RGB colors as different as possible
I have been using the random function to generate color values xi = [a, b, c] where a, b, and c can be any number from 0 to 255. I need ideas to write a function that generate x values as different as possible for the human eye. One of the problems I am having is that I don't know the number of x elements that will be generated. So my previous functions attempts are generating values that end up quickly converging as more and more values are generated. Ideas?
[ "Using a different colour model can help here - for example, you could use HSV, and then cycle through the hue while maintaining a consistent saturation and value.\nHSV also makes it easier to generate colours which complement each other, for example, you could take 2 colours with hues 120 or 180 degrees apart.\nSe...
[ 6 ]
[]
[]
[ "colors", "python", "rgb" ]
stackoverflow_0003950024_colors_python_rgb.txt
Q: Paging python lists in slices of 4 items Possible Duplicate: How do you split a list into evenly sized chunks in Python? mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and process for each go so I'd prefer to do it in the lowest possible number of queries. What I'd like to do is chunk the list into blocks of four and submit each sub-block. So from the above list, I'd expect: [[1, 2, 3, 4], [5, 6, 7, 8], [9]] A: mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] print [mylist[i:i+4] for i in range(0, len(mylist), 4)] # Prints [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
Paging python lists in slices of 4 items
Possible Duplicate: How do you split a list into evenly sized chunks in Python? mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] I need to pass blocks of these to a third party API that can only deal with 4 items at a time. I could do one at a time but it's a HTTP request and process for each go so I'd prefer to do it in the lowest possible number of queries. What I'd like to do is chunk the list into blocks of four and submit each sub-block. So from the above list, I'd expect: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
[ "mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] \nprint [mylist[i:i+4] for i in range(0, len(mylist), 4)]\n# Prints [[1, 2, 3, 4], [5, 6, 7, 8], [9]]\n\n" ]
[ 76 ]
[]
[]
[ "chunks", "python" ]
stackoverflow_0003950079_chunks_python.txt
Q: Automatically add a variable into context on per-application basis in Django? I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty. Example: apps/someapp/views.py: def_context_var('app_name', 'Calendar') templates/base.html: {% if app_name %}You are in {{ app_name }} app.{% endif %} .... {% if app_name %}Subsections of {{ app_name }}: ...{% endif %} I considered the following: Declare a variable in the app (in a view, or in URLs), and make a context processor. But I can't understang how to extract that var given the request object. Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code. #1 but nicer: make methods (like in the example above) that are executed on server restart, write the data into a dict, then a context processor somehow (how?) gets the application name and extracts the data from the dict. Where do I put the method, the dict, how does the context processor know where the view object is in? A: You can call resolve(request.path) in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name.
Automatically add a variable into context on per-application basis in Django?
I want to add a context variable in Django, so that I could define its value on per-application basis, or leave it empty. Example: apps/someapp/views.py: def_context_var('app_name', 'Calendar') templates/base.html: {% if app_name %}You are in {{ app_name }} app.{% endif %} .... {% if app_name %}Subsections of {{ app_name }}: ...{% endif %} I considered the following: Declare a variable in the app (in a view, or in URLs), and make a context processor. But I can't understang how to extract that var given the request object. Put decorators on views. Hm, I don't like the idea: too much boilerplate or duplicated code. #1 but nicer: make methods (like in the example above) that are executed on server restart, write the data into a dict, then a context processor somehow (how?) gets the application name and extracts the data from the dict. Where do I put the method, the dict, how does the context processor know where the view object is in?
[ "You can call resolve(request.path) in a context processor to resolve the current url. See the django documentation on resolve for its return values, especially app_name. \n" ]
[ 2 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003950082_django_django_urls_python.txt
Q: Min heap is, but is a max heap module defined in python? Possible Duplicate: What do I use for a max-heap implementation in Python? Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build from scratch? A: You could multiply your numbers by -1 and use the min heap. A: No need to implement a max heap from scratch. You can easily employ a bit of math to turn your min heap into a max heap! See this and this - but really this SO answer.
Min heap is, but is a max heap module defined in python?
Possible Duplicate: What do I use for a max-heap implementation in Python? Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build from scratch?
[ "You could multiply your numbers by -1 and use the min heap. \n", "No need to implement a max heap from scratch. You can easily employ a bit of math to turn your min heap into a max heap!\nSee this and this - but really this SO answer. \n" ]
[ 2, 0 ]
[]
[]
[ "data_structures", "heap", "python" ]
stackoverflow_0003950368_data_structures_heap_python.txt
Q: How to see the error and still keep the program on in the Python shell? I know try/except can handle errors in my program. But, is there a way of making the error be displayed in the program execution, be ignored and let the execution go on? A: In VBScript and other VB-derived languages, you can get this sort of behavior with "ON ERROR GOTO NEXT". No such behavior exists in Python. Even if you wrap each top-level statement like: try: do_something() except Exception as e: print e try: do_something_else() except Exception as e: print e you'd still have the result that statements within do_something are skipped at the point the exception is thrown. Though perhaps if you have a particular use-case in mind, there may be other acceptable answers. For instance, in a top-level loop: while True: cmd = get_command() if cmd == 'quit': break try: run_command(cmd) except Exception as e: print "Error running " + cmd + ":" print e A: import traceback try: # do whatever you want except Exception: traceback.print_exc() Of course you should be more specific in a real scenario, i.e. you shouldn't catch and ignore all Exception instances, only the ones you are interested in and you know that they are safe to ignore. Also note that if an exception happens somewhere within the try..except block, the execution will continue after the try..except block, not at the next statement. This is probably the closest to what you want to achieve.
How to see the error and still keep the program on in the Python shell?
I know try/except can handle errors in my program. But, is there a way of making the error be displayed in the program execution, be ignored and let the execution go on?
[ "In VBScript and other VB-derived languages, you can get this sort of behavior with \"ON ERROR GOTO NEXT\".\nNo such behavior exists in Python. Even if you wrap each top-level statement like:\ntry:\n do_something()\nexcept Exception as e:\n print e\n\ntry:\n do_something_else()\nexcept Exception as e:\n print e...
[ 3, 2 ]
[]
[]
[ "error_handling", "exception", "exception_handling", "python" ]
stackoverflow_0003950505_error_handling_exception_exception_handling_python.txt
Q: What threading module should I use to prevent disk IO from blocking network IO? I have a Python application that, to be brief, receives data from a remote server, processes it, responds to the server, and occasionally saves the processed data to disk. The problem I've encountered is that there is a lot of data to write, and the save process can take upwards of half a minute. This is apparently a blocking operation, so the network IO is stalled during this time. I'd like to be able to make the save operation take place in the background, so-to-speak, so that the application can continue to communicate with the server reasonably quickly. I know that I probably need some kind of threading module to accomplish this, but I can't tell what the differences are between thread, threading, multiprocessing, and the various other options. Does anybody know what I'm looking for? A: Since you're I/O bound, then use the threading module. You should almost never need to use thread, it's a low-level interface; the threading module is a high-level interface wrapper for thread. The multiprocessing module is different from the threading module, multiprocessing uses multiple subprocesses to execute a task; multiprocessing just happens to use the same interface as threading to reduce learning curve. multiprocessing is typically used when you have CPU bound calculation, and need to avoid the GIL (Global Interpreter Lock) in a multicore CPU. A somewhat more esoteric alternative to multi-threading is asynchronous I/O using asyncore module. Another options includes Stackless Python and Twisted.
What threading module should I use to prevent disk IO from blocking network IO?
I have a Python application that, to be brief, receives data from a remote server, processes it, responds to the server, and occasionally saves the processed data to disk. The problem I've encountered is that there is a lot of data to write, and the save process can take upwards of half a minute. This is apparently a blocking operation, so the network IO is stalled during this time. I'd like to be able to make the save operation take place in the background, so-to-speak, so that the application can continue to communicate with the server reasonably quickly. I know that I probably need some kind of threading module to accomplish this, but I can't tell what the differences are between thread, threading, multiprocessing, and the various other options. Does anybody know what I'm looking for?
[ "Since you're I/O bound, then use the threading module. \nYou should almost never need to use thread, it's a low-level interface; the threading module is a high-level interface wrapper for thread.\nThe multiprocessing module is different from the threading module, multiprocessing uses multiple subprocesses to exec...
[ 7 ]
[]
[]
[ "blocking", "io", "multithreading", "nonblocking", "python" ]
stackoverflow_0003950607_blocking_io_multithreading_nonblocking_python.txt
Q: trying to POST to w3c validator with python script I'm trying to use this python script to upload a file to the w3c validator. ~/Desktop/urllib2_file$ python test-upload.py -u http://validator.w3.org/ -f ../index.php -n uploaded_file -p Content-Type=text/html > ../results.html && firefox ../results.html Any help will be greatly appreciated! EDIT: cyraxjoe pointed out I needed to run it through php first. I tried this, but got the same result: php -f /opt/lampp/htdocs/index.php > index.html && python urllib2_file/test-upload.py -u http://validator.w3.org/ -f index.html -n uploaded_file -p Content-Type=text/html > results.html && firefox results.html A: You are uploading a php-script which is a server-side script, you need to upload the resulting html after the php procesing. Perhaps with php-cli then store in a file the resulting text and upload that file.
trying to POST to w3c validator with python script
I'm trying to use this python script to upload a file to the w3c validator. ~/Desktop/urllib2_file$ python test-upload.py -u http://validator.w3.org/ -f ../index.php -n uploaded_file -p Content-Type=text/html > ../results.html && firefox ../results.html Any help will be greatly appreciated! EDIT: cyraxjoe pointed out I needed to run it through php first. I tried this, but got the same result: php -f /opt/lampp/htdocs/index.php > index.html && python urllib2_file/test-upload.py -u http://validator.w3.org/ -f index.html -n uploaded_file -p Content-Type=text/html > results.html && firefox results.html
[ "You are uploading a php-script which is a server-side script, you need to upload the resulting html after the php procesing. Perhaps with php-cli then store in a file the resulting text and upload that file.\n" ]
[ 1 ]
[]
[]
[ "curl", "post", "python" ]
stackoverflow_0003950591_curl_post_python.txt
Q: Python Implementation of PageRank I am attempting to understand the concepts behind Google PageRank, and am attempting to implement a similar (though rudimentary) version in Python. I have spent the last few hours familiarizing myself with the algorithm, however it's still not all that clear. I've located a particularly interesting website that outlines the implementation of PageRank in Python. However, I can't quite seem to understand the purpose of all of the functions shown on this page. Could anyone clarify what exactly the functions are doing, particularly pageRankeGenerator? A: I'll try to give a simple explanation (definition) of the PageRank algorithm from my personal notes. Let us say that pages T1, T2, ... Tn are pointing to page A, then PR(A) = (1-d) + d * (PR(T1) / C(T1) + ... + PR(Tn) / C(Tn)) where PR(Ti) is the PageRank of Ti C(Ti) is the number of outgoing links from page Ti d is the dumping factor in the range 0 < d < 1, usually set to 0.85 Every PR(x) can have start value 1 and we adjust the page ranks by repeating the algorithm ~10-20 times for each page. Example for pages A, B, C: A <--> B ^ / \ v C Round 1 A = 0.15 + 0.85 (1/2 + 1/1) = 1.425 B = 0.15 + 0.85 (1/1) = 1 C = 0.15 + 0.85 (1/2) = 0.575 round's sum = 3 Round 2 A = 0.15 + 0.85 (1/2 + 0.575) = 1.06375 B = 0.15 + 0.85 (1.425) = 1.36125 C = 0.15 + 0.85 (1/2) = 0.575 round's sum = 3 Round 3 A = 0.15 + 0.85 (1.36125/2 + 0.575) = 1.217 B = 0.15 + 0.85 (1.06375) = 1.054 C = 0.728 round's sum = 3 ...
Python Implementation of PageRank
I am attempting to understand the concepts behind Google PageRank, and am attempting to implement a similar (though rudimentary) version in Python. I have spent the last few hours familiarizing myself with the algorithm, however it's still not all that clear. I've located a particularly interesting website that outlines the implementation of PageRank in Python. However, I can't quite seem to understand the purpose of all of the functions shown on this page. Could anyone clarify what exactly the functions are doing, particularly pageRankeGenerator?
[ "I'll try to give a simple explanation (definition) of the PageRank algorithm from my personal notes.\nLet us say that pages T1, T2, ... Tn are pointing to page A, then\nPR(A) = (1-d) + d * (PR(T1) / C(T1) + ... + PR(Tn) / C(Tn))\n\nwhere\n\nPR(Ti) is the PageRank of Ti\nC(Ti) is the number of outgoing links from p...
[ 8 ]
[]
[]
[ "linear_algebra", "pagerank", "python" ]
stackoverflow_0003950627_linear_algebra_pagerank_python.txt
Q: Minimax: how can I implement it in Python? As long as I've been a programmer I still have a very elementary level education in algorithms (because I'm self-taught). Perhaps there is a good beginner book on them that you could suggest in your answer. A: As a general note, Introduction to Algorithms. That book will get you through pretty much everything you need to know about general algorithms. Edit: As AndrewF mentioned, it doesn't actually contain minimax specifically, but it's still a very good resource for learning to understand and implement algorithms. A: Look at the wikipedia article on Negamax: http://en.wikipedia.org/wiki/Negamax. It's a slight simplification of minimax that's easier to implement. There's pseudocode on that page. A: There is an implementation of minimax as part of an othello game here (and for browsers here). Stepping through this with a debugger and/or through use of logging statements may supplement theoretical descriptions of the algorithm. This visualization applet may also help. At each stage the player will choose the move which is best for himself. What's best for one player will be worst for the other player. So at one stage the game state with the minimum score will be chosen, and at the next stage the game state available with the maximum score will be chosen, etc.
Minimax: how can I implement it in Python?
As long as I've been a programmer I still have a very elementary level education in algorithms (because I'm self-taught). Perhaps there is a good beginner book on them that you could suggest in your answer.
[ "As a general note, Introduction to Algorithms. That book will get you through pretty much everything you need to know about general algorithms.\nEdit:\nAs AndrewF mentioned, it doesn't actually contain minimax specifically, but it's still a very good resource for learning to understand and implement algorithms.\n"...
[ 3, 1, 1 ]
[]
[]
[ "algorithm", "minimax", "python" ]
stackoverflow_0003950728_algorithm_minimax_python.txt
Q: Python IDLE will not open After fumbling with some keys on my keyboard while trying to get a script to run by clicking on Run in python IDLE I must of did something, because now python will not open. It opens from the command prompt fine, but the normal way it will not open whatsoever. I tried repairing and reinstalling. Still no luck. I am on Windows 7 machines 64bit, using the 32bit version of python 2.7. No idea what it could be but I did find something on google that mentioned something about keybindings or something? Please help! A: try executing C:\path\to\python.exe -m idlelib.idle in command prompt, is there any error message?
Python IDLE will not open
After fumbling with some keys on my keyboard while trying to get a script to run by clicking on Run in python IDLE I must of did something, because now python will not open. It opens from the command prompt fine, but the normal way it will not open whatsoever. I tried repairing and reinstalling. Still no luck. I am on Windows 7 machines 64bit, using the 32bit version of python 2.7. No idea what it could be but I did find something on google that mentioned something about keybindings or something? Please help!
[ "try executing C:\\path\\to\\python.exe -m idlelib.idle in command prompt, is there any error message?\n" ]
[ 3 ]
[]
[]
[ "python", "python_idle", "startup" ]
stackoverflow_0003950973_python_python_idle_startup.txt
Q: Python: Fetching and parsing text from html files I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this: file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]] file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]] Fetching links is easy - look for anchor tags. My question is - how do I fetch text? The text in the html files is not enclosed within any tags like <p> Thanks in advance for all the help A: Use an HTML parser - something like BeautifulSoup. A: If the text isn't enclosed in tags is it really HTML? As Amber says, you'll have an easier job of this using some HTML parser like BeautifulSoup. The example below demonstrates a simple method for returning text within tags. This method works for any tag AFAIK. >>> from BeautifulSoup import BeautifulSoup as bs >>> html = ''' ... <div><a href="/link1">link1 contents</a></div> ... <div><a href="/link2">link2 contents</a></div> ... ''' >>> soup = bs(html) >>> for anchor_tag in soup.findAll('a'): ... print anchor_tag.contents[0] ... link1 contents link2 contents Apart from that I can imagine that you'd want a dictionary with a count of how many times a certain term appeared in some HTML document. defaultdict is good for that kind of thing: >>> from collections import defaultdict >>> d = defaultdict(int) >>> for anchor_tag in soup.findAll('a'): ... d[anchor_tag.contents[0]] += 1 ... >>> d defaultdict(<type 'int'>, {u'link1 contents': 1, u'link2 contents': 1}) Hopefully that gives you some ideas to run with. Come back and open another question if you run into other issues.
Python: Fetching and parsing text from html files
I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this: file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]] file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]] Fetching links is easy - look for anchor tags. My question is - how do I fetch text? The text in the html files is not enclosed within any tags like <p> Thanks in advance for all the help
[ "Use an HTML parser - something like BeautifulSoup.\n", "If the text isn't enclosed in tags is it really HTML?\nAs Amber says, you'll have an easier job of this using some HTML parser like BeautifulSoup. \nThe example below demonstrates a simple method for returning text within tags.\nThis method works for any t...
[ 1, 0 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0003950741_html_parsing_python.txt
Q: Safe way to uninstall old version of python I want to update my Python framework on Mac and delete the old versions but I am not sure if is safe to rm -fr /Library/Frameworks/Python.framework/Versions/2.4 - 2.5 - 2.6 -3.0 etc. Any suggestion? A: Yes, it's safe. The Mac's system python's are in /System/Library/.... .dmg's downloaded and installed from python.org are placed in /Library/.... Don't delete the /System ones, but the /Library ones are user installed, so they should be safe to delete.
Safe way to uninstall old version of python
I want to update my Python framework on Mac and delete the old versions but I am not sure if is safe to rm -fr /Library/Frameworks/Python.framework/Versions/2.4 - 2.5 - 2.6 -3.0 etc. Any suggestion?
[ "Yes, it's safe.\nThe Mac's system python's are in /System/Library/....\n.dmg's downloaded and installed from python.org are placed in /Library/....\nDon't delete the /System ones, but the /Library ones are user installed, so they should be safe to delete.\n" ]
[ 30 ]
[ "No, it's not safe. Generally, don't mess with the Python that comes with your OS, many system tools depends on having a specific version of Python.\n" ]
[ -1 ]
[ "installation", "macos", "python" ]
stackoverflow_0003950819_installation_macos_python.txt
Q: Twisted UDP Server - daemonize? I have the following UDP server using Twisted: # init the thread capability threadable.init(1) # set the thread pool size reactor.suggestThreadPoolSize(32) class BaseThreadedUDPServer(DatagramProtocol): def datagramReceived(self, datagram, (host, port)): #do some stuff here... def main(): reactor.listenUDP(PORT, BaseThreadedUDPServer()) reactor.run() if __name__ == '__main__': main() I would like to be able to daemonize this, so from what I have read I should be doing something with a .tac file that I can start with "twistd -y my_udp_server_file.tac" - the problem is I can't find any documentation on how to do this with this kind of setup. All I can find is examples on how to daemonize simple TCP echo servers (with a .tac file, that is) - I need a multi-threaded UDP server like the one I have. Any direction would be greatly appreciated. A: The daemonization code in twistd doesn't care if you're serving up UDP or TCP. The way you daemonize a UDP server is identical to the way you daemonize a TCP server. You should be able to use the TCP echo server as an example to write a .tac file for your UDP server. A: Try this: import twisted.application application = twisted.application.service.Application("Scotty's UDP server") twisted.application.internet.UDPServer(PORT, BaseThreadedUDPServer()).setServiceParent(application)
Twisted UDP Server - daemonize?
I have the following UDP server using Twisted: # init the thread capability threadable.init(1) # set the thread pool size reactor.suggestThreadPoolSize(32) class BaseThreadedUDPServer(DatagramProtocol): def datagramReceived(self, datagram, (host, port)): #do some stuff here... def main(): reactor.listenUDP(PORT, BaseThreadedUDPServer()) reactor.run() if __name__ == '__main__': main() I would like to be able to daemonize this, so from what I have read I should be doing something with a .tac file that I can start with "twistd -y my_udp_server_file.tac" - the problem is I can't find any documentation on how to do this with this kind of setup. All I can find is examples on how to daemonize simple TCP echo servers (with a .tac file, that is) - I need a multi-threaded UDP server like the one I have. Any direction would be greatly appreciated.
[ "The daemonization code in twistd doesn't care if you're serving up UDP or TCP. The way you daemonize a UDP server is identical to the way you daemonize a TCP server. You should be able to use the TCP echo server as an example to write a .tac file for your UDP server.\n", "Try this:\nimport twisted.application\...
[ 3, 3 ]
[]
[]
[ "daemon", "python", "twisted" ]
stackoverflow_0003931346_daemon_python_twisted.txt
Q: How can I extend an embedded python interpreter with C++ functions? How can I extend an embedded interpreter with C++ code? I have embedded the interpreter and I can use boost.python to make a loadable module (as in a shared library) but I don't want the library floating around because I want to directly interface with my C++ application. Sorry if my writing is a bit incoherent. A: At least for the 2.x interpreters: you write your methods as C-style code with PyObject* return values. They all basically look like: PyObject* foo(PyObject *self, PyObject *args); Then, you collect these methods in a static array of PyMethodDef: static PyMethodDef MyMethods[] = { {"mymethod", foo, METH_VARARGS, "What my method does"}, {NULL, NULL, 0, NULL} }; Then, after you've created and initialized the interpreter, you can add these methods "into" the interpreter via the following: Py_InitModule("modulename", MyMethods); You can refer now to your methods via the modulename you've declared here. Some additional info here: http://www.eecs.tufts.edu/~awinsl02/py_c/
How can I extend an embedded python interpreter with C++ functions?
How can I extend an embedded interpreter with C++ code? I have embedded the interpreter and I can use boost.python to make a loadable module (as in a shared library) but I don't want the library floating around because I want to directly interface with my C++ application. Sorry if my writing is a bit incoherent.
[ "At least for the 2.x interpreters: you write your methods as C-style code with PyObject* return values. They all basically look like:\nPyObject* foo(PyObject *self, PyObject *args);\n\nThen, you collect these methods in a static array of PyMethodDef:\nstatic PyMethodDef MyMethods[] =\n{\n {\"mymethod\", foo, M...
[ 2 ]
[]
[]
[ "boost", "boost_python", "embed", "extend", "python" ]
stackoverflow_0003951407_boost_boost_python_embed_extend_python.txt
Q: fetching and parsing text not enclosed within tags I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this: file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]] file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]] Fetching links is easy - look for anchor tags. My question is - how do I fetch text? The text in the html files is not enclosed within any tags like <p>. Here's an example of one of the input HTML files: d_9.html d_3.html bedote charlatanism nondecision pudsey Antaean haec euphoniously Bixa bacteriologically hesitantly Hobbist petrosa emendable counterembattled noble hornlessness chemolyze spittoon flatiron formalith wreathingly hematospermatocele theosophically sarking nontruth possessionist gravimetry matico unlawly abator hyetological Microconodon supermuscan Maybe, the text above is not HTML, but then how do I fetch and parse it? Any ideas? A: One way to go about this is to simply ignore all the tags and what you've got left is assumed to be text. It will make the regex large though. A: I wouldn't use regex, I would use something like lxml, that way you can get the tags, the text and also the structure of the document as needed. A: You say the text is "not HTML," and "is not enclosed within any tags." So it's just plain text, there's nothing to parse. Fetch the url, and the contents returned to you are a string full of words. Split the words with .split(), and you have a list of words. A: i think what you want is to get data (links , keywords ...) from an HTML File , but your problem is that some part of your HTML file does not contain any tags to parse it properly, or is it all the HTML file that don't have tags ? if yes you can format the html file with tidy, it can help you for parsing it ; so if i were you i will just use regex to match links something like : links = re.finditer(".*html", text) # by the way the regex must be more complicated than that. and for the keywords "[cat, ate, food, drank, milk]" i don't know what you are looking for exactly ; hope this can help
fetching and parsing text not enclosed within tags
I'm trying to work on a project about page ranking. I want to make an index (dictionary) which looks like this: file1.html -> [[cat, ate, food, drank, milk], [file2.html, file3.html]] file2.html -> [[dog, barked, ran, away], [file1.html, file4.html]] Fetching links is easy - look for anchor tags. My question is - how do I fetch text? The text in the html files is not enclosed within any tags like <p>. Here's an example of one of the input HTML files: d_9.html d_3.html bedote charlatanism nondecision pudsey Antaean haec euphoniously Bixa bacteriologically hesitantly Hobbist petrosa emendable counterembattled noble hornlessness chemolyze spittoon flatiron formalith wreathingly hematospermatocele theosophically sarking nontruth possessionist gravimetry matico unlawly abator hyetological Microconodon supermuscan Maybe, the text above is not HTML, but then how do I fetch and parse it? Any ideas?
[ "One way to go about this is to simply ignore all the tags and what you've got left is assumed to be text. It will make the regex large though.\n", "I wouldn't use regex, I would use something like lxml, that way you can get the tags, the text and also the structure of the document as needed.\n", "You say the t...
[ 1, 0, 0, 0 ]
[]
[]
[ "html", "html_parsing", "python" ]
stackoverflow_0003951280_html_html_parsing_python.txt
Q: How to revert compiled Python 2.6.4 to system default on Snow Leopard? So earlier this year I manually built 2.6.4 for Snow Leopard because I wanted a slightly more updated version of Python than what Apple released. This has caused all kinds of problems when installing some eggs like PIL and running other 3rd party python apps. Now I just want to revert everything back to what Snow Leopard ships with because I have to get work done and it's getting in the way. If worse comes to worse, I'm going to reinstall the OS but I'd like to avoid that if possible. A: Set the PATH environment variable so that /usr/bin is ahead of wherever you put your custom compiled Python binary.
How to revert compiled Python 2.6.4 to system default on Snow Leopard?
So earlier this year I manually built 2.6.4 for Snow Leopard because I wanted a slightly more updated version of Python than what Apple released. This has caused all kinds of problems when installing some eggs like PIL and running other 3rd party python apps. Now I just want to revert everything back to what Snow Leopard ships with because I have to get work done and it's getting in the way. If worse comes to worse, I'm going to reinstall the OS but I'd like to avoid that if possible.
[ "Set the PATH environment variable so that /usr/bin is ahead of wherever you put your custom compiled Python binary.\n" ]
[ 1 ]
[]
[]
[ "osx_snow_leopard", "python" ]
stackoverflow_0003951608_osx_snow_leopard_python.txt
Q: How to abort python fabric run command? run("if [ -d data.bak ];then mv data.bak data;fi;") sudo('....') sudo('') I am using fabric deploy for my web project. I want to find a way that will stop the rest of the execution of the command, if it doesn't find the data.bak directory. Any way to achieve this in fabric? A: There is a contribute api in fabric.contrib.files import.
How to abort python fabric run command?
run("if [ -d data.bak ];then mv data.bak data;fi;") sudo('....') sudo('') I am using fabric deploy for my web project. I want to find a way that will stop the rest of the execution of the command, if it doesn't find the data.bak directory. Any way to achieve this in fabric?
[ "There is a contribute api in fabric.contrib.files import.\n" ]
[ 1 ]
[]
[]
[ "fabric", "python", "sudo" ]
stackoverflow_0003947827_fabric_python_sudo.txt
Q: How to replace the first occurrence of a regular expression in Python? I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this? A: re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 1: >>> s = "foo foo foofoo foo" >>> re.sub("foo", "bar", s, 1) 'bar foo foofoo foo' >>> s = "baz baz foo baz foo baz" >>> re.sub("foo", "bar", s, 1) 'baz baz bar baz foo baz' Edit: And a version with a compiled SRE object: >>> s = "baz baz foo baz foo baz" >>> r = re.compile("foo") >>> r.sub("bar", s, 1) 'baz baz bar baz foo baz' A: Specify the count argument in re.sub(pattern, repl, string[, count, flags]) The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced.
How to replace the first occurrence of a regular expression in Python?
I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?
[ "re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 1:\n>>> s = \"foo foo foofoo foo\"\n>>> re.sub(\"foo\", \"bar\", s, 1)\n'bar foo foofoo foo'\n>>> s = \"baz baz foo baz foo baz\"\n>>> re.sub(\"foo\", \"bar\", s, 1)\n'baz baz bar baz foo baz'\n\nEdit: And a v...
[ 74, 17 ]
[]
[]
[ "python", "regex", "replace", "search" ]
stackoverflow_0003951660_python_regex_replace_search.txt
Q: How to invoke a function on an object dynamically by name? In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it? That is: obj = MyClass() # this class has a method doStuff() func = "doStuff" # how to call obj.doStuff() using the func variable? A: Use the getattr built-in function. See the documentation obj = MyClass() try: func = getattr(obj, "dostuff") func() except AttributeError: print("dostuff not found")
How to invoke a function on an object dynamically by name?
In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it? That is: obj = MyClass() # this class has a method doStuff() func = "doStuff" # how to call obj.doStuff() using the func variable?
[ "Use the getattr built-in function. See the documentation\nobj = MyClass()\ntry:\n func = getattr(obj, \"dostuff\")\n func()\nexcept AttributeError:\n print(\"dostuff not found\")\n\n" ]
[ 99 ]
[]
[]
[ "python" ]
stackoverflow_0003951840_python.txt
Q: how to launch an exe with a variable path, special characters and arguements I want to copy an installer file from a location where one of the folder names changes as per the build number This works for defining the path where the last folder name changes import glob import os dirname = "z:\\zzinstall\\*.install" filespec = "setup.exe" print glob.glob (os.path.join (dirname, filespec)) # the print is how I'm verifying the path is correct ['z:\\zzinstall\\35115.install\\setup.exe' The problem I have is that I can't get the setup.exe to launch due to the arguments needed I need to launch setup.exe with, for example setup.exe /S /z" There are numerous other arguments that need to be passed with double quotes, slashes and whitespaces. Due to the documentation provided which is inconsistent, I have to test via trial and error. There are even instances that state I need to use a "" after a switch! So how can I do this? Ideally I'd like to pass the entrire path, including the file I need to glob or I'd like to declare the result of the path with glob as a variable then concatenate with setup.exe and the arguements. That did not work, the error list can't be combined with string is returned. Basically anything that works, so far I've failed because of my inability to handle the filename that varies and the obscene amount of whitespaces and special characters in the arguements. The following link is related howevers does not include a clear answer for my specific question link text The response provided below does not answer the question nor does the link I provided, that's why I'm asking this question. I will rephrase in case I'm not understood. I have a file that I need to copy at random times. The file is prependedned with unique, unpredicatable number e.g. a build number. Note this is a windows system. For this example I will cite the same folder/file structure. The build server creates a build any time in a 4 hour range. The path to the build server folder is Z:\data\builds*.install\setup.exe Note the wildcard in the path. This means the folder name is prepended with a random(yes, random) string of 8 digits then a dot. then "install". So, the path at one time may be Z:\data\builds\12345678.install\setup.exe or it could be Z:\data\builds\66666666.install\setup.exe This is one, major portion of this problem. Note, I did not design this build numbering system. I've never seen anything like this my years as a QA engineer. So to deal with the first issue I plan on using a glob. import glob import os dirname = "Z:\\data\\builds\\*.install" filespec = "setup.exe" instlpath = glob.glob (os.path.join (dirname, filespec)) print instlpath # this is the test,printsthe accurate path to launch an install, problem #is I have to add arguements OK so I thought I could use path that I defined as instlpath, concatnenate it and execute. when it try and use prinnt to test print instlpath + [" /S /z" ] I get ['Z:\builds\install\12343333.install\setup.exe', ' /S /z'] I need Z:\builds\install\12343333.install\setup.exe /S /z" #yes, I need the whitespace as #well and amy also need a z"" Why are all of the installs called setup.exe and not uniquely named? No freaking idea! Thank You, Surfdork A: The related question you linked to does contain a relatively clear answer to your problem: import subprocess subprocess.call(['z:/zzinstall/35115.install/setup.exe', '/S', '/z', '']) So you don't need to concatenate the path of setup.exe and its arguments. The arguments you specify in the list are passed directly to the program and not processed by the shell. For an empty string, which would be "" in a shell command, use an empty python string. See also http://docs.python.org/library/subprocess.html#subprocess.call
how to launch an exe with a variable path, special characters and arguements
I want to copy an installer file from a location where one of the folder names changes as per the build number This works for defining the path where the last folder name changes import glob import os dirname = "z:\\zzinstall\\*.install" filespec = "setup.exe" print glob.glob (os.path.join (dirname, filespec)) # the print is how I'm verifying the path is correct ['z:\\zzinstall\\35115.install\\setup.exe' The problem I have is that I can't get the setup.exe to launch due to the arguments needed I need to launch setup.exe with, for example setup.exe /S /z" There are numerous other arguments that need to be passed with double quotes, slashes and whitespaces. Due to the documentation provided which is inconsistent, I have to test via trial and error. There are even instances that state I need to use a "" after a switch! So how can I do this? Ideally I'd like to pass the entrire path, including the file I need to glob or I'd like to declare the result of the path with glob as a variable then concatenate with setup.exe and the arguements. That did not work, the error list can't be combined with string is returned. Basically anything that works, so far I've failed because of my inability to handle the filename that varies and the obscene amount of whitespaces and special characters in the arguements. The following link is related howevers does not include a clear answer for my specific question link text The response provided below does not answer the question nor does the link I provided, that's why I'm asking this question. I will rephrase in case I'm not understood. I have a file that I need to copy at random times. The file is prependedned with unique, unpredicatable number e.g. a build number. Note this is a windows system. For this example I will cite the same folder/file structure. The build server creates a build any time in a 4 hour range. The path to the build server folder is Z:\data\builds*.install\setup.exe Note the wildcard in the path. This means the folder name is prepended with a random(yes, random) string of 8 digits then a dot. then "install". So, the path at one time may be Z:\data\builds\12345678.install\setup.exe or it could be Z:\data\builds\66666666.install\setup.exe This is one, major portion of this problem. Note, I did not design this build numbering system. I've never seen anything like this my years as a QA engineer. So to deal with the first issue I plan on using a glob. import glob import os dirname = "Z:\\data\\builds\\*.install" filespec = "setup.exe" instlpath = glob.glob (os.path.join (dirname, filespec)) print instlpath # this is the test,printsthe accurate path to launch an install, problem #is I have to add arguements OK so I thought I could use path that I defined as instlpath, concatnenate it and execute. when it try and use prinnt to test print instlpath + [" /S /z" ] I get ['Z:\builds\install\12343333.install\setup.exe', ' /S /z'] I need Z:\builds\install\12343333.install\setup.exe /S /z" #yes, I need the whitespace as #well and amy also need a z"" Why are all of the installs called setup.exe and not uniquely named? No freaking idea! Thank You, Surfdork
[ "The related question you linked to does contain a relatively clear answer to your problem:\nimport subprocess\nsubprocess.call(['z:/zzinstall/35115.install/setup.exe', '/S', '/z', ''])\n\nSo you don't need to concatenate the path of setup.exe and its arguments. The arguments you specify in the list are passed dire...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003950338_python.txt
Q: How do you embed album art into an MP3 using Python? I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file. A: Here is how to add example.png as album cover into example.mp3 with mutagen: from mutagen.mp3 import MP3 from mutagen.id3 import ID3, APIC, error audio = MP3('example.mp3', ID3=ID3) # add ID3 tag if it doesn't exist try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/png', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=open('example.png').read() ) ) audio.save() A: I've used the eyeD3 module to do this exact thing. def update_id3(mp3_file_name, artwork_file_name, artist, item_title): #edit the ID3 tag to add the title, artist, artwork, date, and genre tag = eyeD3.Tag() tag.link(mp3_file_name) tag.setVersion([2,3,0]) tag.addImage(0x08, artwork_file_name) tag.setArtist(artist) tag.setDate(localtime().tm_year) tag.setTitle(item_title) tag.setGenre("Trance") tag.update() A: Looks like you have to add a special type of frame to the MP3. See the site on ID3 tags Also the tutorial for mutagen implies that you can add ID3 tags in mutagen see A: Possible solution Are you trying to embed images into a lot of files? If so, I found a script (see the link) that goes through a set of directories, looks for images, and the embeds them into MP3 files. This was useful for me when I wanted to actually have something to look at in CoverFlow on my (now defunct) iPhone. A: A nice small CLI tool which helped me a lot with checking what I did while developing id3 stuff is mid3v2 which is the mutagen version of id3v2. It comes bundled with the Python mutagen library. The source of this little tool gave me also lots of answers about how to use mutagen.
How do you embed album art into an MP3 using Python?
I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
[ "Here is how to add example.png as album cover into example.mp3 with mutagen:\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3, APIC, error\n\naudio = MP3('example.mp3', ID3=ID3)\n\n# add ID3 tag if it doesn't exist\ntry:\n audio.add_tags()\nexcept error:\n pass\n\naudio.tags.add(\n APIC(\n ...
[ 38, 13, 3, 1, 0 ]
[]
[]
[ "albumart", "id3", "metadata", "mp3", "python" ]
stackoverflow_0000409949_albumart_id3_metadata_mp3_python.txt
Q: Trouble with easy_install cheetah on WIndows Xp I have installed PyQT from this URL: http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7.7-1.exe I have Python 2.6 installed. My OS is Windows XP SP3. I entered this into cmd.exe: easy_install cheetah This is the output: C:\Documents and Settings\All Users>easy_install cheetah Searching for cheetah Best match: cheetah 2.4.3 Processing cheetah-2.4.3-py2.6.egg cheetah 2.4.3 is already the active version in easy-install.pth Installing cheetah-script.py script to C:\Python26\Scripts Installing cheetah.exe script to C:\Python26\Scripts Installing cheetah.exe.manifest script to C:\Python26\Scripts Installing cheetah-compile-script.py script to C:\Python26\Scripts Installing cheetah-compile.exe script to C:\Python26\Scripts Installing cheetah-compile.exe.manifest script to C:\Python26\Scripts Using c:\python26\lib\site-packages\cheetah-2.4.3-py2.6.egg Processing dependencies for cheetah Searching for Markdown>=2.0.1 Reading http://pypi.python.org/simple/Markdown/ Reading http://www.freewisdom.org/projects/python-markdown/ Reading http://www.freewisdom.org/projects/python-markdown Reading https://sourceforge.net/project/showfiles.php?group_id=153041 Best match: Markdown 2.0.3 Downloading http://sourceforge.net/projects/python-markdown/files/markdown/2.0.3 /Markdown-2.0.3.win32.exe/download Processing download error: Couldn't find a setup script in c:\docume~1\admini~1\locals~1\temp\easy_i nstall-awtoum\download C:\Documents and Settings\All Users> Any help? A: The error you're getting on 'awtoum' is probably for the Autumn-ORM, which you can probably install with the command easy_install autumn. Once you have that prerequisite working, you can give the Cheetah installation another try, and it should skip right on past the error if the Autumn-ORM is already installed. Alternately, you might have better luck installing via pip (which, perhaps ironically, you can install with the command easy_install pip). With pip, running pip install cheetah will try to get the latest version and all prerequisites/dependencies).
Trouble with easy_install cheetah on WIndows Xp
I have installed PyQT from this URL: http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7.7-1.exe I have Python 2.6 installed. My OS is Windows XP SP3. I entered this into cmd.exe: easy_install cheetah This is the output: C:\Documents and Settings\All Users>easy_install cheetah Searching for cheetah Best match: cheetah 2.4.3 Processing cheetah-2.4.3-py2.6.egg cheetah 2.4.3 is already the active version in easy-install.pth Installing cheetah-script.py script to C:\Python26\Scripts Installing cheetah.exe script to C:\Python26\Scripts Installing cheetah.exe.manifest script to C:\Python26\Scripts Installing cheetah-compile-script.py script to C:\Python26\Scripts Installing cheetah-compile.exe script to C:\Python26\Scripts Installing cheetah-compile.exe.manifest script to C:\Python26\Scripts Using c:\python26\lib\site-packages\cheetah-2.4.3-py2.6.egg Processing dependencies for cheetah Searching for Markdown>=2.0.1 Reading http://pypi.python.org/simple/Markdown/ Reading http://www.freewisdom.org/projects/python-markdown/ Reading http://www.freewisdom.org/projects/python-markdown Reading https://sourceforge.net/project/showfiles.php?group_id=153041 Best match: Markdown 2.0.3 Downloading http://sourceforge.net/projects/python-markdown/files/markdown/2.0.3 /Markdown-2.0.3.win32.exe/download Processing download error: Couldn't find a setup script in c:\docume~1\admini~1\locals~1\temp\easy_i nstall-awtoum\download C:\Documents and Settings\All Users> Any help?
[ "The error you're getting on 'awtoum' is probably for the Autumn-ORM, which you can probably install with the command easy_install autumn. Once you have that prerequisite working, you can give the Cheetah installation another try, and it should skip right on past the error if the Autumn-ORM is already installed.\nA...
[ 2 ]
[]
[]
[ "cheetah", "python" ]
stackoverflow_0003949532_cheetah_python.txt
Q: Simple python regex groups can't parse date I'm trying to parse dates with regex, using groups, but python is returning empty lists. I'm not doing anything fancy, just 12/25/10 sort of stuff. I want it to reject 12/25-10 though. date = re.compile("\d{1,2}([/.-])\d{1,2}\1\d{2}") I've tried online regex libraries, but their solutions don't seem to run either. Any ideas? Sample input: "Hello today is 10/18/10, and the time is 10:50am" Hopeful output: "10/18/10" I'm running Python 2.5. A: Use a raw string: date = re.compile(r"\d{1,2}([/.-])\d{1,2}\1\d{2}") Otherwise, the \1 in the string literal is interpreted as the character 1 (Start of Heading). EDIT: To add groups for the date components, use: re.compile(r"(\d{1,2})([/.-])(\d{1,2})\2(\d{2})") A: You should use Python's builtin strptime. A: No doubt overkill, but the "parsedatetime" library has been working for me: http://code.google.com/p/parsedatetime/ It does use regexes internally, but does a lot more than parse MM/DD/YY formats.
Simple python regex groups can't parse date
I'm trying to parse dates with regex, using groups, but python is returning empty lists. I'm not doing anything fancy, just 12/25/10 sort of stuff. I want it to reject 12/25-10 though. date = re.compile("\d{1,2}([/.-])\d{1,2}\1\d{2}") I've tried online regex libraries, but their solutions don't seem to run either. Any ideas? Sample input: "Hello today is 10/18/10, and the time is 10:50am" Hopeful output: "10/18/10" I'm running Python 2.5.
[ "Use a raw string:\ndate = re.compile(r\"\\d{1,2}([/.-])\\d{1,2}\\1\\d{2}\")\n\nOtherwise, the \\1 in the string literal is interpreted as the character 1 (Start of Heading).\nEDIT: To add groups for the date components, use:\nre.compile(r\"(\\d{1,2})([/.-])(\\d{1,2})\\2(\\d{2})\")\n\n", "You should use Python's ...
[ 5, 5, 2 ]
[]
[]
[ "python", "python_2.x", "regex", "regex_group" ]
stackoverflow_0003951971_python_python_2.x_regex_regex_group.txt
Q: Is there a more Pythonic approach to this? This is my first python script, be ye warned. I pieced this together from Dive Into Python, and it works great. However since it is my first Python script I would appreciate any tips on how it can be made better or approaches that may better embrace the Python way of programming. import os import shutil def getSourceDirectory(): """Get the starting source path of folders/files to backup""" return "/Users/robert/Music/iTunes/iTunes Media/" def getDestinationDirectory(): """Get the starting destination path for backup""" return "/Users/robert/Desktop/Backup/" def walkDirectory(source, destination): """Walk the path and iterate directories and files""" sourceList = [os.path.normcase(f) for f in os.listdir(source)] destinationList = [os.path.normcase(f) for f in os.listdir(destination)] for f in sourceList: sourceItem = os.path.join(source, f) destinationItem = os.path.join(destination, f) if os.path.isfile(sourceItem): """ignore system files""" if f.startswith("."): continue if not f in destinationList: "Copying file: " + f shutil.copyfile(sourceItem, destinationItem) elif os.path.isdir(sourceItem): if not f in destinationList: print "Creating dir: " + f os.makedirs(destinationItem) walkDirectory(sourceItem, destinationItem) """Make sure starting destination path exists""" source = getSourceDirectory() destination = getDestinationDirectory() if not os.path.exists(destination): os.makedirs(destination) walkDirectory(source, destination) A: As others mentioned, you probably want to use walk from the built-in os module. Also, consider using PEP 8 compatible style (no camel-case but this_stye_of_function_naming()). Wrapping directly executable code (i.e. no library/module) into a if __name__ == '__main__': ... block is also a good practice. A: The code has no docstring describing what it does re-invents the "battery" of shutil.copytree has a function called walkDirectory which doesn't do what its name implies contains get* functions that provide no utility those get functions embed high-level arguments deeper than they ought is obligatorily chatty (print whether you want it or not) A: Use os.path.walk. It does most all the bookkeeping for you; you then just feed a visitor function to it to do what you need. Or, oh damn, looks like os.path.walk has been deprecated. Use os.walk then, and you get for r, d, f in os.walk('/root/path') for file in f: # do something good. A: I recommend using os.walk. It does what it looks like you're doing. It offers a nice interface that's easy to utilize to do whatever you need. A: The main thing to make things more Pythonic is to adopt Python's PEP8, the style guide. It uses underscore for functions.1 If you're returning a fixed string, e.g. your get* functions, a variable is probably a better approach. By this, I mean replace your getSourceDirectory with something like this: source_directory = "/Users/robert/Music/iTunes/iTunes Media/" Adding the following conditional will mean that code that is specific for running the module as a program does not get called when the module is imported. if __name__ == '__main__': source = getSourceDirectory() destination = getDestinationDirectory() if not os.path.exists(destination): os.makedirs(destination) walkDirectory(source, destination) I would use a try & except block, rather than a conditional to test if walkDirectory can operate successfully. Weird things can happen with multiple processes & filesystems: try: walkDirectory(source, destination) except IOError: os.makedirs(destination) walkDirectory(source, destination) 1 I've left out discussion about whether to use the standard library. At this stage of your Python journey, I think you're just after a feel how the language should be used in general terms. I don't think knowing the details of os.walk is really that important right now.
Is there a more Pythonic approach to this?
This is my first python script, be ye warned. I pieced this together from Dive Into Python, and it works great. However since it is my first Python script I would appreciate any tips on how it can be made better or approaches that may better embrace the Python way of programming. import os import shutil def getSourceDirectory(): """Get the starting source path of folders/files to backup""" return "/Users/robert/Music/iTunes/iTunes Media/" def getDestinationDirectory(): """Get the starting destination path for backup""" return "/Users/robert/Desktop/Backup/" def walkDirectory(source, destination): """Walk the path and iterate directories and files""" sourceList = [os.path.normcase(f) for f in os.listdir(source)] destinationList = [os.path.normcase(f) for f in os.listdir(destination)] for f in sourceList: sourceItem = os.path.join(source, f) destinationItem = os.path.join(destination, f) if os.path.isfile(sourceItem): """ignore system files""" if f.startswith("."): continue if not f in destinationList: "Copying file: " + f shutil.copyfile(sourceItem, destinationItem) elif os.path.isdir(sourceItem): if not f in destinationList: print "Creating dir: " + f os.makedirs(destinationItem) walkDirectory(sourceItem, destinationItem) """Make sure starting destination path exists""" source = getSourceDirectory() destination = getDestinationDirectory() if not os.path.exists(destination): os.makedirs(destination) walkDirectory(source, destination)
[ "As others mentioned, you probably want to use walk from the built-in os module. Also, consider using PEP 8 compatible style (no camel-case but this_stye_of_function_naming()). Wrapping directly executable code (i.e. no library/module) into a if __name__ == '__main__': ... block is also a good practice.\n", "Th...
[ 6, 4, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003951780_python.txt
Q: Python Range Class/Subclass I have code for a Range class like this: class Range: def __init__(self, start, end): self.setStart(start) self.setEnd(end) def getStart(self): return self.start def setStart(self, s): self.start = s def getEnd(self): return self.end def setEnd(self, e): self.end = e def getLength(self): return len(range(self.start, self.end)) def overlaps(self, r): if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \ (self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \ (self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \ (r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()): return True else: return False My assignment is to create a subclass of Range, called DNAFeature, that represents a Range that also has a strand and a sequence name: Implement setStrand and getStrand, which set and return strand information, and setSeqName and getSeqName, which set or return the name of the sequence the feature belongs to. If a feature is on the minus (reverse) strand, getStrand() should return ‐1. If a feature is on the plus strand, getStrand() should return 1. If strand is not set, getStrand() should return 0. I have tried to write something but doesn't look right at all for me, can everyone please help me with this, thank you so much guys, this is my code: class DNAFeature(Range): def __init__(self, strand, sequence): self.setStrand(strand) self.setSeqName(sequence) def getSeqName(self): return self.plus or minus def setSeqName(self, seq): self.sequence = seq def getStrand(self): if self.getSeqName(self.strand) == 'plus': return 1 if self.getSeqName(self.strand) == 'minus': return -1 else: return 0 def setStrand(self, strand): self.strand = strand A: In general it is much easier to answer questions if you provide a specific error message or thing that is going wrong. Here's what happened when I tried to run the above: First up: `SyntaxError: invalid syntax` on if seq == POSITIVE. What's wrong here? Oh yes, you're missing a colon after the conditional. If you add that the file at least parses. So let's try doing some coding: # Your code here, then: feature = DNAFeature() Running that gives: TypeError: __init__() takes exactly 3 positional arguments (1 given) Oh, OK, we need to pass some arguments to the initialiser of DNAFeature. Let's put this on the + strand, and call it foo: feature = DNAFeature(1, "foo") Now we get: AttributeError: 'DNAFeature' object has no attribute 'setStrand' What's that about? OK, you haven't defined setStrand. (Note: you shouldn't have to. But more on that later.) Let's define it: def setStrand(self, strand): self.strand = strand I don't want to go through the rest of the problems with the code (hint: you need to define variables before you use them), but this is the sort of thing you should be doing. Right, something different. The above is bad code. I hope you've written the Range class and that it hasn't been provided as part of the course, because if it has you're taking a badly-taught course. The main problem is the use of getters and setters -- I'm guessing you're Java-born and bred? In Python you don't need to write getters and setters for everything, because you can always add them in later if you need them. Instead, just use class attributes. Look at the following code for Range: class Range: def __init__(self, start, end): self.start = start self.end = end def length(self): return self.end - self.start def overlaps(self, other): return not(self.end < other.start or other.end < self.start) Isn't that much nicer? No more nasty accessors, no icky comparisons in the overlaps method... It helps if you work out the logic that your code is trying to implement before you implement it. See if you can write a better DNAFeature now. You still haven't told me what getStrand should, do, but here's what I think you're aiming towards. Suppose the strand name that gets passed to __init__ is of the form "+name" or "-name". You can then do the following: def __init__(self, strand): sequence = strand[0] #first character of strand if sequence == "+": self.strand = 1 self.sequence= strand[1:] elif sequence == "-": self.strand = -1 self.sequence = strand[1:] else: self.strand = 0 self.sequence = strand See if you can work out how that works. A: In the most generic case (without making any assumptions), it seems that this is what you need: class DNAFeature(Range): def __init__(self, start, end): self.setStart(start) self.setEnd(end) self.strand = None self.sequencename = None def setStrand(self, s): self.strand = s def getStrand(self): if self.sequenceName == 'plus': return 1 elif self.sequenceName == 'minus': return -1 else: return 0 def setSequenceName(self, s): self.sequencename = s def getSequenceName(self, s): return self.sequenceName You will notice that here, I have redefined init. There is a reason for this. I remember that in one of your earlier questions, you had mentioned that this was a Java assignment, just renamed to python. In Java, constructors are not inherited (correct me if I'm wrong). Therefore, if the same grading rubric is being used, you will lose marks for not redefining the constructor here. Hope this helps
Python Range Class/Subclass
I have code for a Range class like this: class Range: def __init__(self, start, end): self.setStart(start) self.setEnd(end) def getStart(self): return self.start def setStart(self, s): self.start = s def getEnd(self): return self.end def setEnd(self, e): self.end = e def getLength(self): return len(range(self.start, self.end)) def overlaps(self, r): if (r.getStart() < self.getEnd() and r.getEnd() >= self.getEnd()) or \ (self.getStart() < r.getEnd() and self.getEnd() >= r.getEnd()) or \ (self.getStart() >= r.getStart() and self.getEnd() <= r.getEnd()) or \ (r.getStart() >= self.getStart() and r.getEnd() <= self.getEnd()): return True else: return False My assignment is to create a subclass of Range, called DNAFeature, that represents a Range that also has a strand and a sequence name: Implement setStrand and getStrand, which set and return strand information, and setSeqName and getSeqName, which set or return the name of the sequence the feature belongs to. If a feature is on the minus (reverse) strand, getStrand() should return ‐1. If a feature is on the plus strand, getStrand() should return 1. If strand is not set, getStrand() should return 0. I have tried to write something but doesn't look right at all for me, can everyone please help me with this, thank you so much guys, this is my code: class DNAFeature(Range): def __init__(self, strand, sequence): self.setStrand(strand) self.setSeqName(sequence) def getSeqName(self): return self.plus or minus def setSeqName(self, seq): self.sequence = seq def getStrand(self): if self.getSeqName(self.strand) == 'plus': return 1 if self.getSeqName(self.strand) == 'minus': return -1 else: return 0 def setStrand(self, strand): self.strand = strand
[ "In general it is much easier to answer questions if you provide a specific error message or thing that is going wrong. Here's what happened when I tried to run the above:\n\nFirst up:\n`SyntaxError: invalid syntax` \n\non if seq == POSITIVE. What's wrong here? Oh yes, you're missing a colon after the conditional. ...
[ 4, 0 ]
[]
[]
[ "python", "subclass" ]
stackoverflow_0003909733_python_subclass.txt
Q: How do I use ReverseProxyProtocol I have the following: My webserver running on twisted My comet server, aka orbited Note that 1 and 2 are different processes. Basically, I want 1 and 2 to share the same port. Request that are http://mysite.com/a/b/c should go to the webserver and anything starting with http://mysite.com/orbited/ should go to the orbited server, i.e. (http://mysite.com/orbited/a/b/c => do a request to http://mysite.com:12345/a/b/c and return that). This is what I have right now: # Reverse Proxy class OrbitedResource(Resource): isLeaf = True def __init__(self, orbited_url='http://127.0.0.1:12345'): self.orbited = orbited_url Resource.__init__(self) def render_GET(self, request): def callback(html): request.write(html) request.finish() def errback(failure, *args): request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write(failure.getErrorMessage()) request.finish() request.setHeader('Connection', 'close') # TODO find cleaner way to do this: # Currently request.uri is "/orbited/....", you must trim it target_uri = request.uri.replace('/orbited', '') final_uri = self.orbited + target_uri print "final_uri is", final_uri deferred = getPage(final_uri) deferred.addCallbacks(callback, errback) return server.NOT_DONE_YET class SimpleRoutingResource(Resource): isLeaf = False def __init__(self, wsgiApp): Resource.__init__(self) self.WSGIApp = wsgiApp self.orbitedResource = OrbitedResource() def getChild(self, name, request): if name == "orbited": request.prepath.pop() print "Simple request.path is", request.path return self.orbitedResource else: request.prepath.pop() request.postpath.insert(0,name) return self.WSGIApp # Attaching proxy + django log_dir = './.log' if not os.path.exists(log_dir): os.makedirs(log_dir) reactor.listenTCP(DJANGO_PORT, server.Site(SimpleRoutingResource(WSGIRoot), logPath=os.path.join(log_dir, '.django.log'))) Currently this works . However, I see that there's a class called ReverseProxyProtocol, and I have been doing tried it with the following modification: class SimpleRoutingResource(Resource): isLeaf = False def __init__(self, wsgiApp): Resource.__init__(self) self.WSGIApp = wsgiApp def getChild(self, name, request): if name == "orbited": request.prepath.pop() print "Simple request.path is", request.path, name return ReverseProxyResource( 'http://localhost', 12345, name ) else: request.prepath.pop() request.postpath.insert(0,name) return self.WSGIApp This is NOT Working. I have inserted a lot of prints into the twisted's reverseProxyResource class, and I discovered the following: Given http://mysite.com/orbited/a/b/c OrbitedResource will keep calling ReverseProxyResource with getChild until c by the time you get to c, the url is messed up and the client class calling the orbited server will be wrong I tried setting isLeaf = True in the ReverseProxyResource, but to no avail. Anybody can point me a more effecient way to write the getPage? Do I really need to use ReverseProxyResource if it's such a black box in nature? A: The cleanest way is to put something like nginx in front of both servers.
How do I use ReverseProxyProtocol
I have the following: My webserver running on twisted My comet server, aka orbited Note that 1 and 2 are different processes. Basically, I want 1 and 2 to share the same port. Request that are http://mysite.com/a/b/c should go to the webserver and anything starting with http://mysite.com/orbited/ should go to the orbited server, i.e. (http://mysite.com/orbited/a/b/c => do a request to http://mysite.com:12345/a/b/c and return that). This is what I have right now: # Reverse Proxy class OrbitedResource(Resource): isLeaf = True def __init__(self, orbited_url='http://127.0.0.1:12345'): self.orbited = orbited_url Resource.__init__(self) def render_GET(self, request): def callback(html): request.write(html) request.finish() def errback(failure, *args): request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write(failure.getErrorMessage()) request.finish() request.setHeader('Connection', 'close') # TODO find cleaner way to do this: # Currently request.uri is "/orbited/....", you must trim it target_uri = request.uri.replace('/orbited', '') final_uri = self.orbited + target_uri print "final_uri is", final_uri deferred = getPage(final_uri) deferred.addCallbacks(callback, errback) return server.NOT_DONE_YET class SimpleRoutingResource(Resource): isLeaf = False def __init__(self, wsgiApp): Resource.__init__(self) self.WSGIApp = wsgiApp self.orbitedResource = OrbitedResource() def getChild(self, name, request): if name == "orbited": request.prepath.pop() print "Simple request.path is", request.path return self.orbitedResource else: request.prepath.pop() request.postpath.insert(0,name) return self.WSGIApp # Attaching proxy + django log_dir = './.log' if not os.path.exists(log_dir): os.makedirs(log_dir) reactor.listenTCP(DJANGO_PORT, server.Site(SimpleRoutingResource(WSGIRoot), logPath=os.path.join(log_dir, '.django.log'))) Currently this works . However, I see that there's a class called ReverseProxyProtocol, and I have been doing tried it with the following modification: class SimpleRoutingResource(Resource): isLeaf = False def __init__(self, wsgiApp): Resource.__init__(self) self.WSGIApp = wsgiApp def getChild(self, name, request): if name == "orbited": request.prepath.pop() print "Simple request.path is", request.path, name return ReverseProxyResource( 'http://localhost', 12345, name ) else: request.prepath.pop() request.postpath.insert(0,name) return self.WSGIApp This is NOT Working. I have inserted a lot of prints into the twisted's reverseProxyResource class, and I discovered the following: Given http://mysite.com/orbited/a/b/c OrbitedResource will keep calling ReverseProxyResource with getChild until c by the time you get to c, the url is messed up and the client class calling the orbited server will be wrong I tried setting isLeaf = True in the ReverseProxyResource, but to no avail. Anybody can point me a more effecient way to write the getPage? Do I really need to use ReverseProxyResource if it's such a black box in nature?
[ "The cleanest way is to put something like nginx in front of both servers.\n" ]
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003952487_python_twisted.txt
Q: python and sqlite - escape input Using python with a sqlite DB - whats the method used for escaping the data going out and pulling the data coming out? Using pysqlite2 Google has conflicting suggestions. A: Use the second parameter args to pass arguments; don't do the escaping yourself. Not only is this easier, it also helps prevent SQL injection attacks. cursor.execute(sql,args) for example, cursor.execute('INSERT INTO foo VALUES (?, ?)', ("It's okay", "No escaping necessary") )
python and sqlite - escape input
Using python with a sqlite DB - whats the method used for escaping the data going out and pulling the data coming out? Using pysqlite2 Google has conflicting suggestions.
[ "Use the second parameter args to pass arguments; don't do the escaping yourself. Not only is this easier, it also helps prevent SQL injection attacks.\ncursor.execute(sql,args)\n\nfor example,\ncursor.execute('INSERT INTO foo VALUES (?, ?)', (\"It's okay\", \"No escaping necessary\") )\n\n" ]
[ 23 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0003952543_pysqlite_python_sqlite.txt
Q: PyQt4: AttributeError: 'QLineEdit' object has no attribute 'setPlaceholderText' I have a QLineEdit, and I want to set a placeholder text. When I call setPlaceholderText(string) I get an AttributeError, but: >>> from PyQt4 import QtCore >>> QtCore.PYQT_VERSION_STR '4.7.4' >>> QtCore.QT_VERSION_STR '4.7.0' and from the QAssistant: This property holds the line edit's placeholder text. ... This property was introduced in Qt 4.7. A: I would guess that although the libraries are very recent, the bindings are simply not that up to date. You might want to check out PySide - a Nokia project with (IMO) fewer license issues than PyQt.
PyQt4: AttributeError: 'QLineEdit' object has no attribute 'setPlaceholderText'
I have a QLineEdit, and I want to set a placeholder text. When I call setPlaceholderText(string) I get an AttributeError, but: >>> from PyQt4 import QtCore >>> QtCore.PYQT_VERSION_STR '4.7.4' >>> QtCore.QT_VERSION_STR '4.7.0' and from the QAssistant: This property holds the line edit's placeholder text. ... This property was introduced in Qt 4.7.
[ "I would guess that although the libraries are very recent, the bindings are simply not that up to date.\nYou might want to check out PySide - a Nokia project with (IMO) fewer license issues than PyQt.\n" ]
[ 3 ]
[]
[]
[ "pyqt4", "python", "qlineedit" ]
stackoverflow_0003952850_pyqt4_python_qlineedit.txt
Q: Issues with implementing a network server with SocketServer I am beginner in socket programming and need your help. I have implemented simple echo server using ThreadedTCPServer example from the Python documentation. It works fine, but I have the following problems: Server hangs (in socket.recv) when Client tries to send zero-length data. Server hangs (in socket.recv) when the data sent by Client is multiple of BUF_SIZE. I don't know the right way to stop the server from the outside. I'd like to have a script, for example, stopServer.py which can be started from the server's host when need to stop the server. I've implemented "STOP" command which is send to the server's port. This approach looks good for me, but has security risk. Note that I need a cross-platform solution. So, probably, signals are not suitable. I will appreciate if you have any ideas how to fix the issues listed above. The example's code is listed below. Have a nice day! Zakhar client.py import sys import socket from common import recv if len (sys.argv) == 1 : print "The file to be sent is not specified" sys.exit (1) fname = sys.argv [1] print "Reading '%s' file..." % fname, f = open (sys.argv [1]) msg = f.read () f.close() print "OK" if len (msg) == 0 : print "Nothing to send. Exit." sys.exit (0) print "Client is sending:" print msg print "len (msg)=%d" % len (msg) sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) sock.connect ( ('localhost', 9997) ) sock.sendall (msg) print "Sending has been finished" print "Waiting for response..." response = recv (sock) print "Client received:" print response print "len (response)=%d\n" % len (response) sock.close () server.py import threading import SocketServer from common import recv class ThreadedTCPRequestHandler (SocketServer.BaseRequestHandler): def handle(self) : recvData = recv (self.request) print "NEW MSG RECEIVED from %s" % self.client_address [0] print "Data:" print recvData print "dataSize=%d" % len (recvData) if recvData == "!!!exit!!!" : print 'Server has received exit command. Exit.' self.server.shutdown() else : curThread = threading.currentThread () response = "%s: %s" % (curThread.getName (), recvData) self.request.sendall (response) class ThreadedTCPServer (SocketServer.ThreadingMixIn, SocketServer.TCPServer) : pass if __name__ == "__main__": HOST, PORT = "localhost", 9997 server = ThreadedTCPServer ((HOST, PORT), ThreadedTCPRequestHandler) server.serve_forever () common.py ''' Common code for both: client and server. ''' def recv (sock) : ''' Reads data from the specified socket and returns them to the caller. IMPORTANT: This method hangs in socket.recv () in the following situations (at least on Windows): 1. If client sends zero-length data. 2. If data sent by client is multiple of BUF_SIZE. ''' BUF_SIZE = 4096 recvData = "" while 1 : buf = sock.recv (BUF_SIZE) if not buf : break recvData += buf if len (buf) < BUF_SIZE : # all data have been read break return recvData A: I don't know python but I will try and answer based on my socket programming knowledge. A zero byte message will NOT cause "sock.recv" to come out. Refer here for an explanation. If sock.recv returns with length 0, it is an indication that the other side has disconnected the TCP connection. if len (buf) < BUF_SIZE How does this line determine that ALL data has been read. TCP recv call is not a 1-1 mapping between TCP send call i.e. what client sends in 1 send call can be received in multiple recv calls. When you send multiple of BUF_SIZE i.e lets say 2 * BUF_SIZE, it is possible that you might receive all of it in one go. At that point, your server would hang as len(buf) > BUF_SIZE and you would get stuck in sock.recv. Try & figure out how to use non-blocking sockets. A: After some experiments I found the following: Need to rename common.recv to common.recvall Need to comment the following 2 lines in common.recv (bug): if len (buf) < BUF_SIZE : # all data have been read break This example will work only if the data sent to the server can be read by 1 socket.recv call on the server side. So, the sent data must be less than BUF_SIZE. Otherwise, the client and server are in deadlock, both in their sock.recv call. This occurs because of the concurrent access to the shared resource (socket). To solve this the client must listen for reply on different port.
Issues with implementing a network server with SocketServer
I am beginner in socket programming and need your help. I have implemented simple echo server using ThreadedTCPServer example from the Python documentation. It works fine, but I have the following problems: Server hangs (in socket.recv) when Client tries to send zero-length data. Server hangs (in socket.recv) when the data sent by Client is multiple of BUF_SIZE. I don't know the right way to stop the server from the outside. I'd like to have a script, for example, stopServer.py which can be started from the server's host when need to stop the server. I've implemented "STOP" command which is send to the server's port. This approach looks good for me, but has security risk. Note that I need a cross-platform solution. So, probably, signals are not suitable. I will appreciate if you have any ideas how to fix the issues listed above. The example's code is listed below. Have a nice day! Zakhar client.py import sys import socket from common import recv if len (sys.argv) == 1 : print "The file to be sent is not specified" sys.exit (1) fname = sys.argv [1] print "Reading '%s' file..." % fname, f = open (sys.argv [1]) msg = f.read () f.close() print "OK" if len (msg) == 0 : print "Nothing to send. Exit." sys.exit (0) print "Client is sending:" print msg print "len (msg)=%d" % len (msg) sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) sock.connect ( ('localhost', 9997) ) sock.sendall (msg) print "Sending has been finished" print "Waiting for response..." response = recv (sock) print "Client received:" print response print "len (response)=%d\n" % len (response) sock.close () server.py import threading import SocketServer from common import recv class ThreadedTCPRequestHandler (SocketServer.BaseRequestHandler): def handle(self) : recvData = recv (self.request) print "NEW MSG RECEIVED from %s" % self.client_address [0] print "Data:" print recvData print "dataSize=%d" % len (recvData) if recvData == "!!!exit!!!" : print 'Server has received exit command. Exit.' self.server.shutdown() else : curThread = threading.currentThread () response = "%s: %s" % (curThread.getName (), recvData) self.request.sendall (response) class ThreadedTCPServer (SocketServer.ThreadingMixIn, SocketServer.TCPServer) : pass if __name__ == "__main__": HOST, PORT = "localhost", 9997 server = ThreadedTCPServer ((HOST, PORT), ThreadedTCPRequestHandler) server.serve_forever () common.py ''' Common code for both: client and server. ''' def recv (sock) : ''' Reads data from the specified socket and returns them to the caller. IMPORTANT: This method hangs in socket.recv () in the following situations (at least on Windows): 1. If client sends zero-length data. 2. If data sent by client is multiple of BUF_SIZE. ''' BUF_SIZE = 4096 recvData = "" while 1 : buf = sock.recv (BUF_SIZE) if not buf : break recvData += buf if len (buf) < BUF_SIZE : # all data have been read break return recvData
[ "I don't know python but I will try and answer based on my socket programming knowledge.\nA zero byte message will NOT cause \"sock.recv\" to come out. Refer here for an explanation. If sock.recv returns with length 0, it is an indication that the other side has disconnected the TCP connection.\nif len (buf) < BUF_...
[ 2, 0 ]
[]
[]
[ "python", "sockets", "socketserver" ]
stackoverflow_0003845885_python_sockets_socketserver.txt
Q: Regular expression match from right direction Normally, we use regular expression match from left to right direction. I want to know whether there is some switch that can be used to match from the right to left in python? Or is this feature embedded in any other language? e.g. abcd1_abcd2 If given regular expression abcd, it will match two abcd strings. What I want is to put the last match at first, thus matching in reverse direction. A: You can reverse the list as proposed by @SilentGhost: import re for s in reversed(re.findall('abcd.', 'abcd1_abcd2')): print s
Regular expression match from right direction
Normally, we use regular expression match from left to right direction. I want to know whether there is some switch that can be used to match from the right to left in python? Or is this feature embedded in any other language? e.g. abcd1_abcd2 If given regular expression abcd, it will match two abcd strings. What I want is to put the last match at first, thus matching in reverse direction.
[ "You can reverse the list as proposed by @SilentGhost:\nimport re\n\nfor s in reversed(re.findall('abcd.', 'abcd1_abcd2')):\n print s\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex", "reverse" ]
stackoverflow_0003953142_python_regex_reverse.txt
Q: Extra output none while printing an command line argument It's my day 1 of learning python. so it's a noob question for many of you. See the following code: #!/usr/bin/env python import sys def hello(name): name = name + '!!!!' print 'hello', name def main(): print hello(sys.argv[1]) if __name__ == '__main__': main() when I run it $ ./Python-1.py alice hello alice!!!! None Now, I have trouble understanding where this "None" came from? A: Count the number of print statements in your code. You'll see that you're printing "hello alice!!!" in the hello function, and printing the result of the hello function. Because the hello function doesn't return a value (which you'd do with the return statement), it ends up returning the object None. Your print inside the main function ends up printing None. A: Change your def main(): print hello(sys.argv[1]) to def main(): hello(sys.argv[1]) You are explicitly printing the return value from your hello method. Since you do not have a return value specified, it returns None which is what you see in the output.
Extra output none while printing an command line argument
It's my day 1 of learning python. so it's a noob question for many of you. See the following code: #!/usr/bin/env python import sys def hello(name): name = name + '!!!!' print 'hello', name def main(): print hello(sys.argv[1]) if __name__ == '__main__': main() when I run it $ ./Python-1.py alice hello alice!!!! None Now, I have trouble understanding where this "None" came from?
[ "Count the number of print statements in your code. You'll see that you're printing \"hello alice!!!\" in the hello function, and printing the result of the hello function. Because the hello function doesn't return a value (which you'd do with the return statement), it ends up returning the object None. Your print ...
[ 26, 6 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003953233_function_python.txt
Q: pymongo: a more efficient update I am trying to push some big files (around 4 million records) into a mongo instance. What I am basically trying to achieve is to update the existent data with the one from the files. The algorithm would look something like: rowHeaders = ('orderId', 'manufacturer', 'itemWeight') for row in dataFile: row = row.strip('\n').split('\t') row = dict(zip(rowHeaders, row)) mongoRow = mongoCollection.find({'orderId': 12344}) if mongoRow is not None: if mongoRow['itemWeight'] != row['itemWeight']: row['tsUpdated'] = time.time() else: row['tsUpdated'] = time.time() mongoCollection.update({'orderId': 12344}, row, upsert=True) So, update the whole row besides 'tsUpdated' if weights are the same, add a new row if the row is not in mongo or update the whole row including 'tsUpdated' ... this is the algorithm The question is: can this be done faster, easier and more efficient from mongo's point of view ? (eventually with some kind of bulk insert) A: Combine an unique index on orderId with an update query where you also check for a change in itemWeight. The unique index prevents an insert with only a modified timestamp if the orderId is already present and itemWeight is the same. mongoCollection.ensure_index('orderId', unique=True) mongoCollection.update({'orderId': row['orderId'], 'itemWeight': {'$ne': row['itemWeight']}}, row, upsert=True) My benchmark shows a 5-10x performance improvement against your algorithm (depending on the amount of inserts vs updates).
pymongo: a more efficient update
I am trying to push some big files (around 4 million records) into a mongo instance. What I am basically trying to achieve is to update the existent data with the one from the files. The algorithm would look something like: rowHeaders = ('orderId', 'manufacturer', 'itemWeight') for row in dataFile: row = row.strip('\n').split('\t') row = dict(zip(rowHeaders, row)) mongoRow = mongoCollection.find({'orderId': 12344}) if mongoRow is not None: if mongoRow['itemWeight'] != row['itemWeight']: row['tsUpdated'] = time.time() else: row['tsUpdated'] = time.time() mongoCollection.update({'orderId': 12344}, row, upsert=True) So, update the whole row besides 'tsUpdated' if weights are the same, add a new row if the row is not in mongo or update the whole row including 'tsUpdated' ... this is the algorithm The question is: can this be done faster, easier and more efficient from mongo's point of view ? (eventually with some kind of bulk insert)
[ "Combine an unique index on orderId with an update query where you also check for a change in itemWeight. The unique index prevents an insert with only a modified timestamp if the orderId is already present and itemWeight is the same.\nmongoCollection.ensure_index('orderId', unique=True)\nmongoCollection.update({'o...
[ 6 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0003815633_mongodb_pymongo_python.txt
Q: PyMongo: group with 2d geospatial index in conditions returns an error The error returned is: exception: manual matcher config not allowed Here's my code: cond = {'id': id, 'date': {'$gte': start_date}, 'date': {'$lte': end_date}, 'location': {'$within': {'$box': box }}} reduce = 'function(obj, prev) { prev.count++; }' rows = collection.group({'location': True}, cond, {'count': 0}, reduce) When I remove location from condition then it works fine. If I change the query to find it works fine too so it's a problem with group. What am I doing wrong? A: MongoDB currently (version 1.6.2) doesn't support geo queries for mapreduce and group functions. See http://jira.mongodb.org/browse/SERVER-1742 for the issue ticket (and consider voting it up).
PyMongo: group with 2d geospatial index in conditions returns an error
The error returned is: exception: manual matcher config not allowed Here's my code: cond = {'id': id, 'date': {'$gte': start_date}, 'date': {'$lte': end_date}, 'location': {'$within': {'$box': box }}} reduce = 'function(obj, prev) { prev.count++; }' rows = collection.group({'location': True}, cond, {'count': 0}, reduce) When I remove location from condition then it works fine. If I change the query to find it works fine too so it's a problem with group. What am I doing wrong?
[ "MongoDB currently (version 1.6.2) doesn't support geo queries for mapreduce and group functions. See http://jira.mongodb.org/browse/SERVER-1742 for the issue ticket (and consider voting it up).\n" ]
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0003841208_mongodb_pymongo_python.txt
Q: Cooperative multitasking using TPL We are porting modeling application, which uses IronPython scripts for custom actions in modeling process. The existing application executes each Python script in separate thread and uses cooperative model for this. Now we want to port it to TPL, but first we want to measure context switching . Basically, what we have right now: Tasks queue each Task from this queue executes one IronPython script Inside IronPython script we call for C# class method, which is synchronization point and should transfer Task (IronPython execution) to waiting state What we want to do: We want to make infinite loop, which will iterate through Tasks queue when we get one Task we try to execute it In PythonScript we want to call C# method and transfer this script to waiting state. but not remove it from the queue. On next iteration when we get another Task we check is it in the waiting state. if so we wake it up and try to execute. In each moment we should have only one active Task And finally we want to measure how many Task we could execute per second I don't really know is it something about cooperative multitasking? We are thinking about custom TaskScheduler, is it good approach? Or does someone know better solution? Thanks. Updated: Ok ,so for example, I have such code: public class CooperativeScheduler : TaskScheduler, IDisposable { private BlockingCollection<Task> _tasks; private Thread _thread; private Task _currentTask; public CooperativeScheduler() { this._tasks = new BlockingCollection<Task>(); this._thread = new Thread(() => { foreach (Task task in this._tasks.GetConsumingEnumerable()) { this._currentTask = task; TryExecuteTask(this._currentTask); } } ); this._thread.Name = "Cooperative scheduler thread"; this._thread.Start(); } public void SleepCurrentTask() { if (this._currentTask != null) { // what to do here? } } protected override IEnumerable<Task> GetScheduledTasks() { return this._tasks.ToArray<Task>(); } protected override void QueueTask(Task task) { // No long task this._tasks.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new NotImplementedException(); } public void Dispose() { this._tasks.CompleteAdding(); this._thread.Join(); } } Custom Task Scheduler, it has one _thread for Task execution and _currentTask field for running task, also it has SleepCurrentTask in this method I want to suspend current Task execution, but I don't know how. Client code is simple: CancellationTokenSource tokenSource = new CancellationTokenSource(); Application app = Application.Create(); Task task = Task.Factory.StartNew(() => { app.Scheduler.SleepCurrentTask(); }, tokenSource.Token, TaskCreationOptions.None, app.Scheduler); } Maybe someone has better ideas? A: It sounds like you'd be well served to use the producer/consumer pattern .NET 4 has built in to a few collections. Check out page 55 in this free PDF from Microsoft, Patterns of Parallel Programming
Cooperative multitasking using TPL
We are porting modeling application, which uses IronPython scripts for custom actions in modeling process. The existing application executes each Python script in separate thread and uses cooperative model for this. Now we want to port it to TPL, but first we want to measure context switching . Basically, what we have right now: Tasks queue each Task from this queue executes one IronPython script Inside IronPython script we call for C# class method, which is synchronization point and should transfer Task (IronPython execution) to waiting state What we want to do: We want to make infinite loop, which will iterate through Tasks queue when we get one Task we try to execute it In PythonScript we want to call C# method and transfer this script to waiting state. but not remove it from the queue. On next iteration when we get another Task we check is it in the waiting state. if so we wake it up and try to execute. In each moment we should have only one active Task And finally we want to measure how many Task we could execute per second I don't really know is it something about cooperative multitasking? We are thinking about custom TaskScheduler, is it good approach? Or does someone know better solution? Thanks. Updated: Ok ,so for example, I have such code: public class CooperativeScheduler : TaskScheduler, IDisposable { private BlockingCollection<Task> _tasks; private Thread _thread; private Task _currentTask; public CooperativeScheduler() { this._tasks = new BlockingCollection<Task>(); this._thread = new Thread(() => { foreach (Task task in this._tasks.GetConsumingEnumerable()) { this._currentTask = task; TryExecuteTask(this._currentTask); } } ); this._thread.Name = "Cooperative scheduler thread"; this._thread.Start(); } public void SleepCurrentTask() { if (this._currentTask != null) { // what to do here? } } protected override IEnumerable<Task> GetScheduledTasks() { return this._tasks.ToArray<Task>(); } protected override void QueueTask(Task task) { // No long task this._tasks.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new NotImplementedException(); } public void Dispose() { this._tasks.CompleteAdding(); this._thread.Join(); } } Custom Task Scheduler, it has one _thread for Task execution and _currentTask field for running task, also it has SleepCurrentTask in this method I want to suspend current Task execution, but I don't know how. Client code is simple: CancellationTokenSource tokenSource = new CancellationTokenSource(); Application app = Application.Create(); Task task = Task.Factory.StartNew(() => { app.Scheduler.SleepCurrentTask(); }, tokenSource.Token, TaskCreationOptions.None, app.Scheduler); } Maybe someone has better ideas?
[ "It sounds like you'd be well served to use the producer/consumer pattern .NET 4 has built in to a few collections.\nCheck out page 55 in this free PDF from Microsoft, Patterns of Parallel Programming\n" ]
[ 2 ]
[]
[]
[ "c#", "multithreading", "python", "scheduled_tasks", "task" ]
stackoverflow_0003921930_c#_multithreading_python_scheduled_tasks_task.txt
Q: Programming books in ePub format I purchased an iPad hoping to read books on it that've been aging on my desk for months, but it turned out that there're NO programming books available on iBookstore. Are there any (Python, PHP, jQuery) books available in ePub format? Conversion from pdf to epub is not an option because the formatting is lost in the process. Thanks A: You can buy all O'Reilly books straight off their website in ePub and many other formats. Should work fine on the iPad (don't have one myself). A: I found two free and good ePub programming books so far Structure and Interpretation of Computer Programs (SICP) ProGIT A: Manning has some programming books available in epub and mobi formats. A: Pragmatic Programmers (http://pragprog.com/) publish a variety of good to excellent programming books, all of which are available in ePub format from their website. You can purchase text, digital, or a mix (where digital is available in both epub and pdf format). That said, I'm afraid little of their content is towards python, php, or jquery. It's mostly ruby, ruby on rails, iphone/mac, and general programming issues and techniques. Still, the content is excellent. I would also repeat @Hagge's comment that OReilly has quite a bit available in ePub format, and they do cover the python, php, and (to a small extent) jquery topics. Dig around in the site at http://oreilly.com/ebooks/ for more details. A: Does it have to be ePub format? Here in Australia the iBookstore is basically completely bare, except for books out of copyright (The illiad, Bible etc) My understanding is that they are still negotiating with the publishers. The guy at the Apple store said to me, oh thats no problem, download the free Kindle app and just buy your books from Amazon, they have a much better range anyway. Would that work for you?
Programming books in ePub format
I purchased an iPad hoping to read books on it that've been aging on my desk for months, but it turned out that there're NO programming books available on iBookstore. Are there any (Python, PHP, jQuery) books available in ePub format? Conversion from pdf to epub is not an option because the formatting is lost in the process. Thanks
[ "You can buy all O'Reilly books straight off their website in ePub and many other formats. Should work fine on the iPad (don't have one myself).\n", "I found two free and good ePub programming books so far\n\nStructure and Interpretation of Computer Programs (SICP)\nProGIT\n\n", "Manning has some programming bo...
[ 13, 8, 5, 3, 0 ]
[]
[]
[ "epub", "jquery", "php", "python" ]
stackoverflow_0003278477_epub_jquery_php_python.txt
Q: What is PyObjC? I understand the concept of PyObjC, but can nowhere find any information on what exactly it is or how to get started with it. Is it like a converter, where youinput python files and get an objective c one? Or is it a library you can import to your objective c files which let's you write python in them? Or is it something else entirely? If anyone can give tips on how to approach it, an outline of how it works, or just some instructions on a hello world with it, I would be very grateful. A: It's a language binding, meaning it allows you to call ObjC code from Python and vice versa. You write wrapper modules in ObjC that can be linked into the Python interpreter (which is written in C) to give it access to ObjC functions (tutorial for this use case). Apparently, the entire Cocoa framework is already wrapped, so you can use that from Python with ease. Vice versa, it enables you to link the Python interpreter into your ObjC app and use it to execute Python code in your app (tutorial).
What is PyObjC?
I understand the concept of PyObjC, but can nowhere find any information on what exactly it is or how to get started with it. Is it like a converter, where youinput python files and get an objective c one? Or is it a library you can import to your objective c files which let's you write python in them? Or is it something else entirely? If anyone can give tips on how to approach it, an outline of how it works, or just some instructions on a hello world with it, I would be very grateful.
[ "It's a language binding, meaning it allows you to call ObjC code from Python and vice versa. You write wrapper modules in ObjC that can be linked into the Python interpreter (which is written in C) to give it access to ObjC functions (tutorial for this use case). Apparently, the entire Cocoa framework is already w...
[ 6 ]
[]
[]
[ "language_binding", "objective_c", "pyobjc", "python" ]
stackoverflow_0003953679_language_binding_objective_c_pyobjc_python.txt
Q: How to write a port scanner listening for 'ACK' in python? please can anyone help me with the port scanner program to scan ports on the IP address provided,for ACK. i want to know the technique used to scan for ACK & use multi-threading so please help me in that perspective. Thank you A: Just a heads-up - Windows XP SP2 and later disable raw sockets, so you won't be able to scan for TCP ACK messages specifically on Windows. Since an ACK message is the last message in establishing a TCP connection, you can implicitly detect the ACK message by attempting to establish a connection with a simple socket.connect call (if it connects, you've sent your ACK). If you want to see an example of a multithreaded port scanner that I wrote, see inet.py and scanner.py in jaraco.net. A: this is a multi-threaded port scanner i wrote http://appusajeev.wordpress.com/2009/08/13/optimized-port-scanner-with-threading/ theres no way to track ACKs though.
How to write a port scanner listening for 'ACK' in python?
please can anyone help me with the port scanner program to scan ports on the IP address provided,for ACK. i want to know the technique used to scan for ACK & use multi-threading so please help me in that perspective. Thank you
[ "Just a heads-up - Windows XP SP2 and later disable raw sockets, so you won't be able to scan for TCP ACK messages specifically on Windows. Since an ACK message is the last message in establishing a TCP connection, you can implicitly detect the ACK message by attempting to establish a connection with a simple socke...
[ 3, 1 ]
[]
[]
[ "multithreading", "port_scanning", "python", "sockets" ]
stackoverflow_0003952978_multithreading_port_scanning_python_sockets.txt
Q: Is XML parsing in PHP as fast as Python or other alternatives? So I have 16 GB worth of XML files to process (about 700 files total), and I already have a functional PHP script to do that (With XMLReader) but it's taking forever. I was wondering if parsing in Python would be faster (Python being the only other language I'm proficient in, I'm sure something in C would be faster). A: I think that both of them can rely over wrappers for fast C libraries (mostly libxml2) so there's shouldn't be too much difference in parsing per se. You could try if there are differences caused by overhead, then it depends what are you gonna do over that XML. Parsing it for what? A: There's actually three differing performance problems here: The time it takes to parse a file, which depends on the size of individual files. The time it takes to handle the files and directories in the filesystem, if there's a lot of them. Writing the data into your databases. Where you should look for performance improvements depends on which one of these is the biggest bottleneck. My guess is that the last one is the biggest problem because writes is almost always the slowest: writes can't be cached, they requires writing to disk and if the data is sorted it can take a considerable time to find the right spot to write it. You presume that the bottleneck is the first alternative, the XML parsing. If that is the case, changing language is not the first thing to do. Instead you should see if there's some sort of SAX parser for your language. SAX parsing is much faster and memory effective than DOM parsing. A: I can't tell you for sure if Python will end up performing better than PHP (because I'm not terribly familiar with the performance characteristics of PHP). I can, however, give you a few suggestions. If there's a huge difference between your understanding of Python and PHP (i.e. you know way more PHP than Python, stick with PHP. The worst thing for performance in any language is a lack of mastery. If you want to implement a Python solution, there's a lot in the library to work with, and depending on what you're looking for, you can find it here. Write a Python script to process the XML, and then use it on one item. Compare that script's running time to the PHP script. If the Python script is much faster and you have faith that it is bugfree, use Python. Also, if you have some knowledge of C, in Python you can identify bottlenecks in the code and easily reimplement them in C (though I suspect you won't have a chance to do this).
Is XML parsing in PHP as fast as Python or other alternatives?
So I have 16 GB worth of XML files to process (about 700 files total), and I already have a functional PHP script to do that (With XMLReader) but it's taking forever. I was wondering if parsing in Python would be faster (Python being the only other language I'm proficient in, I'm sure something in C would be faster).
[ "I think that both of them can rely over wrappers for fast C libraries (mostly libxml2) so there's shouldn't be too much difference in parsing per se.\nYou could try if there are differences caused by overhead, then it depends what are you gonna do over that XML. Parsing it for what?\n", "There's actually three d...
[ 2, 2, 1 ]
[]
[]
[ "php", "python", "xml" ]
stackoverflow_0003953563_php_python_xml.txt
Q: recursively downloading files from webpage http://examples.oreilly.com/9780735615366/ I actually want to be able to have all these files in my disk. as u can see there are many folders each with different type of files. and u cannot download "the-folder" directly...only individual files ~ is there any way to automate process..? I will need regular expressions on urls to arrange them in a "folder" like hierarchy. what do I use...some scripting language like python? A: Take a look at wget tool. It can do exactly what you want. A: wget (GNU command line tool) will do this for you. The documentation for what you want to do is here: http://www.gnu.org/software/wget/manual/html_node/Recursive-Retrieval-Options.html A: Try Wget. it's a simple command line utility able to do that. A: A cheating answer is to use FTP: ftp://examples.oreilly.com/pub/examples/9780735615366/ is for the example you gave...
recursively downloading files from webpage
http://examples.oreilly.com/9780735615366/ I actually want to be able to have all these files in my disk. as u can see there are many folders each with different type of files. and u cannot download "the-folder" directly...only individual files ~ is there any way to automate process..? I will need regular expressions on urls to arrange them in a "folder" like hierarchy. what do I use...some scripting language like python?
[ "Take a look at wget tool. It can do exactly what you want.\n", "wget (GNU command line tool) will do this for you.\nThe documentation for what you want to do is here:\nhttp://www.gnu.org/software/wget/manual/html_node/Recursive-Retrieval-Options.html\n", "Try Wget. it's a simple command line utility able to do...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "recursion", "regex", "scripting" ]
stackoverflow_0003953853_python_recursion_regex_scripting.txt
Q: python: how to slice/store iter pointed data in a fixed buffer class? All, As you know, by python iter we can use iter.next() to get the next item of data. take a list for example: l = [x for x in range(100)] itl = iter(l) itl.next() # 0 itl.next() # 1 Now I want a buffer can store *general iter pointed data * slice in fixed size, use above list iter to demo my question. class IterPage(iter, size): # class code here itp = IterPage(itl, 5) what I want is print itp.first() # [0,1,2,3,4] print itp.next() # [5,6,7,8,9] print itp.prev() # [0,1,2,3,4] len(itp) # 20 # 100 item / 5 fixed size = 20 print itp.last() # [96,97,98,99,100] for y in itp: # iter may not support "for" and len(iter) then something alike code also needed here print y [0,1,2,3,4] [5,6,7,8,9] ... [96,97,98,99,100] it is not a homework, but as a beginner of the python know little about to design an iter class, could someone share me how to code the class "IterPage" here? Also, by below answers I found if the raw data what I want to slice is very big, for example a 8Giga text file or a 10^100 records table on a database, it may not able to read all of them into a list - I have no so much physical memories. Take the snippet in python document for example: http://docs.python.org/library/sqlite3.html# >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') >>> for row in c: ... print row ... (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14) (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0) If here we've got about 10^100 records, In that case, it it possible only store line/records I want by this class with itp = IterPage(c, 5)? if I invoke the itp.next() the itp can just fetch next 5 records from database? Thanks! PS: I got an approach in below link: http://code.activestate.com/recipes/577196-windowing-an-iterable-with-itertools/ and I also found someone want to make a itertools.iwindow() function however it is just been rejected. http://mail.python.org/pipermail/python-dev/2006-May/065304.html A: Since you asked about design, I'll write a bit about what you want - it's not a iterator. The defining property of a iterator is that it only supports iteration, not random access. But methods like .first and .last do random access, so what you ask for is not a iterator. There are of course containers that allow this. They are called sequences and the simplest of them is the list. It's .first method is written as [0] and it's .last is [-1]. So here is such a object that slices a given sequence. It stores a list of slice objects, which is what Python uses to slice out parts of a list. The methods that a class must implement to be a sequence are given by the abstact base class Sequence. It's nice to inherit from it because it throws errors if you forget to implement a required method. from collections import Sequence class SlicedList(Sequence): def __init__(self, iterable, size): self.seq = list(iterable) self.slices = [slice(i,i+size) for i in range(0,len(self.seq), size)] def __contains__(self, item): # checks if a item is in this sequence return item in self.seq def __iter__(self): """ iterates over all slices """ return (self.seq[slice] for slice in self.slices) def __len__(self): """ implements len( .. ) """ return len(self.slices) def __getitem__(self, n): # two forms of getitem .. if isinstance(n, slice): # implements sliced[a:b] return [self.seq[x] for x in self.slices[n]] else: # implements sliced[a] return self.seq[self.slices[n]] s = SlicedList(range(100), 5) # length print len(s) # 20 #iteration print list(s) # [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], ... , [95, 96, 97, 98, 99]] # explicit iteration: it = iter(s) print next(it) # [0, 1, 2, 3, 4] # we can slice it too print s[0], s[-1] # [0, 1, 2, 3, 4] [95, 96, 97, 98, 99] # get the first two print s[0:2] # [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] # every other item print s[::2] # [[0, 1, 2, 3, 4], [10, 11, 12, 13, 14], [20, 21, 22, 23, 24], ... ] Now if you really want methods like .start (what for anyways, just a verbose way for [0] ) you can write a class like this: class Navigator(object): def __init__(self, seq): self.c = 0 self.seq = seq def next(self): self.c +=1 return self.seq[self.c] def prev(self): self.c -=1 return self.seq[self.c] def start(self): self.c = 0 return self.seq[self.c] def end(self): self.c = len(self.seq)-1 return self.seq[self.c] n = Navigator(SlicedList(range(100), 5)) print n.start(), n.next(), n.prev(), n.end() A: The raw data that I want to slice is very big, for example a 8Giga text file... I may not be able to read all of them into a list - I do not have so much physical memory. In that case, is it possible only get line/records I want by this class? No, as it stands, the class originally proposed below converts the iterator into a list, which make it 100% useless for your situation. Just use the grouper idiom (also mentioned below). You'll have to be smart about remembering previous groups. To save on memory, only store those previous groups that you need. For example, if you only need the most recent previous group, you could store that in a single variable, previous_group. If you need the 5 most recent previous groups, you could use a collections.deque with a maximum size of 5. Or, you could use the window idiom to get a sliding window of n groups of groups... Given what you've told us so far, I would not define a class for this, because I don't see many reusable elements to the solution. Mainly, what you want can be done with the grouper idiom: In [22]: l = xrange(100) In [23]: itl=iter(l) In [24]: import itertools In [25]: for y in itertools.izip(*[itl]*5): ....: print(y) (0, 1, 2, 3, 4) (5, 6, 7, 8, 9) (10, 11, 12, 13, 14) ... (95, 96, 97, 98, 99) Calling next is no problem: In [28]: l = xrange(100) In [29]: itl=itertools.izip(*[iter(l)]*5) In [30]: next(itl) Out[30]: (0, 1, 2, 3, 4) In [31]: next(itl) Out[31]: (5, 6, 7, 8, 9) But making a previous method is a big problem, because iterators don't work this way. Iterators are meant to produce values without remembering past values. If you need all past values, then you need a list, not an iterator: In [32]: l = xrange(100) In [33]: ll=list(itertools.izip(*[iter(l)]*5)) In [34]: ll[0] Out[34]: (0, 1, 2, 3, 4) In [35]: ll[1] Out[35]: (5, 6, 7, 8, 9) # Get the last group In [36]: ll[-1] Out[36]: (95, 96, 97, 98, 99) Now getting the previous group is just a matter of keeping track of the list index.
python: how to slice/store iter pointed data in a fixed buffer class?
All, As you know, by python iter we can use iter.next() to get the next item of data. take a list for example: l = [x for x in range(100)] itl = iter(l) itl.next() # 0 itl.next() # 1 Now I want a buffer can store *general iter pointed data * slice in fixed size, use above list iter to demo my question. class IterPage(iter, size): # class code here itp = IterPage(itl, 5) what I want is print itp.first() # [0,1,2,3,4] print itp.next() # [5,6,7,8,9] print itp.prev() # [0,1,2,3,4] len(itp) # 20 # 100 item / 5 fixed size = 20 print itp.last() # [96,97,98,99,100] for y in itp: # iter may not support "for" and len(iter) then something alike code also needed here print y [0,1,2,3,4] [5,6,7,8,9] ... [96,97,98,99,100] it is not a homework, but as a beginner of the python know little about to design an iter class, could someone share me how to code the class "IterPage" here? Also, by below answers I found if the raw data what I want to slice is very big, for example a 8Giga text file or a 10^100 records table on a database, it may not able to read all of them into a list - I have no so much physical memories. Take the snippet in python document for example: http://docs.python.org/library/sqlite3.html# >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') >>> for row in c: ... print row ... (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14) (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) (u'2006-04-06', u'SELL', u'IBM', 500, 53.0) (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0) If here we've got about 10^100 records, In that case, it it possible only store line/records I want by this class with itp = IterPage(c, 5)? if I invoke the itp.next() the itp can just fetch next 5 records from database? Thanks! PS: I got an approach in below link: http://code.activestate.com/recipes/577196-windowing-an-iterable-with-itertools/ and I also found someone want to make a itertools.iwindow() function however it is just been rejected. http://mail.python.org/pipermail/python-dev/2006-May/065304.html
[ "Since you asked about design, I'll write a bit about what you want - it's not a iterator. \nThe defining property of a iterator is that it only supports iteration, not random access. But methods like .first and .last do random access, so what you ask for is not a iterator. \nThere are of course containers that all...
[ 4, 3 ]
[]
[]
[ "buffer", "iterator", "python" ]
stackoverflow_0003953282_buffer_iterator_python.txt
Q: Getting local variables of function I'm trying to get a local variable from a decorator. An example: def needs_privilege(privilege, project=None): """Check whether the logged-in user is authorised based on the given privilege @type privilege: Privilege object, id, or str @param privilege: The requested privilege""" def validate(func, self, *args, **kwargs): """Validator of needs_privillige""" try: check(self.user, privilege, project) except AccessDenied: return abort(status_code=401) else: return func(self, *args, **kwargs) return decorator(validate) After decorating a function, like this: @needs_privilege("some_privilege") def some_function(): pass I would like to retrieve the 'privilige' variable (which validate() uses) from some_function. After searching more than one hour, I'm feeling pretty lost. Is this possible? Edit: Let me describe my problem a bit more thoroughly: can I get the string "some_prvilege" without executing some_function? Something like: a = getattr(module, 'somefunction') print a.decorator_arguments ? Thanks for helping me so far! A: Your decorator basically check if a user have the permission to execute a given function, i don't actually understand why you want to retrieve (to attach) the privilege to the function that was being wrapped but you can do this without adding another argument to all your functions. def needs_privilege(privilege, project=None): """Check whether the logged-in user is authorised based on the given privilege @type privilege: Privilege object, id, or str @param privilege: The requested privilege""" def validate(func, self, *args, **kwargs): """Validator of needs_privillige""" try: check(self.user, privilege, project) except AccessDenied: return abort(status_code=401) else: return func(self, *args, **kwargs) validate.privelege = privelege return decorator(validate) by the way your decorator should be like this : def needs_privilege(privilege, project=None): def validate(func): def new_func(self, *args, **kwargs): try: check(self.user, privilege, project) except AccessDenied: return abort(status_code=401) else: return func(self, *args, **kwargs) new_func.privilege = privilege return new_func return validate A: You could pass it as a parameter: def needs_privilege(privilege, project=None): """Check whether the logged-in user is authorised based on the given privilege @type privilege: Privilege object, id, or str @param privilege: The requested privilege""" def validate(func, self, *args, **kwargs): """Validator of needs_privillige""" try: check(self.user, privilege, project) except AccessDenied: return abort(status_code=401) else: return func(self, privilege, *args, **kwargs) return decorator(validate) @needs_privilege("some_privilege") def some_function(privilege): pass A: Your problem would be much simpler if you didn't need the decorator module. If you don't strictly need the decorator module, you could write the decorator like this: def needs_privilege(privilege, project=None): def validate(func): def _validate(self, *args, **kwargs): return func(self, *args, **kwargs) _validate.decorator_args=(privilege,project) return _validate return validate @needs_privilege("some_privilege") def some_function(self): pass a = some_function print(a.decorator_args) # ('some_privilege', None) A: Functions are objects that can have attributes too. You can set attributes in the decorator. Here's an example: class TestClass(object): def needs_privilege(privilege, project=None): def wrapper(func): def validate(self, *args, **kwargs): """Validator of needs_privillige""" print 'validator check for %s' % privilege return func(*args, **kwargs) validate.privilege = privilege return validate return wrapper @needs_privilege("foo") def bar(): print "called" >>> test.TestClass().bar() validator check for foo called >>> test.TestClass.bar.privilege 'foo' >>> test.TestClass().bar.privilege 'foo'
Getting local variables of function
I'm trying to get a local variable from a decorator. An example: def needs_privilege(privilege, project=None): """Check whether the logged-in user is authorised based on the given privilege @type privilege: Privilege object, id, or str @param privilege: The requested privilege""" def validate(func, self, *args, **kwargs): """Validator of needs_privillige""" try: check(self.user, privilege, project) except AccessDenied: return abort(status_code=401) else: return func(self, *args, **kwargs) return decorator(validate) After decorating a function, like this: @needs_privilege("some_privilege") def some_function(): pass I would like to retrieve the 'privilige' variable (which validate() uses) from some_function. After searching more than one hour, I'm feeling pretty lost. Is this possible? Edit: Let me describe my problem a bit more thoroughly: can I get the string "some_prvilege" without executing some_function? Something like: a = getattr(module, 'somefunction') print a.decorator_arguments ? Thanks for helping me so far!
[ "Your decorator basically check if a user have the permission to execute a given function, i don't actually understand why you want to retrieve (to attach) the privilege to the function that was being wrapped but you can do this without adding another argument to all your functions.\ndef needs_privilege(privilege, ...
[ 3, 2, 1, 0 ]
[]
[]
[ "decorator", "locals", "python", "unix" ]
stackoverflow_0003953216_decorator_locals_python_unix.txt
Q: Python vs Flash Can python be used as a language to develop browser based games? Like we do in flash. If yes then what frameworks are available to get my hands dirty? If no then what are the reasons? A: Give it a try to Panda3D. I have successfully used it before to create and deploy 3D game environments that run in a browser (runtime is required). Works for Mac. Linux and Windows. Examples here: http://www.panda3d.org/gallery/ Their manual is very clear and has a bunch of examples. http://www.panda3d.org/manual/index.php/Main_Page A: Flash uses a separate plugin that runs within the browser in order to have better access to the resources on the system. Python can currently only be used to generate the various formats that the browser uses (HTML, SVG, JavaScript, etc.), which restricts the feature set that can be exposed using Python. There is Pyjamas for easily converting between Python and JavaScript, but it hasn't really been applied to games as far as I know, and graphics would still be a separate issue. And of course, it may also be possible to generate Flash applets using Python via various libraries. A: You can run IronPython code in the Silverlight plug-in. A: I am not aware of a browser plug-in for Python. With that in mind, no in-browser games. If you used PyGame you could do network delivered game. Alternately, you could go the AJAXy route and have a Python server work with JavaScript or some other tool a browser. If you go for a hybrid approach pretty much any AJAXy framework would work.
Python vs Flash
Can python be used as a language to develop browser based games? Like we do in flash. If yes then what frameworks are available to get my hands dirty? If no then what are the reasons?
[ "Give it a try to Panda3D. I have successfully used it before to create and deploy 3D game environments that run in a browser (runtime is required). Works for Mac. Linux and Windows.\nExamples here: http://www.panda3d.org/gallery/\nTheir manual is very clear and has a bunch of examples. http://www.panda3d.org/manua...
[ 3, 1, 1, 0 ]
[]
[]
[ "actionscript", "flash", "python" ]
stackoverflow_0003953999_actionscript_flash_python.txt
Q: calculate IP checksum in python I need to calculate the checksum of an IP packet as described in http://www.faqs.org/rfcs/rfc1071.html. I have already the following code: #!/usr/bin/python import struct data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1" # a test for the checksum calculation def _checksum(data): #calculate the header sum ip_header_sum = sum(struct.unpack_from("6H", data)) #add the carry ip_header_sum = (ip_header_sum & 0xFFFF) + (ip_header_sum >> 16 & 0xFFFF) #invert the sum, python does not support inversion (~a is -a + 1) so we have to do #little trick: ~a is the same as 0xFFFF & ~a ip_header_sum = ~ip_header_sum & 0xFFFF return ip_header_sum #should return 0 if correct data = data.split() data = map(lambda x: int(x,16), data) data = struct.pack("%dB" % len(data), *data) print " ".join(map(lambda x: "0x%02x" % ord(x), data)) print "Checksum: 0x%04x" % _checksum(data) It works with a package that I have captured with wireshark and which should have the correct checksum and should therefore evaluate to 0 Unfortunately the result is 0x6524. It is also interesting, that the result is always 0x6524 for every correct packet... Who spots the error? Edited to make the error more clear *Edited a second time* A: You can use the solution directly from checksum udp calculation python, which results in the expected checksum value of zero. import struct data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1" def carry_around_add(a, b): c = a + b return (c & 0xffff) + (c >> 16) def checksum(msg): s = 0 for i in range(0, len(msg), 2): w = ord(msg[i]) + (ord(msg[i+1]) << 8) s = carry_around_add(s, w) return ~s & 0xffff data = data.split() data = map(lambda x: int(x,16), data) data = struct.pack("%dB" % len(data), *data) print ' '.join('%02X' % ord(x) for x in data) print "Checksum: 0x%04x" % checksum(data) Results: 45 00 00 47 73 88 40 00 40 06 A2 C4 83 9F 0E 85 83 9F 0E A1 Checksum: 0x0000 A: You've got two issues here. First, your call to struct.unpack_from only unpacks 4 16-bit values (that is, 8 bytes) from the buffer. If you want to unpack the whole header, you'll need to do something like struct.unpack_from("!nH"), where n is the number of shorts you want to unpack. You can generate the appropriate format string with struct.unpack_from("!%dH"%(len(data)/2), data), assuming that data contains nothing but the IP header. Second, once you do that, you'll find that the checksum now works out to 0. This is the correct result for a packet that already has its checksum set, as this one does. (You highlighted the A2 and C4 bytes in the packet above.) To calculate the correct checksum for a packet from scratch, you need to set the checksum bytes to 0. (See the start of step 2 in RFC1071: "To generate a checksum, the checksum field itself is cleared".)
calculate IP checksum in python
I need to calculate the checksum of an IP packet as described in http://www.faqs.org/rfcs/rfc1071.html. I have already the following code: #!/usr/bin/python import struct data = "45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1" # a test for the checksum calculation def _checksum(data): #calculate the header sum ip_header_sum = sum(struct.unpack_from("6H", data)) #add the carry ip_header_sum = (ip_header_sum & 0xFFFF) + (ip_header_sum >> 16 & 0xFFFF) #invert the sum, python does not support inversion (~a is -a + 1) so we have to do #little trick: ~a is the same as 0xFFFF & ~a ip_header_sum = ~ip_header_sum & 0xFFFF return ip_header_sum #should return 0 if correct data = data.split() data = map(lambda x: int(x,16), data) data = struct.pack("%dB" % len(data), *data) print " ".join(map(lambda x: "0x%02x" % ord(x), data)) print "Checksum: 0x%04x" % _checksum(data) It works with a package that I have captured with wireshark and which should have the correct checksum and should therefore evaluate to 0 Unfortunately the result is 0x6524. It is also interesting, that the result is always 0x6524 for every correct packet... Who spots the error? Edited to make the error more clear *Edited a second time*
[ "You can use the solution directly from checksum udp calculation python, which results in the expected checksum value of zero.\nimport struct\n\ndata = \"45 00 00 47 73 88 40 00 40 06 a2 c4 83 9f 0e 85 83 9f 0e a1\"\n\ndef carry_around_add(a, b):\n c = a + b\n return (c & 0xffff) + (c >> 16)\n\ndef checksum(m...
[ 9, 6 ]
[]
[]
[ "checksum", "network_protocols", "python" ]
stackoverflow_0003949726_checksum_network_protocols_python.txt
Q: Is it possible to make a cross browser extension linked to a Python web app backend? Current Situation I am in the early phases of designing a web app that the user will interact with via a browser extension that will be in the form of a horizontal nav bar. I wanted to use Pylons and Python on this project but am unsure how it fits in. As I understand it a browser extension is "just bundled HTML, CSS, JS and image files, plus some metadata". But what does that mean? Does that mean that HTML, CSS, JS, image files and meta data are used to create just the front end GUI nav bar part of the browser extension? Or Does that mean that HTML, CSS, JS and image files make up the front end GUI nav bar and JS and meta data will take care of the back end logic? I ask this because I know that one can program web apps in Java Script alone. Conclusion Ideally I would like Python/Pylons to be the main brain of the web app and do the heavy lifting in terms of logic. Python/Pylons would basically take in data via JavaScript and give back data to Java Script/AJAX which would then, in real-time, update the GUI nav bar. Is this possible? A: As long as the extension uses HTTP to communicate, you can use whatever server-side technology you like to generate the data passed back to the client.
Is it possible to make a cross browser extension linked to a Python web app backend?
Current Situation I am in the early phases of designing a web app that the user will interact with via a browser extension that will be in the form of a horizontal nav bar. I wanted to use Pylons and Python on this project but am unsure how it fits in. As I understand it a browser extension is "just bundled HTML, CSS, JS and image files, plus some metadata". But what does that mean? Does that mean that HTML, CSS, JS, image files and meta data are used to create just the front end GUI nav bar part of the browser extension? Or Does that mean that HTML, CSS, JS and image files make up the front end GUI nav bar and JS and meta data will take care of the back end logic? I ask this because I know that one can program web apps in Java Script alone. Conclusion Ideally I would like Python/Pylons to be the main brain of the web app and do the heavy lifting in terms of logic. Python/Pylons would basically take in data via JavaScript and give back data to Java Script/AJAX which would then, in real-time, update the GUI nav bar. Is this possible?
[ "As long as the extension uses HTTP to communicate, you can use whatever server-side technology you like to generate the data passed back to the client.\n" ]
[ 2 ]
[]
[]
[ "browser", "cross_browser", "javascript", "python" ]
stackoverflow_0003954243_browser_cross_browser_javascript_python.txt
Q: When would we need a javascript client template engine? Recently, I found out that jQuery has an official template engine which was contributed by the Microsoft team. Also I had heard about jTemplate from my friends, but I'm still confused: When & where might I need to use these plugins? How should I choose between the many client side template engines? A: The reason for a jQuery template engine is this: developers write Javascript code to create new chunks of HTML to inject into the page. This usually is done by concatenating many strings with variables for values, and it becomes difficult to maintain. With a jQuery template engine, the process of creating HTML at the client can benefit from all the same advantages that server-side developers now have with their templating engines. A: I'll address your first question. You can store data in JavaScript objects (instead of SQL databases, for example). Those JavaScript objects can be stored in .js files, or inline as part of the HTML document. You can take a look at the source code of my w3viewer.com. All data is stored inside a JavaScript array. In the example of my web-site, I dynamically create HTML lists with data taken from that JavaScript object (I generate the HTML code string). One could use templating to get this job done. A: A template-engine prevents unnecessary HTML-code in the actual code. This makes it much easier to read.
When would we need a javascript client template engine?
Recently, I found out that jQuery has an official template engine which was contributed by the Microsoft team. Also I had heard about jTemplate from my friends, but I'm still confused: When & where might I need to use these plugins? How should I choose between the many client side template engines?
[ "The reason for a jQuery template engine is this: developers write Javascript code to create new chunks of HTML to inject into the page. This usually is done by concatenating many strings with variables for values, and it becomes difficult to maintain.\nWith a jQuery template engine, the process of creating HTML ...
[ 1, 0, 0 ]
[]
[]
[ "client_side", "javascript", "python", "template_engine" ]
stackoverflow_0003954099_client_side_javascript_python_template_engine.txt
Q: Shuffle position of elements in a list Possible Duplicate: Shuffling a list of objects in python IF I have a list: a = ["a", "b", "c", ..., "zzz"] how can I randomly shuffle its elements in order to obtain a list: b = ["c", "zh", ...] without consuming a lot of the system's resources? A: import random b = list(a) random.shuffle(b) A: random.shuffle() shuffles a sequence in-place. A: Not sure how much resources it consumes, but shuffle in the random module does exactly like this. import random a = [1,2,3,4,5] random.shuffle(a)
Shuffle position of elements in a list
Possible Duplicate: Shuffling a list of objects in python IF I have a list: a = ["a", "b", "c", ..., "zzz"] how can I randomly shuffle its elements in order to obtain a list: b = ["c", "zh", ...] without consuming a lot of the system's resources?
[ "import random\nb = list(a)\nrandom.shuffle(b)\n\n", "random.shuffle() shuffles a sequence in-place.\n", "Not sure how much resources it consumes, but shuffle in the random module does exactly like this.\nimport random\na = [1,2,3,4,5]\nrandom.shuffle(a)\n\n" ]
[ 9, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003954321_python.txt
Q: How to serve up dynamic content via django and php on same domain? I just finished rewriting a significant portion of my web site using python's django, but I also have some legacy code in php that I haven't finished migrating over yet. Is it possible to get these two working on the same domain and if so, how do I go about doing it? I'm running this site on a virtual Ubuntu instance and serving content up via apache. I'm also using mod_wsgi to hook into the python content. One simplification is that the whole site, except for one sub-directory, runs off python. Let's say for arguments sake that my php code is at http://www.mysite.com/myphpapp/. A: Basically you have to configure apache to use the default handler for the path hosting your legacy code, usually adding a <directory> or <location> section to your apache site config. Something like: <Location "/legacy"> SetHandler None </Location>
How to serve up dynamic content via django and php on same domain?
I just finished rewriting a significant portion of my web site using python's django, but I also have some legacy code in php that I haven't finished migrating over yet. Is it possible to get these two working on the same domain and if so, how do I go about doing it? I'm running this site on a virtual Ubuntu instance and serving content up via apache. I'm also using mod_wsgi to hook into the python content. One simplification is that the whole site, except for one sub-directory, runs off python. Let's say for arguments sake that my php code is at http://www.mysite.com/myphpapp/.
[ "Basically you have to configure apache to use the default handler for the path hosting your legacy code, usually adding a <directory> or <location> section to your apache site config.\nSomething like:\n<Location \"/legacy\">\n SetHandler None\n</Location>\n\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "php", "python" ]
stackoverflow_0003954467_apache_django_php_python.txt
Q: TkInter: how can I pass a numeric value to specify the color? how can I assign a numeric value instead of a string to specify the color of my button ? What the exact syntax ? button = tk.Button(itemFrame, text="", bg="red", width=10, command=callback) i.e bg = #FF0000 thanks A: There are two general ways to specify colors in Tkinter. You can use a string specifying the proportion of red, green, and blue in hexadecimal digits. You can also use any locally defined standard color name #rgb Four bits per color #rrggbb Eight bits per color #rrrgggbbb Twelve bits per color The format should be string bg='#FF0000' and not bg=#FF0000
TkInter: how can I pass a numeric value to specify the color?
how can I assign a numeric value instead of a string to specify the color of my button ? What the exact syntax ? button = tk.Button(itemFrame, text="", bg="red", width=10, command=callback) i.e bg = #FF0000 thanks
[ "There are two general ways to specify colors in Tkinter.\n\nYou can use a string specifying the proportion of red, green, and blue in hexadecimal digits.\nYou can also use any locally defined standard color name\n\n\n#rgb Four bits per color\n#rrggbb Eight bits per color\n#rrrgggbbb Twelve bits per color\n\nThe...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003954524_python_tkinter.txt
Q: Left hand side of assignment with infinite generators Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator)) as this is not possible a, b, c, d = (val for val in infite_generator) actually then I want to do in single line for var in var_list: var = next(infinite_generator) Is there any interpreter hook to take metainformation of number of vars at left hand side of assignement? Better would be though that I could just do automatically this last bit of code (including cases with left side which is slice with variable indexes and step) Also is there way to make generator of variables which would be left hands side of assignment. EDIT: This does not stop in Python3: def incr(a): while True: yield a a += 1 a = [None for i in range(20)] a[3:3:3], *_ = incr(1) print(a) Same with: a,b,c,d, *_ = incr(1) print(a, b, c, d) Even it has not slice (actually the indexes would be variables, this is only test). I am aware of islice etc but it is too slow. This produce also error: a = 1000*[True] bound = int(len(a) ** 0.5) for i in range(3, bound, 2): a[3::i], *x = [[False] for _ in range(bound)] """ Error: ValueError: attempt to assign sequence of size 1 to extended slice of size 333 """ And this: a = 1000*[True] bound = int(len(a) ** 0.5) for i in range(3, bound, 2): a[3::i], *x = [False] * bound """ Error: TypeError: must assign iterable to extended slice """ A: When you know the var_list's length, you could use itertools.islice to cut off the infinite generator: >>> import itertools >>> infgen = itertools.cycle([1,4,9]) >>> a,b,c,d = itertools.islice(infgen, 4) >>> a,b,c,d (1, 4, 9, 1) It works for assignment to a slice of list too. >>> lst = [0]*20 >>> lst[2:10:2] = itertools.islice(infgen, 4) >>> lst [0, 0, 4, 0, 9, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Left hand side of assignment with infinite generators
Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator)) as this is not possible a, b, c, d = (val for val in infite_generator) actually then I want to do in single line for var in var_list: var = next(infinite_generator) Is there any interpreter hook to take metainformation of number of vars at left hand side of assignement? Better would be though that I could just do automatically this last bit of code (including cases with left side which is slice with variable indexes and step) Also is there way to make generator of variables which would be left hands side of assignment. EDIT: This does not stop in Python3: def incr(a): while True: yield a a += 1 a = [None for i in range(20)] a[3:3:3], *_ = incr(1) print(a) Same with: a,b,c,d, *_ = incr(1) print(a, b, c, d) Even it has not slice (actually the indexes would be variables, this is only test). I am aware of islice etc but it is too slow. This produce also error: a = 1000*[True] bound = int(len(a) ** 0.5) for i in range(3, bound, 2): a[3::i], *x = [[False] for _ in range(bound)] """ Error: ValueError: attempt to assign sequence of size 1 to extended slice of size 333 """ And this: a = 1000*[True] bound = int(len(a) ** 0.5) for i in range(3, bound, 2): a[3::i], *x = [False] * bound """ Error: TypeError: must assign iterable to extended slice """
[ "When you know the var_list's length, you could use itertools.islice to cut off the infinite generator:\n>>> import itertools\n>>> infgen = itertools.cycle([1,4,9])\n>>> a,b,c,d = itertools.islice(infgen, 4)\n>>> a,b,c,d\n(1, 4, 9, 1)\n\nIt works for assignment to a slice of list too.\n>>> lst = [0]*20\n>>> lst[2:1...
[ 1 ]
[]
[]
[ "generator", "infinite", "lazy_evaluation", "python" ]
stackoverflow_0003954564_generator_infinite_lazy_evaluation_python.txt