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: Should I use a metaclass, class decorator, or override the __new__ method? Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be. class Test(object): def calculate_attr(self, attr): # do calculaty stuff return attr @property def foo(self): return self.calculate_attr('foo') @property def bar(self): return self.calculate_attr('bar') A: Magic is bad. It makes your code harder to understand and maintain. You virtually never need metaclasses or __new__. It looks like your use case could be implemented with pretty straightforward code (with only a small hint of magic): class Test(object): def calculate_attr(self, attr): return something def __getattr__(self, name): return self.calculate_attr(name) A: A metaclass's __new__ does not become the __new__ for the class you make—it's used to make the class itself. The actual class object is returned by the metaclass. A new instance of a class is returned by __new__. Consider the following (insane) code: def MyMetaClass(name, bases, dict): print "name", name print "bases", bases print "dict", dict return 7 class C('hello', 'world'): __metaclass__ = MyMetaClass foo = "bar" def baz(self, qux): pass print "C", C (I used a function instead of a class as the metaclass. Any callable can be used as a metaclass, but many people choose to right theirs as classes that inherit from type with new overrided. The differences between that an a function are subtle.) It outputs name C bases ('hello', 'world') dict {'baz': <function baz at 0x4034c844>, '__module__': '__main__', 'foo': 'bar', '__metaclass__': <function MyMetaClass at 0x40345c34>} C 7 Does that help you better make sense of what metaclasses are? You will very seldom need to define a metaclass of your own. A: Metaclass is used when new class - not instance - is created. This way you can for example register classes (django does it and uses it for example to create tables in the database). Since class is an instruction you can think about as a decorator for a class.
Should I use a metaclass, class decorator, or override the __new__ method?
Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be. class Test(object): def calculate_attr(self, attr): # do calculaty stuff return attr @property def foo(self): return self.calculate_attr('foo') @property def bar(self): return self.calculate_attr('bar')
[ "Magic is bad. It makes your code harder to understand and maintain. You virtually never need metaclasses or __new__. \nIt looks like your use case could be implemented with pretty straightforward code (with only a small hint of magic):\nclass Test(object):\n def calculate_attr(self, attr):\n return something\n\n def __getattr__(self, name):\n return self.calculate_attr(name)\n\n", "A metaclass's __new__ does not become the __new__ for the class you make—it's used to make the class itself. The actual class object is returned by the metaclass. A new instance of a class is returned by __new__.\nConsider the following (insane) code:\ndef MyMetaClass(name, bases, dict):\n print \"name\", name\n print \"bases\", bases\n print \"dict\", dict\n return 7\n\nclass C('hello', 'world'):\n __metaclass__ = MyMetaClass\n\n foo = \"bar\"\n\n def baz(self, qux):\n pass\n\nprint \"C\", C\n\n(I used a function instead of a class as the metaclass. Any callable can be used as a metaclass, but many people choose to right theirs as classes that inherit from type with new overrided. The differences between that an a function are subtle.)\nIt outputs \nname C\nbases ('hello', 'world')\ndict {'baz': <function baz at 0x4034c844>, '__module__': '__main__', 'foo': 'bar', '__metaclass__': <function MyMetaClass at 0x40345c34>}\nC 7\n\nDoes that help you better make sense of what metaclasses are?\nYou will very seldom need to define a metaclass of your own.\n", "Metaclass is used when new class - not instance - is created. This way you can for example register classes (django does it and uses it for example to create tables in the database). Since class is an instruction you can think about as a decorator for a class.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "inheritance", "metaclass", "python" ]
stackoverflow_0002503676_inheritance_metaclass_python.txt
Q: Keeping track of changes - Django I have various models of which I would like to keep track and collect statistical data. The problem is how to store the changes throughout time. I thought of various alternative: Storing a log in a TextField, open it and update it every time the model is saved. Alternatively pickle a list and store it in a TextField. Save logs on hard drive. What are your suggestions? A: Don't reinvent the wheel.. Use django-reversion for logging changes. I'd break statistics off into a separate model though. A: Quoth my elementary chemistry teacher: "If you don't write it down, it didn't happen", therefore save logs in a file. Since the log information is disjoint from your application data (it's meta-data, actually), keep them separate. You could log to a database table but it should be distinct from your model. Text pickle data is difficult for humans to read, binary pickle data even more so; log in an easily parsed format and the data can be imported into analysis software easily. A: I've had similar situation in which we were supposed to keep the history of changed. But we also needed audit to track who made the changes and the ability to revert. In our approach storing in database seemed more logical. However considering you have statistical data and it's gonnna be large, perhaps separate file based approach would be better for you. In any case you should use a generic mechanism to log the changes on models rather than coding each model invidually. Take a look at this: http://www.djangosnippets.org/snippets/1052/
Keeping track of changes - Django
I have various models of which I would like to keep track and collect statistical data. The problem is how to store the changes throughout time. I thought of various alternative: Storing a log in a TextField, open it and update it every time the model is saved. Alternatively pickle a list and store it in a TextField. Save logs on hard drive. What are your suggestions?
[ "Don't reinvent the wheel.. Use django-reversion for logging changes.\nI'd break statistics off into a separate model though.\n", "Quoth my elementary chemistry teacher: \"If you don't write it down, it didn't happen\", therefore save logs in a file.\nSince the log information is disjoint from your application data (it's meta-data, actually), keep them separate. You could log to a database table but it should be distinct from your model.\nText pickle data is difficult for humans to read, binary pickle data even more so; log in an easily parsed format and the data can be imported into analysis software easily.\n", "I've had similar situation in which we were supposed to keep the history of changed. But we also needed audit to track who made the changes and the ability to revert. In our approach storing in database seemed more logical. However considering you have statistical data and it's gonnna be large, perhaps separate file based approach would be better for you.\nIn any case you should use a generic mechanism to log the changes on models rather than coding each model invidually.\nTake a look at this: http://www.djangosnippets.org/snippets/1052/\n" ]
[ 6, 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002504386_django_django_models_python.txt
Q: wx Menu disappears from frame when shown as a popup I'm trying to create a wx.Menu that will be shared between a popup (called on right-click), and a sub menu accessible from the frame menubar. The following code demonstrates the problem. If you open the "MENU>submenu" from the menubar the item "asdf" is visible. If you right click on the frame content area, "asdf" will be visible from there as well... however, returning to the menubar, you will find that "MENU>submenu" is vacant. Why is this happening and how can I fix it? import wx app = wx.PySimpleApp() m = wx.Menu() m.Append(-1, 'asdf') def show_popup(evt): ''' R-click callback ''' f.PopupMenu(m, (evt.X, evt.Y)) f = wx.Frame(None) f.SetMenuBar(wx.MenuBar()) frame_menu = wx.Menu() f.MenuBar.Append(frame_menu, 'MENU') frame_menu.AppendMenu(-1,'submenu', m) f.Show() f.Bind(wx.EVT_RIGHT_DOWN, show_popup) app.MainLoop() Interestingly, appending the menu to MenuBar works, but is not the behavior I want: import wx app = wx.PySimpleApp() m = wx.Menu() m.Append(-1, 'asdf') def show_popup(evt): f.PopupMenu(m, (evt.X, evt.Y)) f = wx.Frame(None) f.SetMenuBar(wx.MenuBar()) f.MenuBar.Append(m, 'MENU') f.Show() f.Bind(wx.EVT_RIGHT_DOWN, show_popup) app.MainLoop() A: I would make a function, create_menu, that creates and returns a wx.Menu object. Call it once to add it to your menu bar and call it in show_popup. So you're using separate Menu objects. Don't worry about creating them on each right-click, it's not a big deal.
wx Menu disappears from frame when shown as a popup
I'm trying to create a wx.Menu that will be shared between a popup (called on right-click), and a sub menu accessible from the frame menubar. The following code demonstrates the problem. If you open the "MENU>submenu" from the menubar the item "asdf" is visible. If you right click on the frame content area, "asdf" will be visible from there as well... however, returning to the menubar, you will find that "MENU>submenu" is vacant. Why is this happening and how can I fix it? import wx app = wx.PySimpleApp() m = wx.Menu() m.Append(-1, 'asdf') def show_popup(evt): ''' R-click callback ''' f.PopupMenu(m, (evt.X, evt.Y)) f = wx.Frame(None) f.SetMenuBar(wx.MenuBar()) frame_menu = wx.Menu() f.MenuBar.Append(frame_menu, 'MENU') frame_menu.AppendMenu(-1,'submenu', m) f.Show() f.Bind(wx.EVT_RIGHT_DOWN, show_popup) app.MainLoop() Interestingly, appending the menu to MenuBar works, but is not the behavior I want: import wx app = wx.PySimpleApp() m = wx.Menu() m.Append(-1, 'asdf') def show_popup(evt): f.PopupMenu(m, (evt.X, evt.Y)) f = wx.Frame(None) f.SetMenuBar(wx.MenuBar()) f.MenuBar.Append(m, 'MENU') f.Show() f.Bind(wx.EVT_RIGHT_DOWN, show_popup) app.MainLoop()
[ "I would make a function, create_menu, that creates and returns a wx.Menu object. Call it once to add it to your menu bar and call it in show_popup. So you're using separate Menu objects. Don't worry about creating them on each right-click, it's not a big deal.\n" ]
[ 1 ]
[]
[]
[ "menu", "python", "wxpython" ]
stackoverflow_0002504962_menu_python_wxpython.txt
Q: Yahoo BOSS Python Library, ExpatError I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 & 4 give Expat errors. Here is the output from ex3.py: gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "examples/ex3.py", line 27, in <module> digg = db.select(name="dg", udf=titlef, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news") File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 214, in select tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 201, in create return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/crawl/rest.py", line 38, in load return xml2dict.fromstring(dl) File "/usr/lib/python2.5/site-packages/yos/crawl/xml2dict.py", line 41, in fromstring t = ET.fromstring(s) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 963, in XML parser.feed(text) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 It looks like both examples are failing when trying to query Digg.com. Here is the query that is constructed in ex3.py's code: diggf = lambda r: {"title": r["title"]["value"], "diggs": int(r["diggCount"]["value"])} digg = db.select(name="dg", udf=diggf, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news") A: The problem is the digg search string. It should be "s=". Not "search=" A: I believe that must be an error in the example: it's getting a JSON result (indeed if you copy and paste that URL in your browser, you'll download a file names search.json which starts with {"results":[{"profile_image_url": "http://a3.twimg.com/profile_images/255524395/KEN_OMALLEY_REVISED_normal.jpg", "created_at":"Mon, 14 Sep 2009 14:52:07 +0000","from_user":"twilightlords", i.e. perfectly normal JSON; but then instead of parsing it with modules such as json or simplejson, it tries to parse it as XML -- and obviously this attempt fails. I believe the fix (which probably needs to be brought to the attention of whoever maintains that code so they can incorporate it) is either to ask for XML instead of JSON output, OR to parse the resulting JSON with appropriate means instead of trying to look at it as XML (not sure how to best implement either change, as I'm not familiar with that code).
Yahoo BOSS Python Library, ExpatError
I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 & 4 give Expat errors. Here is the output from ex3.py: gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "examples/ex3.py", line 27, in <module> digg = db.select(name="dg", udf=titlef, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news") File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 214, in select tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 201, in create return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/crawl/rest.py", line 38, in load return xml2dict.fromstring(dl) File "/usr/lib/python2.5/site-packages/yos/crawl/xml2dict.py", line 41, in fromstring t = ET.fromstring(s) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 963, in XML parser.feed(text) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 It looks like both examples are failing when trying to query Digg.com. Here is the query that is constructed in ex3.py's code: diggf = lambda r: {"title": r["title"]["value"], "diggs": int(r["diggCount"]["value"])} digg = db.select(name="dg", udf=diggf, url="http://digg.com/rss_search?search=google+android&area=dig&type=both&section=news")
[ "The problem is the digg search string. It should be \"s=\". Not \"search=\"\n", "I believe that must be an error in the example: it's getting a JSON result (indeed if you copy and paste that URL in your browser, you'll download a file names search.json which starts with \n{\"results\":[{\"profile_image_url\":\n\"http://a3.twimg.com/profile_images/255524395/KEN_OMALLEY_REVISED_normal.jpg\",\n\"created_at\":\"Mon, 14 Sep 2009 14:52:07 +0000\",\"from_user\":\"twilightlords\",\n\ni.e. perfectly normal JSON; but then instead of parsing it with modules such as json or simplejson, it tries to parse it as XML -- and obviously this attempt fails.\nI believe the fix (which probably needs to be brought to the attention of whoever maintains that code so they can incorporate it) is either to ask for XML instead of JSON output, OR to parse the resulting JSON with appropriate means instead of trying to look at it as XML (not sure how to best implement either change, as I'm not familiar with that code).\n" ]
[ 1, 0 ]
[]
[]
[ "expat_parser", "python", "yahoo_boss_api" ]
stackoverflow_0001421099_expat_parser_python_yahoo_boss_api.txt
Q: Splitting a list in python Hey im new to python. How do you get a portion of a list by the relative value of its sorting key. example... list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10] list.sort() newList = list.split("all numbers that are over 13") assert newList == [14,15,16] A: >>> l = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10] >>> sorted(x for x in l if x > 13) [14, 15, 16] or with filter (would be a little bit slower if you have big list, because of lambda) >>> sorted(filter(lambda x: x > 13, l)) [14, 15, 16] A: Use [item for item in newList if item > 13]. There is a decent chance this could be replaced with the generator expression (item for item in newList if item > 13), which filters lazily rather than storing the whole list in memory. You might also be interested in changing the code just a bit to something like all_numbers = [11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered_sorted_numbers = sorted(number for number in all_numbers if number > 13) which performs the sorting—a worst case O(n log n) operation—on only the filtered values.
Splitting a list in python
Hey im new to python. How do you get a portion of a list by the relative value of its sorting key. example... list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10] list.sort() newList = list.split("all numbers that are over 13") assert newList == [14,15,16]
[ ">>> l = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]\n>>> sorted(x for x in l if x > 13)\n[14, 15, 16]\n\nor with filter (would be a little bit slower if you have big list, because of lambda)\n>>> sorted(filter(lambda x: x > 13, l))\n[14, 15, 16]\n\n", "Use [item for item in newList if item > 13].\nThere is a decent chance this could be replaced with the generator expression (item for item in newList if item > 13), which filters lazily rather than storing the whole list in memory.\n\nYou might also be interested in changing the code just a bit to something like\nall_numbers = [11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nfiltered_sorted_numbers = sorted(number for number in all_numbers if number > 13)\n\nwhich performs the sorting—a worst case O(n log n) operation—on only the filtered values.\n" ]
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002505251_python.txt
Q: s/mime v3 with M2Crypto I would like to send a mail with a s/mime v3 attachment through SMTP. The excellent HOWTO below describes the procedure in detail for s/mime v2. http://sandbox.rulemaker.net/ngps/m2/howto.smime.html I would greatly appreciate any help in doing the same for s/mime v3. Arye. A: I don't know about v3, but some updated info... The new location for that howto is at http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html. Note that it is still for v2. There are also some smime tests at http://svn.osafoundation.org/m2crypto/trunk/tests/test_smime.py
s/mime v3 with M2Crypto
I would like to send a mail with a s/mime v3 attachment through SMTP. The excellent HOWTO below describes the procedure in detail for s/mime v2. http://sandbox.rulemaker.net/ngps/m2/howto.smime.html I would greatly appreciate any help in doing the same for s/mime v3. Arye.
[ "I don't know about v3, but some updated info...\nThe new location for that howto is at http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html. Note that it is still for v2. There are also some smime tests at http://svn.osafoundation.org/m2crypto/trunk/tests/test_smime.py\n" ]
[ 2 ]
[]
[]
[ "m2crypto", "python", "smime" ]
stackoverflow_0002469271_m2crypto_python_smime.txt
Q: Open Source CMS with linked sub-sections and users I work at a small college that wants to make "sites" for all of the academic departments (~30). I managed to talk them out of their original idea: 30 individual Wordpress installations. What a maintenance nightmare! What I'm looking for is a CMS (preferably Python or PHP, as those are my areas of expertise) that can automagically create a subsection (or subsite, whatever the appropriate vernacular) complete with user and a couple of headings based on a template. So, I could just click a button and have a new subsection for a new department complete with its own authorized user, and default subsection headings/menu/pages. Is this just wishful thinking? I don't mind getting my hands dirty (this would be the whole of my job duties), so what platform would be a good starting point for something like this? Open source is a must for me as I have literally no budget, and I'm probably going to have to dig pretty deep into the application. A: Take a look at Drupal or Wordpress MU. With a little bit of scripting and code I think these could do what you need. Take a close look at Wordpress MU especially. If they were talking about 30 Wordpress installations then Wordpress MU might be exactly what you want. It provides a unified administration backend to manage multiple wordpress blogs. It's based on the software used to run Wordpress.com. I used to work in an Academic Technologies department as a student programmer and while I was there I helped them get an installation of it set up. Let me tell you - compared to MovableType and Blackboard - it was a dream. A: Take a look at Pinax. It uses a templating system to rapidly develop sites. Pinax was created around the idea that there are 'types' of websites and its ridiculous to keep writing the same code over and over for similar sites. This means you could use one of their pre-built templates or create your own and then when you want to build a new site just invoke the template and the site will be ready to go. A: Plone does this use case very well. The WebLion project at Penn State is using Plone to deliver many such sub-sites for their university. You may be interested in their work. http://plone.org http://weblion.psu.edu
Open Source CMS with linked sub-sections and users
I work at a small college that wants to make "sites" for all of the academic departments (~30). I managed to talk them out of their original idea: 30 individual Wordpress installations. What a maintenance nightmare! What I'm looking for is a CMS (preferably Python or PHP, as those are my areas of expertise) that can automagically create a subsection (or subsite, whatever the appropriate vernacular) complete with user and a couple of headings based on a template. So, I could just click a button and have a new subsection for a new department complete with its own authorized user, and default subsection headings/menu/pages. Is this just wishful thinking? I don't mind getting my hands dirty (this would be the whole of my job duties), so what platform would be a good starting point for something like this? Open source is a must for me as I have literally no budget, and I'm probably going to have to dig pretty deep into the application.
[ "Take a look at Drupal or Wordpress MU. With a little bit of scripting and code I think these could do what you need.\nTake a close look at Wordpress MU especially. If they were talking about 30 Wordpress installations then Wordpress MU might be exactly what you want. It provides a unified administration backend to manage multiple wordpress blogs. It's based on the software used to run Wordpress.com. I used to work in an Academic Technologies department as a student programmer and while I was there I helped them get an installation of it set up. Let me tell you - compared to MovableType and Blackboard - it was a dream.\n", "Take a look at Pinax. It uses a templating system to rapidly develop sites. Pinax was created around the idea that there are 'types' of websites and its ridiculous to keep writing the same code over and over for similar sites. This means you could use one of their pre-built templates or create your own and then when you want to build a new site just invoke the template and the site will be ready to go.\n", "Plone does this use case very well. The WebLion project at Penn State is using Plone to deliver many such sub-sites for their university. You may be interested in their work.\nhttp://plone.org\nhttp://weblion.psu.edu \n" ]
[ 2, 0, 0 ]
[]
[]
[ "content_management_system", "open_source", "php", "python" ]
stackoverflow_0002455091_content_management_system_open_source_php_python.txt
Q: WxPython, popup menus, callbacks and Windows XP My goal: the user clicks a button. From the button pops up a two-level menu. The user clicks on something, and this triggers a callback which does stuff. Here is a minimal example: import wx class MyApp(wx.App): def OnInit(self): frame = TestFrame(None, -1, "Hello from wxPython") frame.Show(True) self.SetTopWindow(frame) return True class TestFrame(wx.Frame): def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) sizer = wx.BoxSizer() button = wx.Button(self, label='Click me') sizer.Add(button) self.SetSizerAndFit(sizer) mainmenu = wx.Menu() next_id = 1000000 submenus = {} for title in ['Submenu 1', 'Submenu 2', 'Submenu 3']: mit = wx.MenuItem(mainmenu, id=next_id, text=title) submenu = wx.Menu() mit.SetSubMenu(submenu) mainmenu.AppendItem(mit) next_id = next_id + 1 submenus[title] = submenu items = [('Submenu 1', 'foo'), ('Submenu 1', 'bar'), ('Submenu 2', 'one'), ('Submenu 2', 'two'), ('Submenu 2', 'three'), ('Submenu 3', 'zif'), ('Submenu 3', 'zaf')] for title, item in items: submenu = submenus[title] mit = wx.MenuItem(submenu, id=next_id, text=item) submenu.AppendItem(mit) next_id = next_id + 1 def callback(e, title=title, item=item): print 'Item clicked: %s, %s' % (title, item) self.Bind(wx.EVT_MENU, callback, mit) def show(e): self.PopupMenu(mainmenu, button.GetPosition()) button.Bind(wx.EVT_BUTTON, show) app = MyApp(0) app.MainLoop() Also: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> wx.version() '2.8.10.1 (msw-unicode)' A: You are handling ID generation yourself and in doing that mixing up IDs, anyway you do not need to generate IDs yourself use wx.NewId(), if you replace next_id with that it will work e.g. mit = wx.MenuItem(submenu, id=wx.NewId(), text=item)
WxPython, popup menus, callbacks and Windows XP
My goal: the user clicks a button. From the button pops up a two-level menu. The user clicks on something, and this triggers a callback which does stuff. Here is a minimal example: import wx class MyApp(wx.App): def OnInit(self): frame = TestFrame(None, -1, "Hello from wxPython") frame.Show(True) self.SetTopWindow(frame) return True class TestFrame(wx.Frame): def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) sizer = wx.BoxSizer() button = wx.Button(self, label='Click me') sizer.Add(button) self.SetSizerAndFit(sizer) mainmenu = wx.Menu() next_id = 1000000 submenus = {} for title in ['Submenu 1', 'Submenu 2', 'Submenu 3']: mit = wx.MenuItem(mainmenu, id=next_id, text=title) submenu = wx.Menu() mit.SetSubMenu(submenu) mainmenu.AppendItem(mit) next_id = next_id + 1 submenus[title] = submenu items = [('Submenu 1', 'foo'), ('Submenu 1', 'bar'), ('Submenu 2', 'one'), ('Submenu 2', 'two'), ('Submenu 2', 'three'), ('Submenu 3', 'zif'), ('Submenu 3', 'zaf')] for title, item in items: submenu = submenus[title] mit = wx.MenuItem(submenu, id=next_id, text=item) submenu.AppendItem(mit) next_id = next_id + 1 def callback(e, title=title, item=item): print 'Item clicked: %s, %s' % (title, item) self.Bind(wx.EVT_MENU, callback, mit) def show(e): self.PopupMenu(mainmenu, button.GetPosition()) button.Bind(wx.EVT_BUTTON, show) app = MyApp(0) app.MainLoop() Also: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx >>> wx.version() '2.8.10.1 (msw-unicode)'
[ "You are handling ID generation yourself and in doing that mixing up IDs, anyway you do not need to generate IDs yourself use wx.NewId(), if you replace next_id with that it will work\ne.g.\nmit = wx.MenuItem(submenu, id=wx.NewId(), text=item)\n\n" ]
[ 2 ]
[]
[]
[ "python", "windows_xp", "wxpython" ]
stackoverflow_0002504094_python_windows_xp_wxpython.txt
Q: Hooking up Sproutcore frontend and custom Python backend I am building a web-based application. The frontend has been designed in Sproutcore. For the backend, we have our own python API which handles all transactions with multiple databases. What is the best way to hook up the front-end with the back-end. AFAIK django is pretty monolithic (correct me if i am wrong) and it would be cumbersome if I dont use its native ORM...I would prefer a python-based solution..any ideas? thanks! Suvir A: The only thing I know about sproutcore is what I read about 10 seconds ago to answer this. Javascript can do ajax so I assume so can sproutcore. So providing a restful api+json to your backend would be an option. If you need to sell it to your boss, call it a service oriented architecture. You'll probably have it working before he can look it up in this weeks Information Weekly. All that's required for that to work is anything that can answer an http request and return json. There are a bizillion web frameworks out there that can do this. You mentioned one already and it will probably be mentioned again. I'll go ahead and state my preference though. bfg or pylons either of which will work for you and pretty much stay out of your way. There are others of course, and maybe after playing with them you might find you could write your own pretty easy either using just Webob (used by pylons and bfg and others) or straight wsgi OR a combination of all of them using pieces where appropriate according to your needs. A: There's also Bottle.py if you just want it simple.
Hooking up Sproutcore frontend and custom Python backend
I am building a web-based application. The frontend has been designed in Sproutcore. For the backend, we have our own python API which handles all transactions with multiple databases. What is the best way to hook up the front-end with the back-end. AFAIK django is pretty monolithic (correct me if i am wrong) and it would be cumbersome if I dont use its native ORM...I would prefer a python-based solution..any ideas? thanks! Suvir
[ "The only thing I know about sproutcore is what I read about 10 seconds ago to answer this. Javascript can do ajax so I assume so can sproutcore. So providing a restful api+json to your backend would be an option. If you need to sell it to your boss, call it a service oriented architecture. You'll probably have it working before he can look it up in this weeks Information Weekly. \nAll that's required for that to work is anything that can answer an http request and return json. There are a bizillion web frameworks out there that can do this. You mentioned one already and it will probably be mentioned again. I'll go ahead and state my preference though. bfg or pylons either of which will work for you and pretty much stay out of your way. There are others of course, and maybe after playing with them you might find you could write your own pretty easy either using just Webob (used by pylons and bfg and others) or straight wsgi OR a combination of all of them using pieces where appropriate according to your needs.\n", "There's also Bottle.py if you just want it simple.\n" ]
[ 2, 2 ]
[]
[]
[ "django", "django_models", "python", "sproutcore" ]
stackoverflow_0002504772_django_django_models_python_sproutcore.txt
Q: How do I do multiple processes for Django, on my WSGI apache? My friend says that Django only has 1 thread or something? And I have to edit my 000-default in order to add more processes? He suggests 4 or 5. What exactly is this, and what do I have to do? Thanks, I'm a noob. A: Use the WSGIDaemonProcess directive to put the app in daemon mode and specify the number of daemon processes and threads.
How do I do multiple processes for Django, on my WSGI apache?
My friend says that Django only has 1 thread or something? And I have to edit my 000-default in order to add more processes? He suggests 4 or 5. What exactly is this, and what do I have to do? Thanks, I'm a noob.
[ "Use the WSGIDaemonProcess directive to put the app in daemon mode and specify the number of daemon processes and threads.\n" ]
[ 3 ]
[]
[]
[ "apache", "django", "linux", "python", "unix" ]
stackoverflow_0002505541_apache_django_linux_python_unix.txt
Q: Backup of folder + database - Python I feel like this is quite delicate, I have various folders whith projects I would like to backup into a zip/tar file, but would like to avoid backing up files such as pyc files and temporary files. I also have a Postgres db I need to backup. Any tips for running this operation as a python script? Also, would there be anyway to stop the process from hogging resources in the process? Help would be very much appreciated. A: If you're on Linux (or any other form of Unix, such as MacOSX), a simple way to reduce a process's priority -- and therefore, indirectly, its consumption of CPU if other processes want some -- is the nice command. In Python (same OSs), os.nice lets your program "make itself nicer" (reduce priority &c). For backing up a PostgreSQL DB, I recommend PostgreSQL's own tools; for zipping up a folder except the pyc files (and temporary files -- however it is you identify those), Python is quite suitable. For example: >>> os.chdir('/tmp/az') >>> f = open('/tmp/a.zip', 'wb') >>> z = zipfile.ZipFile(f, 'w') >>> for root, dirs, files in os.walk('.'): ... for fn in files: ... if fn.endswith('.pyc'): continue ... fp = os.path.join(root, fn) ... z.write(fp) ... >>> z.close() >>> f.close() >>> this zips all files in said subtree except those ending in .pyc (without compression -- if you want compression, add a third argument zipfile.ZIP_DEFLATED to the zipfile.ZipFile call). Could hardly be easier. A: On linux, you can use tar with --exclude option. an example, to exclude your .pyc files and temp files (in this example, .tmp) $ tar zcvf backup.tar.gz --exclude "*.tmp" --exclude "*.pyc" use the z option to zip it up as well. A: With today's multicore cpus, you may find that cpu is not the bottle neck. It is now far more likely to the the disk I/O that needs to be shared better. Linux has the ionice command to allow you to control this ionice(1) NAME ionice - get/set program io scheduling class and priority SYNOPSIS ionice [[-c class] [-n classdata ] [-t]] -p PID [PID ...] ionice [-c class] [-n classdata ] [-t] COMMAND [ARG ...] DESCRIPTION This program sets or gets the io scheduling class and priority for a program. If no arguments or just -p is given, ionice will query the current io scheduling class and priority for that process. A: Backup is at least as much about the importance of recovery using whatever backup you make. The right way to back up source code is to keep source files in a VCS (version control system), and back up the VCS repository. Exclude any auto-generated easily-replaced files (like those *.pyc files, etc.) from the VCS repository. I recommend Bazaar for very efficient storage and user-friendliness, but your team will likely already have a VCS they prefer. For backup of a PostgreSQL database, it's best to use pg_dump to regularly dump the database to a text file, compress that, and back up the result. This is because the backup then becomes restorable on any machine, by re-playing the database dump into another PostgreSQL server. As for how to automate it: you would be best using a Bash program for the purpose, since it's just a matter of connecting some commands to files, which is what the shell excels at.
Backup of folder + database - Python
I feel like this is quite delicate, I have various folders whith projects I would like to backup into a zip/tar file, but would like to avoid backing up files such as pyc files and temporary files. I also have a Postgres db I need to backup. Any tips for running this operation as a python script? Also, would there be anyway to stop the process from hogging resources in the process? Help would be very much appreciated.
[ "If you're on Linux (or any other form of Unix, such as MacOSX), a simple way to reduce a process's priority -- and therefore, indirectly, its consumption of CPU if other processes want some -- is the nice command. In Python (same OSs), os.nice lets your program \"make itself nicer\" (reduce priority &c).\nFor backing up a PostgreSQL DB, I recommend PostgreSQL's own tools; for zipping up a folder except the pyc files (and temporary files -- however it is you identify those), Python is quite suitable. For example:\n>>> os.chdir('/tmp/az')\n>>> f = open('/tmp/a.zip', 'wb')\n>>> z = zipfile.ZipFile(f, 'w')\n>>> for root, dirs, files in os.walk('.'):\n... for fn in files:\n... if fn.endswith('.pyc'): continue\n... fp = os.path.join(root, fn)\n... z.write(fp)\n... \n>>> z.close()\n>>> f.close()\n>>> \n\nthis zips all files in said subtree except those ending in .pyc (without compression -- if you want compression, add a third argument zipfile.ZIP_DEFLATED to the zipfile.ZipFile call). Could hardly be easier.\n", "On linux, you can use tar with --exclude option. an example, to exclude your .pyc files and temp files (in this example, .tmp)\n$ tar zcvf backup.tar.gz --exclude \"*.tmp\" --exclude \"*.pyc\"\n\nuse the z option to zip it up as well.\n", "With today's multicore cpus, you may find that cpu is not the bottle neck. It is now far more likely to the the disk I/O that needs to be shared better.\nLinux has the ionice command to allow you to control this\n\nionice(1)\nNAME \n ionice - get/set program io scheduling class and priority\n\nSYNOPSIS \n ionice [[-c class] [-n classdata ] [-t]] -p PID [PID ...]\n\n ionice [-c class] [-n classdata ] [-t] COMMAND [ARG ...]\n\nDESCRIPTION\n This program sets or gets the io scheduling class and priority for a\n program. If no arguments\n or just -p is given, ionice will query the current io scheduling\n class and priority for that\n process.\n\n", "Backup is at least as much about the importance of recovery using whatever backup you make.\nThe right way to back up source code is to keep source files in a VCS (version control system), and back up the VCS repository. Exclude any auto-generated easily-replaced files (like those *.pyc files, etc.) from the VCS repository. I recommend Bazaar for very efficient storage and user-friendliness, but your team will likely already have a VCS they prefer.\nFor backup of a PostgreSQL database, it's best to use pg_dump to regularly dump the database to a text file, compress that, and back up the result. This is because the backup then becomes restorable on any machine, by re-playing the database dump into another PostgreSQL server.\nAs for how to automate it: you would be best using a Bash program for the purpose, since it's just a matter of connecting some commands to files, which is what the shell excels at.\n" ]
[ 4, 2, 1, 1 ]
[]
[]
[ "archiving", "backup", "bash", "postgresql", "python" ]
stackoverflow_0002504907_archiving_backup_bash_postgresql_python.txt
Q: BioPython: extracting sequence IDs from a Blast output file I have a BLAST output file in XML format. It is 22 query sequences with 50 hits reported from each sequence. And I want to extract all the 50x22 hits. This is the code I currently have, but it only extracts the 50 hits from the first query. from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) blast_record = blast_records.next() save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w') for alignment in blast_record.alignments: for hsp in alignment.hsps: save_file.write('>%s\n' % (alignment.title,)) save_file.close() Somebody have any suggestions as to extract all the hits? I guess I have to use something else than alignments. Hope this was clear. Thanks! Jon A: This should get all records. The novelty compared with the original is the for blast_record in blast_records which is a python idiom to iterate through items in a "list-like" object, such as the blast_records (checking the CBIXML module documentation showed that parse() indeed returns an iterator) from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w') for blast_record in blast_records: for alignment in blast_record.alignments: for hsp in alignment.hsps: save_file.write('>%s\n' % (alignment.title,)) #here possibly to output something to file, between each blast_record save_file.close() A: I used this code for extract all the results from Bio.Blast import NCBIXML for record in NCBIXML.parse(open("rpoD.xml")) : print "QUERY: %s" % record.query for align in record.alignments : print " MATCH: %s..." % align.title[:60] for hsp in align.hsps : print " HSP, e=%f, from position %i to %i" \ % (hsp.expect, hsp.query_start, hsp.query_end) if hsp.align_length < 60 : print " Query: %s" % hsp.query print " Match: %s" % hsp.match print " Sbjct: %s" % hsp.sbjct else : print " Query: %s..." % hsp.query[:57] print " Match: %s..." % hsp.match[:57] print " Sbjct: %s..." % hsp.sbjct[:57] print "Done" or for less details from Bio.Blast import NCBIXML for record in NCBIXML.parse(open("NC_003197.xml")) : #We want to ignore any queries with no search results: if record.alignments : print "QUERY: %s..." % record.query[:60] for align in record.alignments : for hsp in align.hsps : print " %s HSP, e=%f, from position %i to %i" \ % (align.hit_id, hsp.expect, hsp.query_start, hsp.query_end) print "Done" I used this site http://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/python/rpsblast/
BioPython: extracting sequence IDs from a Blast output file
I have a BLAST output file in XML format. It is 22 query sequences with 50 hits reported from each sequence. And I want to extract all the 50x22 hits. This is the code I currently have, but it only extracts the 50 hits from the first query. from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) blast_record = blast_records.next() save_file = open("/Users/jonbra/Desktop/my_fasta_seq.fasta", 'w') for alignment in blast_record.alignments: for hsp in alignment.hsps: save_file.write('>%s\n' % (alignment.title,)) save_file.close() Somebody have any suggestions as to extract all the hits? I guess I have to use something else than alignments. Hope this was clear. Thanks! Jon
[ "This should get all records. The novelty compared with the original is the\nfor blast_record in blast_records\n\nwhich is a python idiom to iterate through items in a \"list-like\" object, such as the blast_records (checking the CBIXML module documentation showed that parse() indeed returns an iterator)\nfrom Bio.Blast import NCBIXM\nblast_records = NCBIXML.parse(result_handle)\n\nsave_file = open(\"/Users/jonbra/Desktop/my_fasta_seq.fasta\", 'w')\n\nfor blast_record in blast_records:\n for alignment in blast_record.alignments:\n for hsp in alignment.hsps:\n save_file.write('>%s\\n' % (alignment.title,))\n #here possibly to output something to file, between each blast_record\nsave_file.close()\n\n", "I used this code for extract all the results\nfrom Bio.Blast import NCBIXML\nfor record in NCBIXML.parse(open(\"rpoD.xml\")) :\n print \"QUERY: %s\" % record.query\n for align in record.alignments :\n print \" MATCH: %s...\" % align.title[:60]\n for hsp in align.hsps :\n print \" HSP, e=%f, from position %i to %i\" \\\n % (hsp.expect, hsp.query_start, hsp.query_end)\n if hsp.align_length < 60 :\n print \" Query: %s\" % hsp.query\n print \" Match: %s\" % hsp.match\n print \" Sbjct: %s\" % hsp.sbjct\n else :\n print \" Query: %s...\" % hsp.query[:57]\n print \" Match: %s...\" % hsp.match[:57]\n print \" Sbjct: %s...\" % hsp.sbjct[:57]\n\n\nprint \"Done\"\n\nor for less details\nfrom Bio.Blast import NCBIXML\nfor record in NCBIXML.parse(open(\"NC_003197.xml\")) :\n #We want to ignore any queries with no search results:\n if record.alignments :\n print \"QUERY: %s...\" % record.query[:60]\n for align in record.alignments :\n for hsp in align.hsps :\n print \" %s HSP, e=%f, from position %i to %i\" \\\n % (align.hit_id, hsp.expect, hsp.query_start, hsp.query_end)\nprint \"Done\"\n\nI used this site\nhttp://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/python/rpsblast/\n" ]
[ 3, 2 ]
[]
[]
[ "biopython", "python", "xml_parsing", "xmlblaster" ]
stackoverflow_0001684470_biopython_python_xml_parsing_xmlblaster.txt
Q: sqlite3 'database is locked' won't go away with retries I have a sqlite3 database that is accessed by a few threads (3-4). I am aware of the general limitations of sqlite3 with regards to concurrency as stated http://www.sqlite.org/faq.html#q6 , but I am convinced that is not the problem. All of the threads both read and write from this database. Whenever I do a write, I have the following construct: try: Cursor.execute(q, params) Connection.commit() except sqlite3.IntegrityError: Notify except sqlite3.OperationalError: print sys.exc_info() print("DATABASE LOCKED; sleeping for 3 seconds and trying again") time.sleep(3) Retry On some runs, I won't even hit this block, but when I do, it never comes out of it (keeps retrying, but I keep getting the 'database is locked' error from exc_info. If I understand the reader/writer lock usage correctly, some amount of waiting should help with the contention. What this sounds like is deadlock, but I do not use any transactions in my code, and every SELECT or INSERT is simply a one off. Some threads, however, keep the same connection when they do their operation (which includes a mix of SELECTS and INSERTS and other modifiers). I would appericiate it if you could shade a light on this, and also ways around fixing it (besides using a different database engine.) A: Sqlite locks the entire database every time you try to write to the database. Is there any chance one of your threads is constantly writing? Is only one thread hitting the Database lock or all buy one of them? A: Here is a not-so-elegant temporary fix: using an external exclusive lock around the writes rather than depend on internal sqlite locking. The above block in the question is basically wrapped with a system wide lock that every thread has to acquire before writing. Since sqlite3 locks the entire DB when writing anyways, I am hoping this doesn't add a lot more overhead. On the other hand, reads can proceed without acquiring the lock, which I think might work ok with the less-restrictive reader lock sqlite3 needs. A: I also suffered from this, on a website that had ~200 users per day (which transalted to maybe 1000 page views). Retries just didn't help (and I finally increased their number up to 100, with short sleeps in between). I don't remember which version of SQLite it was, but I learned the lesson that if you want to have reliable concurrent writes to SQLite database, then you better use some other database like MySQL or PostgreSQL. This holds up even if you solve your problem with OperationalError-s, because eventually concurrent writes to SQLite file will kill performance for good.
sqlite3 'database is locked' won't go away with retries
I have a sqlite3 database that is accessed by a few threads (3-4). I am aware of the general limitations of sqlite3 with regards to concurrency as stated http://www.sqlite.org/faq.html#q6 , but I am convinced that is not the problem. All of the threads both read and write from this database. Whenever I do a write, I have the following construct: try: Cursor.execute(q, params) Connection.commit() except sqlite3.IntegrityError: Notify except sqlite3.OperationalError: print sys.exc_info() print("DATABASE LOCKED; sleeping for 3 seconds and trying again") time.sleep(3) Retry On some runs, I won't even hit this block, but when I do, it never comes out of it (keeps retrying, but I keep getting the 'database is locked' error from exc_info. If I understand the reader/writer lock usage correctly, some amount of waiting should help with the contention. What this sounds like is deadlock, but I do not use any transactions in my code, and every SELECT or INSERT is simply a one off. Some threads, however, keep the same connection when they do their operation (which includes a mix of SELECTS and INSERTS and other modifiers). I would appericiate it if you could shade a light on this, and also ways around fixing it (besides using a different database engine.)
[ "Sqlite locks the entire database every time you try to write to the database. Is there any chance one of your threads is constantly writing? Is only one thread hitting the Database lock or all buy one of them?\n", "Here is a not-so-elegant temporary fix: using an external exclusive lock around the writes rather than depend on internal sqlite locking. The above block in the question is basically wrapped with a system wide lock that every thread has to acquire before writing. Since sqlite3 locks the entire DB when writing anyways, I am hoping this doesn't add a lot more overhead.\nOn the other hand, reads can proceed without acquiring the lock, which I think might work ok with the less-restrictive reader lock sqlite3 needs. \n", "I also suffered from this, on a website that had ~200 users per day (which transalted to maybe 1000 page views). Retries just didn't help (and I finally increased their number up to 100, with short sleeps in between). I don't remember which version of SQLite it was, but I learned the lesson that if you want to have reliable concurrent writes to SQLite database, then you better use some other database like MySQL or PostgreSQL.\nThis holds up even if you solve your problem with OperationalError-s, because eventually concurrent writes to SQLite file will kill performance for good.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002051243_python_sqlite.txt
Q: A business Case for Enterprise Python This will not be a "programming" question but more technology / platform related question. I'm trying to figure out whether Python can be a suitable Java alternative for enterprise / web applications. Which are the ideal cases where you would prefer to use Python instead of Java? How would a typical Python web application (databases/sessions/concurrency) perform as compared to a typical Java application? How do specific Python frameworks square up against Java based frameworks (Spring, SEAM, Grails etc.)? For businesses, switching from the Java infrastructure to a Python infrastructure .. is it too hard/expensive/resource intensive/not viable? Also shed some light on the business case for providing a Python + Google AppEngine based solution to the end customer. Will it be cost effective in an typical scenario? Sorry if I am asking too wide a question, I would have liked to keep it specific, but I need your help to evaluate Python as a whole from the perspectives of the programmers, service providing company and end business customer. For an SME, a Python/GoogleAppEngine based technology stack is a clear scalable and affordable platform. But what about a large MNC that already has a lot invested in Java. Thank you so much. I am researching this myself and will gladly share my conclusions here! Thank you, Srirangan A: An enterprise that already has a terabucks of Java investments should add jython to their mix of technologies -- it can be adopted gradually and progressively, at first for ancillary functions such as testing, "one-off" data migrations &c, prototyping of new functionality, cases in which using some existing open source Python library is obviously very handy, and so on, and so forth -- then, as the many Java developers in the company learn to use Jython, some of the prototypes will just be put in production as Jython code because there would be no advantage recoding them, some old subsystem needing recoding will be recoded in Jython, and so forth. It's never really a wise decision to throw away a huge existing and working codebase and the ginormous investment it represents -- Python's strengths include its wealth of strong, production-level implementations, how well they "play with others", and how well Python can gradually and incrementally infiltrate most any development shop. A: The larger your investment in an existing technology is, the more expensive it is to move away from it. COBOL is perhaps the best example here. That investment isn't just in porting existing solutions, but also in retraining or hiring new staff so that you have the skill sets to build and support the new technologies even while still maintaining your legacy solutions. Add to that the fact that for most large Multinational Corporations, software isn't their core business. As long as it functions effectively and fulfills the business need, they don't tend to care so much about the 'details'. You need to be able to offer some pretty compelling benefits to overcome this kind of inertia. Sad but true. A: If you need to do the sort of things you can do with Django, then Django and Python is totally what you want. Google App Engine runs Django as well. So, you can do a Django app and host it on Google App Engine, and later change your mind and switch to conventional server hosting, or self-hosting if you have your own server. I haven't tried Google App Engine but my understanding is that the price is quite reasonable for what you get. Google's IT department does a great job of keeping their data centers going; if you outsource the hosting to Google App Engine you know your data is backed up, you know the servers won't go down, and even if a backhoe takes a whole Google data center off the Internet, some other Google data center will keep serving up your application to your customers. You also know that if your application suddenly becomes hugely popular, Google App Engine wil l scale up automatically to handle the load. (I think you set a cap for the maximum you are willing to pay, and it scales until it hits the cap. But as I said I haven't used it and I'm not certain.) I haven't used Java yet, but from what I have seen of it, Python is a much more expressive language and skilled Python coders can get more work done in a day just because the language is that much better. However, if you already have invested in Java and have in-house expertise in Java, you would be crazy to walk away from that overnight. The correct thing is to pick one new project to just try out that crazy Python thing. And I really do recommend Django. You can get the Django book and try out the tutorial. If your first pilot project in Python is a Django project, you should have an easy time of things. A: The answer to your question is yes. Python can be well suited for Enterprise because python is a language which has raw power, flexible and can be glued with other programming languages. What enterprise really requires is a language which does everything and i feel python is already enterprise ready. If you want examples then i believe there can be no bigger example than google. Google is running python internally and externally for its business critical applications. The only problem with python is that it is not very well recognized by top MNC company and we as a python programmer find hard time convincing the management team. I guess you will face the same issue. But i guarantee you once you get your feet wet in python, you will understand its true power A: There is -- almost -- no usable "Business Case" for any technology choice. "what about a large MNC that already has a lot invested in Java" Ask around. See if there's a business case for Java. I doubt you'll find anything. Most companies drift into technology choices slowly. There was no business case for COBOL -- it was the only game in town in the olden days. There is rarely a business case for Java. What usually happens is that some visionary individual started building the first web site (probably in Perl). The "web thing" gained traction, and some vision individual started building web sites in Java. Eventually, the success of those small teams indicated to others that Java had advantages over COBOL. Managers say the words "make a business case", but watch what they actually do. They listen to (1) their peers, (2) successful people. To make the "business case" for Python, you have to be that visionary individual. 1) Use Python. 2) Be successful. 3) Share your successes. 4) Be prepared to explain that your success is due to your tools, not your personal level of genius and charisma.
A business Case for Enterprise Python
This will not be a "programming" question but more technology / platform related question. I'm trying to figure out whether Python can be a suitable Java alternative for enterprise / web applications. Which are the ideal cases where you would prefer to use Python instead of Java? How would a typical Python web application (databases/sessions/concurrency) perform as compared to a typical Java application? How do specific Python frameworks square up against Java based frameworks (Spring, SEAM, Grails etc.)? For businesses, switching from the Java infrastructure to a Python infrastructure .. is it too hard/expensive/resource intensive/not viable? Also shed some light on the business case for providing a Python + Google AppEngine based solution to the end customer. Will it be cost effective in an typical scenario? Sorry if I am asking too wide a question, I would have liked to keep it specific, but I need your help to evaluate Python as a whole from the perspectives of the programmers, service providing company and end business customer. For an SME, a Python/GoogleAppEngine based technology stack is a clear scalable and affordable platform. But what about a large MNC that already has a lot invested in Java. Thank you so much. I am researching this myself and will gladly share my conclusions here! Thank you, Srirangan
[ "An enterprise that already has a terabucks of Java investments should add jython to their mix of technologies -- it can be adopted gradually and progressively, at first for ancillary functions such as testing, \"one-off\" data migrations &c, prototyping of new functionality, cases in which using some existing open source Python library is obviously very handy, and so on, and so forth -- then, as the many Java developers in the company learn to use Jython, some of the prototypes will just be put in production as Jython code because there would be no advantage recoding them, some old subsystem needing recoding will be recoded in Jython, and so forth.\nIt's never really a wise decision to throw away a huge existing and working codebase and the ginormous investment it represents -- Python's strengths include its wealth of strong, production-level implementations, how well they \"play with others\", and how well Python can gradually and incrementally infiltrate most any development shop.\n", "The larger your investment in an existing technology is, the more expensive it is to move away from it. COBOL is perhaps the best example here.\nThat investment isn't just in porting existing solutions, but also in retraining or hiring new staff so that you have the skill sets to build and support the new technologies even while still maintaining your legacy solutions.\nAdd to that the fact that for most large Multinational Corporations, software isn't their core business. As long as it functions effectively and fulfills the business need, they don't tend to care so much about the 'details'. \nYou need to be able to offer some pretty compelling benefits to overcome this kind of inertia.\nSad but true.\n", "If you need to do the sort of things you can do with Django, then Django and Python is totally what you want. Google App Engine runs Django as well. So, you can do a Django app and host it on Google App Engine, and later change your mind and switch to conventional server hosting, or self-hosting if you have your own server.\nI haven't tried Google App Engine but my understanding is that the price is quite reasonable for what you get. Google's IT department does a great job of keeping their data centers going; if you outsource the hosting to Google App Engine you know your data is backed up, you know the servers won't go down, and even if a backhoe takes a whole Google data center off the Internet, some other Google data center will keep serving up your application to your customers. You also know that if your application suddenly becomes hugely popular, Google App Engine wil l scale up automatically to handle the load. (I think you set a cap for the maximum you are willing to pay, and it scales until it hits the cap. But as I said I haven't used it and I'm not certain.)\nI haven't used Java yet, but from what I have seen of it, Python is a much more expressive language and skilled Python coders can get more work done in a day just because the language is that much better. However, if you already have invested in Java and have in-house expertise in Java, you would be crazy to walk away from that overnight. The correct thing is to pick one new project to just try out that crazy Python thing.\nAnd I really do recommend Django. You can get the Django book and try out the tutorial. If your first pilot project in Python is a Django project, you should have an easy time of things.\n", "The answer to your question is yes. Python can be well suited for Enterprise because python is a language which has raw power, flexible and can be glued with other programming languages. What enterprise really requires is a language which does everything and i feel python is already enterprise ready. If you want examples then i believe there can be no bigger example than google. Google is running python internally and externally for its business critical applications. The only problem with python is that it is not very well recognized by top MNC company and we as a python programmer find hard time convincing the management team. I guess you will face the same issue. But i guarantee you once you get your feet wet in python, you will understand its true power\n", "There is -- almost -- no usable \"Business Case\" for any technology choice.\n\"what about a large MNC that already has a lot invested in Java\" Ask around. See if there's a business case for Java.\nI doubt you'll find anything. Most companies drift into technology choices slowly.\nThere was no business case for COBOL -- it was the only game in town in the olden days.\nThere is rarely a business case for Java. What usually happens is that some visionary individual started building the first web site (probably in Perl). The \"web thing\" gained traction, and some vision individual started building web sites in Java. Eventually, the success of those small teams indicated to others that Java had advantages over COBOL.\nManagers say the words \"make a business case\", but watch what they actually do. They listen to (1) their peers, (2) successful people. \nTo make the \"business case\" for Python, you have to be that visionary individual.\n1) Use Python.\n2) Be successful.\n3) Share your successes.\n4) Be prepared to explain that your success is due to your tools, not your personal level of genius and charisma.\n" ]
[ 14, 4, 1, 1, 0 ]
[]
[]
[ "enterprise", "python" ]
stackoverflow_0001879113_enterprise_python.txt
Q: ways to execute python So far to execute a Python program, I'm using > python file.py I want to run the Python script simply using file name, like > file.py similar to shell scripts like > sh file.sh > chmod +x file.sh > ./file.sh or move file.sh to bin and then run > file.sh A: Put this at the top of your Python script: #!/usr/bin/env python The #! part is called a shebang, and the env command will simply locate python on your $PATH and execute the script through it. You could hard-code the path to the python interpreter, too, but calling /usr/bin/env is a little more flexible. (For instance, if you're using virtualenv, that python interpreter will be found on your $PATH.) A: You ca also target the specific location of the python interpreter you wan to use, if you need to specify it (e.g, you're using different versions) Just add to the shebang line (the one starting with #!) the complete path of the interpreter you wan to use, for example #!/home/user/python2.6/bin/python But, in general, is better just to take the default using /usr/bin/env, as Mike says, as you don't have to rely on a particular path.
ways to execute python
So far to execute a Python program, I'm using > python file.py I want to run the Python script simply using file name, like > file.py similar to shell scripts like > sh file.sh > chmod +x file.sh > ./file.sh or move file.sh to bin and then run > file.sh
[ "Put this at the top of your Python script:\n#!/usr/bin/env python\n\nThe #! part is called a shebang, and the env command will simply locate python on your $PATH and execute the script through it. You could hard-code the path to the python interpreter, too, but calling /usr/bin/env is a little more flexible. (For instance, if you're using virtualenv, that python interpreter will be found on your $PATH.)\n", "You ca also target the specific location of the python interpreter you wan to use, if you need to specify it (e.g, you're using different versions) Just add to the shebang line (the one starting with #!) the complete path of the interpreter you wan to use, for example\n#!/home/user/python2.6/bin/python\n\nBut, in general, is better just to take the default using /usr/bin/env, as Mike says, as you don't have to rely on a particular path.\n" ]
[ 17, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002506437_python.txt
Q: Bash or python for changing spacing in files I have a set of 10000 files. In all of them, the second line, looks like: AAA 3.429 3.84 so there is just one space (requirement) between AAA and the two other columns. The rest of lines on each file are completely different and correspond to 10 columns of numbers. Randomly, in around 20% of the files, and due to some errors, one gets BBB 3.429 3.84 so now there are two spaces between the first and second column. This is a big error so I need to fix it, changing from 2 to 1 space in the files where the error takes place. The first approach I thought of was to write a bash script that for each file reads the 3 values of the second line and then prints them with just one space, doing it for all the files. I wonder what do oyu think about this approach and if you could suggest something better, bashm python or someother approach. Thanks A: Performing line-based changes to text files is often simplest to do in sed. sed -e '2s/ */ /g' infile.txt will replace any runs of multiple spaces with a single space. This may be changing more than you want, though. sed -e '2s/^\([^ ]*\) /\1 /' infile.txt should just replace instances of two spaces after the first block of space-free text with a single space (though I have not tested this). (edit: inserted 2 before s in each instance to tie the edit to the second line, specifically.) A: Use sed. for file in * do sed -i '' '2s/ / /' "$file" done The -i '' flag means to edit in-place without a backup. Or use ed! for file in * do printf "2s/ / /\nwq\n" |ed -s "$file" done A: if the error always can occur at 2nd line, for file in file* do awk 'NR==2{$1=$1}1' file >temp mv temp "$file" done or sed sed -i.bak '2s/ */ /' file* # do 2nd line Or just pure bash scripting i=1 while read -r line do if [ "$i" -eq 2 ];then echo $line else echo "$line" fi ((i++)) done <"file" A: I am going to be different and go with AWK: awk '{print $1,$2,$3}' file.txt > file1.txt This will handle any number of spaces between fields, and replace them with one space To handle a specific line you can add line addresses: awk 'NR==2{print $1,$2,$3} NR!=2{print $0}' file.txt > file1.txt i.e. rewrite line 2, but leave unchanged the other lines. A line address can be a regular expression as well: awk '/regexp/{print $1,$2,$3} !/regexp/{print}' file.txt > file1.txt A: Since it seems every column is separated by one space, another approach not yet mentioned is to use tr to squeeze all multi spaces into single spaces: tr -s " " < infile > outfile A: I don't quite understand, but yes, sed is an option. I don't think any POSIX compliant version of sed has an in file option (-i), so a fully POSIX compliant solution would be. sed -e 's/^BBB /BBB /' <file> > <newfile> A: This answer assumes you don't want to mess with any except the second line. #!/usr/bin/env python import sys, os for fname in sys.argv[1:]: with open(fname, "r") as fin: line1 = fin.readline() line2 = fin.readline() fixedLine2 = " ".join(line2.split()) + '\n' if fixedLine2 == line2: continue with open(fname + ".fixed", "w") as fout: fout.write(line1) fout.write(line2) for line in fin: fout.write(line) # Enable these lines if you want the old files replaced with the new ones. #os.remove(fname) #os.rename(fname + ".fixed", fname) A: Use sed: sed -e 's/[[:space:]][[:space:]]/ /g' yourfile.txt >> newfile.txt This will replace any two adjacent spaces with one. The use of [[:space:]] just makes it a little bit clearer A: sed -i -e '2s/ / /g' input.txt -i: edit files in place
Bash or python for changing spacing in files
I have a set of 10000 files. In all of them, the second line, looks like: AAA 3.429 3.84 so there is just one space (requirement) between AAA and the two other columns. The rest of lines on each file are completely different and correspond to 10 columns of numbers. Randomly, in around 20% of the files, and due to some errors, one gets BBB 3.429 3.84 so now there are two spaces between the first and second column. This is a big error so I need to fix it, changing from 2 to 1 space in the files where the error takes place. The first approach I thought of was to write a bash script that for each file reads the 3 values of the second line and then prints them with just one space, doing it for all the files. I wonder what do oyu think about this approach and if you could suggest something better, bashm python or someother approach. Thanks
[ "Performing line-based changes to text files is often simplest to do in sed.\nsed -e '2s/ */ /g' infile.txt\n\nwill replace any runs of multiple spaces with a single space. This may be changing more than you want, though.\nsed -e '2s/^\\([^ ]*\\) /\\1 /' infile.txt\n\nshould just replace instances of two spaces after the first block of space-free text with a single space (though I have not tested this).\n(edit: inserted 2 before s in each instance to tie the edit to the second line, specifically.)\n", "Use sed.\nfor file in *\ndo\n sed -i '' '2s/ / /' \"$file\"\ndone\n\nThe -i '' flag means to edit in-place without a backup.\nOr use ed!\nfor file in *\ndo\n printf \"2s/ / /\\nwq\\n\" |ed -s \"$file\"\ndone\n\n", "if the error always can occur at 2nd line, \nfor file in file*\ndo\n awk 'NR==2{$1=$1}1' file >temp\n mv temp \"$file\" \ndone\n\nor sed\nsed -i.bak '2s/ */ /' file* # do 2nd line\n\nOr just pure bash scripting\ni=1\nwhile read -r line\ndo\n if [ \"$i\" -eq 2 ];then\n echo $line\n else\n echo \"$line\"\n fi\n ((i++))\ndone <\"file\"\n\n", "I am going to be different and go with AWK:\nawk '{print $1,$2,$3}' file.txt > file1.txt\n\nThis will handle any number of spaces between fields, and replace them with one space\nTo handle a specific line you can add line addresses:\nawk 'NR==2{print $1,$2,$3} NR!=2{print $0}' file.txt > file1.txt\n\ni.e. rewrite line 2, but leave unchanged the other lines.\nA line address can be a regular expression as well:\nawk '/regexp/{print $1,$2,$3} !/regexp/{print}' file.txt > file1.txt\n\n", "Since it seems every column is separated by one space, another approach not yet mentioned is to use tr to squeeze all multi spaces into single spaces:\n\ntr -s \" \" < infile > outfile\n", "I don't quite understand, but yes, sed is an option. I don't think any POSIX compliant version of sed has an in file option (-i), so a fully POSIX compliant solution would be.\nsed -e 's/^BBB /BBB /' <file> > <newfile>\n\n", "This answer assumes you don't want to mess with any except the second line.\n#!/usr/bin/env python\nimport sys, os\nfor fname in sys.argv[1:]:\n with open(fname, \"r\") as fin:\n line1 = fin.readline()\n line2 = fin.readline()\n fixedLine2 = \" \".join(line2.split()) + '\\n'\n if fixedLine2 == line2:\n continue\n with open(fname + \".fixed\", \"w\") as fout:\n fout.write(line1)\n fout.write(line2)\n for line in fin:\n fout.write(line)\n # Enable these lines if you want the old files replaced with the new ones.\n #os.remove(fname)\n #os.rename(fname + \".fixed\", fname)\n\n", "Use sed:\nsed -e 's/[[:space:]][[:space:]]/ /g' yourfile.txt >> newfile.txt\n\nThis will replace any two adjacent spaces with one. The use of [[:space:]] just makes it a little bit clearer\n", "sed -i -e '2s/ / /g' input.txt\n\n-i: edit files in place\n" ]
[ 8, 6, 4, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002500358_bash_python.txt
Q: SWIG: Python list to uint32_t *? I'm trying to work with a Python module that was generated by SWIG. There's a C++ class defined that works like this (simplified): namespace Foo { class Thing { public: Thing(); ~Thing(); bool DoSomething(uint32_t x, uint32_t y, uint32_t z, uint32_t *buffer); }; }; When I try to call it from Python, I get an error about the last argument needing to be of type 'uint32_t*'. Normal Python integers work just fine for the other arguments, so I can't understand why a list of ints wouldn't work for the buffer. Any suggestions? A: The last parameter to DoSomething is a pointer to uint32_t, not uint32_t. So unlike the other parameters, the function expects to receive a pointer to an integer or an array of integers (since arrays can be used wherever pointers are expected). I suspect in this case (because it's called 'buffer') that the function expects an array. You should take a look at the SWIG documentation on Unbounded C arrays.
SWIG: Python list to uint32_t *?
I'm trying to work with a Python module that was generated by SWIG. There's a C++ class defined that works like this (simplified): namespace Foo { class Thing { public: Thing(); ~Thing(); bool DoSomething(uint32_t x, uint32_t y, uint32_t z, uint32_t *buffer); }; }; When I try to call it from Python, I get an error about the last argument needing to be of type 'uint32_t*'. Normal Python integers work just fine for the other arguments, so I can't understand why a list of ints wouldn't work for the buffer. Any suggestions?
[ "The last parameter to DoSomething is a pointer to uint32_t, not uint32_t. So unlike the other parameters, the function expects to receive a pointer to an integer or an array of integers (since arrays can be used wherever pointers are expected).\nI suspect in this case (because it's called 'buffer') that the function expects an array. You should take a look at the SWIG documentation on Unbounded C arrays.\n" ]
[ 2 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0002503592_c++_python_swig.txt
Q: Python and .exe files, another way How to build exe files from py files (compatible with win32)? please don't refer to py2exe. that is blocked service in IRI. for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge? A: Pick up a mirror like this http://git.kitsu.ru/mirrors/py2exe.git and download it with git clone, and compile it by running setup.py after that. A: How about PyInstaller (link to preliminary python 2.6 on Windows bin)? A: Legal issues aside, blocked sites can be accessed (and downloaded from) using any external web proxy. Edit: Does this work for you? Sourceforge.net through hidemyass.com. A: How about cx_Freeze, is that blocked? Refer to: http://cx-freeze.sourceforge.net/
Python and .exe files, another way
How to build exe files from py files (compatible with win32)? please don't refer to py2exe. that is blocked service in IRI. for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?
[ "Pick up a mirror like this \nhttp://git.kitsu.ru/mirrors/py2exe.git\nand download it with git clone, and compile it by running setup.py after that.\n", "How about PyInstaller (link to preliminary python 2.6 on Windows bin)?\n", "Legal issues aside, blocked sites can be accessed (and downloaded from) using any external web proxy.\nEdit: Does this work for you? Sourceforge.net through hidemyass.com.\n", "How about cx_Freeze, is that blocked?\nRefer to: http://cx-freeze.sourceforge.net/\n" ]
[ 4, 3, 1, 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0002506857_py2exe_python.txt
Q: String searching algorithm for Chinese characters There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese characters? I am referring to this: http://en.literateprograms.org/Boyer-Moore_string_search_algorithm_(Python)#References A: As long as all your text is in unicodes it should work just fine. The algorithm looks sequence-independent, provided each "element" is one sequence-unit in length.
String searching algorithm for Chinese characters
There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese characters? I am referring to this: http://en.literateprograms.org/Boyer-Moore_string_search_algorithm_(Python)#References
[ "As long as all your text is in unicodes it should work just fine. The algorithm looks sequence-independent, provided each \"element\" is one sequence-unit in length.\n" ]
[ 3 ]
[]
[]
[ "cjk", "python", "string_search", "unicode" ]
stackoverflow_0002506970_cjk_python_string_search_unicode.txt
Q: Having trouble scraping an ASP .NET web page I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup: conn = Http() # do a get first to retrieve important values page = conn.request(u"http://somepage.com/Search.aspx", "GET") #event_validation and viewstate variables retrieved from GET here... body = {"__EVENTARGUMENT" : "", "__EVENTTARGET" : "" , "__EVENTVALIDATION": event_validation, "__VIEWSTATE" : viewstate, "ctl00_ContentPlaceHolder1_GovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_NonGovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_SchoolKeyValue" : "", "ctl00_ContentPlaceHolder1_SchoolNameTextBox" : "", "ctl00_ContentPlaceHolder1_ScriptManager1" : "ctl00_ContentPlaceHolder1_UpdatePanel1|cct100_ContentPlaceHolder1_SearchImageButton", "ct100_ContentPlaceHolder1_SearchImageButton.x" : "375", "ct100_ContentPlaceHolder1_SearchImageButton.y" : "11", "ctl00_ContentPlaceHolder1_SuburbTownTextBox" : "Adelaide,SA,5000", "hiddenInputToUpdateATBuffer_CommonToolkitScripts" : 1} headers = {"Content-type": "application/x-www-form-urlencoded"} resp, content = conn.request(url,"POST", headers=headers, body=urlencode(body)) When I print content I still seem to be getting the same results as the "GET" or is there a fundamental concept I'm missing to retrieve the result values of an ASP .NET post? A: This isn't technically an answer, but you could use Fiddler to examine the difference between what you are sending with your python code, versus what would be sent if you used a web browser to do the post. I find that usually helps in these types of situations. A: Well, You need to see first what you have written in the page for get and post, but I hope you are making sure both requests are sending different contents. here is how you can do that if(!IsPostBack) { Response.Write("<h1>Get Request</h1>"); } else { Response.Write("<h1>POST Request</h1>"); } I hope you are using C# as code behind
Having trouble scraping an ASP .NET web page
I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup: conn = Http() # do a get first to retrieve important values page = conn.request(u"http://somepage.com/Search.aspx", "GET") #event_validation and viewstate variables retrieved from GET here... body = {"__EVENTARGUMENT" : "", "__EVENTTARGET" : "" , "__EVENTVALIDATION": event_validation, "__VIEWSTATE" : viewstate, "ctl00_ContentPlaceHolder1_GovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_NonGovernmentCheckBox" : "On", "ctl00_ContentPlaceHolder1_SchoolKeyValue" : "", "ctl00_ContentPlaceHolder1_SchoolNameTextBox" : "", "ctl00_ContentPlaceHolder1_ScriptManager1" : "ctl00_ContentPlaceHolder1_UpdatePanel1|cct100_ContentPlaceHolder1_SearchImageButton", "ct100_ContentPlaceHolder1_SearchImageButton.x" : "375", "ct100_ContentPlaceHolder1_SearchImageButton.y" : "11", "ctl00_ContentPlaceHolder1_SuburbTownTextBox" : "Adelaide,SA,5000", "hiddenInputToUpdateATBuffer_CommonToolkitScripts" : 1} headers = {"Content-type": "application/x-www-form-urlencoded"} resp, content = conn.request(url,"POST", headers=headers, body=urlencode(body)) When I print content I still seem to be getting the same results as the "GET" or is there a fundamental concept I'm missing to retrieve the result values of an ASP .NET post?
[ "This isn't technically an answer, but you could use Fiddler to examine the difference between what you are sending with your python code, versus what would be sent if you used a web browser to do the post.\nI find that usually helps in these types of situations.\n", "Well, You need to see first what you have written in the page for get and post, but I hope you are making sure both requests are sending different contents. \nhere is how you can do that\n\nif(!IsPostBack)\n{\nResponse.Write(\"<h1>Get Request</h1>\");\n}\nelse\n{\nResponse.Write(\"<h1>POST Request</h1>\");\n}\n\nI hope you are using C# as code behind\n" ]
[ 2, 0 ]
[]
[]
[ "asp.net", "python" ]
stackoverflow_0002507280_asp.net_python.txt
Q: Use BeautifulSoup to extract sibling nodes between two nodes I've got a document like this: <p class="top">I don't want this</p> <p>I want this</p> <table> <!-- ... --> </table> <img ... /> <p> and all that stuff too</p> <p class="end>But not this and nothing after it</p> I want to extract everything between the p[class=top] and p[class=end] paragraphs. Is there a nice way I can do this with BeautifulSoup? A: node.nextSibling attribute is your solution: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) nextNode = soup.find('p', {'class': 'top'}) while True: # process nextNode = nextNode.nextSibling if getattr(nextNode, 'name', None) == 'p' and nextNode.get('class', None) == 'end': break This complicated condition is to be sure that you're accessing attributes of HTML tag and not string nodes.
Use BeautifulSoup to extract sibling nodes between two nodes
I've got a document like this: <p class="top">I don't want this</p> <p>I want this</p> <table> <!-- ... --> </table> <img ... /> <p> and all that stuff too</p> <p class="end>But not this and nothing after it</p> I want to extract everything between the p[class=top] and p[class=end] paragraphs. Is there a nice way I can do this with BeautifulSoup?
[ "node.nextSibling attribute is your solution:\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(html)\n\nnextNode = soup.find('p', {'class': 'top'})\nwhile True:\n # process\n nextNode = nextNode.nextSibling\n if getattr(nextNode, 'name', None) == 'p' and nextNode.get('class', None) == 'end':\n break\n\nThis complicated condition is to be sure that you're accessing attributes of HTML tag and not string nodes.\n" ]
[ 8 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002507301_beautifulsoup_python.txt
Q: Detecting Infinite recursion in Python or dynamic languages Recently I tried compiling program something like this with GCC: int f(int i){ if(i<0){ return 0;} return f(i-1); f(100000); and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f. And - the compiler wasn't even running in optimized mode. Now, when I try the same thing in Python - I hit maximum recursion wall (or probably stack overflow if i set recursion depth too high). Is there way that a dynamic language like python can take advantage of these nice optimizations? Maybe it's possible to use a compiler instead of an interpreter to make this work? Just curious! A: The optimisation you're talking about is known as tail call elimination - a recursive call is unfolded into an iterative loop. There has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See Guido's blog entry for some discussion. However, there do exist some decorators that manipulate the function to perform this optimisation. They generally only obtain the space saving though, not time (in fact, they're generally slower) A: When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f. What you're describing is called "tail recursion". Some compilers/interpreters support it, some don't. Most don't, in fact. As you noticed, gcc does. And in fact, tail recursion is a part of the spec for the Scheme programming language, so all Scheme compilers/interpreters must support tail recursion. On the other hand, the compilers for languages like Java and Python (as well as most other languages, I'd wager) don't do tail recursion. Is there way that a dynamic language like python can take advantage of these nice optimizations? Do you mean, right now, or are you asking in more abstract terms? Speaking abstractly, yes! It would absolutely be possible for dynamic languages to take advantage of tail recursion (Scheme does, for example). But speaking concretely, no, CPython (the canonical Python interpreter) doesn't have a flag or other parameter to enable tail recursion. A: It has nothing to do with the fact that it is a dynamic language or that it is interpreted. CPython just doesn't implement Tail Recursion optimization. You may find that JPython etc do.
Detecting Infinite recursion in Python or dynamic languages
Recently I tried compiling program something like this with GCC: int f(int i){ if(i<0){ return 0;} return f(i-1); f(100000); and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f. And - the compiler wasn't even running in optimized mode. Now, when I try the same thing in Python - I hit maximum recursion wall (or probably stack overflow if i set recursion depth too high). Is there way that a dynamic language like python can take advantage of these nice optimizations? Maybe it's possible to use a compiler instead of an interpreter to make this work? Just curious!
[ "The optimisation you're talking about is known as tail call elimination - a recursive call is unfolded into an iterative loop.\nThere has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See Guido's blog entry for some discussion.\nHowever, there do exist some decorators that manipulate the function to perform this optimisation. They generally only obtain the space saving though, not time (in fact, they're generally slower)\n", "\nWhen I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f.\n\nWhat you're describing is called \"tail recursion\". Some compilers/interpreters support it, some don't. Most don't, in fact. As you noticed, gcc does. And in fact, tail recursion is a part of the spec for the Scheme programming language, so all Scheme compilers/interpreters must support tail recursion. On the other hand, the compilers for languages like Java and Python (as well as most other languages, I'd wager) don't do tail recursion.\n\nIs there way that a dynamic language like python can take advantage of these nice optimizations?\n\nDo you mean, right now, or are you asking in more abstract terms? Speaking abstractly, yes! It would absolutely be possible for dynamic languages to take advantage of tail recursion (Scheme does, for example). But speaking concretely, no, CPython (the canonical Python interpreter) doesn't have a flag or other parameter to enable tail recursion.\n", "It has nothing to do with the fact that it is a dynamic language or that it is interpreted. CPython just doesn't implement Tail Recursion optimization. You may find that JPython etc do.\n" ]
[ 12, 6, 4 ]
[]
[]
[ "compiler_construction", "gcc", "python" ]
stackoverflow_0002507395_compiler_construction_gcc_python.txt
Q: C++ Arrays manipulations (python-like operations) I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this: values = numpy.array(inp.data) idx1 = numpy.where(values > -2.14) idx2 = numpy.where(values < 2.0) res1 = (values[idx1] - diff1)/1000 res2 = (values[idx2] - diff2)*1000 In python it's just 5 lines, but the simplest way in C++ i can think of is quite a number of nested loops. Pls advise.. Basically my question is concerning the array/vector operations like array multiplications, operations on indexs, etc.. In the example above, res1 is an array, containing a set of elements filtered out of values array and some arithmetics applied afterward (subtraction, multiplication for all selected elements). In this python example I'm not copying elements of values array as it could be big enough in terms of memory, i'm keeping only the indexes and want to be able to run arithmetic operations on a selected set of elements of the original array. A: You should not be using arrays at all. Please sit down and learn about the std::vector class and about iterators and Standard Library algorithms. I strongly suggest reading the book The C++ Standard Library. A: You can achieve something similar in C++ but you shouldn't use plain C arrays for it. The easiest way I can see this work would be using a std::set of floats (your code looks like it assumes that the data is sorted in ascending order). You could also use a std::vector of float but you'll have to sort that yourself, probably by using std::sort. In that case, your example code could look like this - the set assumes the values are unique, if they aren't, you could use a std::multiset instead; std::set<float> values(inp.data.begin(), inp.data.end()); std::set<float>::iterator idx1 = values.lower_bound(-2.14); std::set<float>::iterator idx2 = values.upper_bound(2.0); float res1 = (*idx1 - diff1) / 1000.0; float res2 = (*idx2 - diff2) / 1000.0; Please note that the above code sample is not a 100% conversion of your original code - lower_boundgives you the first element that's equal or larger than -2.14. I also didn't put any checking code in for failures - if lower_bound or upper_bound can't find matching elements, they would return values.end(), for example. Using vector, the example would look very similar, just one line more to pre-sort the vector: std::vector<float> values(inp.data.begin(), inp.data.end()); std::sort(values.begin(), values.end(); std::vector<float>::iterator idx1 = std::lower_bound(values.begin(), values.end(), -2.14); std::vector<float>::iterator idx2 = std::upper_bound(values.begin(), values.end(), 2.0); float res1 = (*idx1 - diff1) / 1000.0; float res2 = (*idx2 - diff2) / 1000.0; A: I suggest you to check the algorithm header. Also don't work with arrays, you have std::vector or boost(soon to be std)::array. wikipedia article Reference for all algorithms A: If I'm not mistaken, numpy is written mostly in C (with a Python wrapper), so you could be able to use it directly from C++ without much effort. A: If you combine std::vector and boost::lambda, you can come really close to your example: #include <algorithm> #include <iostream> #include <vector> #include <boost/lambda/lambda.hpp> using boost::lambda::_1; int main() { float ary[10] = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }; std::vector<float> v(&ary[0], &ary[10]); std::vector<float>::iterator iter1, iter2; iter1 = std::find_if(v.begin(), v.end(), (_1 > -2.14)); iter2 = std::find_if(v.begin(), v.end(), (_1 < 2.0)); // output: // iter1 = -2.000 // iter2 = 1.000 std::cout << "iter1 = " << *iter1 << "\n" << "iter2 = " << *iter2 << "\n" << std::endl; return 0; }
C++ Arrays manipulations (python-like operations)
I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this: values = numpy.array(inp.data) idx1 = numpy.where(values > -2.14) idx2 = numpy.where(values < 2.0) res1 = (values[idx1] - diff1)/1000 res2 = (values[idx2] - diff2)*1000 In python it's just 5 lines, but the simplest way in C++ i can think of is quite a number of nested loops. Pls advise.. Basically my question is concerning the array/vector operations like array multiplications, operations on indexs, etc.. In the example above, res1 is an array, containing a set of elements filtered out of values array and some arithmetics applied afterward (subtraction, multiplication for all selected elements). In this python example I'm not copying elements of values array as it could be big enough in terms of memory, i'm keeping only the indexes and want to be able to run arithmetic operations on a selected set of elements of the original array.
[ "You should not be using arrays at all. Please sit down and learn about the std::vector class and about iterators and Standard Library algorithms. I strongly suggest reading the book The C++ Standard Library.\n", "You can achieve something similar in C++ but you shouldn't use plain C arrays for it.\nThe easiest way I can see this work would be using a std::set of floats (your code looks like it assumes that the data is sorted in ascending order). You could also use a std::vector of float but you'll have to sort that yourself, probably by using std::sort.\nIn that case, your example code could look like this - the set assumes the values are unique, if they aren't, you could use a std::multiset instead;\nstd::set<float> values(inp.data.begin(), inp.data.end());\nstd::set<float>::iterator idx1 = values.lower_bound(-2.14);\nstd::set<float>::iterator idx2 = values.upper_bound(2.0);\n\nfloat res1 = (*idx1 - diff1) / 1000.0;\nfloat res2 = (*idx2 - diff2) / 1000.0;\n\nPlease note that the above code sample is not a 100% conversion of your original code - lower_boundgives you the first element that's equal or larger than -2.14. I also didn't put any checking code in for failures - if lower_bound or upper_bound can't find matching elements, they would return values.end(), for example.\nUsing vector, the example would look very similar, just one line more to pre-sort the vector:\nstd::vector<float> values(inp.data.begin(), inp.data.end());\nstd::sort(values.begin(), values.end();\nstd::vector<float>::iterator idx1 = std::lower_bound(values.begin(), values.end(), -2.14);\nstd::vector<float>::iterator idx2 = std::upper_bound(values.begin(), values.end(), 2.0);\n\nfloat res1 = (*idx1 - diff1) / 1000.0;\nfloat res2 = (*idx2 - diff2) / 1000.0;\n\n", "I suggest you to check the algorithm header.\nAlso don't work with arrays, you have std::vector or boost(soon to be std)::array.\nwikipedia article\nReference for all algorithms\n", "If I'm not mistaken, numpy is written mostly in C (with a Python wrapper), so you could be able to use it directly from C++ without much effort.\n", "If you combine std::vector and boost::lambda, you can come really close to your example:\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <boost/lambda/lambda.hpp>\n\nusing boost::lambda::_1;\n\nint main() {\n float ary[10] = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };\n std::vector<float> v(&ary[0], &ary[10]);\n std::vector<float>::iterator iter1, iter2;\n\n iter1 = std::find_if(v.begin(), v.end(), (_1 > -2.14));\n iter2 = std::find_if(v.begin(), v.end(), (_1 < 2.0));\n\n // output:\n // iter1 = -2.000\n // iter2 = 1.000\n std::cout\n << \"iter1 = \" << *iter1 << \"\\n\"\n << \"iter2 = \" << *iter2 << \"\\n\"\n << std::endl;\n return 0;\n}\n\n" ]
[ 5, 5, 4, 1, 1 ]
[]
[]
[ "arrays", "c++", "python" ]
stackoverflow_0002507422_arrays_c++_python.txt
Q: Scripting in Java Me and some friends are writing a MORPG in Java, and we would like to use a scripting language to, eg. to create quests. We have non experience with scripting in Java. We have used Python, but we are very inexperienced with it. One of us also have used Javascript. What scripting language should we use? What scripting language should we not use? A: I'm responsible for a fairly large hybrid Java/Jython system. We use java for core API development, then wire Java objects together using Jython. This is in a scientific computing environment where we need to be able to put together ad-hoc data analysis scripts quickly. If I were starting this system from scratch today, I would not choose Jython as the scripting language. I like Python fine, but I frequently encounter awkward mismatches between the Python type system and the Java type system. For example, if you just want a hashtable, should you use a Python dictionary or a Java HashMap? The decision might be different depending on whether you are just using the data structure locally in Python code or passing it across the Java boundary. Jython does a certain amount of type coercion for you, but it's not perfect. It's annoying to even have to think about issues like this when the purpose of using a scripting language in the first place is to enhance your productivity. I assume JavaScript or JRuby would have similar issues. Today I would choose a scripting language that is specifically targeted to the JVM and leverages the Java type system. The obvious candidates are Groovy and Beanshell; Groovy seems to have been picking up momentum lately so I'd look most closely at it. A: I agree with Viktor's Jython suggestion. Other than that and JavaScript (which you've mentioned, and is built into Java 6+ via the javax.script package), Groovy and JRuby are also worth looking at too. By the way, you should look at Wyvern, also an MMORPG written in Java and using Jython for scripting. Steve Yegge, its author, has much to say about it from time to time. :-) A: Java supports a variety of (scripting) languages, some are listed in Wikipedia here and here. You probably should choose language with powerful DSL and metaprogramming capabilities, such as Clojure. But if you need something simpler, JavaScript might be a viable alternative. A: How about Jython? http://www.jython.org/Project/ A: what about creating your own specialized scripting language? If your app is written with java, you can use ANTLR (http://www.antlr.org/) to create your language parsing code. The reason I say this is because a general purpose scripting language may provide too much power (because the script it to be used for quests only i assume). But if making your own language is too hard then any of the above suggestions works - you just have to figure out how to bind the game's runtime into the script. I also suggest Lua (http://www.lua.org/) as another choice that lots of games use. A: Short version Don’t use a scripting language! Instead focus on configurability (which is something that a non-programmer can do well). Longer version One oft-used argument in favour of having a scripting language is that it allows for lesser programmers to more trivial tasks. Don't belive this, it will not save you any time, since trivial tasks are already accomplished by real programmers in no time. Aim for configurability instead of scripting, and you will have a much lower risk of bleeding over complex algorithms and concepts into the incapable hands of game designers. :) Lack of hotswapping (edit-and-continue) would have been a reason to implement a scripting language in an MMOG (you don’t want to reload the whole game for a minor code change), but using Java, with built-in hotswap, you really have no reason for adding a scripting language on top. I have spent years pondering these questions; in the day I implemented a complete scripting language, IDE, VM, debugger, etc for an MMOG myself. Since, I have grown wiser. If you still choose to go down the infinitely crappy path of no return, keep the following in mind. Pick a mature language which has been around for a while. Auto testing, debugging and editing will suck bigtime until you make your own tools/plugins/start hacking around in the VM. To date, I have never seen a DSL that improved the situation (getting a more maintainable product). Myself, I integrated Python into my indie game engine, but eventually came to my senses and ripped it out. "Stackless Python" is just a way of saying "unmaintainable but fast". Please, anyone correct me if I'm wrong? A: See Java: Scripting language (macro) to embed into a Java desktop application A: You have quite a few options: Groovy - http://groovy.codehaus.org/ Jython - http://www.jython.org/Project/ JRuby - http://jruby.codehaus.org/ Possibly even BeanShell (http://www.beanshell.org/) I'm a fan of Python myself so I'd recommend Jython, but they're probably all reasonable options. A: I would have to recommend Javascript for this purpose. Mozilla Rhino http://www.mozilla.org/rhino/ is an excellent implementation that would fit your needs perfectly. I recommend Javascript over Jython or JRuby because of familiarity. Trivial Javascript follows a very familiar syntax that anybody can use. However if someone wants to do something more intense, Javascript is a very powerful functional programming language. I regularly use Groovy and Ruby professionally and believe that their purpose is best for writing parts of applications with particularly complex logic where Java is cumbersome to write. Javascript is a much better choice as an embedded, general scripting language to use in a game. I haven't used Python, but it's syntactically similar to Ruby and I would believe it's purpose would also be similar. A: LuaJ seems to be a nice way to embed Lua into Java: http://sourceforge.net/projects/luaj/ A: I am a big fan of Python/Jython due to the clean syntax - which may suit you if you have some python experience. Otherwise Groovy which is based on Java syntax and may be an easier learning curve if most of your developers are Java guys. It also has the advantage of closer ties with the Java language and libraries. Beanshell is good if you have simple scripting in mind - it doesn't support classes. However I don't think it has had any support over the last few years (the JSR seemed to kill it off...) so is perhaps a bad choice if support is important to you.
Scripting in Java
Me and some friends are writing a MORPG in Java, and we would like to use a scripting language to, eg. to create quests. We have non experience with scripting in Java. We have used Python, but we are very inexperienced with it. One of us also have used Javascript. What scripting language should we use? What scripting language should we not use?
[ "I'm responsible for a fairly large hybrid Java/Jython system. We use java for core API development, then wire Java objects together using Jython. This is in a scientific computing environment where we need to be able to put together ad-hoc data analysis scripts quickly.\nIf I were starting this system from scratch today, I would not choose Jython as the scripting language. I like Python fine, but I frequently encounter awkward mismatches between the Python type system and the Java type system. For example, if you just want a hashtable, should you use a Python dictionary or a Java HashMap? The decision might be different depending on whether you are just using the data structure locally in Python code or passing it across the Java boundary. Jython does a certain amount of type coercion for you, but it's not perfect. It's annoying to even have to think about issues like this when the purpose of using a scripting language in the first place is to enhance your productivity. \nI assume JavaScript or JRuby would have similar issues. Today I would choose a scripting language that is specifically targeted to the JVM and leverages the Java type system. The obvious candidates are Groovy and Beanshell; Groovy seems to have been picking up momentum lately so I'd look most closely at it.\n", "I agree with Viktor's Jython suggestion. Other than that and JavaScript (which you've mentioned, and is built into Java 6+ via the javax.script package), Groovy and JRuby are also worth looking at too.\nBy the way, you should look at Wyvern, also an MMORPG written in Java and using Jython for scripting. Steve Yegge, its author, has much to say about it from time to time. :-)\n", "Java supports a variety of (scripting) languages, some are listed in Wikipedia here and here. You probably should choose language with powerful DSL and metaprogramming capabilities, such as Clojure.\nBut if you need something simpler, JavaScript might be a viable alternative.\n", "How about Jython?\nhttp://www.jython.org/Project/\n", "what about creating your own specialized scripting language? If your app is written with java, you can use ANTLR (http://www.antlr.org/) to create your language parsing code. \nThe reason I say this is because a general purpose scripting language may provide too much power (because the script it to be used for quests only i assume). \nBut if making your own language is too hard then any of the above suggestions works - you just have to figure out how to bind the game's runtime into the script. I also suggest Lua (http://www.lua.org/) as another choice that lots of games use.\n", "Short version\nDon’t use a scripting language! Instead focus on configurability (which is something that a non-programmer can do well).\nLonger version\nOne oft-used argument in favour of having a scripting language is that it allows for lesser programmers to more trivial tasks. Don't belive this, it will not save you any time, since trivial tasks are already accomplished by real programmers in no time. Aim for configurability instead of scripting, and you will have a much lower risk of bleeding over complex algorithms and concepts into the incapable hands of game designers. :)\nLack of hotswapping (edit-and-continue) would have been a reason to implement a scripting language in an MMOG (you don’t want to reload the whole game for a minor code change), but using Java, with built-in hotswap, you really have no reason for adding a scripting language on top.\nI have spent years pondering these questions; in the day I implemented a complete scripting language, IDE, VM, debugger, etc for an MMOG myself. Since, I have grown wiser.\nIf you still choose to go down the infinitely crappy path of no return, keep the following in mind.\n\nPick a mature language which has been around for a while.\nAuto testing, debugging and editing will suck bigtime until you make your own tools/plugins/start hacking around in the VM.\n\nTo date, I have never seen a DSL that improved the situation (getting a more maintainable product). Myself, I integrated Python into my indie game engine, but eventually came to my senses and ripped it out. \"Stackless Python\" is just a way of saying \"unmaintainable but fast\". Please, anyone correct me if I'm wrong?\n", "See Java: Scripting language (macro) to embed into a Java desktop application\n", "You have quite a few options:\n\nGroovy - http://groovy.codehaus.org/\nJython - http://www.jython.org/Project/\nJRuby - http://jruby.codehaus.org/\n\nPossibly even BeanShell (http://www.beanshell.org/)\nI'm a fan of Python myself so I'd recommend Jython, but they're probably all reasonable options. \n", "I would have to recommend Javascript for this purpose. Mozilla Rhino http://www.mozilla.org/rhino/ is an excellent implementation that would fit your needs perfectly.\nI recommend Javascript over Jython or JRuby because of familiarity. Trivial Javascript follows a very familiar syntax that anybody can use. However if someone wants to do something more intense, Javascript is a very powerful functional programming language.\nI regularly use Groovy and Ruby professionally and believe that their purpose is best for writing parts of applications with particularly complex logic where Java is cumbersome to write. Javascript is a much better choice as an embedded, general scripting language to use in a game. I haven't used Python, but it's syntactically similar to Ruby and I would believe it's purpose would also be similar.\n", "LuaJ seems to be a nice way to embed Lua into Java:\nhttp://sourceforge.net/projects/luaj/\n", "I am a big fan of Python/Jython due to the clean syntax - which may suit you if you have some python experience. \nOtherwise Groovy which is based on Java syntax and may be an easier learning curve if most of your developers are Java guys. It also has the advantage of closer ties with the Java language and libraries. \nBeanshell is good if you have simple scripting in mind - it doesn't support classes. However I don't think it has had any support over the last few years (the JSR seemed to kill it off...) so is perhaps a bad choice if support is important to you.\n" ]
[ 9, 7, 5, 4, 4, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "javascript", "python", "scripting_language" ]
stackoverflow_0000211536_java_javascript_python_scripting_language.txt
Q: read only permission in admin interface I saw this post, https://stackoverflow.com/posts/1348076/revisions , only at step 3 i'm getting confused, he tells to put 3. Add "get_view_permission" to default model class but what's the default model class? It doesn't seem to work to me, i get following error message: AttributeError at /admin/ 'Options' object has no attribute 'get_view_permission' Request Method: GET Request URL: Exception Type: AttributeError Exception Value: 'Options' object has no attribute 'get_view_permission' So he complains about no get_view_permission, but where to place this get_view_permission??? Regards, T A: Looks like he means in django/db/models.py.
read only permission in admin interface
I saw this post, https://stackoverflow.com/posts/1348076/revisions , only at step 3 i'm getting confused, he tells to put 3. Add "get_view_permission" to default model class but what's the default model class? It doesn't seem to work to me, i get following error message: AttributeError at /admin/ 'Options' object has no attribute 'get_view_permission' Request Method: GET Request URL: Exception Type: AttributeError Exception Value: 'Options' object has no attribute 'get_view_permission' So he complains about no get_view_permission, but where to place this get_view_permission??? Regards, T
[ "Looks like he means in django/db/models.py.\n" ]
[ 0 ]
[]
[]
[ "admin", "django", "permissions", "python" ]
stackoverflow_0002508027_admin_django_permissions_python.txt
Q: Repeatedly querying xml using python I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. The way it works is I run the scripts several times with different arguments, depending on what I want to find out. These files can be relatively large (10MB+) and so it takes rather a long time to parse them. On my system, just running: tree = ElementTree.parse(document) takes around 30 seconds, with a subsequent findall query only adding around a second to that. Seeing as the way I'm doing this requires me to repeatedly parse the file, I was wondering if there was some sort of caching mechanism I can use so that the ElementTree.parse computation can be reduced on subsequent queries. I realise the smart thing to do here may be to try and batch as many queries as possible together in the python script, but I was hoping there might be another way. Thanks. A: While I second the suggestion to use lxml, you can get a huge performance boost by using the builtin cElementTree. from xml.etree import cElementTree as ElementTree A: First off, consider using the lxml implementation of ElementTree: http://lxml.de/ This is a wrapper for libxml2, which I find performs well. Run python interactively, make multiple queries against the same etree object. ipython is an enhanced interactive python interpreter with easy access to introspection and convenience-syntax. E.g. interactively examining note.xml with ipython using lxml.etree. $ ipython Python 2.5.1 (r251:54863, Jul 10 2008, 17:24:48) Type "copyright", "credits" or "license" for more information. IPython 0.8.2 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: from lxml import etree In [2]: doc = etree.parse(open("note.xml")) In [3]: etree.dump(doc.getroot()) <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In [4]: doc.xpath('/note/*') Out[4]: [<Element to at 89cf02c>, <Element from at 89cf054>, <Element heading at 89cf07c>, <Element body at 89cf0a4>] A: Seconding the lxml recommendation, look at this article for how to improve performance by using an iterative (SAX-like) parsing method. It can be a pain at first since it can turn really procedural and messy, but it makes things faster. As you can see from these benchmarks, lxml is most likely your best bet for performance.
Repeatedly querying xml using python
I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. The way it works is I run the scripts several times with different arguments, depending on what I want to find out. These files can be relatively large (10MB+) and so it takes rather a long time to parse them. On my system, just running: tree = ElementTree.parse(document) takes around 30 seconds, with a subsequent findall query only adding around a second to that. Seeing as the way I'm doing this requires me to repeatedly parse the file, I was wondering if there was some sort of caching mechanism I can use so that the ElementTree.parse computation can be reduced on subsequent queries. I realise the smart thing to do here may be to try and batch as many queries as possible together in the python script, but I was hoping there might be another way. Thanks.
[ "While I second the suggestion to use lxml, you can get a huge performance boost by using the builtin cElementTree.\nfrom xml.etree import cElementTree as ElementTree\n\n", "First off, consider using the lxml implementation of ElementTree:\nhttp://lxml.de/\nThis is a wrapper for libxml2, which I find performs well.\nRun python interactively, make multiple queries against the same etree object. ipython is an enhanced interactive python interpreter with easy access to introspection and convenience-syntax.\nE.g. interactively examining note.xml with ipython using lxml.etree.\n$ ipython\nPython 2.5.1 (r251:54863, Jul 10 2008, 17:24:48)\nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython 0.8.2 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython's features.\n%quickref -> Quick reference.\nhelp -> Python's own help system.\nobject? -> Details about 'object'. ?object also works, ?? prints more.\n\nIn [1]: from lxml import etree\n\nIn [2]: doc = etree.parse(open(\"note.xml\"))\n\nIn [3]: etree.dump(doc.getroot())\n<note>\n <to>Tove</to>\n <from>Jani</from>\n <heading>Reminder</heading>\n <body>Don't forget me this weekend!</body>\n</note>\nIn [4]: doc.xpath('/note/*')\nOut[4]:\n[<Element to at 89cf02c>,\n <Element from at 89cf054>,\n <Element heading at 89cf07c>,\n <Element body at 89cf0a4>]\n\n", "Seconding the lxml recommendation, look at this article for how to improve performance by using an iterative (SAX-like) parsing method. It can be a pain at first since it can turn really procedural and messy, but it makes things faster. As you can see from these benchmarks, lxml is most likely your best bet for performance.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "caching", "elementtree", "python", "xml" ]
stackoverflow_0002507772_caching_elementtree_python_xml.txt
Q: Getting the previous line in Jython I want to print the line immediately before the searched string. How can I do that? Lets say my two lines are AADRG SDFJGKDFSDF and I am searching for SDF. I have found SDFJGKDFSDF, but how can I obtain the previous line AADRG? Does file.readline()-1 work? A: lastLine = "" for line in lines: if line.find("SDF"): print lastLine lastLine = line or lines = open("file").readlines() for line in lines: if "SDF" in line: # test for not being the first line of course. print lines[lines.index(line) - 1]
Getting the previous line in Jython
I want to print the line immediately before the searched string. How can I do that? Lets say my two lines are AADRG SDFJGKDFSDF and I am searching for SDF. I have found SDFJGKDFSDF, but how can I obtain the previous line AADRG? Does file.readline()-1 work?
[ "lastLine = \"\"\nfor line in lines:\n if line.find(\"SDF\"):\n print lastLine\n\n lastLine = line\n\nor \nlines = open(\"file\").readlines()\nfor line in lines:\n if \"SDF\" in line:\n # test for not being the first line of course.\n print lines[lines.index(line) - 1]\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002508279_python.txt
Q: wxPython & pyGame Assignment I'm actually in need of your help and advice here on my assignment that I am working on. First of all, I was task to do a program that runs langton's ant simulation. For that, I've managed to get the source code (from snippets.dzone.com/posts/show/5143) and edited it accordingly to my requirements. This was done and ran in pygame module extension. In addition, my task requires a GUI to interface for users to run and navigate through the screens effectively with the langton's ant program running. I used wxPython with the help of an IDE called BOA constructor to create the frames, buttons, textboxes, etc. Basically, all the stuff needed in the interfaces. However, I've ran into some problems listed below: Found problem integrating pyGame with wxPython. On this note, I've research the internet for answers and tutorials where I found out from website: wiki.wxpython.org/IntegratingPyGame & aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3178042. I understand from the sites that integrating pyGame with wxPython will be a difficult task where it has caused common problems like the inability to placing other controls into the frames as the pyGame application will cover the entire panel. I really hope that you can clarify my doubts on this and advise me on the path that I should take from here. Therefore, I ask the following questions: Is it feasible to integrate pyGame with wxPython? If it is not feasible to integrate pyGame with wxPython, what other alternatives do I have to create a GUI interface integrating pyGame into it. If so how do I go about? If it is possible to go about integrating pyGame with wxPython, how do I go about doing so? Really need you guys opinion on this. A: Here's the page for you: pygame GUI discussion To sum it up: Don't use any standard GUI stuff together with pygame. It might work, but it's most definitely gonna annoy you big time. Also on this page, there's a discussion of various different GUI libraries available which work directly in pygame. It sounds like you only need some standard widgets, so you should be up and running in no time with one of these.
wxPython & pyGame Assignment
I'm actually in need of your help and advice here on my assignment that I am working on. First of all, I was task to do a program that runs langton's ant simulation. For that, I've managed to get the source code (from snippets.dzone.com/posts/show/5143) and edited it accordingly to my requirements. This was done and ran in pygame module extension. In addition, my task requires a GUI to interface for users to run and navigate through the screens effectively with the langton's ant program running. I used wxPython with the help of an IDE called BOA constructor to create the frames, buttons, textboxes, etc. Basically, all the stuff needed in the interfaces. However, I've ran into some problems listed below: Found problem integrating pyGame with wxPython. On this note, I've research the internet for answers and tutorials where I found out from website: wiki.wxpython.org/IntegratingPyGame & aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3178042. I understand from the sites that integrating pyGame with wxPython will be a difficult task where it has caused common problems like the inability to placing other controls into the frames as the pyGame application will cover the entire panel. I really hope that you can clarify my doubts on this and advise me on the path that I should take from here. Therefore, I ask the following questions: Is it feasible to integrate pyGame with wxPython? If it is not feasible to integrate pyGame with wxPython, what other alternatives do I have to create a GUI interface integrating pyGame into it. If so how do I go about? If it is possible to go about integrating pyGame with wxPython, how do I go about doing so? Really need you guys opinion on this.
[ "Here's the page for you: pygame GUI discussion\nTo sum it up: Don't use any standard GUI stuff together with pygame. It might work, but it's most definitely gonna annoy you big time. Also on this page, there's a discussion of various different GUI libraries available which work directly in pygame. It sounds like you only need some standard widgets, so you should be up and running in no time with one of these.\n" ]
[ 1 ]
[]
[]
[ "pygame", "python", "wxpython" ]
stackoverflow_0002508352_pygame_python_wxpython.txt
Q: List of dict in Python I've got a list of dict in Python: dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream} self.list_cfg.append(dico_cfg) I append to my list a lot of dict in the same way. Now I would like to delete one dict and only one dict in this list? What is the best way to proceed? I've try with the index of the list, but when I remove a dict from the list, the index is modify, so after some random remove my index doesn't correspond anymore to the dict I want to remove in my list. I hope that is clear. Maybe I can add an "id" row in my dict, so I can ask to remove more preciously the dict I want. I'll ask to remove the dict where id is equal to the id's dict I want to remove. How can I do that? I hope I'm enough clear. Sorry but I'm a newbie in Python. A: A better solution would be to have a dict of dicts instead, indexed by the id attribute. This way, even if you remove a single dict, the other id's still remain the same. A: If you have a reference to the dictionary you want to remove, you can try: self.list_cfg.remove( your_dictionary ) If you don't have any reference to it, you'll have to try to find it first: for d in self.list_cfg: if d['name']=='Some name': # or some other check to identify your dict self.list_cfg.remove(d) break A: If I get you correctly, you don't want the indices to change when you remove an element from your list of dicts. One solution is to use a dict of dicts instead. dictOne = {'foo':'bar'} dictTwo = {'bar':'foo'} dictOfDicts = {0:dictOne, 1:dictTwo} #and so on #now, del(dict[1]) will remove your element without affecting the indices of the other ones. A: Identifying the dictionaries with an extra entry, as you suggest, is one viable idea: dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream, 'id': 'dico_cfg'} self.list_cfg.append(dico_cfg) and later self.list_cfg[:] = [d for d in self.list_cfg if d.get('id') != 'dico_cfg'] Note that I'm assigning to the full list slice (the [:] syntax), not to the list name -- the latter may give the impression of working sometimes, but it doesn't modify the list object (just rebinds a name), so if there are other references to the list object they won't be modified. Anyway, assigning to the name (instead of to the [:]) has no advantage unless you want to keep the original object unmodified through other references. A: If you have a reference to a dict, d in the list, you can remove it directly without needing to use an index: list.remove(d)
List of dict in Python
I've got a list of dict in Python: dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream} self.list_cfg.append(dico_cfg) I append to my list a lot of dict in the same way. Now I would like to delete one dict and only one dict in this list? What is the best way to proceed? I've try with the index of the list, but when I remove a dict from the list, the index is modify, so after some random remove my index doesn't correspond anymore to the dict I want to remove in my list. I hope that is clear. Maybe I can add an "id" row in my dict, so I can ask to remove more preciously the dict I want. I'll ask to remove the dict where id is equal to the id's dict I want to remove. How can I do that? I hope I'm enough clear. Sorry but I'm a newbie in Python.
[ "A better solution would be to have a dict of dicts instead, indexed by the id attribute. This way, even if you remove a single dict, the other id's still remain the same.\n", "If you have a reference to the dictionary you want to remove, you can try:\nself.list_cfg.remove( your_dictionary )\n\nIf you don't have any reference to it, you'll have to try to find it first:\nfor d in self.list_cfg:\n if d['name']=='Some name': # or some other check to identify your dict\n self.list_cfg.remove(d)\n break\n\n", "If I get you correctly, you don't want the indices to change when you remove an element from your list of dicts. One solution is to use a dict of dicts instead.\ndictOne = {'foo':'bar'}\ndictTwo = {'bar':'foo'}\ndictOfDicts = {0:dictOne, 1:dictTwo} #and so on\n\n#now, del(dict[1]) will remove your element without affecting the indices of the other ones.\n\n", "Identifying the dictionaries with an extra entry, as you suggest, is one viable idea:\ndico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor,\n 'stream': combo_stream, 'id': 'dico_cfg'}\nself.list_cfg.append(dico_cfg)\n\nand later\nself.list_cfg[:] = [d for d in self.list_cfg if d.get('id') != 'dico_cfg']\n\nNote that I'm assigning to the full list slice (the [:] syntax), not to the list name -- the latter may give the impression of working sometimes, but it doesn't modify the list object (just rebinds a name), so if there are other references to the list object they won't be modified. Anyway, assigning to the name (instead of to the [:]) has no advantage unless you want to keep the original object unmodified through other references.\n", "If you have a reference to a dict, d in the list, you can remove it directly without needing to use an index:\nlist.remove(d)\n" ]
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002508513_dictionary_list_python.txt
Q: Most efficient way to concatenate and rearrange files I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. Currently I am using two loops: one to pull out all the headers and write them, and the second to write the body of each file (I also include a tmp_count variable to limit the number of lines to be loading into memory before dumping to file). This is pretty slow - about 6min for 13gb file. Can anyone tell me how to optimize this or if there is a faster way to do this in python ? Thanks! Here is my code: def cat_files_sam(final_file_name,work_directory_master,file_count): final_file = open(final_file_name,"w") if len(file_count) > 1: file_count=sort_output_files(file_count) # only for @ headers for bowtie_file in file_count: #print bowtie_file tmp_list = [] tmp_count = 0 for line in open(os.path.join(work_directory_master,bowtie_file)): if line.startswith("@"): if tmp_count == 1000000: final_file.writelines(tmp_list) tmp_list = [] tmp_count = 0 tmp_list.append(line) tmp_count += 1 else: final_file.writelines(tmp_list) break for bowtie_file in file_count: #print bowtie_file tmp_list = [] tmp_count = 0 for line in open(os.path.join(work_directory_master,bowtie_file)): if line.startswith("@"): continue if tmp_count == 1000000: final_file.writelines(tmp_list) tmp_list = [] tmp_count = 0 tmp_list.append(line) tmp_count += 1 final_file.writelines(tmp_list) final_file.close() A: How fast would you expect it to be to move 13Gb of data around? This problem is I/O bound and not a problem with Python. To make it faster, do less I/O. Which means that you are either (a) stuck with the speed you've got or (b) should retool later elements of your toolchain to handle the files in-place rather than requiring one giant 13 Gb file. A: You can save the time it takes the 2nd time to skip the headers, as long as you have a reasonable amount of spare disk space: as well as the final file, also open (for 'w+') a temporary file temp_file, and do: import shutil hdr_list = [] bod_list = [] dispatch = {True: (hdr_list, final_file), False: (bod_list, temp_file)} for bowtie_file in file_count: with open(os.path.join(work_directory_master,bowtie_file)) as f: for line in f: L, fou = dispatch[line[0]=='@'] L.append(f) if len(L) == 1000000: fou.writelines(L) del L[:] # write final parts, if any for L, fou in dispatch.items(): if L: fou.writelines(L) temp_file.seek(0) shutil.copyfileobj(temp_file, final_file) This should enhance your program's performance. Fine-tuning that now-hard-coded 1000000, or even completely doing away with the lists and writing each line directly to the appropriate file (final or temporary), are other options you should benchmark (but if you have unbounded amounts of memory, then I expect that they won't matter much -- however, intuitions about performance are often misleading, so it's best to try and measure!-). A: There are two gross inefficiencies in the code you meant to write (which is not the code presented): You are building up huge lists of header lines in the first major for block instead of just writing them out. You are skipping the headers of the files again in the second major for block line by line when you've already determined where the headers end in (1). See file.seek and file.tell
Most efficient way to concatenate and rearrange files
I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. Currently I am using two loops: one to pull out all the headers and write them, and the second to write the body of each file (I also include a tmp_count variable to limit the number of lines to be loading into memory before dumping to file). This is pretty slow - about 6min for 13gb file. Can anyone tell me how to optimize this or if there is a faster way to do this in python ? Thanks! Here is my code: def cat_files_sam(final_file_name,work_directory_master,file_count): final_file = open(final_file_name,"w") if len(file_count) > 1: file_count=sort_output_files(file_count) # only for @ headers for bowtie_file in file_count: #print bowtie_file tmp_list = [] tmp_count = 0 for line in open(os.path.join(work_directory_master,bowtie_file)): if line.startswith("@"): if tmp_count == 1000000: final_file.writelines(tmp_list) tmp_list = [] tmp_count = 0 tmp_list.append(line) tmp_count += 1 else: final_file.writelines(tmp_list) break for bowtie_file in file_count: #print bowtie_file tmp_list = [] tmp_count = 0 for line in open(os.path.join(work_directory_master,bowtie_file)): if line.startswith("@"): continue if tmp_count == 1000000: final_file.writelines(tmp_list) tmp_list = [] tmp_count = 0 tmp_list.append(line) tmp_count += 1 final_file.writelines(tmp_list) final_file.close()
[ "How fast would you expect it to be to move 13Gb of data around? This problem is I/O bound and not a problem with Python. To make it faster, do less I/O. Which means that you are either (a) stuck with the speed you've got or (b) should retool later elements of your toolchain to handle the files in-place rather than requiring one giant 13 Gb file.\n", "You can save the time it takes the 2nd time to skip the headers, as long as you have a reasonable amount of spare disk space: as well as the final file, also open (for 'w+') a temporary file temp_file, and do:\nimport shutil\n\nhdr_list = []\nbod_list = []\ndispatch = {True: (hdr_list, final_file), \n False: (bod_list, temp_file)}\n\nfor bowtie_file in file_count:\n with open(os.path.join(work_directory_master,bowtie_file)) as f:\n for line in f:\n L, fou = dispatch[line[0]=='@']\n L.append(f)\n if len(L) == 1000000:\n fou.writelines(L)\n del L[:]\n\n# write final parts, if any\nfor L, fou in dispatch.items():\n if L: fou.writelines(L)\n\ntemp_file.seek(0)\nshutil.copyfileobj(temp_file, final_file)\n\nThis should enhance your program's performance. Fine-tuning that now-hard-coded 1000000, or even completely doing away with the lists and writing each line directly to the appropriate file (final or temporary), are other options you should benchmark (but if you have unbounded amounts of memory, then I expect that they won't matter much -- however, intuitions about performance are often misleading, so it's best to try and measure!-).\n", "There are two gross inefficiencies in the code you meant to write (which is not the code presented):\n\nYou are building up huge lists of header lines in the first major for block instead of just writing them out.\nYou are skipping the headers of the files again in the second major for block line by line when you've already determined where the headers end in (1). See file.seek and file.tell\n\n" ]
[ 2, 2, 0 ]
[]
[]
[ "concatenation", "file", "python" ]
stackoverflow_0002508610_concatenation_file_python.txt
Q: Need to understand Python signals and modules I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is: import sys, signal sigterm_caught = False def SignalHandler(signum, stackframe): if signum == signal.SIGTERM: sigterm_caught = True sys.stdout.write("SIGTERM caught\n") def SignalSetup(): signal.signal(signal.SIGTERM, SignalHandler) and my main code has a loop like this: signals.SignalSetup() while signals.sigterm_caught == False: sys.stdout.write("sigterm_caught=%s\n" % str(signals.sigterm_caught)) time.sleep(5) I run it, then kill the process, inside signals.py it gets the signal, sets sigterm_caught to True, but the loop in the main process does not see a change in value of sigterm_caught. So (a) is my approach completely wrong for the Python way? (b) am I doing something wrong in trying to reference variables in the module? and (c) should I be handling signals differently, like raising an exception? Addition: Is it better to handle signals by raising an exception, or is my old C approach still a valid one? A: You need to add a global statement to the handler: def SignalHandler(signum, stackframe): global sigterm_caught if signum == signal.SIGTERM: sigterm_caught = True sys.stdout.write("SIGTERM caught\n") The Python compiler, by default, deems each name (like sigterm_caught) to be local to a function if it seems the function assign to the name; the role of the global statement is to reverse this default, so that the Python compiler will deem the name to be global (i.e., a module-level top name) instead. A: If you are writing to a global variable, use global: sigterm_caught = False def SignalHandler(signum, stackframe): global sigterm_caught if signum == signal.SIGTERM: sigterm_caught = True sys.stdout.write("SIGTERM caught\n")
Need to understand Python signals and modules
I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is: import sys, signal sigterm_caught = False def SignalHandler(signum, stackframe): if signum == signal.SIGTERM: sigterm_caught = True sys.stdout.write("SIGTERM caught\n") def SignalSetup(): signal.signal(signal.SIGTERM, SignalHandler) and my main code has a loop like this: signals.SignalSetup() while signals.sigterm_caught == False: sys.stdout.write("sigterm_caught=%s\n" % str(signals.sigterm_caught)) time.sleep(5) I run it, then kill the process, inside signals.py it gets the signal, sets sigterm_caught to True, but the loop in the main process does not see a change in value of sigterm_caught. So (a) is my approach completely wrong for the Python way? (b) am I doing something wrong in trying to reference variables in the module? and (c) should I be handling signals differently, like raising an exception? Addition: Is it better to handle signals by raising an exception, or is my old C approach still a valid one?
[ "You need to add a global statement to the handler:\ndef SignalHandler(signum, stackframe):\n global sigterm_caught\n if signum == signal.SIGTERM:\n sigterm_caught = True\n sys.stdout.write(\"SIGTERM caught\\n\")\n\nThe Python compiler, by default, deems each name (like sigterm_caught) to be local to a function if it seems the function assign to the name; the role of the global statement is to reverse this default, so that the Python compiler will deem the name to be global (i.e., a module-level top name) instead.\n", "If you are writing to a global variable, use global:\nsigterm_caught = False\n\ndef SignalHandler(signum, stackframe):\n global sigterm_caught\n if signum == signal.SIGTERM:\n sigterm_caught = True\n sys.stdout.write(\"SIGTERM caught\\n\")\n\n" ]
[ 8, 3 ]
[]
[]
[ "module", "python", "signals" ]
stackoverflow_0002508748_module_python_signals.txt
Q: Named pipe is not flushing in Python I have a named pipe created via the os.mkfifo() command. I have two different Python processes accessing this named pipe, process A is reading, and process B is writing. Process A uses the select function to determine when there is data available in the fifo/pipe. Despite the fact that process B flushes after each write call, process A's select function does not always return (it keeps blocking as if there is no new data). After looking into this issue extensively, I finally just programmed process B to add 5KB of garbage writes before and after my real call, and likewise process A is programmed to ignore those 5KB. Now everything works fine, and select is always returning appropriately. I came to this hack-ish solution by noticing that process A's select would return if process B were to be killed (after it was writing and flushing, it would sleep on a read pipe). Is there a problem with flush in Python for named pipes? A: What APIs are you using? os.read() and os.write() don't buffer anything. A: To find out if Python's internal buffering is causing your problems, when running your scripts do "python -u" instead of "python". This will force python in to "unbuffered mode" which will cause all output to be printed instantaneously. A: The flush operation is irrelevant for named pipes; the data for named pipes is held strictly in memory, and won't be released until it is read or the FIFO is closed.
Named pipe is not flushing in Python
I have a named pipe created via the os.mkfifo() command. I have two different Python processes accessing this named pipe, process A is reading, and process B is writing. Process A uses the select function to determine when there is data available in the fifo/pipe. Despite the fact that process B flushes after each write call, process A's select function does not always return (it keeps blocking as if there is no new data). After looking into this issue extensively, I finally just programmed process B to add 5KB of garbage writes before and after my real call, and likewise process A is programmed to ignore those 5KB. Now everything works fine, and select is always returning appropriately. I came to this hack-ish solution by noticing that process A's select would return if process B were to be killed (after it was writing and flushing, it would sleep on a read pipe). Is there a problem with flush in Python for named pipes?
[ "What APIs are you using? os.read() and os.write() don't buffer anything.\n", "To find out if Python's internal buffering is causing your problems, when running your scripts do \"python -u\" instead of \"python\". This will force python in to \"unbuffered mode\" which will cause all output to be printed instantaneously.\n", "The flush operation is irrelevant for named pipes; the data for named pipes is held strictly in memory, and won't be released until it is read or the FIFO is closed.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "flush", "ipc", "named_pipes", "python", "select" ]
stackoverflow_0002136844_flush_ipc_named_pipes_python_select.txt
Q: Convert or strip out "illegal" Unicode characters I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 1916: ordinal not in range(128) Is there some way I can convert the chars to proper unicode versions? Or strip them out? A: When you decode, just pass 'ignore' to strip those characters there is some more way of stripping / converting those are 'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd' 'ignore': ignore malformed data and continue without further notice 'backslashreplace': replace with backslashed escape sequences (for encoding only) Test >>> "abcd\x97".decode("ascii") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 4: ordinal not in range(128) >>> >>> "abcd\x97".decode("ascii","ignore") u'abcd' A: Once you have the string of bytes s, instead of using it as a unicode obj directly, convert it explicitly with the right codec, e.g.: u = s.decode('latin-1') and use u instead of s in the code that follows this point (presumably the part that writes to sqlite). That's assuming latin-1 is the encoding that was used to make the byte string originally -- it's impossible for us to guess, so try to find out;-). As a general rule, I suggest: don't process in your applications any text as encoded byte strings -- decode them to unicode objects right after input, and, if necessary, encode them back to byte strings right before output.
Convert or strip out "illegal" Unicode characters
I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 1916: ordinal not in range(128) Is there some way I can convert the chars to proper unicode versions? Or strip them out?
[ "When you decode, just pass 'ignore' to strip those characters\nthere is some more way of stripping / converting those are\n'replace': replace malformed data with a suitable replacement marker, such as '?' or '\\ufffd' \n\n'ignore': ignore malformed data and continue without further notice \n\n'backslashreplace': replace with backslashed escape sequences (for encoding only) \n\nTest\n>>> \"abcd\\x97\".decode(\"ascii\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 4: ordinal not in range(128)\n>>>\n>>> \"abcd\\x97\".decode(\"ascii\",\"ignore\")\nu'abcd'\n\n", "Once you have the string of bytes s, instead of using it as a unicode obj directly, convert it explicitly with the right codec, e.g.:\nu = s.decode('latin-1')\n\nand use u instead of s in the code that follows this point (presumably the part that writes to sqlite). That's assuming latin-1 is the encoding that was used to make the byte string originally -- it's impossible for us to guess, so try to find out;-).\nAs a general rule, I suggest: don't process in your applications any text as encoded byte strings -- decode them to unicode objects right after input, and, if necessary, encode them back to byte strings right before output.\n" ]
[ 11, 11 ]
[]
[]
[ "pymssql", "python", "unicode" ]
stackoverflow_0002508847_pymssql_python_unicode.txt
Q: ValidationError while running Google adwords client library examples I get the following error when I try to run sample example of Google adwords [root@some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get 'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root@some v200909]# A: This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that: a) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete). b) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13 If this still doesn't work for you, the SOAP logs for your request might be useful.
ValidationError while running Google adwords client library examples
I get the following error when I try to run sample example of Google adwords [root@some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get 'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root@some v200909]#
[ "This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:\na) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete).\nb) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13\nIf this still doesn't work for you, the SOAP logs for your request might be useful.\n" ]
[ 0 ]
[]
[]
[ "google_ads_api", "python" ]
stackoverflow_0002479395_google_ads_api_python.txt
Q: How to format contour lines from Matplotlib I am working on using Matplotlib to produce plots of implicit equations (eg. y^x=x^y). With many thanks to the help I have already received I have got quite far with it. I have used a contour line to produce the plot. My remaining problem is with formatting the contour line eg width, color and especially zorder, where the contour appears behind my gridlines. These work fine when plotting a standard function of course. import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import numpy as np fig = plt.figure(1) ax = fig.add_subplot(111) # set up axis ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # setup x and y ranges and precision x = np.arange(-0.5,5.5,0.01) y = np.arange(-0.5,5.5,0.01) # draw a curve line, = ax.plot(x, x**2,zorder=100,linewidth=3,color='red') # draw a contour X,Y=np.meshgrid(x,y) F=X**Y G=Y**X ax.contour(X,Y,(F-G),[0],zorder=100,linewidth=3,color='green') #set bounds ax.set_xbound(-1,7) ax.set_ybound(-1,7) #add gridlines ax.xaxis.set_minor_locator(MultipleLocator(0.2)) ax.yaxis.set_minor_locator(MultipleLocator(0.2)) ax.xaxis.grid(True,'minor',linestyle='-',color='0.8') ax.yaxis.grid(True,'minor',linestyle='-',color='0.8') plt.show() A: This is rather hackish but... Apparently in the current release Matplotlib does not support zorder on contours. This support, however, was recently added to the trunk. So, the right way to do this is either to wait for the 1.0 release or just go ahead and re-install from trunk. Now, here's the hackish part. I did a quick test and if I changed line 618 in python/site-packages/matplotlib/contour.py to add a zorder into the collections.LineCollection call, it fixes your specific problem. col = collections.LineCollection(nlist, linewidths = width, linestyle = lstyle, alpha=self.alpha,zorder=100) Not the right way to do things, but might just work in a pinch. Also off-topic, if you accept some responses to your previous questions, you probably get quicker help around here. People love those rep points :)
How to format contour lines from Matplotlib
I am working on using Matplotlib to produce plots of implicit equations (eg. y^x=x^y). With many thanks to the help I have already received I have got quite far with it. I have used a contour line to produce the plot. My remaining problem is with formatting the contour line eg width, color and especially zorder, where the contour appears behind my gridlines. These work fine when plotting a standard function of course. import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import numpy as np fig = plt.figure(1) ax = fig.add_subplot(111) # set up axis ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # setup x and y ranges and precision x = np.arange(-0.5,5.5,0.01) y = np.arange(-0.5,5.5,0.01) # draw a curve line, = ax.plot(x, x**2,zorder=100,linewidth=3,color='red') # draw a contour X,Y=np.meshgrid(x,y) F=X**Y G=Y**X ax.contour(X,Y,(F-G),[0],zorder=100,linewidth=3,color='green') #set bounds ax.set_xbound(-1,7) ax.set_ybound(-1,7) #add gridlines ax.xaxis.set_minor_locator(MultipleLocator(0.2)) ax.yaxis.set_minor_locator(MultipleLocator(0.2)) ax.xaxis.grid(True,'minor',linestyle='-',color='0.8') ax.yaxis.grid(True,'minor',linestyle='-',color='0.8') plt.show()
[ "This is rather hackish but...\nApparently in the current release Matplotlib does not support zorder on contours. This support, however, was recently added to the trunk.\nSo, the right way to do this is either to wait for the 1.0 release or just go ahead and re-install from trunk.\nNow, here's the hackish part. I did a quick test and if I changed line 618 in \n\npython/site-packages/matplotlib/contour.py\n\nto add a zorder into the collections.LineCollection call, it fixes your specific problem.\ncol = collections.LineCollection(nlist,\n linewidths = width,\n linestyle = lstyle,\n alpha=self.alpha,zorder=100)\n\nNot the right way to do things, but might just work in a pinch.\nAlso off-topic, if you accept some responses to your previous questions, you probably get quicker help around here. People love those rep points :)\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python", "sympy" ]
stackoverflow_0002488800_matplotlib_python_sympy.txt
Q: Restful authentication between two GAE apps I am trying to write a RESTful Google app engine application (Python) that accepts requests only from another GAE that I wrote. I dont like any of the ways that I thought of getting this done, please advise if you know of something better than: Get SSL setup, and simply add the credentials on the request that my consuming app will send. I dont like it cause SSL will slow things down. Security by obsecurity. Add a random number in my request that is in Xmod0, where X is a secret number that both applications know. I just don't like this. Check the HTTP header to see where is the request coming from. This option is the one that I hate the least, not alot of processing, and spoofing an HTTP request is not really worth it, for my application's data. Is there any other clean solution for this? A: Use an HMAC. Embed the same secret in each app, and sign requests and responses using the HMAC. Don't forget to include nonces and timestamps to prevent replay attacks!
Restful authentication between two GAE apps
I am trying to write a RESTful Google app engine application (Python) that accepts requests only from another GAE that I wrote. I dont like any of the ways that I thought of getting this done, please advise if you know of something better than: Get SSL setup, and simply add the credentials on the request that my consuming app will send. I dont like it cause SSL will slow things down. Security by obsecurity. Add a random number in my request that is in Xmod0, where X is a secret number that both applications know. I just don't like this. Check the HTTP header to see where is the request coming from. This option is the one that I hate the least, not alot of processing, and spoofing an HTTP request is not really worth it, for my application's data. Is there any other clean solution for this?
[ "Use an HMAC. Embed the same secret in each app, and sign requests and responses using the HMAC. Don't forget to include nonces and timestamps to prevent replay attacks!\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "rest", "restful_authentication" ]
stackoverflow_0002509205_google_app_engine_python_rest_restful_authentication.txt
Q: catalogue a list of dictionaries I have a list of dictionaries: people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] I want to catalogue them, for example I choose these keys: field = ("sex", "age") I need a function catalogue(field, people) that give me: { "M": { 20: [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}], 21: [{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}] }, { "F": { 30: [{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] } } when len(field)==1 it's simple. I want to do something like this: c = catalogue(field, people) for (sex, sex_value) in c.iteritems(): for (age, age_value) in sex_value.iteritems(): print sex, age, age_value["name"] A: recursively: import itertools, operator def catalog(fields,people): cur_field = operator.itemgetter(fields[0]) groups = itertools.groupby(sorted(people, key=cur_field),cur_field) if len(fields)==1: return dict((k,list(v)) for k,v in groups) else: return dict((k,catalog(fields[1:],v)) for k,v in groups) test: import pprint pprint.pprint(catalog(('sex','age'), people)) {'F': {30: [{'age': 30, 'city': 'Dallas', 'name': 'Dana', 'sex': 'F'}]}, 'M': {20: [{'age': 20, 'city': 'NY', 'name': 'Roger', 'sex': 'M'}, {'age': 20, 'city': 'Boston', 'name': 'Dan', 'sex': 'M'}], 21: [{'age': 21, 'city': 'Boston', 'name': 'Roger', 'sex': 'M'}]}} A: import pprint people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] fields = ("sex", "age") result = {} for person in people: tempdict = result for field in fields[:-1]: if person[field] in tempdict: tempdict = tempdict[person[field]] else: t = tempdict tempdict = {} t[person[field]] = tempdict key = person[fields[-1]] if key in tempdict: tempdict[key].append(person) else: tempdict[key] = [person] pprint.pprint(result) seems do the job A: Not optimal (could be improved using defaultdict, for instance, but I had Python2.4 installed on my machine), but does the job: def catalogue(dicts, criteria): if not criteria: return dicts criterion, rest = criteria[0], criteria[1:] cat = {} for d in dicts: reducedDict = dict(d) del reducedDict[criterion] if d[criterion] in cat: cat[d[criterion]].append(reducedDict) else: cat[d[criterion]] = [reducedDict] retDict = {} for key, val in cat.items(): retDict[key] = catalogue(val, rest) return retDict print catalogue(people, ("sex", "age"))
catalogue a list of dictionaries
I have a list of dictionaries: people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] I want to catalogue them, for example I choose these keys: field = ("sex", "age") I need a function catalogue(field, people) that give me: { "M": { 20: [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}], 21: [{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}] }, { "F": { 30: [{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] } } when len(field)==1 it's simple. I want to do something like this: c = catalogue(field, people) for (sex, sex_value) in c.iteritems(): for (age, age_value) in sex_value.iteritems(): print sex, age, age_value["name"]
[ "recursively:\nimport itertools, operator\n\ndef catalog(fields,people):\n cur_field = operator.itemgetter(fields[0])\n groups = itertools.groupby(sorted(people, key=cur_field),cur_field)\n if len(fields)==1:\n return dict((k,list(v)) for k,v in groups)\n else:\n return dict((k,catalog(fields[1:],v)) for k,v in groups)\n\ntest:\nimport pprint\npprint.pprint(catalog(('sex','age'), people))\n{'F': {30: [{'age': 30, 'city': 'Dallas', 'name': 'Dana', 'sex': 'F'}]},\n 'M': {20: [{'age': 20, 'city': 'NY', 'name': 'Roger', 'sex': 'M'},\n {'age': 20, 'city': 'Boston', 'name': 'Dan', 'sex': 'M'}],\n 21: [{'age': 21, 'city': 'Boston', 'name': 'Roger', 'sex': 'M'}]}}\n\n", "import pprint\npeople = [{\"name\": \"Roger\", \"city\": \"NY\", \"age\": 20, \"sex\": \"M\"},\n {\"name\": \"Dan\", \"city\": \"Boston\", \"age\": 20, \"sex\": \"M\"},\n {\"name\": \"Roger\", \"city\": \"Boston\", \"age\": 21, \"sex\": \"M\"},\n {\"name\": \"Dana\", \"city\": \"Dallas\", \"age\": 30, \"sex\": \"F\"}]\nfields = (\"sex\", \"age\")\nresult = {}\nfor person in people:\n tempdict = result\n for field in fields[:-1]:\n if person[field] in tempdict:\n tempdict = tempdict[person[field]]\n else:\n t = tempdict\n tempdict = {}\n t[person[field]] = tempdict\n key = person[fields[-1]]\n if key in tempdict:\n tempdict[key].append(person)\n else:\n tempdict[key] = [person]\n\npprint.pprint(result)\n\nseems do the job\n", "Not optimal (could be improved using defaultdict, for instance, but I had Python2.4 installed on my machine), but does the job:\ndef catalogue(dicts, criteria):\n if not criteria:\n return dicts\n\n criterion, rest = criteria[0], criteria[1:]\n\n cat = {}\n for d in dicts:\n reducedDict = dict(d)\n del reducedDict[criterion]\n\n if d[criterion] in cat:\n cat[d[criterion]].append(reducedDict)\n else:\n cat[d[criterion]] = [reducedDict]\n\n retDict = {}\n for key, val in cat.items():\n retDict[key] = catalogue(val, rest)\n\n return retDict\n\nprint catalogue(people, (\"sex\", \"age\"))\n\n" ]
[ 7, 0, 0 ]
[]
[]
[ "catalog", "dictionary", "nested", "python" ]
stackoverflow_0002509260_catalog_dictionary_nested_python.txt
Q: python urllib2.openurl doesn't work with specific URL (redirect)? I need to download a CSV file, which works fine in browsers using: http://www.ftse.com/objects/csv_to_csv.jsp?infoCode=100a&theseFilters=&csvAll=&theseColumns=Mw==&theseTitles=&tableTitle=FTSE%20100%20Index%20Constituents&dl=&p_encoded=1&e=.csv The following code works for any other file (url) (with a fully qualified path), however with the above URL is downloads 800 bytes of gibberish. def getFile(self,URL): proxy_support = urllib2.ProxyHandler({'http': 'http://proxy.REMOVED.com:8080/'}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) response = urllib2.urlopen(URL) print response.geturl() newfile = response.read() output = open("testFile.csv",'wb') output.write(newfile) output.close() A: urllib2 uses httplib under the hood, so the best way to diagnose this is to turn on http connection debugging. Add this code before you access the url and you should get a nice summary of exactly what http traffic is being generated: import httplib httplib.HTTPConnection.debuglevel = 1
python urllib2.openurl doesn't work with specific URL (redirect)?
I need to download a CSV file, which works fine in browsers using: http://www.ftse.com/objects/csv_to_csv.jsp?infoCode=100a&theseFilters=&csvAll=&theseColumns=Mw==&theseTitles=&tableTitle=FTSE%20100%20Index%20Constituents&dl=&p_encoded=1&e=.csv The following code works for any other file (url) (with a fully qualified path), however with the above URL is downloads 800 bytes of gibberish. def getFile(self,URL): proxy_support = urllib2.ProxyHandler({'http': 'http://proxy.REMOVED.com:8080/'}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) response = urllib2.urlopen(URL) print response.geturl() newfile = response.read() output = open("testFile.csv",'wb') output.write(newfile) output.close()
[ "urllib2 uses httplib under the hood, so the best way to diagnose this is to turn on http connection debugging. Add this code before you access the url and you should get a nice summary of exactly what http traffic is being generated:\nimport httplib\nhttplib.HTTPConnection.debuglevel = 1\n\n" ]
[ 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002509073_python_urllib2.txt
Q: Convert UTF-8 bytes to some other encoding in Python I need to do in Python 2.4 (yes, 2.4 :-( ). I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified. So, what I think I need to do, is to create an Unicode object using bytes from that source object, and then convert it to some other encoding (iso-8859-2, actually). The plain string object is 'x'. "unicode()" seems to not work: >>> x 'Sk\xc5\x82odowski' >>> str(unicode(x, encoding='iso-8859-2')) Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128) >>> unicode(x, encoding='iso-8859-2') u'Sk\u0139\x82odowski' A: >>> x.decode('utf8').encode('iso-8859-2') 'Sk\xb3odowski'
Convert UTF-8 bytes to some other encoding in Python
I need to do in Python 2.4 (yes, 2.4 :-( ). I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified. So, what I think I need to do, is to create an Unicode object using bytes from that source object, and then convert it to some other encoding (iso-8859-2, actually). The plain string object is 'x'. "unicode()" seems to not work: >>> x 'Sk\xc5\x82odowski' >>> str(unicode(x, encoding='iso-8859-2')) Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128) >>> unicode(x, encoding='iso-8859-2') u'Sk\u0139\x82odowski'
[ ">>> x.decode('utf8').encode('iso-8859-2')\n'Sk\\xb3odowski'\n\n" ]
[ 9 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0002509578_encoding_python_unicode.txt
Q: compare two following values in numpy array What is the best way to touch two following values in an numpy array? example: npdata = np.array([13,15,20,25]) for i in range( len(npdata) ): print npdata[i] - npdata[i+1] this looks really messed up and additionally needs exception code for the last iteration of the loop. any ideas? Thanks! A: numpy provides a function diff for this basic use case >>> import numpy >>> x = numpy.array([1, 2, 4, 7, 0]) >>> numpy.diff(x) array([ 1, 2, 3, -7]) Your snippet computes something closer to -numpy.diff(x). A: How about range(len(npdata) - 1) ? Here's code (using a simple array, but it doesn't matter): >>> ar = [1, 2, 3, 4, 5] >>> for i in range(len(ar) - 1): ... print ar[i] + ar[i + 1] ... 3 5 7 9 As you can see it successfully prints the sums of all consecutive pairs in the array, without any exceptions for the last iteration. A: You can use ediff1d to get differences of consecutive elements. More generally, a[1:] - a[:-1] will give the differences of consecutive elements and can be used with other operators as well.
compare two following values in numpy array
What is the best way to touch two following values in an numpy array? example: npdata = np.array([13,15,20,25]) for i in range( len(npdata) ): print npdata[i] - npdata[i+1] this looks really messed up and additionally needs exception code for the last iteration of the loop. any ideas? Thanks!
[ "numpy provides a function diff for this basic use case\n>>> import numpy\n>>> x = numpy.array([1, 2, 4, 7, 0])\n>>> numpy.diff(x)\narray([ 1, 2, 3, -7])\n\nYour snippet computes something closer to -numpy.diff(x).\n", "How about range(len(npdata) - 1) ?\nHere's code (using a simple array, but it doesn't matter):\n>>> ar = [1, 2, 3, 4, 5]\n>>> for i in range(len(ar) - 1):\n... print ar[i] + ar[i + 1]\n... \n3\n5\n7\n9\n\nAs you can see it successfully prints the sums of all consecutive pairs in the array, without any exceptions for the last iteration.\n", "You can use ediff1d to get differences of consecutive elements. More generally, a[1:] - a[:-1] will give the differences of consecutive elements and can be used with other operators as well.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "indexing", "iteration", "loops", "numpy", "python" ]
stackoverflow_0002509644_indexing_iteration_loops_numpy_python.txt
Q: Defining the context of a word - Python I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Technology Web Design I need to try and match words with the appropriate context/contexts if possible. Maybe discovering word relationships in some way. Any ideas? Help would be much appreciated! A: This sounds like it's more of a categorization/ontology problem than NLP. Try WordNet for a standard ontology. I don't see any real NLP in your stated problem, but if you do need some semantic analysis or a parser try NLTK. A: Where do these words come from? Do they come from real texts. If they are then it is a classic data mining problem. What you need to do is to your set of documents into the matrix where rows represent which document the word came from and the columns represent the words in the documents. For example if you have two documents like this: D1: Need to find meaning. D2: Need to separate Apples from oranges you matrix will look like this: Need to find meaning Apples Oranges Separate From D1: 1 1 1 1 0 0 0 0 D2: 1 1 0 0 1 1 1 1 This is called term by document matrix Having collected this statistics you can use algorithms like K-Means to group similar documents together. Since you already know how many concepts you have your tasks should be soomewhat easier. K-Means is very slow algorithm, so you can try to optimize it using techniques such as SVD A: I just found this a couple days ago: ConceptNet It's a commonsense ontology, so it might not be as specific as you would like, but it has a python API and you can download their entire database (currently around 1GB decompressed). Just keep in mind their licensing restrictions. If you read the papers that were published by the team that developed it, you may get some ideas on how to relate your words to concepts/contexts. A: The answer to your question obviously depends on the target taxonomy you are trying to map your terms into. Once you have decided on this you need to figure out how fine-grained the concepts should be. WordNet, as it has been suggested in other responses, will give you synsets, i.e. sets of terms which are more or less synonymous but which you will have to map to concepts like 'Web Design' or 'World News' by some other mechanism since these are not encoded in WordNet. If you're aiming at a very broad semantic categorization, you could use WordNet's higher-level concept nodes which differentiate, e.g. (going up the hierarchy) human from animal, animates from plants, substances from solids, concrete from abstract things, etc. Another kind-of-taxonomy which may be quite useful to you is the Wikipedia category system. This is not just a spontaneous idea I just came up with, but there has been a lot of work on deriving real ontologies from Wikipedia categories. Take a look at the Java Wikipedia Library - the idea would be to find a wikipedia article for the term in question (e.g. 'css3'), extract the categories this article belongs to, and pick the best ones with respect to some criterion (i.e. 'programming', 'technology', and 'web-development'). Depending on what you're trying to do this last step (choosing the best of several given categories) may or may not be difficult. See here for a list of other ontologies / knowledge bases you could use.
Defining the context of a word - Python
I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Technology Web Design I need to try and match words with the appropriate context/contexts if possible. Maybe discovering word relationships in some way. Any ideas? Help would be much appreciated!
[ "This sounds like it's more of a categorization/ontology problem than NLP. Try WordNet for a standard ontology.\nI don't see any real NLP in your stated problem, but if you do need some semantic analysis or a parser try NLTK.\n", "Where do these words come from? Do they come from real texts. If they are then it is a classic data mining problem. What you need to do is to your set of documents into the matrix where rows represent which document the word came from and the columns represent the words in the documents.\nFor example if you have two documents like this:\nD1: Need to find meaning.\nD2: Need to separate Apples from oranges\nyou matrix will look like this:\n Need to find meaning Apples Oranges Separate From\nD1: 1 1 1 1 0 0 0 0\nD2: 1 1 0 0 1 1 1 1\n\nThis is called term by document matrix\nHaving collected this statistics you can use algorithms like K-Means to group similar documents together. Since you already know how many concepts you have your tasks should be soomewhat easier. K-Means is very slow algorithm, so you can try to optimize it using techniques such as SVD\n", "I just found this a couple days ago: ConceptNet\nIt's a commonsense ontology, so it might not be as specific as you would like, but it has a python API and you can download their entire database (currently around 1GB decompressed). Just keep in mind their licensing restrictions.\nIf you read the papers that were published by the team that developed it, you may get some ideas on how to relate your words to concepts/contexts.\n", "The answer to your question obviously depends on the target taxonomy you are trying to map your terms into. Once you have decided on this you need to figure out how fine-grained the concepts should be. WordNet, as it has been suggested in other responses, will give you synsets, i.e. sets of terms which are more or less synonymous but which you will have to map to concepts like 'Web Design' or 'World News' by some other mechanism since these are not encoded in WordNet. If you're aiming at a very broad semantic categorization, you could use WordNet's higher-level concept nodes which differentiate, e.g. (going up the hierarchy) human from animal, animates from plants, substances from solids, concrete from abstract things, etc. \nAnother kind-of-taxonomy which may be quite useful to you is the Wikipedia category system. This is not just a spontaneous idea I just came up with, but there has been a lot of work on deriving real ontologies from Wikipedia categories. Take a look at the Java Wikipedia Library - the idea would be to find a wikipedia article for the term in question (e.g. 'css3'), extract the categories this article belongs to, and pick the best ones with respect to some criterion (i.e. 'programming', 'technology', and 'web-development'). Depending on what you're trying to do this last step (choosing the best of several given categories) may or may not be difficult. \nSee here for a list of other ontologies / knowledge bases you could use.\n" ]
[ 3, 2, 2, 1 ]
[]
[]
[ "dictionary", "django", "nlp", "python" ]
stackoverflow_0002500732_dictionary_django_nlp_python.txt
Q: Python - Nested List to Tab Delimited File? I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g., nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]. I wish to create a function in order to output this data construct into a tab delimited format, e.g., x y z a b c Any help greatly appreciated! Thanks in advance, Seafoid. A: >>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']] >>> for line in nested_list: ... print '\t'.join(line) ... x y z a b c >>> A: with open('fname', 'w') as file: file.writelines('\t'.join(i) + '\n' for i in nested_list) A: In my view, it's a simple one-liner: print '\n'.join(['\t'.join(l) for l in nested_list]) A: >>> print '\n'.join(map('\t'.join,nested_list)) x y z a b c >>> A: out = file("yourfile", "w") for line in nested_list: print >> out, "\t".join(line)
Python - Nested List to Tab Delimited File?
I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g., nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]. I wish to create a function in order to output this data construct into a tab delimited format, e.g., x y z a b c Any help greatly appreciated! Thanks in advance, Seafoid.
[ ">>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]\n>>> for line in nested_list:\n... print '\\t'.join(line)\n... \nx y z\na b c\n>>> \n\n", "with open('fname', 'w') as file:\n file.writelines('\\t'.join(i) + '\\n' for i in nested_list)\n\n", "In my view, it's a simple one-liner:\nprint '\\n'.join(['\\t'.join(l) for l in nested_list])\n\n", ">>> print '\\n'.join(map('\\t'.join,nested_list))\nx y z\na b c\n>>>\n\n", "out = file(\"yourfile\", \"w\")\nfor line in nested_list:\n print >> out, \"\\t\".join(line)\n\n" ]
[ 6, 6, 5, 3, 1 ]
[]
[]
[ "csv", "list", "nested", "python" ]
stackoverflow_0002509706_csv_list_nested_python.txt
Q: Can this be done with the ORM? - Django I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z=x return (log(z) + y * t/45000) I'm wondering if there is any clever way of using Django's ORM, in order to UPDATE the models in bulk. Without doing this: items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7)) for item in items: item.reddit_rank = reddit_rank(item) item.save() I know about the F() object, but I can't figure out if this function can be performed inside the ORM. Any ideas? Help would be very much appreciated! A: It's not much work to do it manually: from django.db import connection items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7)) cursor = connection.cursor() cursor.executemany("UPDATE myapp_item SET reddit_rank = %s WHERE id = %s", [(reddit_rank(item), item.pk) for item in items]) cursor.close()
Can this be done with the ORM? - Django
I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z=x return (log(z) + y * t/45000) I'm wondering if there is any clever way of using Django's ORM, in order to UPDATE the models in bulk. Without doing this: items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7)) for item in items: item.reddit_rank = reddit_rank(item) item.save() I know about the F() object, but I can't figure out if this function can be performed inside the ORM. Any ideas? Help would be very much appreciated!
[ "It's not much work to do it manually:\nfrom django.db import connection\n\nitems = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7))\ncursor = connection.cursor()\ncursor.executemany(\"UPDATE myapp_item SET reddit_rank = %s WHERE id = %s\",\n [(reddit_rank(item), item.pk) for item in items])\ncursor.close()\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_orm", "orm", "python", "sql" ]
stackoverflow_0002510031_django_django_orm_orm_python_sql.txt
Q: More nest Python nested dictionaries After reading What is the best way to implement nested dictionaries? why is it wrong to do: c = collections.defaultdict(collections.defaultdict(int)) in python? I would think this would work to produce {key:{key:1}} or am I thinking about it wrong? A: The constructor of defaultdict expects a callable. defaultdict(int) is a default dictionary object, not a callable. Using a lambda it can work, however: c = collections.defaultdict(lambda: collections.defaultdict(int)) This works since what I pass to the outer defaultdict is a callable that creates a new defaultdict when called. Here's an example: >>> import collections >>> c = collections.defaultdict(lambda: collections.defaultdict(int)) >>> c[5][6] += 1 >>> c[5][6] 1 >>> c[0][0] 0 >>> A: Eli Bendersky provides a great direct answer for this question. It might also be better to restructure your data to >>> import collections >>> c = collections.defaultdict(int) >>> c[1, 2] = 'foo' >>> c[5, 6] = 'bar' >>> c defaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'}) depending on what you actually need.
More nest Python nested dictionaries
After reading What is the best way to implement nested dictionaries? why is it wrong to do: c = collections.defaultdict(collections.defaultdict(int)) in python? I would think this would work to produce {key:{key:1}} or am I thinking about it wrong?
[ "The constructor of defaultdict expects a callable. defaultdict(int) is a default dictionary object, not a callable. Using a lambda it can work, however:\nc = collections.defaultdict(lambda: collections.defaultdict(int))\n\nThis works since what I pass to the outer defaultdict is a callable that creates a new defaultdict when called.\nHere's an example:\n>>> import collections\n>>> c = collections.defaultdict(lambda: collections.defaultdict(int))\n>>> c[5][6] += 1\n>>> c[5][6]\n1\n>>> c[0][0]\n0\n>>> \n\n", "Eli Bendersky provides a great direct answer for this question. It might also be better to restructure your data to\n>>> import collections\n>>> c = collections.defaultdict(int)\n>>> c[1, 2] = 'foo'\n>>> c[5, 6] = 'bar'\n>>> c\ndefaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'})\n\ndepending on what you actually need.\n" ]
[ 14, 5 ]
[]
[]
[ "collections", "nested", "python" ]
stackoverflow_0002510126_collections_nested_python.txt
Q: Why can't my Apache see my media folder? Alias /media/ /home/matt/repos/hello/media <Directory /home/matt/repos/hello/media> Options -Indexes Order deny,allow Allow from all </Directory> WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi /media is my directory. When I go to mydomain.com/media/, it says 403 Forbidden. And, the rest of my site doesn't work because all static files are 404s. Why? The page loads. Just not the media folder. Edit: hello is my project folder. I have tried 777 all my permissions of that folder. A: You have Indexes disabled, so Apache won't generate a listing of the files when you request the directory /media (instead, it shows the 403 Forbidden error). Try accessing a file directly within there, e.g.: http://localhost/media/some_image.jpg A: It looks to me that WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi tells to apache that everything under / should be handled by the specified WSGI script. This also includes /media. You should tell apache to exclude /media from that rule. Try adding this to your config file: <LocationMatch "^/media/"> SetHandler None </LocationMatch> Or craft a regex that matches everything but files under /media and replace your WSGIScriptAlias line with this: WSGIScriptAliasMatch <regex> /home/matt/repos/hello/wsgi/django.wsgi A: I solved it. I missed a trailing slash. after media/ A: If memory serves me correctly, Apache runs under it's own user account. Are you sure that this account has the correct permissions to that directory? A: its all about the dash Options -Indexes and here is a complete editon to yours Alias /media/ /home/matt/repos/hello/media <Directory "/home/matt/repos/hello/media"> Options Indexes AllowOverride all Order Deny,Allow Allowfrom all </Directory and i'd love to add AllowOverride all Feel free to delete it:)
Why can't my Apache see my media folder?
Alias /media/ /home/matt/repos/hello/media <Directory /home/matt/repos/hello/media> Options -Indexes Order deny,allow Allow from all </Directory> WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi /media is my directory. When I go to mydomain.com/media/, it says 403 Forbidden. And, the rest of my site doesn't work because all static files are 404s. Why? The page loads. Just not the media folder. Edit: hello is my project folder. I have tried 777 all my permissions of that folder.
[ "You have Indexes disabled, so Apache won't generate a listing of the files when you request the directory /media (instead, it shows the 403 Forbidden error). Try accessing a file directly within there, e.g.: http://localhost/media/some_image.jpg\n", "It looks to me that WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi tells to apache that everything under / should be handled by the specified WSGI script. This also includes /media. You should tell apache to exclude /media from that rule.\nTry adding this to your config file:\n<LocationMatch \"^/media/\">\nSetHandler None\n</LocationMatch>\n\nOr craft a regex that matches everything but files under /media and replace your WSGIScriptAlias line with this:\nWSGIScriptAliasMatch <regex> /home/matt/repos/hello/wsgi/django.wsgi\n\n", "I solved it. I missed a trailing slash. after media/\n", "If memory serves me correctly, Apache runs under it's own user account. Are you sure that this account has the correct permissions to that directory?\n", "its all about the dash Options -Indexes \nand here is a complete editon to yours \n Alias /media/ /home/matt/repos/hello/media\n<Directory \"/home/matt/repos/hello/media\">\n Options Indexes\n AllowOverride all\n Order Deny,Allow\n Allowfrom all\n</Directory\n\nand i'd love to add \nAllowOverride all\n\nFeel free to delete it:) \n" ]
[ 4, 3, 2, 0, 0 ]
[]
[]
[ "apache", "django", "linux", "python", "unix" ]
stackoverflow_0002506883_apache_django_linux_python_unix.txt
Q: What's the best django way to do a query that spans several tables? I have a reviews/ratings web application, a la Digg. My django app content has the following model: class Content(models.Model): title = models.CharField(max_length=128) url = models.URLField(max_length=2048) description = models.TextField(blank=True) class Recommendation(models.Model): user = models.ForeignKey(User) content = models.ForeignKey(Content) review = models.TextField() rating = models.PositiveSmallIntegerField() class Meta: unique_together = ('user', 'content') class Subscription(models.Model): subscriber = models.ForeignKey(User, related_name='subscription_set') publisher = models.ForeignKey(User, related_name='publication_set') class Meta: unique_together = ('subscriber', 'publisher') I want to construct a page with all the recommendations of all the users to whom a current user (request.user) subscribes. If I write this in SQL, I believe I'll end up with a query similar to the following: select content_content.*, content_recommendation.*, auth_user.* from content_content, content_recommendation, content_subscription, auth_user where content_content.id = content_recommendation.content_id and content_recommendation.user_id = content_subscription.publisher_id and content_subscription.subscriber_id = ? and auth_user.id = content_subscription.publisher_id; How would I express this using Django's query APIs? I've read the docs, but just can't get my head around it. A: I would use: Recommendation.objects.filter(user__publication_set__subscriber=request.user).select_related() That will get you all the Recommendation objects as you requested, and the select_related will load all the related User and Content objects into memory so that subsequent access of them won't hit the DB again. How you'd contruct this query really has a lot to do with your handling of the returned data afterwards though. It may be more or less efficient to go one way vs. another based on what you do with it.alt text http://sonicloft.net/im/52 A: I think that it's: Content.objects.filter(recommendation_set__user__publication_set__subscriber__pk=request.user.pk)/.distinct()/ or Recommendation.objects.filter(user__publication_set__subscriber__pk=request.user.pk)/.distinct()/ -- depending on instances of which model you want to get. Distinct() might be needed to avoid duplicates.
What's the best django way to do a query that spans several tables?
I have a reviews/ratings web application, a la Digg. My django app content has the following model: class Content(models.Model): title = models.CharField(max_length=128) url = models.URLField(max_length=2048) description = models.TextField(blank=True) class Recommendation(models.Model): user = models.ForeignKey(User) content = models.ForeignKey(Content) review = models.TextField() rating = models.PositiveSmallIntegerField() class Meta: unique_together = ('user', 'content') class Subscription(models.Model): subscriber = models.ForeignKey(User, related_name='subscription_set') publisher = models.ForeignKey(User, related_name='publication_set') class Meta: unique_together = ('subscriber', 'publisher') I want to construct a page with all the recommendations of all the users to whom a current user (request.user) subscribes. If I write this in SQL, I believe I'll end up with a query similar to the following: select content_content.*, content_recommendation.*, auth_user.* from content_content, content_recommendation, content_subscription, auth_user where content_content.id = content_recommendation.content_id and content_recommendation.user_id = content_subscription.publisher_id and content_subscription.subscriber_id = ? and auth_user.id = content_subscription.publisher_id; How would I express this using Django's query APIs? I've read the docs, but just can't get my head around it.
[ "I would use:\nRecommendation.objects.filter(user__publication_set__subscriber=request.user).select_related()\n\nThat will get you all the Recommendation objects as you requested, and the select_related will load all the related User and Content objects into memory so that subsequent access of them won't hit the DB again.\nHow you'd contruct this query really has a lot to do with your handling of the returned data afterwards though. It may be more or less efficient to go one way vs. another based on what you do with it.alt text http://sonicloft.net/im/52\n", "I think that it's:\n Content.objects.filter(recommendation_set__user__publication_set__subscriber__pk=request.user.pk)/.distinct()/\n\nor\n Recommendation.objects.filter(user__publication_set__subscriber__pk=request.user.pk)/.distinct()/\n\n-- depending on instances of which model you want to get. Distinct() might be needed to avoid duplicates.\n" ]
[ 10, 1 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002510429_database_django_mysql_python.txt
Q: Looping an executable to get the result from Python script In my python script, I need to call within a for loop an executable, and waiting for that executable to write the result on the "output.xml". How do I manage to use wait() & how do I know when one of my executable is finished generating the result to get the result? How do I close that process and open a new one to call again the executable and wait for the new result? import subprocess args = ("bin/bar") popen = subprocess.Popen(args) I need to wait for the output from "bin/bar" to generate the "output.xml" and from there, read it's content. for index, result in enumerate(results): myModule.callSubProcess(index) #this is where the problem is. fileOutput = open("output.xml") parseAndStoreInSQLiteFileOutput(index, file) A: Popen.wait() will make the script wait until the process ends. There's no need to kill the process afterwards, since it will have already exited. A: I think the easiest way to do is using call: import subprocess retcode = subprocess.call('command', shell=True) It waits for the process to terminate and assign the return code to the variable. For more detailed description see 17.1.subprocess - convenience functions in the python documentation. Hope it helps.
Looping an executable to get the result from Python script
In my python script, I need to call within a for loop an executable, and waiting for that executable to write the result on the "output.xml". How do I manage to use wait() & how do I know when one of my executable is finished generating the result to get the result? How do I close that process and open a new one to call again the executable and wait for the new result? import subprocess args = ("bin/bar") popen = subprocess.Popen(args) I need to wait for the output from "bin/bar" to generate the "output.xml" and from there, read it's content. for index, result in enumerate(results): myModule.callSubProcess(index) #this is where the problem is. fileOutput = open("output.xml") parseAndStoreInSQLiteFileOutput(index, file)
[ "Popen.wait() will make the script wait until the process ends. There's no need to kill the process afterwards, since it will have already exited.\n", "I think the easiest way to do is using call:\nimport subprocess\nretcode = subprocess.call('command', shell=True)\n\nIt waits for the process to terminate and assign the return code to the variable.\nFor more detailed description see 17.1.subprocess - convenience functions in the python documentation. Hope it helps. \n" ]
[ 1, 1 ]
[]
[]
[ "executable", "linux", "python", "system_calls" ]
stackoverflow_0002484049_executable_linux_python_system_calls.txt
Q: python, accessing a psycopg2 form a def? i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python i have tried this: def get_dblink( dbstring): """ Return a database cnx. """ global psycopg2 try cnx = psycopg2.connect( dbstring) except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) but i get this error: global name 'psycopg2' is not defined in my main file script.py i have: import psycopg2, psycopg2.extras from misc_defs import * hostname = '192.168.10.36' database = 'test' username = 'test' password = 'test' dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password) cnx = get_dblink( dbstring) can anyone give me a hand? A: You just need to import psycopg2 in your first snippet. If you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use globals for this is bad practice. So: at the top of every module, import every module which is used within that particular module. Also: note that from x import * (with wildcards) is generally frowned upon: it clutters your namespace and makes your code less explicit.
python, accessing a psycopg2 form a def?
i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python i have tried this: def get_dblink( dbstring): """ Return a database cnx. """ global psycopg2 try cnx = psycopg2.connect( dbstring) except Exception, e: print "Unable to connect to DB. Error [%s]" % ( e,) exit( ) but i get this error: global name 'psycopg2' is not defined in my main file script.py i have: import psycopg2, psycopg2.extras from misc_defs import * hostname = '192.168.10.36' database = 'test' username = 'test' password = 'test' dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password) cnx = get_dblink( dbstring) can anyone give me a hand?
[ "You just need to import psycopg2 in your first snippet.\nIf you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use globals for this is bad practice.\nSo: at the top of every module, import every module which is used within that particular module.\nAlso: note that from x import * (with wildcards) is generally frowned upon: it clutters your namespace and makes your code less explicit.\n" ]
[ 7 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0002510756_psycopg2_python.txt
Q: increment a variable in django templates All, How Can we increment a value like the following in django templates, {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} thanks.. A: I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the forloop.counter variable. For example: {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template{{forloop.counter}}" value="template{{forloop.counter}}"/> {% endfor %} Also note that I added that number to the id attributes of the <input /> tag. Otherwise you'll have multiple inputs with the same id. EDIT: I didn't note that it was a radio input. You could of course have the same name for each <input type="radio" />. A: You explicitly can't do that in a template. Variable assignment is not allowed. However if all you want is a counter in your loop, you just need to use {{ forloop.counter }}. A: You might also want to look into having Django forms produce these values
increment a variable in django templates
All, How Can we increment a value like the following in django templates, {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} thanks..
[ "I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the forloop.counter variable.\nFor example: \n{% for op in options %}\n {{op.choices}}<input type=\"radio\" name=\"template\" id=\"template{{forloop.counter}}\" value=\"template{{forloop.counter}}\"/>\n{% endfor %}\n\nAlso note that I added that number to the id attributes of the <input /> tag. Otherwise you'll have multiple inputs with the same id.\nEDIT: I didn't note that it was a radio input. You could of course have the same name for each <input type=\"radio\" />.\n", "You explicitly can't do that in a template. Variable assignment is not allowed.\nHowever if all you want is a counter in your loop, you just need to use {{ forloop.counter }}.\n", "You might also want to look into having Django forms produce these values\n" ]
[ 20, 9, 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002507284_django_django_templates_python.txt
Q: Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed login attempts - a sort of "blacklist". So basically something like: if "uniqueipaddress" and "authentication failure" appear more than 5 times, add uniqueipaddress to txt file. Any help would be greatly appreciated - please try and make it simple as I am very, very inexperienced in programming in Python! Thanks. A: For each line: read the IP and attempt status keep a dictionary by IP of amount of failed attempts Then go over the dictionary: print to file all IPs with 5 or more attempts Python hints: To read a file line by line: for line in open(filename) Parsing the log line depends entirely on its format. Some useful Python tools are the split method of a string, and regular expressions Keep a dictionary, i.e. ips[ip] is amount of attempts A: The following code should do something similar to what you're looking for. It's not perfect, but it's a good jumping off point. ips = {} for line in open('your_log.txt'): parts = line.split(' ') #assuming this is a good place to split if parts[1] == "AuthenticationFailure": if parts[0] in ips: ips[parts[0]] += 1 else: ips[parts[0]] = 0 for ip in [k for k,v in ips.iteritems() if v >= 5]: #WRITE TO FILE HERE This assumes that your log file is structured something like so: 1.1.1.1 LoginSuccess 2.2.2.2 LoginSuccess 3.3.3.3 AuthenticationFailure
Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog
Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed login attempts - a sort of "blacklist". So basically something like: if "uniqueipaddress" and "authentication failure" appear more than 5 times, add uniqueipaddress to txt file. Any help would be greatly appreciated - please try and make it simple as I am very, very inexperienced in programming in Python! Thanks.
[ "For each line:\n\nread the IP and attempt status\nkeep a dictionary by IP of amount of failed attempts\n\nThen go over the dictionary:\n\nprint to file all IPs with 5 or more attempts\n\n\nPython hints:\n\nTo read a file line by line: for line in open(filename)\nParsing the log line depends entirely on its format. Some useful Python tools are the split method of a string, and regular expressions\nKeep a dictionary, i.e. ips[ip] is amount of attempts\n\n", "The following code should do something similar to what you're looking for. It's not perfect, but it's a good jumping off point.\nips = {}\nfor line in open('your_log.txt'):\n parts = line.split(' ') #assuming this is a good place to split\n if parts[1] == \"AuthenticationFailure\":\n if parts[0] in ips:\n ips[parts[0]] += 1\n else:\n ips[parts[0]] = 0\n\nfor ip in [k for k,v in ips.iteritems() if v >= 5]:\n #WRITE TO FILE HERE\n\nThis assumes that your log file is structured something like so:\n1.1.1.1 LoginSuccess\n2.2.2.2 LoginSuccess\n3.3.3.3 AuthenticationFailure\n\n" ]
[ 1, 0 ]
[]
[]
[ "blacklist", "ip_address", "python", "syslog" ]
stackoverflow_0002510158_blacklist_ip_address_python_syslog.txt
Q: Sqlalchemy layout with WSGI application I'm working on writing a small WSGI application using Bottle and SqlAlchemy and am confused on how the "layout" of my application should be in terms of SqlAlchemy. My confusion is with creating engines and sessions. My understanding is that I should only create one engine with the 'create_engine' method. Should I be creating an engine instance in the global namespace in some sort of singleton pattern and creating sessions based off of it? How have you done this in your projects? Any insight would be appreciated. The examples in the documentation dont seem to make this entirely clear (unless I'm missing something obvious). Any thoughts? A: What you need to achieve is well described in the pylons documentation: Defining Tables and ORM classes: The model consists of two files: __init__.py and meta.py. __init__.py contains your table definitions and ORM classes, and an init_model() function which must be called at application startup. meta.py is merely a container for SQLAlchemy’s housekeeping objects (Session, metadata, and engine), which not all applications will use. The example of the __init__.py is shown in the link, whereas the meta.py looks similar to this: from sqlalchemy import MetaData from sqlalchemy.orm import scoped_session, sessionmaker __all__ = ['Session', 'engine', 'metadata'] engine = None Session = scoped_session(sessionmaker()) metadata = MetaData() You can consider this module a singleton implementation if you like, since it will do the job (of loading and having one instance in more Pythonic) for you when you first load the module. A: You don't have to create an engine manually. For web applications, it's best to use a scoped session which is effectively a threadlocal, used during a single request. from sqlalchemy import MetaData from sqlalchemy.orm import scoped_session, sessionmaker session = scoped_session(sessionmaker()) metadata = MetaData('sqlite://') # or whatever: creates the engine for you The engine will be available as metadata.bind. You don't need to bind a session to an engine - it's optional, see here.
Sqlalchemy layout with WSGI application
I'm working on writing a small WSGI application using Bottle and SqlAlchemy and am confused on how the "layout" of my application should be in terms of SqlAlchemy. My confusion is with creating engines and sessions. My understanding is that I should only create one engine with the 'create_engine' method. Should I be creating an engine instance in the global namespace in some sort of singleton pattern and creating sessions based off of it? How have you done this in your projects? Any insight would be appreciated. The examples in the documentation dont seem to make this entirely clear (unless I'm missing something obvious). Any thoughts?
[ "What you need to achieve is well described in the pylons documentation: Defining Tables and ORM classes:\n\nThe model consists of two files: __init__.py and meta.py. __init__.py contains your table definitions and ORM classes, and an init_model() function which must be called at application startup. meta.py is merely a container for SQLAlchemy’s housekeeping objects (Session, metadata, and engine), which not all applications will use.\n\nThe example of the __init__.py is shown in the link, whereas the meta.py looks similar to this:\nfrom sqlalchemy import MetaData\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n__all__ = ['Session', 'engine', 'metadata']\nengine = None\nSession = scoped_session(sessionmaker())\nmetadata = MetaData()\n\nYou can consider this module a singleton implementation if you like, since it will do the job (of loading and having one instance in more Pythonic) for you when you first load the module.\n", "You don't have to create an engine manually. For web applications, it's best to use a scoped session which is effectively a threadlocal, used during a single request.\nfrom sqlalchemy import MetaData\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nsession = scoped_session(sessionmaker())\nmetadata = MetaData('sqlite://') # or whatever: creates the engine for you\n\nThe engine will be available as metadata.bind.\nYou don't need to bind a session to an engine - it's optional, see here.\n" ]
[ 6, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002505426_python_sqlalchemy.txt
Q: Calling private parent class method from parent class (django) I want to call a redefined private method from an abstract parent class. I am using django if that matters. class Parent(models.Model): def method1(self): #do somthing self.__method2() def method2(self): pass # I also tried calling up a prent method with super class child(Parent): def method1(self) super(Child, self).method1() def __method2(self): #do something I get a AttributeError: "'Chil' object has no attribute '_Parent__method2'" What I am doing wrong ? A: Initial double underscores prevent polymorphism since both the method definition and the method call get mangled, to two different names. Replace with a single underscore to fix this. Also, double underscores are not used for "private" attributes, and you should discard whatever reference told you that they are. They're used for MI disambiguation.
Calling private parent class method from parent class (django)
I want to call a redefined private method from an abstract parent class. I am using django if that matters. class Parent(models.Model): def method1(self): #do somthing self.__method2() def method2(self): pass # I also tried calling up a prent method with super class child(Parent): def method1(self) super(Child, self).method1() def __method2(self): #do something I get a AttributeError: "'Chil' object has no attribute '_Parent__method2'" What I am doing wrong ?
[ "Initial double underscores prevent polymorphism since both the method definition and the method call get mangled, to two different names. Replace with a single underscore to fix this.\nAlso, double underscores are not used for \"private\" attributes, and you should discard whatever reference told you that they are. They're used for MI disambiguation.\n" ]
[ 4 ]
[]
[]
[ "abstract_class", "django", "inheritance", "python" ]
stackoverflow_0002511321_abstract_class_django_inheritance_python.txt
Q: How do I render text with pixel heights rather than points in pyglet? Pyglet only seems to use points. Is there a way to convert easily? Surely there must be a simple way because it's something obviously important, to be able to use pixels for text height. class Font(): def __init__(self,font,size): self.size = size self.font = font def return_surface(self,label): surface = Surface((label.content_width,label.content_height)) surface.set_background_alpha(0) setup_framebuffer(surface,True) label.draw() end_framebuffer() return surface def render(self,text,colour): colour = fix_colour(colour) label = pyglet.text.Label(text,font_name=self.font,font_size=self.size,color = colour,dpi=72) return self.return_surface(label) def render_wordwrap(self,text,width,colour,alignment): if alignment == 0: alignment = 'left' elif alignment == 1: alignment = 'center' else: alignment = 'right' colour = fix_colour(colour) label = pyglet.text.Label(text,font_name=self.font,font_size=self.size,color = colour,width=width,halign=alignment, multiline=True,dpi=72) return self.return_surface(label) A: The number of pixels taken up by a certain point size will depend on your screens DPI. For example, "14pt" is the distance covering 14 points, which at a default DPI of 96 is around 18 pixels. This site give a good explanation of converting point sizes to pixels.
How do I render text with pixel heights rather than points in pyglet?
Pyglet only seems to use points. Is there a way to convert easily? Surely there must be a simple way because it's something obviously important, to be able to use pixels for text height. class Font(): def __init__(self,font,size): self.size = size self.font = font def return_surface(self,label): surface = Surface((label.content_width,label.content_height)) surface.set_background_alpha(0) setup_framebuffer(surface,True) label.draw() end_framebuffer() return surface def render(self,text,colour): colour = fix_colour(colour) label = pyglet.text.Label(text,font_name=self.font,font_size=self.size,color = colour,dpi=72) return self.return_surface(label) def render_wordwrap(self,text,width,colour,alignment): if alignment == 0: alignment = 'left' elif alignment == 1: alignment = 'center' else: alignment = 'right' colour = fix_colour(colour) label = pyglet.text.Label(text,font_name=self.font,font_size=self.size,color = colour,width=width,halign=alignment, multiline=True,dpi=72) return self.return_surface(label)
[ "The number of pixels taken up by a certain point size will depend on your screens DPI.\nFor example, \"14pt\" is the distance covering 14 points, which at a default DPI of 96 is around 18 pixels.\nThis site give a good explanation of converting point sizes to pixels.\n" ]
[ 0 ]
[]
[]
[ "fonts", "label", "pyglet", "python", "text" ]
stackoverflow_0002510278_fonts_label_pyglet_python_text.txt
Q: Is there a way to change lookandfeel for wx Python? i was curious if there is some sort of way to change the look and feel of wxpython to something that is more standardized. I am writing a small application for windows and mac os x. And i noticed that Mac formats the layout and look of my application pretty terribly. I looked around online and could not find anything. Any ideas? A: From http://old.nabble.com/wxPython-Themes-Colors-td20337650.html: Not really. The default colors are always the platform and/or theme defaults, but some things can be changed by setting the colors of the parent window before creating the children. Not everything works that way however, such as things that use a different setting from the theme than the standard bg or fg color, such as the background color of listbox or textctrl.
Is there a way to change lookandfeel for wx Python?
i was curious if there is some sort of way to change the look and feel of wxpython to something that is more standardized. I am writing a small application for windows and mac os x. And i noticed that Mac formats the layout and look of my application pretty terribly. I looked around online and could not find anything. Any ideas?
[ "From http://old.nabble.com/wxPython-Themes-Colors-td20337650.html:\n\nNot really. The default colors are always the platform and/or theme\n defaults, but some things can be changed by setting the colors of the\n parent window before creating the children. Not everything works that\n way however, such as things that use a different setting from the theme\n than the standard bg or fg color, such as the background color of\n listbox or textctrl. \n\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002511228_python_wxpython_wxwidgets.txt
Q: Clear all class variables between instances This is probably a stupid question, but what's the best way to clear class variables between instances? I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? Or am I doing something totally wrong that requires a different approach? Thanks for helping ... class User(): def __init__(self): #RESET ALL CLASS VARIABLES def commit(self): #Commit variables to database >>u = User() >>u.name = 'Jason' >>u.email = 'jason.mendez@yahoo.com.mx' >>u.commit() So that each time User is called the variables are fresh. Thanks. A: Can you just pass the parameters into the constructor like this? class User(object): def __init__(self, name, email): self.name = name self.email = email def commit(self): pass jason = User('jason', 'jason@email.com') jack = User('jack', 'jack@yahoo.com') There's nothing to "reset" in the code you posted. Upon constructing a user, they don't even have a name or email attribute until you set them later. An alternative would be to just initialize them to some default values as shown below, but the code I posted above is better so there won't be any uninitialized User objects. def __init__(self): self.user = None self.email = None A: If you want to reset the values each time you construct a new object then you should be using instance variables, not class variables. If you use class variables and try to create more than one user object at the same time then one will overwrite the other's changes. A: Binding an attribute on an instance creates instance attributes, not class attributes. Perhaps you are seeing another problem that is not shown in the code above. A: This code does not change the name or email attributes of any of the instances of User except for u.
Clear all class variables between instances
This is probably a stupid question, but what's the best way to clear class variables between instances? I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? Or am I doing something totally wrong that requires a different approach? Thanks for helping ... class User(): def __init__(self): #RESET ALL CLASS VARIABLES def commit(self): #Commit variables to database >>u = User() >>u.name = 'Jason' >>u.email = 'jason.mendez@yahoo.com.mx' >>u.commit() So that each time User is called the variables are fresh. Thanks.
[ "Can you just pass the parameters into the constructor like this?\nclass User(object):\n def __init__(self, name, email):\n self.name = name\n self.email = email\n def commit(self):\n pass\n\njason = User('jason', 'jason@email.com')\njack = User('jack', 'jack@yahoo.com')\n\nThere's nothing to \"reset\" in the code you posted. Upon constructing a user, they don't even have a name or email attribute until you set them later. An alternative would be to just initialize them to some default values as shown below, but the code I posted above is better so there won't be any uninitialized User objects.\ndef __init__(self):\n self.user = None\n self.email = None\n\n", "If you want to reset the values each time you construct a new object then you should be using instance variables, not class variables.\nIf you use class variables and try to create more than one user object at the same time then one will overwrite the other's changes.\n", "Binding an attribute on an instance creates instance attributes, not class attributes. Perhaps you are seeing another problem that is not shown in the code above.\n", "This code does not change the name or email attributes of any of the instances of User except for u. \n" ]
[ 3, 3, 0, 0 ]
[]
[]
[ "class", "oop", "pylons", "python" ]
stackoverflow_0002511556_class_oop_pylons_python.txt
Q: running python code in matlab? i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful.... A: You should probably avoid this. Use one or the other - preferably Python. But if you have to use both, you could try this: http://github.com/kw/pymex (scroll down for the readme) Disclaimer: I wrote this. It may be somewhat difficult to get it to compile and work, particularly if you're on Windows (there is a pre-compiled win32 binary in the downloads area that might work). I don't have access to a lot of different machines with Matlab on them, so I haven't got that nailed down yet. A: You can use the system command to execute the Python code externally. To link it in more "natively" I think you'll have to go through C. That is, embed your Python code in C code and then expose it with a DLL to Matlab. P.S. On windows you can also expose Python code to Matlab via COM A: The only thing I know of is pythoncall but it is a little out of date and I'm not sure it will work reliably with recent versions of matlab. http://www.elisanet.fi/ptvirtan/software/pythoncall/index.html Otherwise you would have to interact with matlab through the shell (a bit of a pain I know). If you are dealing with large amounts of data and are on an OS where you can easily create a ramdisk saving matlab files to a ramdisk and passing the filename would be one way to get data from matlab to python without too much of a performance penalty.
running python code in matlab?
i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....
[ "You should probably avoid this. Use one or the other - preferably Python.\nBut if you have to use both, you could try this:\nhttp://github.com/kw/pymex (scroll down for the readme)\nDisclaimer: I wrote this. It may be somewhat difficult to get it to compile and work, particularly if you're on Windows (there is a pre-compiled win32 binary in the downloads area that might work). I don't have access to a lot of different machines with Matlab on them, so I haven't got that nailed down yet. \n", "You can use the system command to execute the Python code externally. To link it in more \"natively\" I think you'll have to go through C. That is, embed your Python code in C code and then expose it with a DLL to Matlab.\nP.S. On windows you can also expose Python code to Matlab via COM\n", "The only thing I know of is pythoncall but it is a little out of date and I'm not sure it will work reliably with recent versions of matlab.\nhttp://www.elisanet.fi/ptvirtan/software/pythoncall/index.html\nOtherwise you would have to interact with matlab through the shell (a bit of a pain I know). If you are dealing with large amounts of data and are on an OS where you can easily create a ramdisk saving matlab files to a ramdisk and passing the filename would be one way to get data from matlab to python without too much of a performance penalty.\n" ]
[ 4, 1, 1 ]
[ "There is a library called PyMat. It allows to call python code from matlab.\n" ]
[ -2 ]
[ "matlab", "python" ]
stackoverflow_0002509927_matlab_python.txt
Q: How to optimize my PageRank calculation? In the book Programming Collective Intelligence I found the following function to compute the PageRank: def calculatepagerank(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") self.con.execute("create index prankidx on pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("insert into pagerank select rowid,1.0 from urllist") self.dbcommit() for i in range(iterations): print "Iteration %d" % i for (urlid,) in self.con.execute("select rowid from urllist"): pr=0.15 # Loop through all the pages that link to this one for (linker,) in self.con.execute("select distinct fromid from link where toid=%d" % urlid): # Get the PageRank of the linker linkingpr=self.con.execute("select score from pagerank where urlid=%d" % linker).fetchone()[0] # Get the total number of links from the linker linkingcount=self.con.execute("select count(*) from link where fromid=%d" % linker).fetchone()[0] pr+=0.85*(linkingpr/linkingcount) self.con.execute("update pagerank set score=%f where urlid=%d" % (pr,urlid)) self.dbcommit() However, this function is very slow, because of all the SQL queries in every iteration >>> import cProfile >>> cProfile.run("crawler.calculatepagerank()") 2262510 function calls in 136.006 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 136.006 136.006 <string>:1(<module>) 1 20.826 20.826 136.006 136.006 searchengine.py:179(calculatepagerank) 21 0.000 0.000 0.528 0.025 searchengine.py:27(dbcommit) 21 0.528 0.025 0.528 0.025 {method 'commit' of 'sqlite3.Connecti 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler 1339864 112.602 0.000 112.602 0.000 {method 'execute' of 'sqlite3.Connec 922600 2.050 0.000 2.050 0.000 {method 'fetchone' of 'sqlite3.Cursor' 1 0.000 0.000 0.000 0.000 {range} So I optimized the function and came up with this: def calculatepagerank2(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") self.con.execute("create index prankidx on pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("insert into pagerank select rowid,1.0 from urllist") self.dbcommit() inlinks={} numoutlinks={} pagerank={} for (urlid,) in self.con.execute("select rowid from urllist"): inlinks[urlid]=[] numoutlinks[urlid]=0 # Initialize pagerank vector with 1.0 pagerank[urlid]=1.0 # Loop through all the pages that link to this one for (inlink,) in self.con.execute("select distinct fromid from link where toid=%d" % urlid): inlinks[urlid].append(inlink) # get number of outgoing links from a page numoutlinks[urlid]=self.con.execute("select count(*) from link where fromid=%d" % urlid).fetchone()[0] for i in range(iterations): print "Iteration %d" % i for urlid in pagerank: pr=0.15 for link in inlinks[urlid]: linkpr=pagerank[link] linkcount=numoutlinks[link] pr+=0.85*(linkpr/linkcount) pagerank[urlid]=pr for urlid in pagerank: self.con.execute("update pagerank set score=%f where urlid=%d" % (pagerank[urlid],urlid)) self.dbcommit() This function is many times faster (but uses a lot more memory for all the temporary dictionaries) because it avoids the unnecessary SQL queries in every iteration: >>> cProfile.run("crawler.calculatepagerank2()") 90070 function calls in 3.527 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.004 0.004 3.527 3.527 <string>:1(<module>) 1 1.154 1.154 3.523 3.523 searchengine.py:207(calculatepagerank2 2 0.000 0.000 0.058 0.029 searchengine.py:27(dbcommit) 23065 0.013 0.000 0.013 0.000 {method 'append' of 'list' objects} 2 0.058 0.029 0.058 0.029 {method 'commit' of 'sqlite3.Connectio 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler 43932 2.261 0.000 2.261 0.000 {method 'execute' of 'sqlite3.Connecti 23065 0.037 0.000 0.037 0.000 {method 'fetchone' of 'sqlite3.Cursor' 1 0.000 0.000 0.000 0.000 {range} But is it possible to further reduce the number of SQL queries to speed up the function even more? Update: Fixed Indentation in calculatepagerank2(). A: If you have a very large database (e.g. # records ~ # pages in the WWW) using the database in a manner similar to what's suggested in the book makes sense, because you're not going to be able to keep all that data in memory. If your dataset is small enough, you can (probably) improve your second version by not doing so many queries. Try replacing your first loop with something like this: for urlid, in self.con.execute('select rowid from urllist'): inlinks[urlid] = [] numoutlinks[urlid] = 0 pagerank[urlid] = 1.0 for src, dest in self.con.execute('select fromid, toid from link'): inlinks[dest].append(src) numoutlinks[src] += 1 This version does exactly 2 queries instead of O(n^2) queries. A: I believe the majority of the time is being spent on these SQL queries: for (urlid,) in self.con.execute("select rowid from urllist"): ... for (inlink,) in self.con.execute("select distinct fromid from link where toid=%d" % urlid): ... numoutlinks[urlid]=self.con.execute("select count(*) from link where fromid=%d" % urlid).fetchone()[0] Assuming you have enough memory, you may be able to reduce this to just two queries: SELECT fromid,toid FROM link WHERE toid IN (SELECT rowid FROM urllist) and SELECT fromid,count(*) FROM link WHERE fromid IN (SELECT rowid FROM urllist) GROUP BY fromid Then you could loop through the results and build inlinks, numoutlinks and pagerank. You may also benefit from using collections.defaultdict: import collections import itertools def constant_factory(value): return itertools.repeat(value).next The following then makes inlinks a dict of sets. Sets are appropriate since you only want distinct urls inlinks=collections.defaultdict(set) And this makes pagerank a dict whose default value is 1.0: pagerank=collections.defaultdict(constant_factory(1.0)) The advantage of using collections.defaultdict is that you do not need to pre-initialize the dicts. So, put together, what I'm suggesting would look something like this: import collections def constant_factory(value): return itertools.repeat(value).next def calculatepagerank2(self,iterations=20): # clear out the current PageRank tables self.con.execute("DROP TABLE IF EXISTS pagerank") self.con.execute("CREATE TABLE pagerank(urlid primary key,score)") self.con.execute("CREATE INDEX prankidx ON pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("INSERT INTO pagerank SELECT rowid,1.0 FROM urllist") self.dbcommit() inlinks=collections.defaultdict(set) sql='''SELECT fromid,toid FROM link WHERE toid IN (SELECT rowid FROM urllist)''' for f,t in self.con.execute(sql): inlinks[t].add(f) numoutlinks={} sql='''SELECT fromid,count(*) FROM link WHERE fromid IN (SELECT rowid FROM urllist) GROUP BY fromid''' for f,c in self.con.execute(sql): numoutlinks[f]=c pagerank=collections.defaultdict(constant_factory(1.0)) for i in range(iterations): print "Iteration %d" % i for urlid in inlinks: pr=0.15 for link in inlinks[urlid]: linkpr=pagerank[link] linkcount=numoutlinks[link] pr+=0.85*(linkpr/linkcount) pagerank[urlid]=pr sql="UPDATE pagerank SET score=? WHERE urlid=?" args=((pagerank[urlid],urlid) for urlid in pagerank) self.con.executemany(sql, args) self.dbcommit() A: Do you have enough RAM to hold the sparse matrix (fromid, toid) in some form? That would allow big optimizations (with big algorithmic changes). At least, caching in memory the (fromid, numlinks) that you now do with a select count(*) in your innermost loop should help (I'd imagine that cache, being O(N) in space if you're dealing with N URLs, would be more likely to fit in memory). A: I'm answering my own question, since in the end it came out that a mixture of all answers worked best for me: def calculatepagerank4(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") self.con.execute("create index prankidx on pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("insert into pagerank select rowid,1.0 from urllist") self.dbcommit() inlinks={} numoutlinks={} pagerank={} for (urlid,) in self.con.execute("select rowid from urllist"): inlinks[urlid]=[] numoutlinks[urlid]=0 # Initialize pagerank vector with 1.0 pagerank[urlid]=1.0 for src,dest in self.con.execute("select distinct fromid, toid from link"): inlinks[dest].append(src) numoutlinks[src]+=1 for i in range(iterations): print "Iteration %d" % i for urlid in pagerank: pr=0.15 for link in inlinks[urlid]: linkpr=pagerank[link] linkcount=numoutlinks[link] pr+=0.85*(linkpr/linkcount) pagerank[urlid]=pr args=((pagerank[urlid],urlid) for urlid in pagerank) self.con.executemany("update pagerank set score=? where urlid=?" , args) self.dbcommit() So I replaced the first two loops as suggested by allyourcode, but in addition also used executemany() as in the solution from ˜unutbu. But unlike ˜unutbu I use a generator expression for args, to not waste too much memory, although using a list comprehension was a little bit faster. In the end the routine was 100 times faster than the routine suggested in the book: >>> cProfile.run("crawler.calculatepagerank4()") 33512 function calls in 1.377 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.004 0.004 1.377 1.377 <string>:1(<module>) 2 0.000 0.000 0.073 0.036 searchengine.py:27(dbcommit) 1 0.693 0.693 1.373 1.373 searchengine.py:286(calculatepagerank4 10432 0.011 0.000 0.011 0.000 searchengine.py:321(<genexpr>) 23065 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} 2 0.073 0.036 0.073 0.036 {method 'commit' of 'sqlite3.Connectio 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler 6 0.379 0.063 0.379 0.063 {method 'execute' of 'sqlite3.Connecti 1 0.209 0.209 0.220 0.220 {method 'executemany' of 'sqlite3.Conn 1 0.000 0.000 0.000 0.000 {range} One should also be aware of the following problems: If you use string formating with %f instead of using a placeholder ? for constructing the SQL statement you will loose precision (e.g. I got 2.9796095721920315 using ? but 2.9796100000000001 using %f. Duplicate links from one page to another are treated as only one link in the default PageRank algorithm. However the solution from the book didn't take that into account. The whole algorithm from the book is flawed: The reason is, that in each iteration, the pagerank score is not stored in a second table. But this means the outcome of an iteration depends on the order of the pages looped through and this might change the result after several iterations quite drastically. To fix this problem one either has to use an additional table/dictionary to store the pagerank for the next iteration or to use a completely different algorithm like Power Iteration.
How to optimize my PageRank calculation?
In the book Programming Collective Intelligence I found the following function to compute the PageRank: def calculatepagerank(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") self.con.execute("create index prankidx on pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("insert into pagerank select rowid,1.0 from urllist") self.dbcommit() for i in range(iterations): print "Iteration %d" % i for (urlid,) in self.con.execute("select rowid from urllist"): pr=0.15 # Loop through all the pages that link to this one for (linker,) in self.con.execute("select distinct fromid from link where toid=%d" % urlid): # Get the PageRank of the linker linkingpr=self.con.execute("select score from pagerank where urlid=%d" % linker).fetchone()[0] # Get the total number of links from the linker linkingcount=self.con.execute("select count(*) from link where fromid=%d" % linker).fetchone()[0] pr+=0.85*(linkingpr/linkingcount) self.con.execute("update pagerank set score=%f where urlid=%d" % (pr,urlid)) self.dbcommit() However, this function is very slow, because of all the SQL queries in every iteration >>> import cProfile >>> cProfile.run("crawler.calculatepagerank()") 2262510 function calls in 136.006 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 136.006 136.006 <string>:1(<module>) 1 20.826 20.826 136.006 136.006 searchengine.py:179(calculatepagerank) 21 0.000 0.000 0.528 0.025 searchengine.py:27(dbcommit) 21 0.528 0.025 0.528 0.025 {method 'commit' of 'sqlite3.Connecti 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler 1339864 112.602 0.000 112.602 0.000 {method 'execute' of 'sqlite3.Connec 922600 2.050 0.000 2.050 0.000 {method 'fetchone' of 'sqlite3.Cursor' 1 0.000 0.000 0.000 0.000 {range} So I optimized the function and came up with this: def calculatepagerank2(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") self.con.execute("create index prankidx on pagerank(urlid)") # initialize every url with a PageRank of 1.0 self.con.execute("insert into pagerank select rowid,1.0 from urllist") self.dbcommit() inlinks={} numoutlinks={} pagerank={} for (urlid,) in self.con.execute("select rowid from urllist"): inlinks[urlid]=[] numoutlinks[urlid]=0 # Initialize pagerank vector with 1.0 pagerank[urlid]=1.0 # Loop through all the pages that link to this one for (inlink,) in self.con.execute("select distinct fromid from link where toid=%d" % urlid): inlinks[urlid].append(inlink) # get number of outgoing links from a page numoutlinks[urlid]=self.con.execute("select count(*) from link where fromid=%d" % urlid).fetchone()[0] for i in range(iterations): print "Iteration %d" % i for urlid in pagerank: pr=0.15 for link in inlinks[urlid]: linkpr=pagerank[link] linkcount=numoutlinks[link] pr+=0.85*(linkpr/linkcount) pagerank[urlid]=pr for urlid in pagerank: self.con.execute("update pagerank set score=%f where urlid=%d" % (pagerank[urlid],urlid)) self.dbcommit() This function is many times faster (but uses a lot more memory for all the temporary dictionaries) because it avoids the unnecessary SQL queries in every iteration: >>> cProfile.run("crawler.calculatepagerank2()") 90070 function calls in 3.527 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.004 0.004 3.527 3.527 <string>:1(<module>) 1 1.154 1.154 3.523 3.523 searchengine.py:207(calculatepagerank2 2 0.000 0.000 0.058 0.029 searchengine.py:27(dbcommit) 23065 0.013 0.000 0.013 0.000 {method 'append' of 'list' objects} 2 0.058 0.029 0.058 0.029 {method 'commit' of 'sqlite3.Connectio 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler 43932 2.261 0.000 2.261 0.000 {method 'execute' of 'sqlite3.Connecti 23065 0.037 0.000 0.037 0.000 {method 'fetchone' of 'sqlite3.Cursor' 1 0.000 0.000 0.000 0.000 {range} But is it possible to further reduce the number of SQL queries to speed up the function even more? Update: Fixed Indentation in calculatepagerank2().
[ "If you have a very large database (e.g. # records ~ # pages in the WWW) using the database in a manner similar to what's suggested in the book makes sense, because you're not going to be able to keep all that data in memory.\nIf your dataset is small enough, you can (probably) improve your second version by not doing so many queries. Try replacing your first loop with something like this:\nfor urlid, in self.con.execute('select rowid from urllist'):\n inlinks[urlid] = []\n numoutlinks[urlid] = 0\n pagerank[urlid] = 1.0\n\nfor src, dest in self.con.execute('select fromid, toid from link'):\n inlinks[dest].append(src)\n numoutlinks[src] += 1\n\nThis version does exactly 2 queries instead of O(n^2) queries.\n", "I believe the majority of the time is being spent on these SQL queries:\nfor (urlid,) in self.con.execute(\"select rowid from urllist\"):\n ...\n for (inlink,) in self.con.execute(\"select distinct fromid from link where toid=%d\" % urlid):\n ...\n numoutlinks[urlid]=self.con.execute(\"select count(*) from link where fromid=%d\" % urlid).fetchone()[0] \n\nAssuming you have enough memory, you may be able to reduce this to just two queries:\n\nSELECT fromid,toid FROM link WHERE toid IN (SELECT rowid FROM urllist)\nand\nSELECT fromid,count(*) FROM link WHERE fromid IN (SELECT rowid FROM urllist) GROUP BY fromid\n\nThen you could loop through the results and build inlinks, numoutlinks and pagerank.\nYou may also benefit from using collections.defaultdict:\nimport collections\nimport itertools\ndef constant_factory(value):\n return itertools.repeat(value).next\n\nThe following then makes inlinks a dict of sets. Sets are appropriate since\nyou only want distinct urls\ninlinks=collections.defaultdict(set)\n\nAnd this makes pagerank a dict whose default value is 1.0:\npagerank=collections.defaultdict(constant_factory(1.0))\n\nThe advantage of using collections.defaultdict is that you\ndo not need to pre-initialize the dicts.\nSo, put together, what I'm suggesting would look something like this:\nimport collections\ndef constant_factory(value):\n return itertools.repeat(value).next\ndef calculatepagerank2(self,iterations=20):\n # clear out the current PageRank tables\n self.con.execute(\"DROP TABLE IF EXISTS pagerank\")\n self.con.execute(\"CREATE TABLE pagerank(urlid primary key,score)\")\n self.con.execute(\"CREATE INDEX prankidx ON pagerank(urlid)\")\n\n # initialize every url with a PageRank of 1.0\n self.con.execute(\"INSERT INTO pagerank SELECT rowid,1.0 FROM urllist\")\n self.dbcommit()\n\n inlinks=collections.defaultdict(set)\n\n sql='''SELECT fromid,toid FROM link WHERE toid IN (SELECT rowid FROM urllist)'''\n for f,t in self.con.execute(sql):\n inlinks[t].add(f)\n\n numoutlinks={}\n sql='''SELECT fromid,count(*) FROM link WHERE fromid IN (SELECT rowid FROM urllist) GROUP BY fromid'''\n for f,c in self.con.execute(sql):\n numoutlinks[f]=c\n\n pagerank=collections.defaultdict(constant_factory(1.0))\n for i in range(iterations):\n print \"Iteration %d\" % i\n for urlid in inlinks:\n pr=0.15\n for link in inlinks[urlid]:\n linkpr=pagerank[link]\n linkcount=numoutlinks[link]\n pr+=0.85*(linkpr/linkcount)\n pagerank[urlid]=pr\n sql=\"UPDATE pagerank SET score=? WHERE urlid=?\"\n args=((pagerank[urlid],urlid) for urlid in pagerank)\n self.con.executemany(sql, args)\n self.dbcommit()\n\n", "Do you have enough RAM to hold the sparse matrix (fromid, toid) in some form? That would allow big optimizations (with big algorithmic changes). At least, caching in memory the (fromid, numlinks) that you now do with a select count(*) in your innermost loop should help (I'd imagine that cache, being O(N) in space if you're dealing with N URLs, would be more likely to fit in memory).\n", "I'm answering my own question, since in the end it came out that a mixture of all answers worked best for me:\n def calculatepagerank4(self,iterations=20):\n # clear out the current PageRank tables\n self.con.execute(\"drop table if exists pagerank\")\n self.con.execute(\"create table pagerank(urlid primary key,score)\")\n self.con.execute(\"create index prankidx on pagerank(urlid)\")\n\n # initialize every url with a PageRank of 1.0\n self.con.execute(\"insert into pagerank select rowid,1.0 from urllist\")\n self.dbcommit()\n\n inlinks={}\n numoutlinks={}\n pagerank={}\n\n for (urlid,) in self.con.execute(\"select rowid from urllist\"):\n inlinks[urlid]=[]\n numoutlinks[urlid]=0\n # Initialize pagerank vector with 1.0\n pagerank[urlid]=1.0\n\n for src,dest in self.con.execute(\"select distinct fromid, toid from link\"):\n inlinks[dest].append(src)\n numoutlinks[src]+=1 \n\n for i in range(iterations):\n print \"Iteration %d\" % i\n\n for urlid in pagerank:\n pr=0.15\n for link in inlinks[urlid]:\n linkpr=pagerank[link]\n linkcount=numoutlinks[link]\n pr+=0.85*(linkpr/linkcount)\n pagerank[urlid]=pr\n\n args=((pagerank[urlid],urlid) for urlid in pagerank)\n self.con.executemany(\"update pagerank set score=? where urlid=?\" , args)\n self.dbcommit() \n\nSo I replaced the first two loops as suggested by allyourcode, but in addition also used executemany() as in the solution from ˜unutbu. But unlike ˜unutbu I use a generator expression for args, to not waste too much memory, although using a list comprehension was a little bit faster. In the end the routine was 100 times faster than the routine suggested in the book:\n>>> cProfile.run(\"crawler.calculatepagerank4()\")\n 33512 function calls in 1.377 CPU seconds\nOrdered by: standard name\n\nncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.004 0.004 1.377 1.377 <string>:1(<module>)\n 2 0.000 0.000 0.073 0.036 searchengine.py:27(dbcommit)\n 1 0.693 0.693 1.373 1.373 searchengine.py:286(calculatepagerank4\n 10432 0.011 0.000 0.011 0.000 searchengine.py:321(<genexpr>)\n 23065 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects}\n 2 0.073 0.036 0.073 0.036 {method 'commit' of 'sqlite3.Connectio\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler\n 6 0.379 0.063 0.379 0.063 {method 'execute' of 'sqlite3.Connecti\n 1 0.209 0.209 0.220 0.220 {method 'executemany' of 'sqlite3.Conn\n 1 0.000 0.000 0.000 0.000 {range}\n\nOne should also be aware of the following problems:\n\nIf you use string formating with %f instead of using a placeholder ? for constructing the SQL statement you will loose precision (e.g. I got 2.9796095721920315 using ? but 2.9796100000000001 using %f.\nDuplicate links from one page to another are treated as only one link in the default PageRank algorithm. However the solution from the book didn't take that into account.\nThe whole algorithm from the book is flawed: The reason is, that in each iteration, the pagerank score is not stored in a second table. But this means the outcome of an iteration depends on the order of the pages looped through and this might change the result after several iterations quite drastically. To fix this problem one either has to use an additional table/dictionary to store the pagerank for the next iteration or to use a completely different algorithm like Power Iteration. \n\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "optimization", "pagerank", "python", "sql" ]
stackoverflow_0002484445_optimization_pagerank_python_sql.txt
Q: Looking for a recommendation of a good tutorial on best practices for a web scraping project? I need to do a fairly extensive project involving web scraping and am considering using Hpricot or Beautiful Soup (i.e. Ruby or Python). Has anyone come across a tutorial that they thought was particularly good on this subject that would help me start the project off on the right foot? A: Two of my favorite tools for Python web scraping are Scrapy and Mechanize. Each of these projects has its own tutorial and best practices. A: Not a tool, really, but a good discussion is Michael Shrenk's book, Webbots, Spiders, and Screen Scrapers. The book succeeds very well in its stated mission: explaining how to build simple web bots and operate them in accordance with community standards. It’s not everything you need to know, but it’s the best introduction I’ve seen. The focus is on simple, single-threaded, bots. There’s some small mention of using multiple bots that store data in a central repository, but there’s no discussion of the issues involved in writing multi-threaded or distributed bots that can process hundreds of pages per second. I recommend that you read this book if you’re at all interested in writing Web bots, even if you’re not familiar with or intending to use PHP. But be sure not to expect more than the book offers. A: Look into using lxml instead of BeautifulSoup. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame - lxml just isn't as vocal about it). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API. Ian Blicking agrees. There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed. A: Take a look at the following screencasts: http://railscasts.com/episodes/190-screen-scraping-with-nokogiri http://railscasts.com/episodes/191-mechanize Or if you like it plain, the corresponding asciicasts: http://asciicasts.com/episodes/190-screen-scraping-with-nokogiri http://asciicasts.com/episodes/191-mechanize A: For Ruby, the Scrubyt web-scraping toolkit is excellent. Here's an extensive introduction to it, which is worth reading even if you'll be using some other tool.
Looking for a recommendation of a good tutorial on best practices for a web scraping project?
I need to do a fairly extensive project involving web scraping and am considering using Hpricot or Beautiful Soup (i.e. Ruby or Python). Has anyone come across a tutorial that they thought was particularly good on this subject that would help me start the project off on the right foot?
[ "Two of my favorite tools for Python web scraping are Scrapy and Mechanize. Each of these projects has its own tutorial and best practices.\n", "Not a tool, really, but a good discussion is Michael Shrenk's book, Webbots, Spiders, and Screen Scrapers.\nThe book succeeds very well in its stated mission: explaining how to build simple web bots and operate them in accordance with community standards. It’s not everything you need to know, but it’s the best introduction I’ve seen. The focus is on simple, single-threaded, bots. There’s some small mention of using multiple bots that store data in a central repository, but there’s no discussion of the issues involved in writing multi-threaded or distributed bots that can process hundreds of pages per second.\nI recommend that you read this book if you’re at all interested in writing Web bots, even if you’re not familiar with or intending to use PHP. But be sure not to expect more than the book offers.\n", "Look into using lxml instead of BeautifulSoup. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles \"broken\" HTML better than BeautifulSoup (their claim to fame - lxml just isn't as vocal about it). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.\nIan Blicking agrees.\nThere's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.\n", "Take a look at the following screencasts:\n\nhttp://railscasts.com/episodes/190-screen-scraping-with-nokogiri\nhttp://railscasts.com/episodes/191-mechanize\n\nOr if you like it plain, the corresponding asciicasts:\n\nhttp://asciicasts.com/episodes/190-screen-scraping-with-nokogiri\nhttp://asciicasts.com/episodes/191-mechanize\n\n", "For Ruby, the Scrubyt web-scraping toolkit is excellent. Here's an extensive introduction to it, which is worth reading even if you'll be using some other tool.\n" ]
[ 9, 5, 4, 3, 0 ]
[]
[]
[ "beautifulsoup", "hpricot", "python", "ruby", "screen_scraping" ]
stackoverflow_0000684629_beautifulsoup_hpricot_python_ruby_screen_scraping.txt
Q: Bundle module with app on Google App Engine This may be a basic question but how can I include a module with my app. I'm very new to python and what I want to do is to include this module simplejson with my app, but after downloading it I have no idea what to do next :( This is how the module looks like after unzip it. I don't know what files to move to my app. A: Put the simplejson directory (that is inside the simplejson-2.1.0) in your app. Or, you could just use the simplejson lib that's bundled with the Django lib that's bundled with App Engine by doing the following import wherever you need it: from django.utils import simplejson That's always available, without needing to bundle anything extra with your app. The only drawback I can think of is that it will be out of date (though I don't know how far out of date). A: Put the directory (or a link) into your deployment directory and appcfg.py update will send it along to the server. This is documented in the Python Runtime Environment page.
Bundle module with app on Google App Engine
This may be a basic question but how can I include a module with my app. I'm very new to python and what I want to do is to include this module simplejson with my app, but after downloading it I have no idea what to do next :( This is how the module looks like after unzip it. I don't know what files to move to my app.
[ "Put the simplejson directory (that is inside the simplejson-2.1.0) in your app.\nOr, you could just use the simplejson lib that's bundled with the Django lib that's bundled with App Engine by doing the following import wherever you need it:\nfrom django.utils import simplejson\n\nThat's always available, without needing to bundle anything extra with your app. The only drawback I can think of is that it will be out of date (though I don't know how far out of date).\n", "Put the directory (or a link) into your deployment directory and appcfg.py update will send it along to the server. This is documented in the Python Runtime Environment page.\n" ]
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002511883_google_app_engine_python.txt
Q: Numpy Matrix keeps giving me an Error, Okay this is werid, i keep getting the error, randomly. ValueError: matrix must be 2-dimensional So i tracked it down, and cornered it to basically something like this: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] numpy.matrix(a_list) Whats wrong with this? If i print a_list it is clearly a 2d matrix of tuples, however numpy does not believe so. A: The easiest way around this is to just use a numpy array, instead of a numpy matrix: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] arr=numpy.array(a_list) Numpy matrices are strictly 2-dimensional, and a_list is 3-dimensional. So numpy matrices are not an option. A: tuples have more than one value, so they are considered a dimension. So you're creating a 3d matrix. A: What are you trying to do? In numpy, a matrix is a 2-d array of numbers. You can make a 32x32x2 "matrix" with numpy.array(a_list). You could also make a 32x32 array of tuples using numpy object arrays, but there is little that would be better for than the 32x32x2 case (since you can think of it as a 32x32 array of 2-element arrays).
Numpy Matrix keeps giving me an Error,
Okay this is werid, i keep getting the error, randomly. ValueError: matrix must be 2-dimensional So i tracked it down, and cornered it to basically something like this: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] numpy.matrix(a_list) Whats wrong with this? If i print a_list it is clearly a 2d matrix of tuples, however numpy does not believe so.
[ "The easiest way around this is to just use a numpy array, instead of a numpy matrix:\na_list = [[(1,100) for _ in range(32)] for _ in range(32)]\narr=numpy.array(a_list)\n\nNumpy matrices are strictly 2-dimensional, and a_list is 3-dimensional. So numpy matrices are not an option.\n", "tuples have more than one value, so they are considered a dimension. So you're creating a 3d matrix.\n", "What are you trying to do? In numpy, a matrix is a 2-d array of numbers.\nYou can make a 32x32x2 \"matrix\" with numpy.array(a_list).\nYou could also make a 32x32 array of tuples using numpy object arrays, but there is little that would be better for than the 32x32x2 case (since you can think of it as a 32x32 array of 2-element arrays).\n" ]
[ 4, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002512033_numpy_python.txt
Q: Allowing threads from python after calling a blocking i/o code in a python extension generated using SWIG I have written a python extension wrapping an existing C++ library live555 (wrapping RTSP client interface to be specific) in SWIG. The extension works when it is operated in a single thread, but as soon as I call the event loop function of the library, python interpreter never gets the control back. So if I create a scheduled task using threading.Timer right before calling the event loop, that task never gets executed once event loop starts. To fix this issue, I added Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros manually in the SWIG auto generated wrapper cxx file around every doEventLoop() function call. But now, I want to do the same (i.e. allow threads) when SWIG generates the code itself and not to change any code manually. Has anyone done something similar in SWIG? P.S. - I would also consider switching to any other framework (like SIP) to get this working. I selected SWIG over any other technology is because writing SWIG interface was really very easy and I just had to include the existing header files. A: SWIG gives you plenty of hooks to help make this happen. If a coarse solution is sufficient for your needs, one thing I've done in the past is put something like this in my .swig file: %exception { Py_BEGIN_ALLOW_THREADS $action Py_END_ALLOW_THREADS } This (ab)uses the SWIG facility for decorating C function calls with some kind of error-handling logic in order to decorate those calls with a GIL unlock/lock. See Exception handling with %exception in the SWIG docs for details on what's going on here.
Allowing threads from python after calling a blocking i/o code in a python extension generated using SWIG
I have written a python extension wrapping an existing C++ library live555 (wrapping RTSP client interface to be specific) in SWIG. The extension works when it is operated in a single thread, but as soon as I call the event loop function of the library, python interpreter never gets the control back. So if I create a scheduled task using threading.Timer right before calling the event loop, that task never gets executed once event loop starts. To fix this issue, I added Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros manually in the SWIG auto generated wrapper cxx file around every doEventLoop() function call. But now, I want to do the same (i.e. allow threads) when SWIG generates the code itself and not to change any code manually. Has anyone done something similar in SWIG? P.S. - I would also consider switching to any other framework (like SIP) to get this working. I selected SWIG over any other technology is because writing SWIG interface was really very easy and I just had to include the existing header files.
[ "SWIG gives you plenty of hooks to help make this happen. If a coarse solution is sufficient for your needs, one thing I've done in the past is put something like this in my .swig file:\n%exception {\n Py_BEGIN_ALLOW_THREADS\n $action\n Py_END_ALLOW_THREADS\n}\n\nThis (ab)uses the SWIG facility for decorating C function calls with some kind of error-handling logic in order to decorate those calls with a GIL unlock/lock. See Exception handling with %exception in the SWIG docs for details on what's going on here.\n" ]
[ 5 ]
[]
[]
[ "python", "rtsp_client", "swig" ]
stackoverflow_0002510696_python_rtsp_client_swig.txt
Q: Unknown syntax error Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead. Please help :) def dealcards(): for i in range(len(cards)): cards[i] = '' for j in range(8): cards[i] = cards[i].append(random.randint(0,9) return cards[i] print (dealcards()) A: cards[i] = cards[i].append(random.randint(0,9) ^ Missing closing parenthesis. And the return statement on the next line is incorrectly indented. A: Missing a close: cards[i] = cards[i].append(random.randint(0,9)) A: Your SyntaxError is due to an unclosed paren after cards[i] = cards[i].append(random.randint(0,9) When you clear that up, you'll find you will get an AttributeError when you call this function. You set cards[i] to be a str object then try to call append on it. Strings don't have an append method. You loop over indices and change each place in cards. This is usually a sign you're doing something wrong; it's more typical in Python simply to make a new list. When you do need indices, which is very rare, it's usually best to use enumerate. More to the point about the last one.....this function modifies a global, cards. Using functions to mutate global state is a bad thing. There are two possibilities that would almost certainly be better: Make a class that stores the cards as a state with a method called deal_cards which mutates some attribute self.cards or whatever. (Probably the way to go.) Make a function that accepts cards as an argument and returns a new list. (Probably not the way to go, but improves modularity, maintainability, and testability over your current technique.)
Unknown syntax error
Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead. Please help :) def dealcards(): for i in range(len(cards)): cards[i] = '' for j in range(8): cards[i] = cards[i].append(random.randint(0,9) return cards[i] print (dealcards())
[ "cards[i] = cards[i].append(random.randint(0,9)\n ^\n\nMissing closing parenthesis. And the return statement on the next line is incorrectly indented.\n", "Missing a close:\ncards[i] = cards[i].append(random.randint(0,9))\n\n", "\nYour SyntaxError is due to an unclosed paren after cards[i] = cards[i].append(random.randint(0,9)\nWhen you clear that up, you'll find you will get an AttributeError when you call this function. You set cards[i] to be a str object then try to call append on it. Strings don't have an append method. \nYou loop over indices and change each place in cards. This is usually a sign you're doing something wrong; it's more typical in Python simply to make a new list.\n\n\nWhen you do need indices, which is very rare, it's usually best to use enumerate.\n\nMore to the point about the last one.....this function modifies a global, cards. Using functions to mutate global state is a bad thing. There are two possibilities that would almost certainly be better:\n\n\nMake a class that stores the cards as a state with a method called deal_cards which mutates some attribute self.cards or whatever. (Probably the way to go.)\nMake a function that accepts cards as an argument and returns a new list. (Probably not the way to go, but improves modularity, maintainability, and testability over your current technique.)\n\n\n" ]
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002511722_python.txt
Q: Pylons/Routes Did url_for() change within templates? I'm getting an error: GenerationException: url_for could not generate URL. Called with args: () {} from this line of a mako template: <p>Your url is ${h.url_for()}</p> Over in my helpers.py, I do have: from routes import url_for Looking at the Routes-1.12.1-py2.6.egg/routes/util.py, I seem to go wrong about line it calls _screenargs(). This is simple functionality from the Pylons book. What silly thing am I doing wrong? Was there a new url_current()? Where? A: I didn't know url_for() (no arguments) was ever legal, but if it was and this is what you're referring to as "url_current", I believe the new approach is to use the url object, calling a method on it as url.current().
Pylons/Routes Did url_for() change within templates?
I'm getting an error: GenerationException: url_for could not generate URL. Called with args: () {} from this line of a mako template: <p>Your url is ${h.url_for()}</p> Over in my helpers.py, I do have: from routes import url_for Looking at the Routes-1.12.1-py2.6.egg/routes/util.py, I seem to go wrong about line it calls _screenargs(). This is simple functionality from the Pylons book. What silly thing am I doing wrong? Was there a new url_current()? Where?
[ "I didn't know url_for() (no arguments) was ever legal, but if it was and this is what you're referring to as \"url_current\", I believe the new approach is to use the url object, calling a method on it as url.current().\n" ]
[ 5 ]
[]
[]
[ "mako", "pylons", "python", "routes" ]
stackoverflow_0002512264_mako_pylons_python_routes.txt
Q: Find new messages added to an imap mailbox since I last checked with python imaplib2? I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. I'm using imaplib2 which implements the IDLE command. Here's my basic program: M = imaplib2.IMAP4("mail.me.com") M.login(username,password) lst = M.list() assert lst[0]=='OK' for mbx in lst[1]: print "Mailboxes:",mbx def process(m): print "m=",m res = M.recent() print res M.select('INBOX') M.examine(mailbox='INBOX',callback=process) while True: print "Calling idle..." M.idle() print "back from idle" M.close() M.logout() It prints the mailboxes properly and runs process() when the first change happens to the mailbox. But the response from recent() doesn't make sense to me, and after the first message I never get any other notifications. Anyone know how to do this? A: See example and references in python-imap-idle-with-imaplib2 (Wayback Machine snapshot). The module involves threading, you should pay attention to event synchronization. The example suggests synchronizing with events, and leaves mail processing to the reader: # The method that gets called when a new email arrives. # Replace it with something better. def dosync(self): print "Got an event!" Taking a hint from the question, "something better" can be: # Replaced with something better. def dosync(self): print "Got an event!" res = self.M.recent() print res A: I am finding that recent() is a bit vague (this is an IMAP vagueness, not imaplib2). Seems better to keep a list of message numbers before and after idle, and the difference is new messages. Then use fetch(messages,"UID") to get the message uid.
Find new messages added to an imap mailbox since I last checked with python imaplib2?
I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. I'm using imaplib2 which implements the IDLE command. Here's my basic program: M = imaplib2.IMAP4("mail.me.com") M.login(username,password) lst = M.list() assert lst[0]=='OK' for mbx in lst[1]: print "Mailboxes:",mbx def process(m): print "m=",m res = M.recent() print res M.select('INBOX') M.examine(mailbox='INBOX',callback=process) while True: print "Calling idle..." M.idle() print "back from idle" M.close() M.logout() It prints the mailboxes properly and runs process() when the first change happens to the mailbox. But the response from recent() doesn't make sense to me, and after the first message I never get any other notifications. Anyone know how to do this?
[ "See example and references in python-imap-idle-with-imaplib2 (Wayback Machine snapshot).\nThe module involves threading, you should pay attention to event synchronization.\nThe example suggests synchronizing with events, and leaves mail processing to the reader:\n# The method that gets called when a new email arrives. \n# Replace it with something better.\ndef dosync(self):\n print \"Got an event!\"\n\nTaking a hint from the question, \"something better\" can be:\n# Replaced with something better.\ndef dosync(self):\n print \"Got an event!\"\n res = self.M.recent()\n print res\n\n", "I am finding that recent() is a bit vague (this is an IMAP vagueness, not imaplib2). Seems better to keep a list of message numbers before and after idle, and the difference is new messages.\nThen use fetch(messages,\"UID\") to get the message uid.\n" ]
[ 2, 2 ]
[]
[]
[ "imap", "imaplib", "python", "python_idle" ]
stackoverflow_0002047067_imap_imaplib_python_python_idle.txt
Q: pyenchant RPM for alt-install of python2.6. ELF class error I know what my problem is with this issue, but I'm a little confused about how to best go about fixing it. I have a RHEL 5.4 system, with Python2.6 alt-installed (via the geekymedia RPMS). everything seems to be working. As I tweak a spec file, I'm able to build out RPMs to work with this new Python install. I'm building all of my RPMs on the same 64-bit system. [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python python-2.4.3-27.el5 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python26 python26-2.6-geekymedia1 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa enchant enchant-1.4.2-4.el5.1 enchant-1.4.2-4.el5.1 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python-enchant python-enchant-1.5.1-7.2 the enchant RPMs are default from the RHEL repositories. When I try to import the enchant module I get the following warning, and I can't create a dictionary object: [jduncan@mgi-ric-squid1 x86_64]$ python26 Python 2.6 (r26:66714, Feb 24 2010, 15:24:02) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import enchant libenchant.so.1 ** (process:10075): WARNING **: Error loading plugin: /usr/lib/enchant/libenchant_myspell.so: wrong ELF class: ELFCLASS32 >>> d = enchant.Dict("en_US") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 470, in __init__ self._switch_this(broker._request_dict_data(tag),broker) File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 256, in _request_dict_data self._raise_error(eStr % (tag,),DictNotFoundError) File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 212, in _raise_error raise eclass(default) enchant.DictNotFoundError: Dictionary for language 'en_US' could not be found Would a simple upgrade to enchant 1.5.1 work? Or is more work than that required? A: Just in case someone else runs into this: I removed the RHEL versions of enchant downloaded the RHEL source RPM for enchant (same version) built my own 64-bit only RPM for enchant installed that my Py2.6 altinstall python-enchant package now works.
pyenchant RPM for alt-install of python2.6. ELF class error
I know what my problem is with this issue, but I'm a little confused about how to best go about fixing it. I have a RHEL 5.4 system, with Python2.6 alt-installed (via the geekymedia RPMS). everything seems to be working. As I tweak a spec file, I'm able to build out RPMs to work with this new Python install. I'm building all of my RPMs on the same 64-bit system. [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python python-2.4.3-27.el5 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python26 python26-2.6-geekymedia1 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa enchant enchant-1.4.2-4.el5.1 enchant-1.4.2-4.el5.1 [jduncan@mgi-ric-squid1 x86_64]$ rpm -qa python-enchant python-enchant-1.5.1-7.2 the enchant RPMs are default from the RHEL repositories. When I try to import the enchant module I get the following warning, and I can't create a dictionary object: [jduncan@mgi-ric-squid1 x86_64]$ python26 Python 2.6 (r26:66714, Feb 24 2010, 15:24:02) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import enchant libenchant.so.1 ** (process:10075): WARNING **: Error loading plugin: /usr/lib/enchant/libenchant_myspell.so: wrong ELF class: ELFCLASS32 >>> d = enchant.Dict("en_US") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 470, in __init__ self._switch_this(broker._request_dict_data(tag),broker) File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 256, in _request_dict_data self._raise_error(eStr % (tag,),DictNotFoundError) File "/usr/lib/python2.6/site-packages/enchant/__init__.py", line 212, in _raise_error raise eclass(default) enchant.DictNotFoundError: Dictionary for language 'en_US' could not be found Would a simple upgrade to enchant 1.5.1 work? Or is more work than that required?
[ "Just in case someone else runs into this:\n\nI removed the RHEL versions of enchant\ndownloaded the RHEL source RPM for enchant (same version)\nbuilt my own 64-bit only RPM for enchant\ninstalled that\n\nmy Py2.6 altinstall python-enchant package now works.\n" ]
[ 1 ]
[]
[]
[ "installation", "pyenchant", "python" ]
stackoverflow_0002495428_installation_pyenchant_python.txt
Q: How to chroot Django Can one run Django in a chroot? Notably, what's necessary in order to set up (for example) /var/www as a chroot'd directory and then have Django run in that chroot'd directory? Thank you - I'm grateful for any input. A: There are many reasons mod_wsgi is preferred for Python web app deployment. One is stability, another is the variety of configuration options... one of which is ability to chroot the mod_wsgi daemon (starting with version 3.00). The chroot option is not yet documented for the WSGIDaemonProcess directive at http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess but there is enough documentation in Changes in Version 3.0. You can also read a disussion of the feature at http://code.google.com/p/modwsgi/issues/detail?id=106 A: You will have to add a Python interpreter to that directory and add Django to it ofcourse. After you've got the environment set-up you will have to create a wrapper script that does something like os.chroot('/var/www/') and you're done :) To create a sandboxed/chrooted environment for Python try one of the following options: http://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29?highlight=%28chroot%29 The PyPy option seems to be getting popular since Google started using it with the App-Engine.
How to chroot Django
Can one run Django in a chroot? Notably, what's necessary in order to set up (for example) /var/www as a chroot'd directory and then have Django run in that chroot'd directory? Thank you - I'm grateful for any input.
[ "There are many reasons mod_wsgi is preferred for Python web app deployment. One is stability, another is the variety of configuration options... one of which is ability to chroot the mod_wsgi daemon (starting with version 3.00).\nThe chroot option is not yet documented for the WSGIDaemonProcess directive at http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess but there is enough documentation in Changes in Version 3.0.\nYou can also read a disussion of the feature at http://code.google.com/p/modwsgi/issues/detail?id=106\n", "You will have to add a Python interpreter to that directory and add Django to it ofcourse.\nAfter you've got the environment set-up you will have to create a wrapper script that does something like os.chroot('/var/www/') and you're done :)\nTo create a sandboxed/chrooted environment for Python try one of the following options: http://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29?highlight=%28chroot%29\nThe PyPy option seems to be getting popular since Google started using it with the App-Engine.\n" ]
[ 3, 2 ]
[]
[]
[ "chroot", "django", "jail", "python", "security" ]
stackoverflow_0002512428_chroot_django_jail_python_security.txt
Q: FancyURLOpener failing since moving to python 3.1.2 I had an application that was downloading a .CSV file from a password-protected website then processing it futher. I was using FancyURLOpener, and simply hardcoding the username and password. (Obviously, security is not a high priority in this particular instance). Since downloading Python 3.1.2, this code has stopped working. After fixing the obvious issue of it now being in the "request" namespace, it's crashing in a less obvious way. Does anyone know of the changes that have happened to the implementation, and how to use it now? The documentation seems to be short of examples. Here is a cut down version of the code: import urllib.request; class TracOpener (urllib.request.FancyURLopener) : def prompt_user_passwd(self, host, realm) : return ('andrew_ee', '_my_unenctryped_password') csvUrl='http://mysite/report/19?format=csv@USER=fred_nukre' opener = TracOpener(); f = opener.open(csvUrl); # This is failing! s = f.read(); f.close(); s; For the sake of completeness, here's the entire call stack: Traceback (most recent call last): File "C:\reporting\download_csv_file.py", line 12, in <module> f = opener.open(csvUrl); File "C:\Program Files\Python31\lib\urllib\request.py", line 1454, in open return getattr(self, name)(url) File "C:\Program Files\Python31\lib\urllib\request.py", line 1628, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1624, in _open_generic_http response.status, response.reason, response.msg, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1640, in http_error result = method(url, fp, errcode, errmsg, headers) File "C:\Program Files\Python31\lib\urllib\request.py", line 1878, in http_error_401 return getattr(self,name)(url, realm) File "C:\Program Files\Python31\lib\urllib\request.py", line 1950, in retry_http_basic_auth return self.open(newurl) File "C:\Program Files\Python31\lib\urllib\request.py", line 1454, in open return getattr(self, name)(url) File "C:\Program Files\Python31\lib\urllib\request.py", line 1628, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1590, in _open_generic_http auth = base64.b64encode(user_passwd).strip() File "C:\Program Files\Python31\lib\base64.py", line 56, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str A: It's a known bug: http://bugs.python.org/issue8123
FancyURLOpener failing since moving to python 3.1.2
I had an application that was downloading a .CSV file from a password-protected website then processing it futher. I was using FancyURLOpener, and simply hardcoding the username and password. (Obviously, security is not a high priority in this particular instance). Since downloading Python 3.1.2, this code has stopped working. After fixing the obvious issue of it now being in the "request" namespace, it's crashing in a less obvious way. Does anyone know of the changes that have happened to the implementation, and how to use it now? The documentation seems to be short of examples. Here is a cut down version of the code: import urllib.request; class TracOpener (urllib.request.FancyURLopener) : def prompt_user_passwd(self, host, realm) : return ('andrew_ee', '_my_unenctryped_password') csvUrl='http://mysite/report/19?format=csv@USER=fred_nukre' opener = TracOpener(); f = opener.open(csvUrl); # This is failing! s = f.read(); f.close(); s; For the sake of completeness, here's the entire call stack: Traceback (most recent call last): File "C:\reporting\download_csv_file.py", line 12, in <module> f = opener.open(csvUrl); File "C:\Program Files\Python31\lib\urllib\request.py", line 1454, in open return getattr(self, name)(url) File "C:\Program Files\Python31\lib\urllib\request.py", line 1628, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1624, in _open_generic_http response.status, response.reason, response.msg, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1640, in http_error result = method(url, fp, errcode, errmsg, headers) File "C:\Program Files\Python31\lib\urllib\request.py", line 1878, in http_error_401 return getattr(self,name)(url, realm) File "C:\Program Files\Python31\lib\urllib\request.py", line 1950, in retry_http_basic_auth return self.open(newurl) File "C:\Program Files\Python31\lib\urllib\request.py", line 1454, in open return getattr(self, name)(url) File "C:\Program Files\Python31\lib\urllib\request.py", line 1628, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Program Files\Python31\lib\urllib\request.py", line 1590, in _open_generic_http auth = base64.b64encode(user_passwd).strip() File "C:\Program Files\Python31\lib\base64.py", line 56, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str
[ "It's a known bug: http://bugs.python.org/issue8123\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002512538_python_python_3.x.txt
Q: Is this the correct way to convert a UTC datetime string into localtime? Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :) import time UTC_STRING = "2010-03-25 02:00:00" stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M:%S")) stamp -= time.timezone now = time.localtime() if now[8] == 1: stamp += 60*60 elif now[8] == -1: stamp -= 60*60 print 'UTC: ', time.gmtime(stamp) print 'Local: ', time.localtime(stamp) --- Results from New Zealand (GMT+12 dst=1) --- UTC: (2010, 3, 25, 2, 0, 0, 3, 84, 0) Local: (2010, 3, 25, 15, 0, 0, 3, 84, 1) A: timezone related calculations are not trivial and there are already good libraries available e.g. use pytz, using that you will be able to convert from any timezone to any other timezone with confidence. usage is as simple as this >>> warsaw = pytz.timezone('Europe/Warsaw') >>> loc_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)
Is this the correct way to convert a UTC datetime string into localtime?
Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :) import time UTC_STRING = "2010-03-25 02:00:00" stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M:%S")) stamp -= time.timezone now = time.localtime() if now[8] == 1: stamp += 60*60 elif now[8] == -1: stamp -= 60*60 print 'UTC: ', time.gmtime(stamp) print 'Local: ', time.localtime(stamp) --- Results from New Zealand (GMT+12 dst=1) --- UTC: (2010, 3, 25, 2, 0, 0, 3, 84, 0) Local: (2010, 3, 25, 15, 0, 0, 3, 84, 1)
[ "timezone related calculations are not trivial and there are already good libraries available e.g. use pytz, using that you will be able to convert from any timezone to any other timezone with confidence. usage is as simple as this\n>>> warsaw = pytz.timezone('Europe/Warsaw')\n>>> loc_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)\n\n" ]
[ 5 ]
[]
[]
[ "python", "time" ]
stackoverflow_0002512854_python_time.txt
Q: How do I constrain the SCons Command builder to run only if its dependencies have changed? I am using the Command builder in scons to specify that a particular script needs to be invoked to produce a particular file. I would like to only run the script if it has been modified since the file was previously generated. The default behaviour of the Command builder seems to be to always run the script. How can I change this? This is my current SConstruct: speed = Command('speed_analysis.tex','','python code/speed.py') report = PDF(target = 'report.pdf', source = 'report.tex') Depends(report, speed) A: First, it looks like code/speed.py has no control on the output filename... Hardcoded output filenames are usually considered bad practice in scons (see yacc tool). It would read better like this: speed = Command('speed_analysis.tex', [], 'python code/speed.py -o $TARGET') Now, the PDF target produces a report.pdf from report.tex. I'm guessing there's an implicit dependency from report.tex to speed_analysis.tex (through Tex include or something like that). This: Depends(report, speed) Is correct to express that dependency if it's missing. Though I'm surprised the scanner for the PDF builder did not see that implicit dependency... You should verify the dep tree using: scons --tree=all It should look something like this: + report.pdf + report.tex + speed_analysis.tex + code/speed.py + /usr/bin/python + /usr/bin/pdflatex Now, to answer your question about the script (speed.py) always running, that's because it has no input. There's nothing for scons to check against. That script file must be reading something as an input, if only the py file itself. You need to tell scons about all direct and implicit dependencies for it to short-circuit subsequent runs: Command('speed_analysis.tex', 'code/speed.py', 'python $SOURCE -o $TARGET') A: Maybe your example is incomplete, but aren't you supposed to do: env = Environment() env.Command(.... I think you need to specify your dependencies as the second argument to Command: Command('speed_analysis.tex','code/speed.py','python code/speed.py')
How do I constrain the SCons Command builder to run only if its dependencies have changed?
I am using the Command builder in scons to specify that a particular script needs to be invoked to produce a particular file. I would like to only run the script if it has been modified since the file was previously generated. The default behaviour of the Command builder seems to be to always run the script. How can I change this? This is my current SConstruct: speed = Command('speed_analysis.tex','','python code/speed.py') report = PDF(target = 'report.pdf', source = 'report.tex') Depends(report, speed)
[ "First, it looks like code/speed.py has no control on the output filename... Hardcoded output filenames are usually considered bad practice in scons (see yacc tool). It would read better like this:\nspeed = Command('speed_analysis.tex', [], 'python code/speed.py -o $TARGET')\n\nNow, the PDF target produces a report.pdf from report.tex. I'm guessing there's an implicit dependency from report.tex to speed_analysis.tex (through Tex include or something like that).\nThis:\nDepends(report, speed)\n\nIs correct to express that dependency if it's missing. Though I'm surprised the scanner for the PDF builder did not see that implicit dependency...\nYou should verify the dep tree using:\nscons --tree=all\n\nIt should look something like this:\n+ report.pdf\n + report.tex\n + speed_analysis.tex\n + code/speed.py\n + /usr/bin/python\n + /usr/bin/pdflatex\n\nNow, to answer your question about the script (speed.py) always running, that's because it has no input. There's nothing for scons to check against. That script file must be reading something as an input, if only the py file itself. You need to tell scons about all direct and implicit dependencies for it to short-circuit subsequent runs:\nCommand('speed_analysis.tex', 'code/speed.py', 'python $SOURCE -o $TARGET')\n\n", "Maybe your example is incomplete, but aren't you supposed to do:\nenv = Environment()\nenv.Command(....\n\nI think you need to specify your dependencies as the second argument to Command:\nCommand('speed_analysis.tex','code/speed.py','python code/speed.py')\n\n" ]
[ 11, 1 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0000828075_python_scons.txt
Q: XML document being parsed as single element instead of sequence of nodes Given xml that looks like this: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store> I am getting this as my parsed xmldoc: >>> from xml.dom import minidom >>> xmldoc = minidom.parse('bar.xml') >>> xmldoc.toxml() u'<?xml version="1.0" ?><Store>\n<foo>\n<book>\n<isbn>123456</isbn>\n</book>\n<t itle>XYZ</title>\n<checkout>no</checkout>\n</foo>\n<bar>\n<book>\n<isbn>7890</is bn>\n</book>\n<title>XYZ2</title>\n<checkout>yes</checkout>\n</bar>\n</Store>' Is there an easy way to pre-process this document so that when it is parsed, it isn't parsed as a single xml element? A: An XML document always has a single root element. If you don't care about the root element, just ignore it and look at its children instead! For example, using the more modern element-tree (but minidom offers similar possibilities in this respect): try: import xml.etree.cElementTree as et except ImportError: import xml.etree.ElementTree as et xmlin = '''<Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store>''' root = et.fromstring(xmlin) for child in root.getchildren(): print et.tostring(child) A: xmldoc is a parsed XML object. toxml() asks it to convert itself back to a string of XML text again. Explore a little further: >>> xmldoc.childNodes [<DOM Element: Store at 0x212b788>] >>> xmldoc.childNodes[0].childNodes [<DOM Text node "u'\n'">, <DOM Element: foo at 0x212bcd8>, <DOM Text node "u'\n'">, <DOM Element: bar at 0x212b2d8>, <DOM Text node "u'\n'">] Then, realize that DOM is difficult to work with and read about ElementTree.
XML document being parsed as single element instead of sequence of nodes
Given xml that looks like this: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store> I am getting this as my parsed xmldoc: >>> from xml.dom import minidom >>> xmldoc = minidom.parse('bar.xml') >>> xmldoc.toxml() u'<?xml version="1.0" ?><Store>\n<foo>\n<book>\n<isbn>123456</isbn>\n</book>\n<t itle>XYZ</title>\n<checkout>no</checkout>\n</foo>\n<bar>\n<book>\n<isbn>7890</is bn>\n</book>\n<title>XYZ2</title>\n<checkout>yes</checkout>\n</bar>\n</Store>' Is there an easy way to pre-process this document so that when it is parsed, it isn't parsed as a single xml element?
[ "An XML document always has a single root element. If you don't care about the root element, just ignore it and look at its children instead!\nFor example, using the more modern element-tree (but minidom offers similar possibilities in this respect):\ntry:\n import xml.etree.cElementTree as et\nexcept ImportError:\n import xml.etree.ElementTree as et\n\nxmlin = '''<Store>\n<foo>\n<book>\n<isbn>123456</isbn>\n</book>\n<title>XYZ</title>\n<checkout>no</checkout>\n</foo>\n<bar>\n<book>\n<isbn>7890</isbn>\n</book>\n<title>XYZ2</title>\n<checkout>yes</checkout>\n</bar>\n</Store>'''\n\nroot = et.fromstring(xmlin)\n\nfor child in root.getchildren():\n print et.tostring(child)\n\n", "xmldoc is a parsed XML object. toxml() asks it to convert itself back to a string of XML text again. Explore a little further:\n>>> xmldoc.childNodes\n[<DOM Element: Store at 0x212b788>]\n>>> xmldoc.childNodes[0].childNodes\n[<DOM Text node \"u'\\n'\">, <DOM Element: foo at 0x212bcd8>, <DOM Text node \"u'\\n'\">, <DOM Element: bar at 0x212b2d8>, <DOM Text node \"u'\\n'\">]\n\nThen, realize that DOM is difficult to work with and read about ElementTree.\n" ]
[ 2, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0002512702_minidom_python_xml.txt
Q: Django debug error I have the following in my model: class info(models.Model): add = models.CharField(max_length=255) name = models.CharField(max_length=255) An in the views when i say info_l = info.objects.filter(id=1) logging.debug(info_l.name) i get an error saying name doesnt exist at debug statement. 'QuerySet' object has no attribute 'name' 1.How can this be resolved. 2.Also how to query for only one field instead of selecting all like select name from info. A: 1. Selecting Single Items It looks like you're trying to get a single object. Using filter will return a QuerySet object (as is happening in your code), which behaves more like a list (and, as you've noticed, lacks the name attribute). You have two options here. First, you can just grab the first element: info_l = info.objects.filter(id=1)[0] You could also use the objects.get method instead, which will return a single object (and raise an exception if it doesn't exist): info_l = info.objects.get(id=1) Django has some pretty good documentation on QuerySets, and it may be worth taking a look at it: Docs on using filters QuerySet reference 2. Retrieving Specific Fields Django provides the defer and only methods, which will let you choose specific fields from the database, rather than fetching everything at once. These don't actually prevent the fields from being read; rather, it loads them lazily. defer is an "opt-in" mode, which lets you specify what fields should be lazily loaded. only is "out-out" -- you call it, and only the fields you pass will by eagerly loaded. So in your example, you'd want to do something like this: info_l = info.objects.filter(id=1).only('name')[0] Though with a model as simple as the example you give, I wouldn't worry much at all about limiting fields.
Django debug error
I have the following in my model: class info(models.Model): add = models.CharField(max_length=255) name = models.CharField(max_length=255) An in the views when i say info_l = info.objects.filter(id=1) logging.debug(info_l.name) i get an error saying name doesnt exist at debug statement. 'QuerySet' object has no attribute 'name' 1.How can this be resolved. 2.Also how to query for only one field instead of selecting all like select name from info.
[ "1. Selecting Single Items\nIt looks like you're trying to get a single object. Using filter will return a QuerySet object (as is happening in your code), which behaves more like a list (and, as you've noticed, lacks the name attribute).\nYou have two options here. First, you can just grab the first element:\ninfo_l = info.objects.filter(id=1)[0]\n\nYou could also use the objects.get method instead, which will return a single object (and raise an exception if it doesn't exist):\ninfo_l = info.objects.get(id=1)\n\nDjango has some pretty good documentation on QuerySets, and it may be worth taking a look at it:\nDocs on using filters\nQuerySet reference\n2. Retrieving Specific Fields\nDjango provides the defer and only methods, which will let you choose specific fields from the database, rather than fetching everything at once. These don't actually prevent the fields from being read; rather, it loads them lazily. defer is an \"opt-in\" mode, which lets you specify what fields should be lazily loaded. only is \"out-out\" -- you call it, and only the fields you pass will by eagerly loaded.\nSo in your example, you'd want to do something like this:\ninfo_l = info.objects.filter(id=1).only('name')[0]\n\nThough with a model as simple as the example you give, I wouldn't worry much at all about limiting fields.\n" ]
[ 2 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0002513237_django_django_views_python.txt
Q: Python: Count lines and differentiate between them I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. An example output is this: 13:48 An event happened. 13:48 Another event happened. 13:49 A new event happened. 13:49 A random event happened. 13:49 An event happened. So, the program would need to understand that 2 things happened at 13:48, and 3 at 13:49. I'm not sure how the information would be stored, but I need to average them after, to determine an average of how often it happens. Sorry for being so complicated! A: You could just use the time as a key for a dictionary and point it to a list of event messages. The length of that value would give you the number of events, while still letting you get at the specific events themselves: >>> from pprint import pprint >>> from collections import defaultdict >>> events = defaultdict(list) >>> with open('log.txt') as f: ... for line in f: ... time, message = line.strip().split(None, 1) ... events[time].append(message) ... >>> pprint(dict(events)) # pprint handles defaultdicts poorly {'13:48': ['An event happened.', 'Another event happened.'], '13:49': ['A new event happened.', 'A random event happened.', 'An event happened.']} If you want to be extra fancy, you could parse the time into a time object. Edit: Take into account Mike Graham's suggestions. A: If you just want a count of how many events happen each minute then you don't really need python, you can do it from bash: cut -d ' ' -f1 filename | uniq -c gives 2 13:48 3 13:49 A: If you don't need to know what happen but only how many times then: $ python3.1 -c'from collections import Counter import fileinput c = Counter(line.split(None, 1)[0] for line in fileinput.input() if line.strip()) print(c)' events.txt Output: Counter({'13:49': 3, '13:48': 2}) A: You can also use a groupby function from an itertools module with time as a grouping key. >>> import itertools >>> from operator import itemgetter >>> lines = (line.strip().split(None, 1) for line in open('log.txt')) >>> for key, group in itertools.groupby(lines, key=itemgetter(0)): ... print '%s - %s' % (key, map(itemgetter(1), group)) ... 13:48 - ['An event happened.', 'Another event happened.'] 13:49 - ['A new event happened.', 'A random event happened.', 'An event happened.'] A: awk '{_[$1]++}END{for(i in _) print i,_[i]}' filename
Python: Count lines and differentiate between them
I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. An example output is this: 13:48 An event happened. 13:48 Another event happened. 13:49 A new event happened. 13:49 A random event happened. 13:49 An event happened. So, the program would need to understand that 2 things happened at 13:48, and 3 at 13:49. I'm not sure how the information would be stored, but I need to average them after, to determine an average of how often it happens. Sorry for being so complicated!
[ "You could just use the time as a key for a dictionary and point it to a list of event messages. The length of that value would give you the number of events, while still letting you get at the specific events themselves:\n>>> from pprint import pprint\n>>> from collections import defaultdict\n>>> events = defaultdict(list)\n>>> with open('log.txt') as f:\n... for line in f:\n... time, message = line.strip().split(None, 1)\n... events[time].append(message)\n... \n>>> pprint(dict(events)) # pprint handles defaultdicts poorly\n{'13:48': ['An event happened.', 'Another event happened.'],\n '13:49': ['A new event happened.',\n 'A random event happened.',\n 'An event happened.']}\n\nIf you want to be extra fancy, you could parse the time into a time object.\nEdit: Take into account Mike Graham's suggestions.\n", "If you just want a count of how many events happen each minute then you don't really need python, you can do it from bash:\n cut -d ' ' -f1 filename | uniq -c\n\ngives \n 2 13:48\n 3 13:49\n\n", "If you don't need to know what happen but only how many times then:\n$ python3.1 -c'from collections import Counter\nimport fileinput\nc = Counter(line.split(None, 1)[0] for line in fileinput.input() if line.strip())\nprint(c)' events.txt \n\nOutput:\nCounter({'13:49': 3, '13:48': 2})\n\n", "You can also use a groupby function from an itertools module with time as a grouping key.\n>>> import itertools\n>>> from operator import itemgetter\n>>> lines = (line.strip().split(None, 1) for line in open('log.txt'))\n>>> for key, group in itertools.groupby(lines, key=itemgetter(0)):\n... print '%s - %s' % (key, map(itemgetter(1), group))\n... \n13:48 - ['An event happened.', 'Another event happened.']\n13:49 - ['A new event happened.', 'A random event happened.', 'An event happened.']\n\n", "awk '{_[$1]++}END{for(i in _) print i,_[i]}' filename\n\n" ]
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "count", "python" ]
stackoverflow_0002510651_count_python.txt
Q: Structure accessible by attribute name or index options I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to figure it out, I've only come across C implementations of the above types. Nothing specifically in Python. What is the Python native way to create this kind of object? I apologize if this has been widely covered already. In searching for an answer, I must be missing some fundamental concept that is excluding me from finding an answer. A: Python 2.6 introduced collections.namedtuple to make this easy. With older Python versions you can use the named tuple recipe. Quoting directly from the docs: >>> Point = namedtuple('Point', 'x y') >>> p = Point(11, y=22) # instantiate with positional or keyword arguments >>> p[0] + p[1] # indexable like the plain tuple (11, 22) 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> p # readable __repr__ with a name=value style Point(x=11, y=22) A: You can't use the same implementation as the result object of os.stat() and others. However Python 2.6 has a new factory function that creates a similar datatype called named tuple. A named tuple is a tuple whose slots can also be addressed by name. The named tuple should not require any more memory, according to the documentation, than a regular tuple, since they don't have a per instance dictionary. The factory function signature is: collections.namedtuple(typename, field_names[, verbose]) The first argument specifies the name of the new type, the second argument is a string (space or comma separated) containing the field names and, finally, if verbose is true, the factory function will also print the class generated. Example Suppose you have a tuple containing a username and password. To access the username you get the item at position zero and the password is accessed at position one: credential = ('joeuser', 'secret123') print 'Username:', credential[0] print 'Password:', credential[1] There's nothing wrong with this code but the tuple isn't self-documenting. You have to find and read the documentation about the positioning of the fields in the tuple. This is where named tuple can come to the rescue. We can recode the previous example as follows: import collections # Create a new sub-tuple named Credential Credential = collections.namedtuple('Credential', 'username, password') credential = Credential(username='joeuser', password='secret123') print 'Username:', credential.username print 'Password:', credential.password If you are interested of what the code looks like for the newly created Credential-type you can add verbose=True to the argument list when creating the type, in this particular case we get the following output: import collections Credential = collections.namedtuple('Credential', 'username, password', verbose=True) class Credential(tuple): 'Credential(username, password)' __slots__ = () _fields = ('username', 'password') def __new__(_cls, username, password): return _tuple.__new__(_cls, (username, password)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Credential object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def __repr__(self): return 'Credential(username=%r, password=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'username': t[0], 'password': t[1]} def _replace(_self, **kwds): 'Return a new Credential object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('username', 'password'), _self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): return tuple(self) username = _property(_itemgetter(0)) password = _property(_itemgetter(1)) The named tuple doesn't only provide access to fields by name but also contains helper functions such as the _make() function which helps creating an Credential instance from a sequence or iterable. For example: cred_tuple = ('joeuser', 'secret123') credential = Credential._make(cred_tuple) The python library documentation for namedtuple has more information and code examples, so I suggest that you take a peek. A: an object that has values that are accessible either by attribute name, or by index I'm not sure what you're finding hard about this. A collection accessible by index implements __getitem__. A collection accessible by names implements __getattr__ (or __getattribute__). You can implement both without any trouble at all. Or, you can use namedtuple. To make life simpler, you could extend the tuple class so you don't have to implement your own __getitem__. Or you can define an ordinary class that also has __getitem__ so you didn't have to mess with __getattr__. For example >>> class Foo( object ): ... def __init__( self, x, y, z ): ... self.x= x ... self.y= y ... self.z= z ... def __getitem__( self, index ): ... return { 0: self.x, 1: self.y, 2: self.z }[index] ... >>> f= Foo(1,2,3) >>> f.x 1 >>> f[0] 1 >>> f[1] 2 >>> f[2] 3 >>> f.y 2
Structure accessible by attribute name or index options
I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to figure it out, I've only come across C implementations of the above types. Nothing specifically in Python. What is the Python native way to create this kind of object? I apologize if this has been widely covered already. In searching for an answer, I must be missing some fundamental concept that is excluding me from finding an answer.
[ "Python 2.6 introduced collections.namedtuple to make this easy. With older Python versions you can use the named tuple recipe.\nQuoting directly from the docs:\n>>> Point = namedtuple('Point', 'x y')\n>>> p = Point(11, y=22) # instantiate with positional or keyword arguments\n>>> p[0] + p[1] # indexable like the plain tuple (11, 22)\n33\n>>> x, y = p # unpack like a regular tuple\n>>> x, y\n(11, 22)\n>>> p.x + p.y # fields also accessible by name\n33\n>>> p # readable __repr__ with a name=value style\nPoint(x=11, y=22)\n\n", "You can't use the same implementation as the result object of os.stat() and others. However Python 2.6 has a new factory function that creates a similar datatype called named tuple. A named tuple is a tuple whose slots can also be addressed by name. The named tuple should not require any more memory, according to the documentation, than a regular tuple, since they don't have a per instance dictionary. The factory function signature is: \ncollections.namedtuple(typename, field_names[, verbose]) \n\nThe first argument specifies the name of the new type, the second argument is a string (space or comma separated) containing the field names and, finally, if verbose is true, the factory function will also print the class generated.\nExample\nSuppose you have a tuple containing a username and password. To access the username you get the item at position zero and the password is accessed at position one: \ncredential = ('joeuser', 'secret123') \nprint 'Username:', credential[0] \nprint 'Password:', credential[1] \n\nThere's nothing wrong with this code but the tuple isn't self-documenting. You have to find and read the documentation about the positioning of the fields in the tuple. This is where named tuple can come to the rescue. We can recode the previous example as follows: \nimport collections \n# Create a new sub-tuple named Credential \nCredential = collections.namedtuple('Credential', 'username, password') \n\ncredential = Credential(username='joeuser', password='secret123') \n\nprint 'Username:', credential.username \nprint 'Password:', credential.password \n\nIf you are interested of what the code looks like for the newly created Credential-type you can add verbose=True to the argument list when creating the type, in this particular case we get the following output:\nimport collections \nCredential = collections.namedtuple('Credential', 'username, password', verbose=True) \n\nclass Credential(tuple): \n 'Credential(username, password)' \n\n __slots__ = () \n\n _fields = ('username', 'password') \n\n def __new__(_cls, username, password): \n return _tuple.__new__(_cls, (username, password)) \n\n @classmethod \n def _make(cls, iterable, new=tuple.__new__, len=len): \n 'Make a new Credential object from a sequence or iterable' \n result = new(cls, iterable) \n if len(result) != 2: \n raise TypeError('Expected 2 arguments, got %d' % len(result)) \n return result \n\n def __repr__(self): \n return 'Credential(username=%r, password=%r)' % self \n\n def _asdict(t): \n 'Return a new dict which maps field names to their values' \n return {'username': t[0], 'password': t[1]} \n\n def _replace(_self, **kwds): \n 'Return a new Credential object replacing specified fields with new values' \n result = _self._make(map(kwds.pop, ('username', 'password'), _self)) \n if kwds: \n raise ValueError('Got unexpected field names: %r' % kwds.keys()) \n return result \n\n def __getnewargs__(self): \n return tuple(self) \n\n username = _property(_itemgetter(0)) \n password = _property(_itemgetter(1)) \n\nThe named tuple doesn't only provide access to fields by name but also contains helper functions such as the _make() function which helps creating an Credential instance from a sequence or iterable. For example: \ncred_tuple = ('joeuser', 'secret123') \ncredential = Credential._make(cred_tuple) \n\nThe python library documentation for namedtuple has more information and code examples, so I suggest that you take a peek.\n", "\nan object that has values that are accessible either by attribute name, or by index\n\nI'm not sure what you're finding hard about this.\nA collection accessible by index implements __getitem__.\nA collection accessible by names implements __getattr__ (or __getattribute__).\nYou can implement both without any trouble at all. Or, you can use namedtuple.\nTo make life simpler, you could extend the tuple class so you don't have to implement your own __getitem__. Or you can define an ordinary class that also has __getitem__ so you didn't have to mess with __getattr__.\nFor example\n>>> class Foo( object ):\n... def __init__( self, x, y, z ):\n... self.x= x\n... self.y= y\n... self.z= z\n... def __getitem__( self, index ):\n... return { 0: self.x, 1: self.y, 2: self.z }[index]\n... \n>>> f= Foo(1,2,3)\n>>> f.x\n1\n>>> f[0]\n1\n>>> f[1]\n2\n>>> f[2]\n3\n>>> f.y\n2\n\n" ]
[ 5, 3, 0 ]
[]
[]
[ "data_structures", "namedtuple", "python" ]
stackoverflow_0002512671_data_structures_namedtuple_python.txt
Q: Apps not showing in Django admin site I have a Django project with about 10 apps in it. But the admin interface only shows Auth and Site models which are part of Django distribution. Yes, the admin interface is up and working but none of my self-written apps shows there. INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.admindocs', 'project.app1', ... app1/admin.py from django.contrib import admin from project.app1.models import * admin.site.register(model1) admin.site.register(model2) admin.site.register(model3) What could be wrong in this case? Looks like everything is configured as what document says. Thank you in advance. A: Which version of Django are you using? Support for files named admin.py was added in version 1.0 (I think). Before that, you'd have to add extra information to your model. A: If something in your app throws an exception, the app or model may be excluded from the admin on subsequent requests. If that is the case, you should get an error on the first request. Also, please make sure your URLCONF has admin.autodiscover()
Apps not showing in Django admin site
I have a Django project with about 10 apps in it. But the admin interface only shows Auth and Site models which are part of Django distribution. Yes, the admin interface is up and working but none of my self-written apps shows there. INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.admindocs', 'project.app1', ... app1/admin.py from django.contrib import admin from project.app1.models import * admin.site.register(model1) admin.site.register(model2) admin.site.register(model3) What could be wrong in this case? Looks like everything is configured as what document says. Thank you in advance.
[ "Which version of Django are you using? Support for files named admin.py was added in version 1.0 (I think). Before that, you'd have to add extra information to your model.\n", "If something in your app throws an exception, the app or model may be excluded from the admin on subsequent requests.\nIf that is the case, you should get an error on the first request.\nAlso, please make sure your URLCONF has admin.autodiscover()\n" ]
[ 0, 0 ]
[]
[]
[ "admin", "django", "model", "python" ]
stackoverflow_0002398721_admin_django_model_python.txt
Q: Discovery of web services using Python I have several devices on a network. I am trying to use a library to discover the presence and itentity of these devices using Python script, the devices all have a web service. My question is, are there any modules that would help me with this problem as the only module I have found is ws-discovery for Python? And if this is the only module does anyone have any example Python script using ws-discovery? Thanks for any help. A: Unfortunately I've never used ws-discovery myself, but there seems to be a Python project which implements it: https://pypi.org/project/WSDiscovery/ From their documentation here's a short example on how to use it: wsd = WSDiscovery() wsd.start() ttype = QName("abc", "def") ttype1 = QName("namespace", "myTestService") scope1 = Scope("http://myscope") ttype2 = QName("namespace", "myOtherTestService_type1") scope2 = Scope("http://other_scope") xAddr = "localhost:8080/abc" wsd.publishService(types=[ttype], scopes=[scope2], xAddrs=[xAddr]) ret = wsd.searchServices() for service in ret: print service.getEPR() + ":" + service.getXAddrs()[0] wsd.stop() A: Are you tied to ws-discovery? If not, you might want to consider the Bonjour protocol, aka ZeroConf and DNS-SD. The protocol is relatively widely implemented. I've never used python to do the advertising or discovery but there is a project that implements an API: http://code.google.com/p/pybonjour/ As I said, I have no direct experience with this project and merely point it out as an alternative to ws-discovery.
Discovery of web services using Python
I have several devices on a network. I am trying to use a library to discover the presence and itentity of these devices using Python script, the devices all have a web service. My question is, are there any modules that would help me with this problem as the only module I have found is ws-discovery for Python? And if this is the only module does anyone have any example Python script using ws-discovery? Thanks for any help.
[ "Unfortunately I've never used ws-discovery myself, but there seems to be a Python project which implements it:\nhttps://pypi.org/project/WSDiscovery/\nFrom their documentation here's a short example on how to use it:\nwsd = WSDiscovery()\nwsd.start()\n\nttype = QName(\"abc\", \"def\")\n\nttype1 = QName(\"namespace\", \"myTestService\")\nscope1 = Scope(\"http://myscope\")\nttype2 = QName(\"namespace\", \"myOtherTestService_type1\")\nscope2 = Scope(\"http://other_scope\")\n\nxAddr = \"localhost:8080/abc\"\nwsd.publishService(types=[ttype], scopes=[scope2], xAddrs=[xAddr])\n\nret = wsd.searchServices()\n\nfor service in ret:\n print service.getEPR() + \":\" + service.getXAddrs()[0]\n\nwsd.stop()\n\n", "Are you tied to ws-discovery? If not, you might want to consider the Bonjour protocol, aka ZeroConf and DNS-SD. The protocol is relatively widely implemented. I've never used python to do the advertising or discovery but there is a project that implements an API: http://code.google.com/p/pybonjour/\nAs I said, I have no direct experience with this project and merely point it out as an alternative to ws-discovery.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "web_services", "ws_discovery" ]
stackoverflow_0002462618_python_web_services_ws_discovery.txt
Q: python manage.py runserver fails I am trying to learn django by following along with this tutorial. I am using django version 1.1.1 I run django-admin.py startproject mysite and it creates the files it should. Then I try to start the server by running python manage.py runserver but here is where I get the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 213, in execute translation.activate('en-us') File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 73, in activate return real_activate(language) File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 43, in delayed_loader return g['real_%s' % caller](*args, **kwargs) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 205, in activate _active[currentThread()] = translation(language) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 172, in _fetch for localepath in settings.LOCALE_PATHS: File "/Library/Python/2.6/site-packages/django/utils/functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'LOCALE_PATHS' Now, I can add a LOCALE_PATH atribute and set to an empty tuple to my settings.py file but then it just complains about another setting and so on. What am I missing here? A: Something is broken in your django installation. maybe you have a (very) old version somewhere in the path? LOCALE_PATHS was given a default value in the global settings file a long time ago. A: Can't really explain that. Try removing the project directory and starting again. Are you definitely running the manage.py from within the directory with the settings file?
python manage.py runserver fails
I am trying to learn django by following along with this tutorial. I am using django version 1.1.1 I run django-admin.py startproject mysite and it creates the files it should. Then I try to start the server by running python manage.py runserver but here is where I get the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 213, in execute translation.activate('en-us') File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 73, in activate return real_activate(language) File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 43, in delayed_loader return g['real_%s' % caller](*args, **kwargs) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 205, in activate _active[currentThread()] = translation(language) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 172, in _fetch for localepath in settings.LOCALE_PATHS: File "/Library/Python/2.6/site-packages/django/utils/functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'LOCALE_PATHS' Now, I can add a LOCALE_PATH atribute and set to an empty tuple to my settings.py file but then it just complains about another setting and so on. What am I missing here?
[ "Something is broken in your django installation. maybe you have a (very) old version somewhere in the path? \nLOCALE_PATHS was given a default value in the global settings file a long time ago.\n", "Can't really explain that. Try removing the project directory and starting again.\nAre you definitely running the manage.py from within the directory with the settings file?\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002506079_django_python.txt
Q: making python 2.6 exception backward compatible I have the following python code: try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you! A: This is both backward AND forward compatible: import sys try: pr.update() except (ConfigurationException,): e = sys.exc_info()[1] returnString = "%s %s" % (e.line, e.errormsg) This gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of the python 2.6/3 variation i.e. can still unambiguously catch multiple exception types e.g. except (ConfigurationException, AnotherExceptionType): and, if per-type handling is needed, can still test for exc_info()[0]==AnotherExceptionType. A: This is backward compatible: try: pr.update() except ConfigurationException, e: returnString=e.line+' '+e.errormsg A: Read this: http://docs.python.org/reference/compound_stmts.html#the-try-statement and this: http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes Don't use as, use a ,. The as syntax is specifically NOT backwards compatible because the , syntax is ambiguous and must go away in Python 3. A: try: pr.update() except ConfigurationException, e: returnString = e.line + " " + e.errormsg
making python 2.6 exception backward compatible
I have the following python code: try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!
[ "This is both backward AND forward compatible:\nimport sys\ntry:\n pr.update()\nexcept (ConfigurationException,):\n e = sys.exc_info()[1]\n returnString = \"%s %s\" % (e.line, e.errormsg)\n\nThis gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of the python 2.6/3 variation i.e. can still unambiguously catch multiple exception types e.g. except (ConfigurationException, AnotherExceptionType): and, if per-type handling is needed, can still test for exc_info()[0]==AnotherExceptionType.\n", "This is backward compatible: \ntry:\n pr.update()\nexcept ConfigurationException, e:\n returnString=e.line+' '+e.errormsg\n\n", "Read this: http://docs.python.org/reference/compound_stmts.html#the-try-statement\nand this: http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes\nDon't use as, use a ,.\nThe as syntax is specifically NOT backwards compatible because the , syntax is ambiguous and must go away in Python 3.\n", "try:\n pr.update()\nexcept ConfigurationException, e:\n returnString = e.line + \" \" + e.errormsg\n\n" ]
[ 12, 9, 5, 1 ]
[]
[]
[ "exception", "python", "python_2.x", "syntax" ]
stackoverflow_0001373255_exception_python_python_2.x_syntax.txt
Q: Number Sequence in MySQL In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL? A: Since there is no such thing as xrange, one could use a separate table stored with integer (as previously answered), or just make a stored procedure to do the job: DROP PROCEDURE IF EXISTS xrange; DELIMITER // CREATE PROCEDURE xrange(x INT, y INT) BEGIN DECLARE i INT DEFAULT x; CREATE TEMPORARY TABLE xrange_tmp (c1 INT); WHILE i < y DO INSERT INTO xrange_tmp VALUES (i); SET i = i + 1; END WHILE; END; // Usage: CALL xrange(-2,10); SELECT c1 FROM xrange_tmp; DROP TABLE xrange_tmp; The above is obviously going to be slower than creating a ready table with integers. It's more flexible though. A: You can use LAST_INSERT_ID() to simulate sequences in MySQL. If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences: Create a table to hold the sequence counter and initialize it: CREATE TABLE sequence (id INT NOT NULL); INSERT INTO sequence VALUES (0); Use the table to generate sequence numbers like this: UPDATE sequence SET id=LAST_INSERT_ID(id+1); SELECT LAST_INSERT_ID(); The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 21.9.3.37, “mysql_insert_id()”. Read up more here as well as some discussion on it here A: Try an integers table variant. This one is taken from Xaprb: create table integers(i int unsigned not null); insert into integers(i) values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9); select (hundreds.i * 100) + (tens.i * 10) + units.i as iii from integers as units cross join integers as tens cross join integers as hundreds; If you made that last select a view named, say, xrange999, then you can simply: SELECT iii FROM xrange999 WHERE iii BETWEEN 0 AND 9 (of course, you can do that with just the ten-row integers table, but I find a thousand integers a little more useful.) A: If Python is your programming language, you can map that same Python range to create an INSERT statement of the form: INSERT INTO Table (IDCol) VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9) Not exactly what you asked for, but a single line of Python code that will handle any range up to the maximum length of a MySQL statement.
Number Sequence in MySQL
In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL?
[ "Since there is no such thing as xrange, one could use a separate table stored with integer (as previously answered), or just make a stored procedure to do the job:\nDROP PROCEDURE IF EXISTS xrange;\nDELIMITER //\nCREATE PROCEDURE xrange(x INT, y INT)\nBEGIN\n DECLARE i INT DEFAULT x;\n CREATE TEMPORARY TABLE xrange_tmp (c1 INT);\n WHILE i < y DO\n INSERT INTO xrange_tmp VALUES (i);\n SET i = i + 1;\n END WHILE;\nEND;\n//\n\nUsage:\nCALL xrange(-2,10);\nSELECT c1 FROM xrange_tmp;\nDROP TABLE xrange_tmp;\n\nThe above is obviously going to be slower than creating a ready table with integers. It's more flexible though.\n", "You can use LAST_INSERT_ID() to simulate sequences in MySQL.\n\nIf expr is given as an argument to\n LAST_INSERT_ID(), the value of the\n argument is returned by the function\n and is remembered as the next value to\n be returned by LAST_INSERT_ID(). This\n can be used to simulate sequences:\nCreate a table to hold the sequence\n counter and initialize it:\n\nCREATE TABLE sequence (id INT NOT NULL);\nINSERT INTO sequence VALUES (0);\n\n\nUse the table to generate sequence numbers like this:\n\n UPDATE sequence SET id=LAST_INSERT_ID(id+1);\n SELECT LAST_INSERT_ID();\n\n\nThe UPDATE statement increments the\n sequence counter and causes the\n\nnext call to LAST_INSERT_ID() to\n return the updated value. The SELECT\n statement retrieves that value. The\n mysql_insert_id() C API function can\n also be used to get the value. See\n Section 21.9.3.37,\n “mysql_insert_id()”.\n\n\nRead up more here as well as some discussion on it here\n", "Try an integers table variant. This one is taken from Xaprb:\ncreate table integers(i int unsigned not null);\ninsert into integers(i) values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);\n\nselect (hundreds.i * 100) + (tens.i * 10) + units.i as iii\nfrom integers as units\n cross join integers as tens\n cross join integers as hundreds;\n\nIf you made that last select a view named, say, xrange999, then you can simply:\nSELECT iii FROM xrange999 WHERE iii BETWEEN 0 AND 9\n\n(of course, you can do that with just the ten-row integers table, but I find a thousand integers a little more useful.)\n", "If Python is your programming language, you can map that same Python range to create an INSERT statement of the form:\nINSERT INTO Table (IDCol) VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9)\n\nNot exactly what you asked for, but a single line of Python code that will handle any range up to the maximum length of a MySQL statement.\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "mysql", "python", "sequence", "sql", "xrange" ]
stackoverflow_0002495487_mysql_python_sequence_sql_xrange.txt
Q: How can I programmatically determine (in Python) when someone connects into my windows 7 machine via RDP? This doesn't need to be a real time solution, but are there some log files or system messages that could be read to identify periods of time where someone was connected via RDP to a Windows 7 machine? I'm building a watchdog script for a computer which will be deployed in a remote place and would like to add this metric to a daily status update. A: Run with os.system or subprocess module C:\> netstat -n | find ":3389 " TCP x.x.x.x:3389 y.y.y.y:zzz ESTABLISHED Where, x.x.x.x is own IP and y.y.y.y is remote IP, and zzz is remote port. A: If you look at the Event viewer and the tab Security you can find when people login/logout there. Not sure if it gets logged if the session is just disconnected though. This seems to be a Python library to access the event log: http://timgolden.me.uk/python/winsys/event_logs.html#module-event_logs Disclaimer: I'm looking at a Windows 2003 server and not Windows 7, so mileage might vary :)
How can I programmatically determine (in Python) when someone connects into my windows 7 machine via RDP?
This doesn't need to be a real time solution, but are there some log files or system messages that could be read to identify periods of time where someone was connected via RDP to a Windows 7 machine? I'm building a watchdog script for a computer which will be deployed in a remote place and would like to add this metric to a daily status update.
[ "Run with os.system or subprocess module\nC:\\> netstat -n | find \":3389 \"\n\nTCP x.x.x.x:3389 y.y.y.y:zzz ESTABLISHED\n\nWhere, x.x.x.x is own IP and y.y.y.y is remote IP, and zzz is remote port.\n", "If you look at the Event viewer and the tab Security you can find when people login/logout there. Not sure if it gets logged if the session is just disconnected though.\nThis seems to be a Python library to access the event log: http://timgolden.me.uk/python/winsys/event_logs.html#module-event_logs\nDisclaimer: I'm looking at a Windows 2003 server and not Windows 7, so mileage might vary :)\n" ]
[ 3, 1 ]
[]
[]
[ "connection", "detection", "logging", "python", "rdp" ]
stackoverflow_0002514450_connection_detection_logging_python_rdp.txt
Q: Count warnings in Python 2.4 I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using with warnings.catch_warnings(record=True) as warn: ... self.assertEquals(len(warn), 2) Unfortunately, with is not available in Python 2.4, so what else could I use? I can't simply check if there's been a single warning (using warning filter with action='error' and try/catch), because the number of warnings is significant. A: I was going to suggest the same workaround as Ignacio, a bit more complete example of testing code: import warnings def setup_warning_catcher(): """ Wrap warnings.showwarning with code that records warnings. """ caught_warnings = [] original_showwarning = warnings.showwarning def custom_showwarning(*args, **kwargs): caught_warnings.append(args[0]) return original_showwarning(*args, **kwargs) warnings.showwarning = custom_showwarning return caught_warnings caught_warnings_list = setup_warning_catcher() # trigger warning here assert len(caught_warnings_list) == 1 A: What you can do is duplicate the behavior of warnings.catch_warnings() yourself. Save the current value of warnings.showwarning and replace it with a function that saves the warning in a list, then after the routine test the length of the list and then restore warnings.showwarning. oldsw = warnings.showwarning warnings.showwarning = myshowwarning ... self.assertEquals(len(somewarninglist), 2) warnings.showwarning = oldsw
Count warnings in Python 2.4
I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using with warnings.catch_warnings(record=True) as warn: ... self.assertEquals(len(warn), 2) Unfortunately, with is not available in Python 2.4, so what else could I use? I can't simply check if there's been a single warning (using warning filter with action='error' and try/catch), because the number of warnings is significant.
[ "I was going to suggest the same workaround as Ignacio, a bit more complete example of testing code:\nimport warnings\n\ndef setup_warning_catcher():\n \"\"\" Wrap warnings.showwarning with code that records warnings. \"\"\"\n\n\n caught_warnings = []\n original_showwarning = warnings.showwarning\n\n def custom_showwarning(*args, **kwargs):\n caught_warnings.append(args[0])\n return original_showwarning(*args, **kwargs)\n\n warnings.showwarning = custom_showwarning\n return caught_warnings\n\n\ncaught_warnings_list = setup_warning_catcher()\n\n# trigger warning here\n\nassert len(caught_warnings_list) == 1\n\n", "What you can do is duplicate the behavior of warnings.catch_warnings() yourself. Save the current value of warnings.showwarning and replace it with a function that saves the warning in a list, then after the routine test the length of the list and then restore warnings.showwarning.\noldsw = warnings.showwarning\nwarnings.showwarning = myshowwarning\n ...\nself.assertEquals(len(somewarninglist), 2)\nwarnings.showwarning = oldsw\n\n" ]
[ 6, 3 ]
[]
[]
[ "python", "python_2.4", "warnings" ]
stackoverflow_0002324820_python_python_2.4_warnings.txt
Q: how to count all distinct records in many-to-many relations in django ORM? class Project(models.Model): categories = models.ManyToManyField(Category) class Category(models.Model): name = models.CharField() now, i make some queryset: query = Project.objects.filter(id__in=[1,2,3,4]) and i like to get list of all distinct categories in this queryset with count of projects with refering to these categories - exactly i would like to get that results: category1 - 10 projects category2 - 5 projects that is opposite to this query: query2 = query.annotate(Count('categories')) what return me: project1 - 2categories project2 - 7categories how can i make it in django ORM? A: Category.objects.filter(project__in=query).annotate(Count('project'))
how to count all distinct records in many-to-many relations in django ORM?
class Project(models.Model): categories = models.ManyToManyField(Category) class Category(models.Model): name = models.CharField() now, i make some queryset: query = Project.objects.filter(id__in=[1,2,3,4]) and i like to get list of all distinct categories in this queryset with count of projects with refering to these categories - exactly i would like to get that results: category1 - 10 projects category2 - 5 projects that is opposite to this query: query2 = query.annotate(Count('categories')) what return me: project1 - 2categories project2 - 7categories how can i make it in django ORM?
[ "Category.objects.filter(project__in=query).annotate(Count('project'))\n\n" ]
[ 1 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0002514910_django_orm_python.txt
Q: How do I create new xml from ElementTree? Bit of a beginner question here: Say I have a block of xml: <root> <district> <house><room><door/><room></house> </district> <district> <street> <house>and so on</house> </street> etc. With ElementTree I can do: houses=doc.findall(".//house") to select all the house nodes, regardless of their parent. What I want to do now is turn each of the house nodes into a separate tree object. Part of the reason for doing this is that I then want to do another find: door=houseXml.findall(".//door") I can do something like: for _house in houses: houseXml=_house.getiterator but this doesn't seem to do what I want. Where am I going wrong? A: You can call findall on the elements returned by the first findall: >>> doc = """<root> ... <district> ... <house><room><door/></room></house> ... </district> ... <district> ... <street> ... <house>and so on</house> ... </street> ... </district> ... </root>""" >>> >>> from xml.etree import cElementTree as ET >>> >>> r = ET.XML(doc) >>> >>> for house in r.findall('.//house'): ... print house, house.findall('.//door') ... <Element 'house' at 0xb7f3ea70> [<Element 'door' at 0xb7f3eab8>] <Element 'house' at 0xb7f3eb00> [] >>>
How do I create new xml from ElementTree?
Bit of a beginner question here: Say I have a block of xml: <root> <district> <house><room><door/><room></house> </district> <district> <street> <house>and so on</house> </street> etc. With ElementTree I can do: houses=doc.findall(".//house") to select all the house nodes, regardless of their parent. What I want to do now is turn each of the house nodes into a separate tree object. Part of the reason for doing this is that I then want to do another find: door=houseXml.findall(".//door") I can do something like: for _house in houses: houseXml=_house.getiterator but this doesn't seem to do what I want. Where am I going wrong?
[ "You can call findall on the elements returned by the first findall:\n>>> doc = \"\"\"<root>\n... <district>\n... <house><room><door/></room></house>\n... </district>\n... <district>\n... <street>\n... <house>and so on</house>\n... </street>\n... </district>\n... </root>\"\"\"\n>>>\n>>> from xml.etree import cElementTree as ET\n>>>\n>>> r = ET.XML(doc)\n>>>\n>>> for house in r.findall('.//house'):\n... print house, house.findall('.//door')\n...\n<Element 'house' at 0xb7f3ea70> [<Element 'door' at 0xb7f3eab8>]\n<Element 'house' at 0xb7f3eb00> []\n>>>\n\n" ]
[ 2 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0002515253_elementtree_python_xml.txt
Q: PRTime to datetime in Python I am writing a script that is retrieving information from file places.sqlite (history) and realized that it stores the time in the PRTime format. Is there a method available in Python which could convert this date time or do I have to make it myself? A: PRTime is the number of microseconds since 1970-01-01 (see https://developer.mozilla.org/en/PRTime), so just do this to get UTC time: datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=pr_time) For example, print datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=time.time()*1000*1000) Output: 2010-03-25 13:30:02.243000 A: There isn't any built-in method, but it does seem quite trivial to implement: >>> t = 1221842272303080 >>> t /= 1e6 >>> t 1221842272.30308 >>> import datetime >>> datetime.datetime.fromtimestamp(t) datetime.datetime(2008, 9, 19, 17, 37, 52, 303080) The result is local time. For UTC you could do: >>> import time >>> time.gmtime(t) time.struct_time(tm_year=2008, tm_mon=9, tm_mday=19, tm_hour=16, tm_min=37, tm_sec=52, tm_wday=4, tm_yday=263, tm_isdst=0) That's py3k output, and it might differ slightly in Python 2.x.
PRTime to datetime in Python
I am writing a script that is retrieving information from file places.sqlite (history) and realized that it stores the time in the PRTime format. Is there a method available in Python which could convert this date time or do I have to make it myself?
[ "PRTime is the number of microseconds since 1970-01-01 (see https://developer.mozilla.org/en/PRTime), so just do this to get UTC time:\ndatetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=pr_time)\n\nFor example,\nprint datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=time.time()*1000*1000)\n\nOutput:\n2010-03-25 13:30:02.243000\n\n", "There isn't any built-in method, but it does seem quite trivial to implement:\n>>> t = 1221842272303080\n>>> t /= 1e6\n>>> t\n1221842272.30308\n>>> import datetime\n>>> datetime.datetime.fromtimestamp(t)\ndatetime.datetime(2008, 9, 19, 17, 37, 52, 303080)\n\nThe result is local time. For UTC you could do:\n>>> import time\n>>> time.gmtime(t)\ntime.struct_time(tm_year=2008, tm_mon=9, tm_mday=19, tm_hour=16, tm_min=37, tm_sec=52, tm_wday=4, tm_yday=263, tm_isdst=0)\n\nThat's py3k output, and it might differ slightly in Python 2.x.\n" ]
[ 3, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002515782_datetime_python.txt
Q: Eclipse PyDev: setting breakpoints in site-packages source I am debugging a problem in Django with Pydev. I can set breakpoint in my django project code with out a problem. However I can't set breakpoints in the Django library source code (in site-packages). The PyDev debugger user interface in this case simply does nothing when I click to set the breakpoint and does not break at that location when I run the debugger. Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code. Any ideas on next steps would be a help. I also have the site-packages configured in PyDev to be in my PYTHONPATH I am using Eclipse on Max OS X if that helps. Thanks A: Have you imported the Django source as a project? To do that you just create a new PyDev project and set it's location to the Django source folder. A: Hey, this is timely! Eric Moritz just announced the release of an interesting new way to debug views using pdb called django-viewtools. A: You might try instead the Python debugger pdb in this instance. This is a helpful link describing it: http://www.ferg.org/papers/debugging_in_python.html A: PyDev 1.5.5 seems to have an issue with Eclipse. Uninstall 1.5.5 and install the 1.5.4 version
Eclipse PyDev: setting breakpoints in site-packages source
I am debugging a problem in Django with Pydev. I can set breakpoint in my django project code with out a problem. However I can't set breakpoints in the Django library source code (in site-packages). The PyDev debugger user interface in this case simply does nothing when I click to set the breakpoint and does not break at that location when I run the debugger. Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code. Any ideas on next steps would be a help. I also have the site-packages configured in PyDev to be in my PYTHONPATH I am using Eclipse on Max OS X if that helps. Thanks
[ "Have you imported the Django source as a project? To do that you just create a new PyDev project and set it's location to the Django source folder.\n", "Hey, this is timely! Eric Moritz just announced the release of an interesting new way to debug views using pdb called django-viewtools.\n", "You might try instead the Python debugger pdb in this instance.\nThis is a helpful link describing it: http://www.ferg.org/papers/debugging_in_python.html\n", "PyDev 1.5.5 seems to have an issue with Eclipse. Uninstall 1.5.5 and install the 1.5.4 version\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "eclipse", "pydev", "python" ]
stackoverflow_0000558999_django_eclipse_pydev_python.txt
Q: Keeping track of user habits and activities? - Django I was working on a project a few months ago, and had the need to implement an award system. Similar to StackOverflow's badge system. Badges I might have not implemented it in the best possible way, and I am curious what your say in it would be. What would a good way to track user activities, needed for badge awarding be? Stackoverflow's system needs to know of a lot of information, and I also get the impression that there would be a lot of data processing complicating things. I would assume that SO calculates badges once or twice every 24, and that maybe logs are stored or a server dedicated to badge calculation. Thoughts? A: I don't think is as complicated as you think. I highly doubt that SO calculates badges with some kind of user activity log (although technically the entire database is a user activity log). When I look at the lists of badges, I don't see anything that can't be implemented by running a SQL select query. Some of the queries could be pretty complicated, and there might be some sort of fancy caching mechanism, but I don't see any reason why you would have to calculate badges in batches. A: In general badge/point systems can be based on two things. Activity log of interesting events, this is effectively the paper register receipt of what has happend such that you can re-compute from the ground up if it's ever needed. Can be as simple as (user_id, timestamp, event_id, event_detail) Most of the time you've pre-designed your scoring/point system so you know exactly which counters to keep on a user. Now it's as simple as having a big record that contains all of the details. (user_id, reply_points, login_points, last_login, thumbs_up_points, etc.,etc.) Now you can slap some simple methods on that model object and have it manage/store the points as needed.
Keeping track of user habits and activities? - Django
I was working on a project a few months ago, and had the need to implement an award system. Similar to StackOverflow's badge system. Badges I might have not implemented it in the best possible way, and I am curious what your say in it would be. What would a good way to track user activities, needed for badge awarding be? Stackoverflow's system needs to know of a lot of information, and I also get the impression that there would be a lot of data processing complicating things. I would assume that SO calculates badges once or twice every 24, and that maybe logs are stored or a server dedicated to badge calculation. Thoughts?
[ "I don't think is as complicated as you think. I highly doubt that SO calculates badges with some kind of user activity log (although technically the entire database is a user activity log). When I look at the lists of badges, I don't see anything that can't be implemented by running a SQL select query.\nSome of the queries could be pretty complicated, and there might be some sort of fancy caching mechanism, but I don't see any reason why you would have to calculate badges in batches.\n", "In general badge/point systems can be based on two things.\n\nActivity log of interesting events, this is effectively the paper register receipt of what has happend such that you can re-compute from the ground up if it's ever needed. Can be as simple as (user_id, timestamp, event_id, event_detail)\nMost of the time you've pre-designed your scoring/point system so you know exactly which counters to keep on a user. Now it's as simple as having a big record that contains all of the details. (user_id, reply_points, login_points, last_login, thumbs_up_points, etc.,etc.)\n\nNow you can slap some simple methods on that model object and have it manage/store the points as needed. \n" ]
[ 2, 0 ]
[]
[]
[ "badge", "django", "logging", "python", "sql" ]
stackoverflow_0002510264_badge_django_logging_python_sql.txt
Q: Python string comparison I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from subprocess.communicate() and trying to do return output == 'true' but it returns False every time. I'm not too familiar with python, but reading about string comparisons says you can compare strings using ==, !=, etc. Here's the code: def verifydeployment(application): from subprocess import Popen, PIPE import socket, time # Loop until jboss is up. After 90 seconds the script stops looping; this # causes twiddle to be unsuccessful and deployment is considered 'failed'. begin = time.time() while True: try: socket.create_connection(('localhost', 8080)) break except socket.error, msg: if (time.time() - begin) > 90: break else: continue time.sleep(15) # sleep for 15 seconds to allow JMX to initialize twiddle = os.path.join(JBOSS_DIR, 'bin', 'twiddle.sh') url = 'file:' + os.path.join(JBOSS_DIR, 'server', 'default', 'deploy', os.path.basename(application)) p = Popen([twiddle, 'invoke', 'jboss.system:service=MainDeployer', 'isDeployed', url], stdout=PIPE) isdeployed = p.communicate()[0] print type(isdeployed) print type('true') print isdeployed return isdeployed == 'true' The output is: <type 'str'> # type(isdeployed) <type 'str'> # type('true') true # isdeployed but False is always returned. I also tried return str(isdeployed) == 'true'. A: Are you sure that there isn't a terminating line feed character, making your string contain "true\n"? That seems likely. You could try return isdeployed.startswith("true"), or some stripping. A: Have you tried to call isdeployed.strip() before the comparision
Python string comparison
I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from subprocess.communicate() and trying to do return output == 'true' but it returns False every time. I'm not too familiar with python, but reading about string comparisons says you can compare strings using ==, !=, etc. Here's the code: def verifydeployment(application): from subprocess import Popen, PIPE import socket, time # Loop until jboss is up. After 90 seconds the script stops looping; this # causes twiddle to be unsuccessful and deployment is considered 'failed'. begin = time.time() while True: try: socket.create_connection(('localhost', 8080)) break except socket.error, msg: if (time.time() - begin) > 90: break else: continue time.sleep(15) # sleep for 15 seconds to allow JMX to initialize twiddle = os.path.join(JBOSS_DIR, 'bin', 'twiddle.sh') url = 'file:' + os.path.join(JBOSS_DIR, 'server', 'default', 'deploy', os.path.basename(application)) p = Popen([twiddle, 'invoke', 'jboss.system:service=MainDeployer', 'isDeployed', url], stdout=PIPE) isdeployed = p.communicate()[0] print type(isdeployed) print type('true') print isdeployed return isdeployed == 'true' The output is: <type 'str'> # type(isdeployed) <type 'str'> # type('true') true # isdeployed but False is always returned. I also tried return str(isdeployed) == 'true'.
[ "Are you sure that there isn't a terminating line feed character, making your string contain \"true\\n\"? That seems likely.\nYou could try return isdeployed.startswith(\"true\"), or some stripping.\n", "Have you tried to call \nisdeployed.strip()\n\nbefore the comparision\n" ]
[ 8, 6 ]
[]
[]
[ "compare", "python", "string" ]
stackoverflow_0002516787_compare_python_string.txt
Q: Loop over a file and write the next line if a condition is met Having a hard time fixing this or finding any good hints about it. I'm trying to loop over one file, modify each line slightly, and then loop over a different file. If the line in the second file starts with the line from the first then the following line in the second file should be written to a third file. with open('ids.txt', 'rU') as f: with open('seqres.txt', 'rU') as g: for id in f: id=id.lower()[0:4]+'_'+id[4] with open(id + '.fasta', 'w') as h: for line in g: if line.startswith('>'+ id): h.write(g.next()) All the correct files appear, but they are empty. Yes, I am sure the if has true cases. :-) "seqres.txt" has lines with an ID number in a certain format, each followed by a line with data. The "ids.txt" has lines with the ID numbers of interest in a different format. I want each line of data with an interesting ID number in its own file. Thanks a million to anyone with a little advice! A: Here's a mostly flattened implementation. Depending on how many hits you're going to get for each ID, and how many entries there are in 'seqres' you could redesign it. # Extract the IDs in the desired format and cache them ids = [ x.lower()[0:4]+'_'+x[4] for x in open('ids.txt','rU')] ids = set(ids) # Create iterator for seqres.txt file and pull the first value iseqres = iter(open('seqres.txt','rU')) lineA = iseqres.next() # iterate through the rest of seqres, staggering for lineB in iseqres: lineID = lineA[1:7] if lineID in ids: with open("%s.fasta" % lineID, 'a') as h: h.write(lineB) lineA = lineB A: I think there is still progress to be made from the code you declare as final. You can make the result a little less nested and avoid a couple sort of silly things. from contextlib import nested from itertools import tee, izip # Stole pairwise recipe from the itertools documentation def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b) with nested(open('ids.txt', 'rU'), open('seqres.txt', 'rU')) as (f, g): for id in f: id = id.lower()[0:4] + '_' + id[4] with open(id + '.fasta', 'w') as h: g.seek(0) # start at the beginning of g each time for line, next_line in pairwise(g): if line.startswith('>' + id): h.write(next_line) This is an improvement over the final code you posted in that It does not unnecessarily read the whole files into memory, but simple iterates over the file objects. (This may or may not be the best option for g, really. It definitely scales better.) It does not contain the crash condition using gl[line+1] if we are already on the last line of gl Depending on how g actually looks, there might be something more applicable than pairwise. It is not as deeply nested. It conforms to PEP8 for things like spaces around operators and indentation depth. This algorithm is O(n * m), where n and m are the number of lines in f and g. If the length of f is unbounded, you can use a set of its ids to reduce the algorithm to O(n) (linear in the number of lines in g). A: The problem is that you are only looping through file g once - after you have read through it the first time the file index position is left at the end of the file, so any further reads will fail with EOF. You would need to reopen g every time round the loop. However this will be massively inefficient - you are reading the same file repeatedly, once for every line in f. It will be orders of magnitude faster to read all of g into an array at the start and use that, so long as it will fit in memory. A: For speed, you really want to avoid looping over the same file multiple times. This means you've turned into an O(N*M) algorithm, when you could be a using an O(N+M) one. To achieve this, read your list of ids into a fast lookup structure, like a set. Since there are only 4600 this in-memory form shouldn't be any problem. The new solution is also reading the list into memory. Probably not a huge problem with just a few hundred thousand lines, but its wasting more memory than you need, since you can do the whole thing in a single pass, only reading the smaller ids.txt file into memory. You can just set a flag when the previous line was something interesting, which will signal the next line to write it out. Here's a reworked version: with open('ids.txt', 'rU') as f: interesting_ids = set('>' + line.lower()[0:4] + "_" + line[4] for line in f) # Get all ids in a set. found_id = None with open('seqres.txt', 'rU') as g: for line in g: if found_id is not None: with open(found_id+'.fasta','w') as h: h.write(line) id = line[:7] if id in interesting_ids: found_id = id else: found_id = None A: After the first line in the ids.txt file has been processed, the file seqres.txt has been exhausted. There is something wrong with the nesting of your loops. Also, you're modifying the iterator inside the for line in g loop. Not a good idea. If you really want to append the line that follows the line whose ID matches, then perhaps something like this might work better: with open('ids.txt', 'rU') as f: ids = f.readlines() with open('seqres.txt', 'rU') as g: seqres = g.readlines() for id in ids: id=id.lower()[0:4]+'_'+id[4] with open(id + '.fasta', 'a') as h: for line in seqres: if line.startswith('>'+ id): h.write(seqres.next())
Loop over a file and write the next line if a condition is met
Having a hard time fixing this or finding any good hints about it. I'm trying to loop over one file, modify each line slightly, and then loop over a different file. If the line in the second file starts with the line from the first then the following line in the second file should be written to a third file. with open('ids.txt', 'rU') as f: with open('seqres.txt', 'rU') as g: for id in f: id=id.lower()[0:4]+'_'+id[4] with open(id + '.fasta', 'w') as h: for line in g: if line.startswith('>'+ id): h.write(g.next()) All the correct files appear, but they are empty. Yes, I am sure the if has true cases. :-) "seqres.txt" has lines with an ID number in a certain format, each followed by a line with data. The "ids.txt" has lines with the ID numbers of interest in a different format. I want each line of data with an interesting ID number in its own file. Thanks a million to anyone with a little advice!
[ "Here's a mostly flattened implementation. Depending on how many hits you're going to get for each ID, and how many entries there are in 'seqres' you could redesign it.\n# Extract the IDs in the desired format and cache them\nids = [ x.lower()[0:4]+'_'+x[4] for x in open('ids.txt','rU')]\nids = set(ids)\n\n# Create iterator for seqres.txt file and pull the first value\niseqres = iter(open('seqres.txt','rU'))\nlineA = iseqres.next()\n\n# iterate through the rest of seqres, staggering\nfor lineB in iseqres:\n lineID = lineA[1:7]\n if lineID in ids:\n with open(\"%s.fasta\" % lineID, 'a') as h:\n h.write(lineB)\n lineA = lineB\n\n", "I think there is still progress to be made from the code you declare as final. You can make the result a little less nested and avoid a couple sort of silly things.\nfrom contextlib import nested\nfrom itertools import tee, izip\n\n# Stole pairwise recipe from the itertools documentation\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return izip(a, b)\n\nwith nested(open('ids.txt', 'rU'), open('seqres.txt', 'rU')) as (f, g):\n for id in f:\n id = id.lower()[0:4] + '_' + id[4]\n with open(id + '.fasta', 'w') as h:\n g.seek(0) # start at the beginning of g each time\n for line, next_line in pairwise(g):\n if line.startswith('>' + id):\n h.write(next_line)\n\nThis is an improvement over the final code you posted in that\n\nIt does not unnecessarily read the whole files into memory, but simple iterates over the file objects. (This may or may not be the best option for g, really. It definitely scales better.)\nIt does not contain the crash condition using gl[line+1] if we are already on the last line of gl\n\nDepending on how g actually looks, there might be something more applicable than pairwise.\n\nIt is not as deeply nested.\nIt conforms to PEP8 for things like spaces around operators and indentation depth.\nThis algorithm is O(n * m), where n and m are the number of lines in f and g. If the length of f is unbounded, you can use a set of its ids to reduce the algorithm to O(n) (linear in the number of lines in g).\n\n", "The problem is that you are only looping through file g once - after you have read through it the first time the file index position is left at the end of the file, so any further reads will fail with EOF. You would need to reopen g every time round the loop.\nHowever this will be massively inefficient - you are reading the same file repeatedly, once for every line in f. It will be orders of magnitude faster to read all of g into an array at the start and use that, so long as it will fit in memory.\n", "For speed, you really want to avoid looping over the same file multiple times. This means you've turned into an O(N*M) algorithm, when you could be a using an O(N+M) one.\nTo achieve this, read your list of ids into a fast lookup structure, like a set. Since there are only 4600 this in-memory form shouldn't be any problem.\nThe new solution is also reading the list into memory. Probably not a huge problem with just a few hundred thousand lines, but its wasting more memory than you need, since you can do the whole thing in a single pass, only reading the smaller ids.txt file into memory. You can just set a flag when the previous line was something interesting, which will signal the next line to write it out.\nHere's a reworked version:\nwith open('ids.txt', 'rU') as f:\n interesting_ids = set('>' + line.lower()[0:4] + \"_\" + line[4] for line in f) # Get all ids in a set.\n\nfound_id = None\nwith open('seqres.txt', 'rU') as g:\n for line in g:\n if found_id is not None:\n with open(found_id+'.fasta','w') as h:\n h.write(line)\n\n id = line[:7]\n if id in interesting_ids: found_id = id\n else: found_id = None\n\n", "After the first line in the ids.txt file has been processed, the file seqres.txt has been exhausted. There is something wrong with the nesting of your loops. Also, you're modifying the iterator inside the for line in g loop. Not a good idea. \nIf you really want to append the line that follows the line whose ID matches, then perhaps something like this might work better:\nwith open('ids.txt', 'rU') as f:\n ids = f.readlines()\nwith open('seqres.txt', 'rU') as g:\n seqres = g.readlines()\n\nfor id in ids:\n id=id.lower()[0:4]+'_'+id[4]\n with open(id + '.fasta', 'a') as h:\n for line in seqres:\n if line.startswith('>'+ id):\n h.write(seqres.next())\n\n" ]
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "file_io", "iterator", "python", "string" ]
stackoverflow_0002513847_file_io_iterator_python_string.txt
Q: Perl for a Python programmer I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) way of doing things; because I don't think it'll be worth the effort if I end up programming Python in Perl. So my questions are basically two: Are there many problems/application areas where it's actually more convenient to use Perl rather than Python? If the first question is positive, where can I found a good place to get started and learn best practices that is not oriented to beginners? A: One area where Perl is more "convenient" is using it for one liners. Python can be used to produced one liners, but often its "clunky" (or ugly). Note that Perl is renowned for its "terseness" or "short and concise", often at the expense of readability. So coming from Python, you have to learn to get used to it. Another area is Perl's vast number of modules in CPAN. The equivalent of that is Pypi but its modules are not as many as CPAN. that said, both do similar things and both have their own merits. As for your second question, you can look at Perl documentation. I find it very useful. Especially also read the Perl FAQ. They are the best resource for myself if I want to learn about Perl. A: For best practices, check out Perl Best Practices by Damian Conway. Not all of the recommended practices make sense, but most of them do. The Perl::Critic module also helps with best practices. Also, check out the Modern Perl Books blog. If you have questions, Perlmonks is the best web forum to get help. There are a large number of very knowledgeable, friendly people who can, and will, answer your questions and discuss the merits of different approaches. A: Have a look at Moose. Its a state of the art OO framework akin to CLOS and what will be available in Perl6. It introduces the new(ish) concepts of roles and will steer you close to Aspect-oriented programming. Functional Programming. Checkout the Higher-Order Perl book by Mark Jason Dominus (PDF download available from this site). A: I think Learning Perl from O'Reilly Media is a pretty good way to get started with Perl, even if you are already proficient in Python. Especialy if you want to get to know the one-liner stuff (and this is what Perl is REALLY good at) A: Impatient Perl One of my favorite books for people who want to learn it and then get stuff done is Impatient Perl by Greg London, a free netbook available from perl.org. If you're a programmer, know scripting, know the concepts behind dynamic languages, and just want to know how perl does it, this is a great starting resource. A: Effective Perl Programming is mostly for people who know the basics of Perl's syntax but need to learn the idioms. We also cover similar stuff in our Effective Perler blog :)
Perl for a Python programmer
I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) way of doing things; because I don't think it'll be worth the effort if I end up programming Python in Perl. So my questions are basically two: Are there many problems/application areas where it's actually more convenient to use Perl rather than Python? If the first question is positive, where can I found a good place to get started and learn best practices that is not oriented to beginners?
[ "One area where Perl is more \"convenient\" is using it for one liners. Python can be used to produced one liners, but often its \"clunky\" (or ugly). Note that Perl is renowned for its \"terseness\" or \"short and concise\", often at the expense of readability. So coming from Python, you have to learn to get used to it.\nAnother area is Perl's vast number of modules in CPAN. The equivalent of that is Pypi but its modules are not as many as CPAN.\nthat said, both do similar things and both have their own merits. \nAs for your second question, you can look at Perl documentation. I find it very useful. Especially also read the Perl FAQ. They are the best resource for myself if I want to learn about Perl.\n", "For best practices, check out Perl Best Practices by Damian Conway. Not all of the recommended practices make sense, but most of them do.\nThe Perl::Critic module also helps with best practices.\nAlso, check out the Modern Perl Books blog.\nIf you have questions, Perlmonks is the best web forum to get help. There are a large number of very knowledgeable, friendly people who can, and will, answer your questions and discuss the merits of different approaches.\n", "\nHave a look at Moose. Its a state of the art OO framework akin to CLOS and what will be available in Perl6. It introduces the new(ish) concepts of roles and will steer you close to Aspect-oriented programming.\nFunctional Programming. Checkout the Higher-Order Perl book by Mark Jason Dominus (PDF download available from this site).\n\n", "I think Learning Perl from O'Reilly Media is a pretty good way to get started with Perl, even if you are already proficient in Python.\nEspecialy if you want to get to know the one-liner stuff (and this is what Perl is REALLY good at)\n", "Impatient Perl\nOne of my favorite books for people who want to learn it and then get stuff done is Impatient Perl by Greg London, a free netbook available from perl.org. If you're a programmer, know scripting, know the concepts behind dynamic languages, and just want to know how perl does it, this is a great starting resource.\n", "Effective Perl Programming is mostly for people who know the basics of Perl's syntax but need to learn the idioms. We also cover similar stuff in our Effective Perler blog :)\n" ]
[ 17, 15, 11, 4, 4, 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002515814_perl_python.txt
Q: Get information about a function in python, looking at source code the following code comes from the matplotlib gallery: #!/usr/bin/env python from pylab import * x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) I am new to python, and would like to change the content of x and y from an input file. I have two short questions: I could guess what array means, but once I see it on the code, how can I know to which library it belongs and more information about it? Should I use some kind of python debug commands? How do I insert the content of my input file into x? Thanks A: As to your 1. that's due to bad habits of the person giving you that program. It should have been: #!/usr/bin/env python import pylab x = pylab.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = pylab.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) help(pylab.array) or #!/usr/bin/env python from pylab import array x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) help(array) Use the help(something). It helps :) Using explicit imports is really handy if programs become a bit more complex. The only case I know where from package import * is nice is when playing at the python prompt, trying stuff out. As to the file, can you sketch how the file looks like? And I believe numpy has an array load function somewhere, look at the cookbook. A: (1) Fire up the python console and use the dir() function on whatever object/class/variable you want to know more about. It'll print out all methods and properties of the object. >> import pylab >> x = pylab.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) >> dir(x) (2) look up File Objects in the python documentation A: Use the help function to find out what an object can do. import pylab help(pylab.array) "What library it belongs to" is a sort of funny question. You can easily know what module you are using it from if you refactor your code not to use import *. (Never ever ever use import *.) That does not mean that's it's original home—pylab is just a place where a bunch of stuff is pooled for convenience. pylab gets it from matplotlib.pylab which gets it from numpy which gets it from numpy.core.multiarray (which is a C extension module). You can see its original home by looking at pylab.array.__module__ when it's important, which is not often. Personally, I think you're better of not using pylab at all, just getting stuff from numpy, scipy, and matplotlib as you need it to keep things organized. To quote The Zen of Python: Namespaces are one honking great idea -- let's do more of those! How to build an numpy array from a file depends on the format of the file. numpy.fromfile/pylab.fromfile can import a binary file storing the array's data. (This is the same format used by numpy.tofile—big shock there.) A: array appears to be a function/class in pylab. You could do help(array) to find out more - this relies on the presence of a proper docstring for array. from module import * is a problematic idiom in several ways precisely for the reason that it makes it hard to find out where identifiers come from. import pylab x = pylab.array(...) might be a better way. A: Replying to question #2, if your file looks like this: 10 8.04 8 6.95 13 7.58 9 8.81 11 8.33 14 9.96 6 7.24 4 4.26 12 10.84 7 4.82 5 5.68 Then I would do like this: x_list = list() y_list = list() fp = open('coords.txt', 'r') for line in fp: line = line.strip() # Remove trailing whitespace if not line: continue # Skip empty lines a,b = line.split() # Split line by whitespace, storing coords in a & b x_list.append(a) # Add a to x_list y_list.append(b) # Add b to y_list fp.close() x = array(x_list) y = array(y_list)
Get information about a function in python, looking at source code
the following code comes from the matplotlib gallery: #!/usr/bin/env python from pylab import * x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) I am new to python, and would like to change the content of x and y from an input file. I have two short questions: I could guess what array means, but once I see it on the code, how can I know to which library it belongs and more information about it? Should I use some kind of python debug commands? How do I insert the content of my input file into x? Thanks
[ "As to your 1. that's due to bad habits of the person giving you that program. It should have been:\n#!/usr/bin/env python\nimport pylab\n\nx = pylab.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])\ny = pylab.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])\n\nhelp(pylab.array)\n\nor\n#!/usr/bin/env python\nfrom pylab import array\n\nx = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])\ny = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])\n\nhelp(array)\n\nUse the help(something). It helps :)\nUsing explicit imports is really handy if programs become a bit more complex. The only case I know where from package import * is nice is when playing at the python prompt, trying stuff out.\nAs to the file, can you sketch how the file looks like? And I believe numpy has an array load function somewhere, look at the cookbook.\n", "(1) Fire up the python console and use the dir() function on whatever object/class/variable you want to know more about. It'll print out all methods and properties of the object.\n>> import pylab \n>> x = pylab.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])\n>> dir(x)\n\n(2) look up File Objects in the python documentation\n", "\nUse the help function to find out what an object can do.\nimport pylab\nhelp(pylab.array)\n\n\"What library it belongs to\" is a sort of funny question. You can easily know what module you are using it from if you refactor your code not to use import *. (Never ever ever use import *.) That does not mean that's it's original home—pylab is just a place where a bunch of stuff is pooled for convenience. pylab gets it from matplotlib.pylab which gets it from numpy which gets it from numpy.core.multiarray (which is a C extension module). You can see its original home by looking at pylab.array.__module__ when it's important, which is not often.\n\nPersonally, I think you're better of not using pylab at all, just getting stuff from numpy, scipy, and matplotlib as you need it to keep things organized. To quote The Zen of Python: Namespaces are one honking great idea -- let's do more of those!\n\nHow to build an numpy array from a file depends on the format of the file. numpy.fromfile/pylab.fromfile can import a binary file storing the array's data. (This is the same format used by numpy.tofile—big shock there.)\n\n", "array appears to be a function/class in pylab. You could do help(array) to find out more - this relies on the presence of a proper docstring for array.\nfrom module import * is a problematic idiom in several ways precisely for the reason that it makes it hard to find out where identifiers come from.\nimport pylab\nx = pylab.array(...)\n\nmight be a better way.\n", "Replying to question #2, if your file looks like this:\n10 8.04\n8 6.95\n13 7.58\n9 8.81\n11 8.33\n14 9.96\n6 7.24\n4 4.26\n12 10.84\n7 4.82\n5 5.68\n\nThen I would do like this:\nx_list = list()\ny_list = list()\n\nfp = open('coords.txt', 'r')\nfor line in fp:\n line = line.strip() # Remove trailing whitespace\n if not line: continue # Skip empty lines\n a,b = line.split() # Split line by whitespace, storing coords in a & b\n x_list.append(a) # Add a to x_list\n y_list.append(b) # Add b to y_list\nfp.close()\n\nx = array(x_list)\ny = array(y_list)\n\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002516034_numpy_python.txt
Q: Downloading RSS using python I have list of 200 rss feeds, which I have to downloading. It's continuous process - I have to download every post, nothing can be missing, but also no duplicates. So best practice should be remember last update of feed and control it for change in x-hour interval? And how to handle if downloader will be restarted? So downloader should remember, what were downloaded and dont download it again... It's somewhere implemented yet? Or any tips for article? Thanks A: Typically this is what you'd want to do: Fetch the feeds periodically and parse them using the universal feedparser and store the entries somewhere. Use ETags and IfModified headers when fetching feeds to avoid parsing feeds that have not changed since your last fetch. you'll have to maintain Etags and Ifmodified values recieved during last fetch of the feed. To avoid duplication, each entry should be stored with its unique guid, then check whether an entry with the same guid is already stored or not. (fall back through entry_link, hash of title+feed url to uniquely identify the entry, in case the feed entries have no guid) A: You can use feedparser to parse the feeds and store in a database the maximal published time per feed. For a simple database you can use shelve.
Downloading RSS using python
I have list of 200 rss feeds, which I have to downloading. It's continuous process - I have to download every post, nothing can be missing, but also no duplicates. So best practice should be remember last update of feed and control it for change in x-hour interval? And how to handle if downloader will be restarted? So downloader should remember, what were downloaded and dont download it again... It's somewhere implemented yet? Or any tips for article? Thanks
[ "Typically this is what you'd want to do:\n\nFetch the feeds periodically and parse them using the universal feedparser and store the entries somewhere.\nUse ETags and IfModified headers when fetching feeds to avoid parsing feeds that have not changed since your last fetch. you'll have to maintain Etags and Ifmodified values recieved during last fetch of the feed.\nTo avoid duplication, each entry should be stored with its unique guid, then check whether an entry with the same guid is already stored or not. (fall back through entry_link, hash of title+feed url to uniquely identify the entry, in case the feed entries have no guid)\n\n", "You can use feedparser to parse the feeds and store in a database the maximal published time per feed.\nFor a simple database you can use shelve.\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002517648_python.txt
Q: Weird Cron ls Behavior I have a Python script that is running a few ls commands. This script runs under cron all day. I use awk to write out the column that the filename is in when ls -l is executed. When I run the script via command line the output looks like this -rw-rw---- 1 mysql adm 141 2010-03-25 08:56 mysql-bin.000485 -rw-rw---- 1 mysql adm 141 2010-03-25 09:01 mysql-bin.000486 -rw-rw---- 1 mysql adm 5073 2010-03-25 09:31 mysql-bin.000487 but when I run the scrupt under cron as root, the output looks like this -rw-rw---- 1 mysql adm 141 Mar 25 10:07 mysql-bin.000488 -rw-rw---- 1 mysql adm 141 Mar 25 10:22 mysql-bin.000489 -rw-rw---- 1 mysql adm 98 Mar 25 10:22 mysql-bin.000490 That makes awk return the wrong column. Is there anyway to get the date to format the same under cron? A: Problem is with different locales between your account and root. You can change them temporarily by: $ LC_ALL="locale name" your-script A: If you're on GNU ls, you can pass --time-style=long-iso. More formats are here.
Weird Cron ls Behavior
I have a Python script that is running a few ls commands. This script runs under cron all day. I use awk to write out the column that the filename is in when ls -l is executed. When I run the script via command line the output looks like this -rw-rw---- 1 mysql adm 141 2010-03-25 08:56 mysql-bin.000485 -rw-rw---- 1 mysql adm 141 2010-03-25 09:01 mysql-bin.000486 -rw-rw---- 1 mysql adm 5073 2010-03-25 09:31 mysql-bin.000487 but when I run the scrupt under cron as root, the output looks like this -rw-rw---- 1 mysql adm 141 Mar 25 10:07 mysql-bin.000488 -rw-rw---- 1 mysql adm 141 Mar 25 10:22 mysql-bin.000489 -rw-rw---- 1 mysql adm 98 Mar 25 10:22 mysql-bin.000490 That makes awk return the wrong column. Is there anyway to get the date to format the same under cron?
[ "Problem is with different locales between your account and root. You can change them temporarily by:\n$ LC_ALL=\"locale name\" your-script\n\n", "If you're on GNU ls, you can pass --time-style=long-iso. More formats are here.\n" ]
[ 3, 3 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0002517961_cron_python.txt
Q: How to convert an UTF string with scandinavian characters to ASCII? I would like to convert this string foo_utf = u'nästy chäräctörs with å and co.' # unicode into this foo_ascii = 'nästy chäräctörs with å and co.' # ASCII . Any idea how to do this in Python (2.6)? I found unicodedata module but I have no idea how to do the transformation. A: I don't think you can. Those "nästy chäräctörs" can't be encoded as ASCII, so you'll have to pick a different encoding (UTF-8 or Latin-1 or Windows-1252 or something). A: Try the encode method of string. >>> u'nästy chäräctörs with å and co.'.encode('latin-1') 'n\xe4sty ch\xe4r\xe4ct\xf6rs with \xe5 and co.' A: There are several options in the codecs module in python's stdlib, depending on how you want the extended characters handled: >>> import codecs >>> u = u'nästy chäräctörs with å and co.' >>> encode = codecs.get_encoder('ascii') >>> encode(u) ' Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128) >>> encode(u, 'ignore') ('nsty chrctrs with and co.', 31) >>> encode(u, 'replace') ('n?sty ch?r?ct?rs with ? and co.', 31) >>> encode(u, 'xmlcharrefreplace') ('n&#228;sty ch&#228;r&#228;ct&#246;rs with &#229; and co.', 31) >>> encode(u, 'backslashreplace') ('n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 and co.', 31) Hopefully one of those will meet your needs. There's more information available in the Python codecs module documentation. A: You can also use the unicodedata module (http://docs.python.org/library/unicodedata.html) provided in python to convert a lot of unicode values into an Ascii variant. IE fix the different "s and such. Follow that up by the encode() method and you can completely clean up a string. The method you mainly what out of the unicodedata is normalize and pass it the NFKC flag. A: This really is a Django question, and not a python one. if the string is in one of your .py files, make sure that you have the following line on top of your file: -*- coding: utf-8 -*- furthermore, your string needs to be of type "unicode" (u'foobar') And then make sure that your html page works in unicode: <meta http-equiv="content-type" content="text/html;charset=utf-8" /> That should do the whole trick. No encoding/decoding etc. necessary, just make sure that everything is unicode, and you are on the safe side.
How to convert an UTF string with scandinavian characters to ASCII?
I would like to convert this string foo_utf = u'nästy chäräctörs with å and co.' # unicode into this foo_ascii = 'nästy chäräctörs with å and co.' # ASCII . Any idea how to do this in Python (2.6)? I found unicodedata module but I have no idea how to do the transformation.
[ "I don't think you can. Those \"nästy chäräctörs\" can't be encoded as ASCII, so you'll have to pick a different encoding (UTF-8 or Latin-1 or Windows-1252 or something).\n", "Try the encode method of string.\n>>> u'nästy chäräctörs with å and co.'.encode('latin-1')\n'n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 and co.'\n\n", "There are several options in the codecs module in python's stdlib, depending on how you want the extended characters handled:\n>>> import codecs\n>>> u = u'nästy chäräctörs with å and co.'\n>>> encode = codecs.get_encoder('ascii')\n>>> encode(u) \n'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xe4' in position 1: ordinal not in range(128)\n>>> encode(u, 'ignore')\n('nsty chrctrs with and co.', 31)\n>>> encode(u, 'replace')\n('n?sty ch?r?ct?rs with ? and co.', 31)\n>>> encode(u, 'xmlcharrefreplace')\n('n&#228;sty ch&#228;r&#228;ct&#246;rs with &#229; and co.', 31)\n>>> encode(u, 'backslashreplace')\n('n\\\\xe4sty ch\\\\xe4r\\\\xe4ct\\\\xf6rs with \\\\xe5 and co.', 31)\n\nHopefully one of those will meet your needs. There's more information available in the Python codecs module documentation.\n", "You can also use the unicodedata module (http://docs.python.org/library/unicodedata.html) provided in python to convert a lot of unicode values into an Ascii variant. IE fix the different \"s and such. Follow that up by the encode() method and you can completely clean up a string. \nThe method you mainly what out of the unicodedata is normalize and pass it the NFKC flag.\n", "This really is a Django question, and not a python one.\nif the string is in one of your .py files, make sure that you have the following line on top of your file:\n-*- coding: utf-8 -*-\nfurthermore, your string needs to be of type \"unicode\" (u'foobar')\nAnd then make sure that your html page works in unicode:\n<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />\nThat should do the whole trick. No encoding/decoding etc. necessary, just make sure that everything is unicode, and you are on the safe side.\n" ]
[ 4, 3, 3, 2, 2 ]
[]
[]
[ "ascii", "python", "utf" ]
stackoverflow_0002518005_ascii_python_utf.txt
Q: Python, a smarter way of string to integer conversion I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 . class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. def to_int(self): return int((self.phone).replace(" ","").replace("(","").replace(")","")) test = Phone("0(532) 222 22 22") print test.to_int() It feels very clumsy to use 3 replace methods to solve this. I am curious if there is a better solution? A: p = "0(532) 222 22 22" print ''.join([x for x in p if x.isdigit()]) Note that you'll "lose" the leading zero if you want to convert it to int (like you suggested in the title). If you want to do that, just wrap the above in a int() call. A telephone number does make more sense as a string though (in my opinion). A: In Python 2.6 or 2.7, (self.phone).translate(None,' ()') will remove any spaces or ( or ) from the phone string. See Python 2.6 doc on str.translate for details. In Python 3.x, str.translate() takes a mapping (rather than two strings as shown above). The corresponding snippet therefore is something like the following, using str.maketrans() to produce the mapping. '(self.phone).translate(str.maketrans('','', '()-/ ')) See Python 3.1 doc on str.translate for details. A: How about just using regular expressions? Example: >>> import re >>> num = '0(532) 222 22 22' >>> re.sub('[\D]', '', num) # Match all non-digits ([\D]), replace them with empty string, where found in the `num` variable. '05322222222' The suggestion made by ChristopheD will work just fine, but is not as efficient. The following is a test program to demonstrate this using the dis module (See Doug Hellman's PyMOTW on the module here for more detailed info). TEST_PHONE_NUM = '0(532) 222 22 22' def replace_method(): print (TEST_PHONE_NUM).replace(" ","").replace("(","").replace(")","") def list_comp_is_digit_method(): print ''.join([x for x in TEST_PHONE_NUM if x.isdigit()]) def translate_method(): print (TEST_PHONE_NUM).translate(None,' ()') import re def regex_method(): print re.sub('[\D]', '', TEST_PHONE_NUM) if __name__ == '__main__': from dis import dis print 'replace_method:' dis(replace_method) print print print 'list_comp_is_digit_method:' dis(list_comp_is_digit_method) print print print 'translate_method:' dis(translate_method) print print print "regex_method:" dis(phone_digit_strip_regex) print Output: replace_method: 5 0 LOAD_GLOBAL 0 (TEST_PHONE_NUM) 3 LOAD_ATTR 1 (replace) 6 LOAD_CONST 1 (' ') 9 LOAD_CONST 2 ('') 12 CALL_FUNCTION 2 15 LOAD_ATTR 1 (replace) 18 LOAD_CONST 3 ('(') 21 LOAD_CONST 2 ('') 24 CALL_FUNCTION 2 27 LOAD_ATTR 1 (replace) 30 LOAD_CONST 4 (')') 33 LOAD_CONST 2 ('') 36 CALL_FUNCTION 2 39 PRINT_ITEM 40 PRINT_NEWLINE 41 LOAD_CONST 0 (None) 44 RETURN_VALUE phone_digit_strip_list_comp: 3 0 LOAD_CONST 1 ('0(532) 222 22 22') 3 STORE_FAST 0 (phone) 4 6 LOAD_CONST 2 ('') 9 LOAD_ATTR 0 (join) 12 BUILD_LIST 0 15 DUP_TOP 16 STORE_FAST 1 (_[1]) 19 LOAD_GLOBAL 1 (test_phone_num) 22 GET_ITER 23 FOR_ITER 30 (to 56) 26 STORE_FAST 2 (x) 29 LOAD_FAST 2 (x) 32 LOAD_ATTR 2 (isdigit) 35 CALL_FUNCTION 0 38 JUMP_IF_FALSE 11 (to 52) 41 POP_TOP 42 LOAD_FAST 1 (_[1]) 45 LOAD_FAST 2 (x) 48 LIST_APPEND 49 JUMP_ABSOLUTE 23 52 POP_TOP 53 JUMP_ABSOLUTE 23 56 DELETE_FAST 1 (_[1]) 59 CALL_FUNCTION 1 62 PRINT_ITEM 63 PRINT_NEWLINE 64 LOAD_CONST 0 (None) 67 RETURN_VALUE translate_method: 11 0 LOAD_GLOBAL 0 (TEST_PHONE_NUM) 3 LOAD_ATTR 1 (translate) 6 LOAD_CONST 0 (None) 9 LOAD_CONST 1 (' ()') 12 CALL_FUNCTION 2 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_CONST 0 (None) 20 RETURN_VALUE phone_digit_strip_regex: 8 0 LOAD_CONST 1 ('0(532) 222 22 22') 3 STORE_FAST 0 (phone) 9 6 LOAD_GLOBAL 0 (re) 9 LOAD_ATTR 1 (sub) 12 LOAD_CONST 2 ('[\\D]') 15 LOAD_CONST 3 ('') 18 LOAD_GLOBAL 2 (test_phone_num) 21 CALL_FUNCTION 3 24 PRINT_ITEM 25 PRINT_NEWLINE 26 LOAD_CONST 0 (None) 29 RETURN_VALUE The translate method will be the most efficient, though relies on py2.6+. regex is slightly less efficient, but more compatible (which I see a requirement for you). The original replace method will add 6 additional instructions per replacement, while all of the others will stay constant. On a side note, store your phone numbers as strings to deal with leading zeros, and use a phone formatter where needed. Trust me, it's bitten me before.
Python, a smarter way of string to integer conversion
I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 . class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. def to_int(self): return int((self.phone).replace(" ","").replace("(","").replace(")","")) test = Phone("0(532) 222 22 22") print test.to_int() It feels very clumsy to use 3 replace methods to solve this. I am curious if there is a better solution?
[ "p = \"0(532) 222 22 22\"\nprint ''.join([x for x in p if x.isdigit()])\n\nNote that you'll \"lose\" the leading zero if you want to convert it to int (like you suggested in the title). If you want to do that, just wrap the above in a int() call. A telephone number does make more sense as a string though (in my opinion).\n", "In Python 2.6 or 2.7,\n(self.phone).translate(None,' ()') will remove any spaces or ( or ) from the phone string. See Python 2.6 doc on str.translate for details.\nIn Python 3.x, str.translate() takes a mapping (rather than two strings as shown above). The corresponding snippet therefore is something like the following, using str.maketrans() to produce the mapping.\n'(self.phone).translate(str.maketrans('','', '()-/ '))\nSee Python 3.1 doc on str.translate for details.\n", "How about just using regular expressions?\nExample:\n>>> import re\n>>> num = '0(532) 222 22 22'\n>>> re.sub('[\\D]', '', num) # Match all non-digits ([\\D]), replace them with empty string, where found in the `num` variable.\n'05322222222'\n\nThe suggestion made by ChristopheD will work just fine, but is not as efficient.\nThe following is a test program to demonstrate this using the dis module (See Doug Hellman's PyMOTW on the module here for more detailed info).\nTEST_PHONE_NUM = '0(532) 222 22 22'\n\ndef replace_method():\n print (TEST_PHONE_NUM).replace(\" \",\"\").replace(\"(\",\"\").replace(\")\",\"\")\n\ndef list_comp_is_digit_method():\n print ''.join([x for x in TEST_PHONE_NUM if x.isdigit()])\n\ndef translate_method():\n print (TEST_PHONE_NUM).translate(None,' ()')\n\nimport re\ndef regex_method():\n print re.sub('[\\D]', '', TEST_PHONE_NUM)\n\nif __name__ == '__main__':\n from dis import dis\n\n print 'replace_method:'\n dis(replace_method)\n print\n print\n\n print 'list_comp_is_digit_method:'\n dis(list_comp_is_digit_method)\n\n print\n print\n\n print 'translate_method:'\n dis(translate_method)\n\n print\n print\n print \"regex_method:\"\n dis(phone_digit_strip_regex)\n print\n\nOutput:\nreplace_method:\n 5 0 LOAD_GLOBAL 0 (TEST_PHONE_NUM)\n 3 LOAD_ATTR 1 (replace)\n 6 LOAD_CONST 1 (' ')\n 9 LOAD_CONST 2 ('')\n 12 CALL_FUNCTION 2\n 15 LOAD_ATTR 1 (replace)\n 18 LOAD_CONST 3 ('(')\n 21 LOAD_CONST 2 ('')\n 24 CALL_FUNCTION 2\n 27 LOAD_ATTR 1 (replace)\n 30 LOAD_CONST 4 (')')\n 33 LOAD_CONST 2 ('')\n 36 CALL_FUNCTION 2\n 39 PRINT_ITEM \n 40 PRINT_NEWLINE \n 41 LOAD_CONST 0 (None)\n 44 RETURN_VALUE \n\nphone_digit_strip_list_comp:\n 3 0 LOAD_CONST 1 ('0(532) 222 22 22')\n 3 STORE_FAST 0 (phone)\n\n 4 6 LOAD_CONST 2 ('')\n 9 LOAD_ATTR 0 (join)\n 12 BUILD_LIST 0\n 15 DUP_TOP \n 16 STORE_FAST 1 (_[1])\n 19 LOAD_GLOBAL 1 (test_phone_num)\n 22 GET_ITER \n 23 FOR_ITER 30 (to 56)\n 26 STORE_FAST 2 (x)\n 29 LOAD_FAST 2 (x)\n 32 LOAD_ATTR 2 (isdigit)\n 35 CALL_FUNCTION 0\n 38 JUMP_IF_FALSE 11 (to 52)\n 41 POP_TOP \n 42 LOAD_FAST 1 (_[1])\n 45 LOAD_FAST 2 (x)\n 48 LIST_APPEND \n 49 JUMP_ABSOLUTE 23\n 52 POP_TOP \n 53 JUMP_ABSOLUTE 23\n 56 DELETE_FAST 1 (_[1])\n 59 CALL_FUNCTION 1\n 62 PRINT_ITEM \n 63 PRINT_NEWLINE \n 64 LOAD_CONST 0 (None)\n 67 RETURN_VALUE \n\ntranslate_method:\n 11 0 LOAD_GLOBAL 0 (TEST_PHONE_NUM)\n 3 LOAD_ATTR 1 (translate)\n 6 LOAD_CONST 0 (None)\n 9 LOAD_CONST 1 (' ()')\n 12 CALL_FUNCTION 2\n 15 PRINT_ITEM \n 16 PRINT_NEWLINE \n 17 LOAD_CONST 0 (None)\n 20 RETURN_VALUE \n\nphone_digit_strip_regex:\n 8 0 LOAD_CONST 1 ('0(532) 222 22 22')\n 3 STORE_FAST 0 (phone)\n\n 9 6 LOAD_GLOBAL 0 (re)\n 9 LOAD_ATTR 1 (sub)\n 12 LOAD_CONST 2 ('[\\\\D]')\n 15 LOAD_CONST 3 ('')\n 18 LOAD_GLOBAL 2 (test_phone_num)\n 21 CALL_FUNCTION 3\n 24 PRINT_ITEM \n 25 PRINT_NEWLINE \n 26 LOAD_CONST 0 (None)\n 29 RETURN_VALUE \n\nThe translate method will be the most efficient, though relies on py2.6+. regex is slightly less efficient, but more compatible (which I see a requirement for you). The original replace method will add 6 additional instructions per replacement, while all of the others will stay constant.\nOn a side note, store your phone numbers as strings to deal with leading zeros, and use a phone formatter where needed. Trust me, it's bitten me before.\n" ]
[ 9, 6, 1 ]
[ "SilentGhost: dis.dis does demonstrate underlying conceptual / executional complexity. after all, the OP complained about the original replacement chain being too ‘clumsy’, not too ‘slow’. \ni recommend against using regular expressions where not inevitable; they just add conceptual overhead and a speed penalty otherwise. to use translate() here is IMHO just the wrong tool, and nowhere as conceptually simple and generic as the original replacement chain.\nso you say tamaytoes, and i say tomahtoes: the original solution is quite good in terms of clarity and genericity. it is not clumsy at all. in order to make it a little denser and more parametrized, consider changing it to\nphone_nr_translations = [ \n ( ' ', '', ), \n ( '(', '', ), \n ( ')', '', ), ]\n\ndef sanitize_phone_nr( phone_nr ):\n R = phone_nr\n for probe, replacement in phone_nr_translations:\n R = R.replace( probe, replacement )\n return R\n\nin this special application, of course, what you really want to do is just cancelling out any unwanted characters, so you can simplify this:\nprobes = ' ()'\n\ndef sanitize_phone_nr( phone_nr ):\n R = phone_nr\n for probe in probes:\n R = R.replace( probe, '' )\n return R\n\ncoming to think of it, it is not quite clear to me why you want to turn a phone nr into an integer—that is simply the wrong data type. this can be demonstrated by the fact that at least in mobile nets, + and # and maybe more are valid characters in a dial string (dial, string—see?). \nbut apart from that, sanitizing a user input phone nr to get out a normalized and safe representation is a very, very valid concern—only i feel that your methodology is too specific. why not re-write the sanitizing method to something very generic without becoming more complex? after all, how can you be sure your users never input other deviant characters in that web form field? \nso what you want is really not to dis-allow specific characters (there are about a hundred thousand defined codepoints in unicode 5.1, so how do catch up with those?), but to allow those very characters that are deemed legal in dial strings. and you can do that with a regular expression...\nfrom re import compile as _new_regex\nillegal_phone_nr_chrs_re = _new_regex( r\"[^0-9#+]\" )\n\ndef sanitize_phone_nr( phone_nr ):\n return illegal_phone_nr_chrs_re.sub( '', phone_nr )\n\n...or with a set: \nlegal_phone_nr_chrs = set( '0123456789#+' )\n\ndef sanitize_phone_nr( phone_nr ):\n return ''.join( \n chr for chr in phone_nr \n if chr in legal_phone_nr_chrs )\n\nthat last stanza could well be written on a single line. the disadvantage of this solution would be that you iterate over the input characters from within Python, not making use of the potentially speeder C traversal as offered by str.replace() or even a regular expression. however, performance would in any case be dependent on the expected usage pattern (i am sure you truncate your phone nrs first thing, right? so those would be many small strings to be processed, not few big ones).\nnotice a few points here: i strive for clarity, which is why i try to avoid over-using abbreviations. chr for character, nr for number and R for the return value (more likely to be, ugh, retval where used in the standard library) are in my style book. programming is about getting things understood and done, not about programmers writing code that approaches the spatial efficiency of gzip. now look, the last solution does fairly much what the OP managed to get done (and more), in...\nlegal_phone_nr_chrs = set( '0123456789#+' )\ndef sanitize_phone_nr( phone_nr ): return ''.join( chr for chr in phone_nr if chr in legal_phone_nr_chrs )\n\n...two lines of code if need be, whereas the OP’s code...\nclass Phone():\n def __init__ ( self, input ): self.phone = self._sanitize( input )\n def __str__ ( self ): return self.phone\n def _sanitize ( self, input ): return input.replace( ' ', '' ).replace( '(', '' ).replace( ')', '' )\n\n...can hardly be compressed below four lines. see what additional baggage that strictly-OOP solution gives you? i believe it can be left out of the picture most of the time. \n" ]
[ -1 ]
[ "integer", "python", "string", "type_conversion" ]
stackoverflow_0002499966_integer_python_string_type_conversion.txt
Q: Counting removed items in a Set in Python Given two sets a = [5,3,4,1,2,6,7] b = [1,2,4,9] c = set(a) - set(b) # c -> [5,3,6,7] is it possible to count how many items were removed from set 'a' ? A: How about len(set(a)) - len(c)? Edit: len(a) could be incorrect if a contains duplicates. A: Assuming lack of duplicates: len(a)-len(c) otherwise try: len(set(a)) - len(c) A: there might be a more efficient way, but len(set(a)-set(c)) will work
Counting removed items in a Set in Python
Given two sets a = [5,3,4,1,2,6,7] b = [1,2,4,9] c = set(a) - set(b) # c -> [5,3,6,7] is it possible to count how many items were removed from set 'a' ?
[ "How about len(set(a)) - len(c)?\nEdit: len(a) could be incorrect if a contains duplicates.\n", "Assuming lack of duplicates:\nlen(a)-len(c)\notherwise try:\nlen(set(a)) - len(c)\n", "there might be a more efficient way, but\n len(set(a)-set(c))\n\nwill work\n" ]
[ 6, 3, 3 ]
[ "a = [5,3,4,1,2,6,7] \nb = [1,2,4,9] \nc = set(a) - set(b)\n\nprint len(c)\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0002518711_python.txt
Q: Python's mechanize proxy support I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', params) rs = mechanize.urlopen(rq) How can I add proxy support into my mechanize script? Whenever I open this www.example.com website, i would like it to go through the proxy. A: I'm not sure whether that help or not but you can set proxy settings on mechanize proxy browser. br = Browser() # Explicitly configure proxies (Browser will attempt to set good defaults). # Note the userinfo ("joe:password@") and port number (":3128") are optional. br.set_proxies({"http": "joe:password@myproxy.example.com:3128", "ftp": "proxy.example.com", }) # Add HTTP Basic/Digest auth username and password for HTTP proxy access. # (equivalent to using "joe:password@..." form above) br.add_proxy_password("joe", "password") A: You use mechanize.Request.set_proxy(host, type) (at least as of 0.1.11) assuming an http proxy running at localhost:8888 req = mechanize.Request("http://www.google.com") req.set_proxy("localhost:8888","http") mechanize.urlopen(req) Should work.
Python's mechanize proxy support
I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', params) rs = mechanize.urlopen(rq) How can I add proxy support into my mechanize script? Whenever I open this www.example.com website, i would like it to go through the proxy.
[ "I'm not sure whether that help or not but you can set proxy settings on mechanize proxy browser.\nbr = Browser()\n# Explicitly configure proxies (Browser will attempt to set good defaults).\n# Note the userinfo (\"joe:password@\") and port number (\":3128\") are optional.\nbr.set_proxies({\"http\": \"joe:password@myproxy.example.com:3128\",\n \"ftp\": \"proxy.example.com\",\n })\n# Add HTTP Basic/Digest auth username and password for HTTP proxy access.\n# (equivalent to using \"joe:password@...\" form above)\nbr.add_proxy_password(\"joe\", \"password\")\n\n", "You use mechanize.Request.set_proxy(host, type) (at least as of 0.1.11)\nassuming an http proxy running at localhost:8888\nreq = mechanize.Request(\"http://www.google.com\")\nreq.set_proxy(\"localhost:8888\",\"http\")\nmechanize.urlopen(req)\n\nShould work.\n" ]
[ 31, 9 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001997894_mechanize_python.txt
Q: best way to implement a deck for a card game in python What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable? For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and values of suits and cards be stored? A: Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human. >>> import random >>> import itertools >>> SUITS = 'cdhs' >>> RANKS = '23456789TJQKA' >>> DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS)) >>> hand = random.sample(DECK, 5) >>> print hand ['Kh', 'Kc', '6c', '7d', '3d'] Edit: This is actually straight from a poker module I wrote to evaluate poker hands, you can see more here: http://pastebin.com/mzNmCdV5 A: The simplest thing would be to use a list of tuples, where the cards are ints and the suits are strings: hand = [(1, 'spade'), (10, 'club'), ...] But simplest may not be what you want. Maybe you want a class to represent a card: class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit def __repr__(self): letters = {1:'A', 11:'J', 12:'Q', 13:'K'} letter = letters.get(self.rank, str(self.rank)) return "<Card %s %s>" % (letter, self.suit) hand = [Card(1, 'spade'), Card(10, 'club')] A: A deck of cards is comprised of the same range of values (1 - 13) in each of four suits, which suggests a Cartesian product. List comprehension is an elegant, dense syntax for doing this: values = range(1, 10) + "Jack Queen King".split() suits = "Diamonds Clubs Hearts Spades".split() deck_of_cards = ["%s of %s" % (v, s) for v in values for s in suits] in python 3: deck_of_cards = ["{0} of {1}".format(v, s) for v in values for s in suits] That's how they are when you take a brand new deck out of the box; to play you need to shuffle them: from random import shuffle shuffle(deck_of_cards) A: You could simply use a number, and decide on a mapping between number and "card". For example: number MOD 13 = face value (after a +1) number DIV 13 = suit A: import collections C, H, D, S = "CLUBS", "HEARTS", "DICE", "SPADE" Card = collections.namedtuple("Card", "suit value") hand = [] hand.append(Card(C, 3)) hand.append(Card(H, "A")) hand.append(Card(D, 10)) hand.append(Card(S, "Q")) for card in hand: print(card.value, card.suit)
best way to implement a deck for a card game in python
What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable? For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and values of suits and cards be stored?
[ "Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human.\n>>> import random\n>>> import itertools\n>>> SUITS = 'cdhs'\n>>> RANKS = '23456789TJQKA'\n>>> DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))\n>>> hand = random.sample(DECK, 5)\n>>> print hand\n['Kh', 'Kc', '6c', '7d', '3d']\n\nEdit: This is actually straight from a poker module I wrote to evaluate poker hands, you can see more here: http://pastebin.com/mzNmCdV5\n", "The simplest thing would be to use a list of tuples, where the cards are ints and the suits are strings:\nhand = [(1, 'spade'), (10, 'club'), ...]\n\nBut simplest may not be what you want. Maybe you want a class to represent a card:\nclass Card:\n def __init__(self, rank, suit):\n self.rank = rank\n self.suit = suit\n\n def __repr__(self):\n letters = {1:'A', 11:'J', 12:'Q', 13:'K'}\n letter = letters.get(self.rank, str(self.rank))\n return \"<Card %s %s>\" % (letter, self.suit)\n\nhand = [Card(1, 'spade'), Card(10, 'club')]\n\n", "A deck of cards is comprised of the same range of values (1 - 13) in each of four suits, which suggests a Cartesian product. List comprehension is an elegant, dense syntax for doing this:\nvalues = range(1, 10) + \"Jack Queen King\".split()\nsuits = \"Diamonds Clubs Hearts Spades\".split()\n\ndeck_of_cards = [\"%s of %s\" % (v, s) for v in values for s in suits]\n\nin python 3:\ndeck_of_cards = [\"{0} of {1}\".format(v, s) for v in values for s in suits]\n\nThat's how they are when you take a brand new deck out of the box; to play you need to shuffle them:\nfrom random import shuffle\n\nshuffle(deck_of_cards)\n\n", "You could simply use a number, and decide on a mapping between number and \"card\". For example:\nnumber MOD 13 = face value (after a +1)\nnumber DIV 13 = suit\n", "import collections\n\nC, H, D, S = \"CLUBS\", \"HEARTS\", \"DICE\", \"SPADE\"\nCard = collections.namedtuple(\"Card\", \"suit value\")\n\nhand = []\n\nhand.append(Card(C, 3))\nhand.append(Card(H, \"A\"))\nhand.append(Card(D, 10))\nhand.append(Card(S, \"Q\"))\n\nfor card in hand:\n print(card.value, card.suit)\n\n" ]
[ 26, 7, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002518753_python.txt
Q: Storing simulation results in a persistent manner for Python? Background: I'm running multiple simulations on a set of data. For each session, I'm allocating projects to students. The difference between each session is that I'm randomising the order of the students such that all the students get a shot at being assigned a project they want. I was writing out some of the allocations in a spreadsheet (i.e. Excel) and it basically looked like this (tiny snapshot, actual table extends to a few thousand sessions, roughly 100 students). | | Session 1 | Session 2 | Session 3 | |----------|-----------|-----------|-----------| |Stu1 |Proj_AA |Proj_AB |Proj_AB | |----------|-----------|-----------|-----------| |Stu2 |Proj_AB |Proj_AA |Proj_AC | |----------|-----------|-----------|-----------| |Stu3 |Proj_AC |Proj_AC |Proj_AA | |----------|-----------|-----------|-----------| Now, the code that deals with the allocation currently stores a session in an object. The next time the allocation is run, the object is over-written. Thus what I'd really like to do is to store all the allocation results. This is important since I later need to derive from the data, information such as: which project Stu1 got assigned to the most or perhaps how popular Proj_AC was (how many times it was assigned / number of sessions). Question(s): What methods can I possibly use to basically store such session information persistently? Basically, each session output needs to add itself to the repository after ending and before beginning the next allocation cycle. One solution that was suggested by a friend was mapping these results to a relational database using SQLAlchemy. I kind of like the idea since this does give me an opportunity to delve into databases. Now the database structure I was recommended was: |----------|-----------|-----------| |Session |Student |Project | |----------|-----------|-----------| |1 |Stu1 |Proj_AA | |----------|-----------|-----------| |1 |Stu2 |Proj_AB | |----------|-----------|-----------| |1 |Stu3 |Proj_AC | |----------|-----------|-----------| |2 |Stu1 |Proj_AB | |----------|-----------|-----------| |2 |Stu2 |Proj_AA | |----------|-----------|-----------| |2 |Stu3 |Proj_AC | |----------|-----------|-----------| |3 |Stu1 |Proj_AB | |----------|-----------|-----------| |3 |Stu2 |Proj_AC | |----------|-----------|-----------| |3 |Stu3 |Proj_AA | |----------|-----------|-----------| Here, it was suggested that I make the Session and Student columns a composite key. That way I can access a specific record for a particular student for a particular session. Or I can merely get the entire allocation run for a particular session. Questions: Is the idea a good one? How does one implement and query a composite key using SQLAlchemy? What happens to the database if a particular student is not assigned a project (happens if all projects that he wants are taken)? In the code, if a student is not assigned a project, instead of a proj_id he simply gets None for that field/object. I apologise for asking multiple questions but since these are closely-related, I thought I'd ask them in the same space. Edit - 25/03/2010 The class structure for Student currently stands like so: class Student(DeptPerson): def __init__(self, name, stud_id): super(Student, self).__init__(name, stud_id) self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 (Misc.) It inherits from a class called DeptPerson that just has name and stud_id. Thus, as the allocation function goes about assigned projects (referenced by a unique ID - Project is its own class) to a student (for a single run/trial/session), it will reflect the value in allocated_project. If a student isn't assigned a project for a particular run (because someone else already has it, mwhahah...sorry), allocated_project remains as None (this is pretty useful information for me). A: A two-dimension display of data is a Relational database table with two keys. In your example, the Student Key and the Session Key. A "Composite key" is a piece of noise that you can ignore. It isn't helpful and isn't necessary. A composite key does not solve any problems well and create many difficulties. Pretend you never heard it. What we do is introduce an additional column with a simple "identifier". It's an "autogenerated, surrogate key" for they row. Autogenerated unique keys for each row are a good thing. Composite keys are a bad thing. A: The logical structure you have can be considered a Ternary Relationship, where recommended to you table is corresponding to the Attendance relationship object. Therefore ideally you should also create you object model similar to this: (source: databasedesignstudio.com) . Now, in your case one could argue why do you need more then 1 table, if you have only one field for each of the Entity tables. But I would still model it this way, as this model better represents the real world, and you still need to store somewhere the Project students prefer to work on, which would be another table with many-to-many relationship to Student table. Working with entities is better and easier for you to understand sqlalchemy; whereas if you just keep one table, how much will you delve into the database really? About composite keys: S.Lott gave you good reasons to avoid using them, and I fully agree with his take on the topic. A: Can't help you on the db stuff, as I'm a total newb and only know enough to query data from sqlite tables... For persistence, though, could you use the pickle module to store your objects? Check the docs for the exact usage, but I think it's pretty much file(filename, 'wb').write(pickle.pickle(myobject)) to write it and myobject = pickle.unpickle(file(filename, 'rb')) to read. Then you can read multiple tables/whatever into multiple variables and do whatever comparisons you want. If you don't need/want to read it back in via Python, you could also just manually format it as tab delimited or something and load that file into the spreadsheet app of your choice (OpenOffice Calc is fantastic).
Storing simulation results in a persistent manner for Python?
Background: I'm running multiple simulations on a set of data. For each session, I'm allocating projects to students. The difference between each session is that I'm randomising the order of the students such that all the students get a shot at being assigned a project they want. I was writing out some of the allocations in a spreadsheet (i.e. Excel) and it basically looked like this (tiny snapshot, actual table extends to a few thousand sessions, roughly 100 students). | | Session 1 | Session 2 | Session 3 | |----------|-----------|-----------|-----------| |Stu1 |Proj_AA |Proj_AB |Proj_AB | |----------|-----------|-----------|-----------| |Stu2 |Proj_AB |Proj_AA |Proj_AC | |----------|-----------|-----------|-----------| |Stu3 |Proj_AC |Proj_AC |Proj_AA | |----------|-----------|-----------|-----------| Now, the code that deals with the allocation currently stores a session in an object. The next time the allocation is run, the object is over-written. Thus what I'd really like to do is to store all the allocation results. This is important since I later need to derive from the data, information such as: which project Stu1 got assigned to the most or perhaps how popular Proj_AC was (how many times it was assigned / number of sessions). Question(s): What methods can I possibly use to basically store such session information persistently? Basically, each session output needs to add itself to the repository after ending and before beginning the next allocation cycle. One solution that was suggested by a friend was mapping these results to a relational database using SQLAlchemy. I kind of like the idea since this does give me an opportunity to delve into databases. Now the database structure I was recommended was: |----------|-----------|-----------| |Session |Student |Project | |----------|-----------|-----------| |1 |Stu1 |Proj_AA | |----------|-----------|-----------| |1 |Stu2 |Proj_AB | |----------|-----------|-----------| |1 |Stu3 |Proj_AC | |----------|-----------|-----------| |2 |Stu1 |Proj_AB | |----------|-----------|-----------| |2 |Stu2 |Proj_AA | |----------|-----------|-----------| |2 |Stu3 |Proj_AC | |----------|-----------|-----------| |3 |Stu1 |Proj_AB | |----------|-----------|-----------| |3 |Stu2 |Proj_AC | |----------|-----------|-----------| |3 |Stu3 |Proj_AA | |----------|-----------|-----------| Here, it was suggested that I make the Session and Student columns a composite key. That way I can access a specific record for a particular student for a particular session. Or I can merely get the entire allocation run for a particular session. Questions: Is the idea a good one? How does one implement and query a composite key using SQLAlchemy? What happens to the database if a particular student is not assigned a project (happens if all projects that he wants are taken)? In the code, if a student is not assigned a project, instead of a proj_id he simply gets None for that field/object. I apologise for asking multiple questions but since these are closely-related, I thought I'd ask them in the same space. Edit - 25/03/2010 The class structure for Student currently stands like so: class Student(DeptPerson): def __init__(self, name, stud_id): super(Student, self).__init__(name, stud_id) self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 (Misc.) It inherits from a class called DeptPerson that just has name and stud_id. Thus, as the allocation function goes about assigned projects (referenced by a unique ID - Project is its own class) to a student (for a single run/trial/session), it will reflect the value in allocated_project. If a student isn't assigned a project for a particular run (because someone else already has it, mwhahah...sorry), allocated_project remains as None (this is pretty useful information for me).
[ "A two-dimension display of data is a Relational database table with two keys.\nIn your example, the Student Key and the Session Key.\nA \"Composite key\" is a piece of noise that you can ignore. It isn't helpful and isn't necessary. A composite key does not solve any problems well and create many difficulties. Pretend you never heard it.\nWhat we do is introduce an additional column with a simple \"identifier\". It's an \"autogenerated, surrogate key\" for they row. Autogenerated unique keys for each row are a good thing. Composite keys are a bad thing.\n", "The logical structure you have can be considered a Ternary Relationship, where recommended to you table is corresponding to the Attendance relationship object. Therefore ideally you should also create you object model similar to this:\n\n(source: databasedesignstudio.com)\n.\nNow, in your case one could argue why do you need more then 1 table, if you have only one field for each of the Entity tables. But I would still model it this way, as this model better represents the real world, and you still need to store somewhere the Project students prefer to work on, which would be another table with many-to-many relationship to Student table.\nWorking with entities is better and easier for you to understand sqlalchemy; whereas if you just keep one table, how much will you delve into the database really?\nAbout composite keys: S.Lott gave you good reasons to avoid using them, and I fully agree with his take on the topic.\n", "Can't help you on the db stuff, as I'm a total newb and only know enough to query data from sqlite tables...\nFor persistence, though, could you use the pickle module to store your objects? Check the docs for the exact usage, but I think it's pretty much file(filename, 'wb').write(pickle.pickle(myobject)) to write it and myobject = pickle.unpickle(file(filename, 'rb')) to read.\nThen you can read multiple tables/whatever into multiple variables and do whatever comparisons you want.\nIf you don't need/want to read it back in via Python, you could also just manually format it as tab delimited or something and load that file into the spreadsheet app of your choice (OpenOffice Calc is fantastic).\n" ]
[ 3, 1, 0 ]
[]
[]
[ "persistence", "python", "sqlalchemy" ]
stackoverflow_0002512609_persistence_python_sqlalchemy.txt
Q: How do I mock a class property with mox? I have a class: class MyClass(object): @property def myproperty(self): return 'hello' Using mox and py.test, how do I mock out myproperty? I've tried: mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' and mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty.AndReturns('goodbye') but both fail with AttributeError: can't set attribute. A: When stubbing out class attributes mox uses setattr. Thus mock.StubOutWithMock(myinstance, 'myproperty') myinstance.myproperty = 'goodbye' is equivalent to # Save old attribute so it can be replaced during teardown saved = getattr(myinstance, 'myproperty') # Replace the existing attribute with a mock mocked = MockAnything() setattr(myinstance, 'myproperty', mocked) Note that because myproperty is a property getattr and setattr will be invoking the property's __get__ and __set__ methods, rather than actually "mocking out" the property itself. Thus to get your desired outcome you just go one step deeper and mock out the property on the instance's class. mock.StubOutWithMock(myinstance.__class__, 'myproperty') myinstance.myproperty = 'goodbye' Note that this might cause issues if you wish to concurrently mock multiple instances of MyClass with different myproperty values. A: Have you read about property? It's read-only, a "getter". If you want a setter, you have two choices of how to create that. Once you have both getter and setter, you can try again to mock out both of them. class MyClass(object): # Upper Case Names for Classes. @property def myproperty(self): return 'hello' @myproperty.setter def myproperty(self,value): self.someValue= value Or class MyClass(object): # Upper Case Names for Classes. def getProperty(self): return 'hello' def setProperty(self,value): self.someValue= value myproperty= property( getProperty, setProperty )
How do I mock a class property with mox?
I have a class: class MyClass(object): @property def myproperty(self): return 'hello' Using mox and py.test, how do I mock out myproperty? I've tried: mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' and mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty.AndReturns('goodbye') but both fail with AttributeError: can't set attribute.
[ "When stubbing out class attributes mox uses setattr. Thus\nmock.StubOutWithMock(myinstance, 'myproperty')\nmyinstance.myproperty = 'goodbye'\n\nis equivalent to\n# Save old attribute so it can be replaced during teardown\nsaved = getattr(myinstance, 'myproperty')\n# Replace the existing attribute with a mock\nmocked = MockAnything()\nsetattr(myinstance, 'myproperty', mocked)\n\nNote that because myproperty is a property getattr and setattr will be invoking the property's __get__ and __set__ methods, rather than actually \"mocking out\" the property itself.\nThus to get your desired outcome you just go one step deeper and mock out the property on the instance's class.\nmock.StubOutWithMock(myinstance.__class__, 'myproperty')\nmyinstance.myproperty = 'goodbye'\n\nNote that this might cause issues if you wish to concurrently mock multiple instances of MyClass with different myproperty values.\n", "Have you read about property? It's read-only, a \"getter\".\nIf you want a setter, you have two choices of how to create that.\nOnce you have both getter and setter, you can try again to mock out both of them.\nclass MyClass(object): # Upper Case Names for Classes.\n @property\n def myproperty(self):\n return 'hello'\n @myproperty.setter\n def myproperty(self,value):\n self.someValue= value\n\nOr\nclass MyClass(object): # Upper Case Names for Classes.\n def getProperty(self):\n return 'hello'\n def setProperty(self,value):\n self.someValue= value\n myproperty= property( getProperty, setProperty )\n\n" ]
[ 9, 3 ]
[]
[]
[ "mocking", "mox", "properties", "python" ]
stackoverflow_0002512453_mocking_mox_properties_python.txt
Q: Creating Read-only logs with python I am writing a python script that needs to make a log entry whenever it's invoked. The log created by the script must not be changeable by the user (except root) who invoked the script. I tried the syslog module and while this does exactly what I want in terms of file permissions, I need to be able to put the resulting log file in an arbitrary location. How would I go about doing this? A: I see you are on linux, Depending on which filesystem you are using, you may be able to use the chattr command. You can make files that are append only by setting the a attribute A: Run your script with setuid root.
Creating Read-only logs with python
I am writing a python script that needs to make a log entry whenever it's invoked. The log created by the script must not be changeable by the user (except root) who invoked the script. I tried the syslog module and while this does exactly what I want in terms of file permissions, I need to be able to put the resulting log file in an arbitrary location. How would I go about doing this?
[ "I see you are on linux,\nDepending on which filesystem you are using, you may be able to use the chattr command. You can make files that are append only by setting the a attribute\n", "Run your script with setuid root.\n" ]
[ 1, 0 ]
[]
[]
[ "linux", "logging", "permissions", "python" ]
stackoverflow_0002519706_linux_logging_permissions_python.txt
Q: Detect user logout / shutdown in Python / GTK under Linux - SIGTERM/HUP not received OK this is presumably a hard one, I've got an pyGTK application that has random crashes due to X Window errors that I can't catch/control. So I created a wrapper that restarts the app as soon as it detects a crash, now comes the problem, when the user logs out or shuts down the system, the app exits with status 1. But on some X errors it does so too. So I tried literally anything to catch the shutdown/logout, with no success, here's what I've tried: import pygtk import gtk import sys class Test(gtk.Window): def delete_event(self, widget, event, data=None): open("delete_event", "wb") def destroy_event(self, widget, data=None): open("destroy_event", "wb") def destroy_event2(self, widget, event, data=None): open("destroy_event2", "wb") def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.show() self.connect("delete_event", self.delete_event) self.connect("destroy", self.destroy_event) self.connect("destroy-event", self.destroy_event2) def foo(): open("add_event", "wb") def ex(): open("sys_event", "wb") from signal import * def clean(sig): f = open("sig_event", "wb") f.write(str(sig)) f.close() exit(0) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, lambda *args: clean(sig)) def at(): open("at_event", "wb") import atexit atexit.register(at) f = Test() sys.exitfunc = ex gtk.quit_add(gtk.main_level(), foo) gtk.main() open("exit_event", "wb") Not one of these succeeds, is there any low level way to detect the system shutdown? Google didn't find anything related to that. I guess there must be a way, am I right? :/ EDIT: OK, more stuff. I've created this shell script: #!/bin/bash trap test_term TERM trap test_hup HUP test_term(){ echo "teeeeeeeeeerm" >~/Desktop/term.info exit 0 } test_hup(){ echo "huuuuuuuuuuup" >~/Desktop/hup.info exit 1 } while [ true ] do echo "idle..." sleep 2 done And also created a .desktop file to run it: [Desktop Entry] Name=Kittens GenericName=Kittens Comment=Kitten Script Exec=kittens StartupNotify=true Terminal=false Encoding=UTF-8 Type=Application Categories=Network;GTK; Name[de_DE]=Kittens Normally this should create the term file on logout and the hup file when it has been started with &. But not on my System. GDM doesn't care about the script at all, when I relog, it's still running. I've also tried using shopt -s huponexit, with no success. EDIT2: Also here's some more information aboute the real code, the whole thing looks like this: Wrapper Script, that catches errors and restarts the programm -> Main Programm with GTK Mainloop -> Background Updater Thread The flow is like this: Start Wrapper -> enter restart loop while restarts < max: -> start program -> check return code -> write error to file or exit the wrapper on 0 Now on shutdown, start program return 1. That means either it did hanup or the parent process terminated, the main problem is to figure out which of these two did just happen. X Errors result in a 1 too. Trapping in the shellscript doesn't work. If you want to take a look at the actual code check it out over at GitHub: http://github.com/BonsaiDen/Atarashii A: OK, I finally found the solution :) You simply can't rely on signals in this case. You have to connect to the Desktop Session in order to get notified that a logout is going to happen. import gnome.ui gnome.program_init('Program', self.version) # This is going to trigger a warning that program name has been set twice, you can ignore this, it seems to be a problem with a recent version of glib, the warning is all over the place out there client = gnome.ui.master_client() # connect us to gnome session manager, we need to init the program before this client.connect('save-yourself', self.on_logout) # This gets called when the user confirms the logout/shutdown client.connect('shutdown-cancelled', self.on_logout_cancel) # This gets called when the logout/shutdown is canceled client.connect('die', self.on_logout) # Don't know when this gets called it never got in my tests def on_logout(self, *args): # save settings an create a file that tells the wrapper that we have exited correctly! # we'll still return with status code 1, but that's just gtk crashing somehow def on_logout_cancel(self, *args): # simply delete the logout file if it exists One important note here: Don't try to exit your program in on_logout, if you do so, GNOME won't recognize that your program has been exited and will give you the dialog that some programs are still running. A: You forgot to close gtk's event loop. This code exits with code 0 when you close the window: import gtk class Test(gtk.Window): def destroy_event(self, widget, data=None): gtk.main_quit() def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.connect("destroy", self.destroy_event) self.show() f = Test() gtk.main() EDIT: Here's the code to catch the SIGTERM signal: import signal def handler(signum, frame): print 'Signal handler called with signal', signum print 'Finalizing main loop' gtk.main_quit() signal.signal(signal.SIGTERM, handler) The rest of the code is exactly as above, no changes. It works here when I send SIGTERM to the python process: gtk main loop ends and program exits with exit code 0.
Detect user logout / shutdown in Python / GTK under Linux - SIGTERM/HUP not received
OK this is presumably a hard one, I've got an pyGTK application that has random crashes due to X Window errors that I can't catch/control. So I created a wrapper that restarts the app as soon as it detects a crash, now comes the problem, when the user logs out or shuts down the system, the app exits with status 1. But on some X errors it does so too. So I tried literally anything to catch the shutdown/logout, with no success, here's what I've tried: import pygtk import gtk import sys class Test(gtk.Window): def delete_event(self, widget, event, data=None): open("delete_event", "wb") def destroy_event(self, widget, data=None): open("destroy_event", "wb") def destroy_event2(self, widget, event, data=None): open("destroy_event2", "wb") def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.show() self.connect("delete_event", self.delete_event) self.connect("destroy", self.destroy_event) self.connect("destroy-event", self.destroy_event2) def foo(): open("add_event", "wb") def ex(): open("sys_event", "wb") from signal import * def clean(sig): f = open("sig_event", "wb") f.write(str(sig)) f.close() exit(0) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, lambda *args: clean(sig)) def at(): open("at_event", "wb") import atexit atexit.register(at) f = Test() sys.exitfunc = ex gtk.quit_add(gtk.main_level(), foo) gtk.main() open("exit_event", "wb") Not one of these succeeds, is there any low level way to detect the system shutdown? Google didn't find anything related to that. I guess there must be a way, am I right? :/ EDIT: OK, more stuff. I've created this shell script: #!/bin/bash trap test_term TERM trap test_hup HUP test_term(){ echo "teeeeeeeeeerm" >~/Desktop/term.info exit 0 } test_hup(){ echo "huuuuuuuuuuup" >~/Desktop/hup.info exit 1 } while [ true ] do echo "idle..." sleep 2 done And also created a .desktop file to run it: [Desktop Entry] Name=Kittens GenericName=Kittens Comment=Kitten Script Exec=kittens StartupNotify=true Terminal=false Encoding=UTF-8 Type=Application Categories=Network;GTK; Name[de_DE]=Kittens Normally this should create the term file on logout and the hup file when it has been started with &. But not on my System. GDM doesn't care about the script at all, when I relog, it's still running. I've also tried using shopt -s huponexit, with no success. EDIT2: Also here's some more information aboute the real code, the whole thing looks like this: Wrapper Script, that catches errors and restarts the programm -> Main Programm with GTK Mainloop -> Background Updater Thread The flow is like this: Start Wrapper -> enter restart loop while restarts < max: -> start program -> check return code -> write error to file or exit the wrapper on 0 Now on shutdown, start program return 1. That means either it did hanup or the parent process terminated, the main problem is to figure out which of these two did just happen. X Errors result in a 1 too. Trapping in the shellscript doesn't work. If you want to take a look at the actual code check it out over at GitHub: http://github.com/BonsaiDen/Atarashii
[ "OK, I finally found the solution :)\nYou simply can't rely on signals in this case. You have to connect to the Desktop Session in order to get notified that a logout is going to happen.\nimport gnome.ui\n\ngnome.program_init('Program', self.version) # This is going to trigger a warning that program name has been set twice, you can ignore this, it seems to be a problem with a recent version of glib, the warning is all over the place out there\nclient = gnome.ui.master_client() # connect us to gnome session manager, we need to init the program before this\nclient.connect('save-yourself', self.on_logout) # This gets called when the user confirms the logout/shutdown\nclient.connect('shutdown-cancelled', self.on_logout_cancel) # This gets called when the logout/shutdown is canceled\nclient.connect('die', self.on_logout) # Don't know when this gets called it never got in my tests\n\ndef on_logout(self, *args):\n # save settings an create a file that tells the wrapper that we have exited correctly!\n # we'll still return with status code 1, but that's just gtk crashing somehow\n\ndef on_logout_cancel(self, *args):\n # simply delete the logout file if it exists\n\nOne important note here: Don't try to exit your program in on_logout, if you do so, GNOME won't recognize that your program has been exited and will give you the dialog that some programs are still running.\n", "You forgot to close gtk's event loop.\nThis code exits with code 0 when you close the window:\nimport gtk\n\nclass Test(gtk.Window):\n def destroy_event(self, widget, data=None):\n gtk.main_quit()\n\n def __init__(self):\n gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)\n self.connect(\"destroy\", self.destroy_event)\n self.show()\n\nf = Test()\ngtk.main()\n\n\nEDIT: Here's the code to catch the SIGTERM signal:\nimport signal\n\ndef handler(signum, frame):\n print 'Signal handler called with signal', signum\n print 'Finalizing main loop'\n gtk.main_quit()\n\nsignal.signal(signal.SIGTERM, handler)\n\nThe rest of the code is exactly as above, no changes. It works here when I send SIGTERM to the python process: gtk main loop ends and program exits with exit code 0.\n" ]
[ 2, 0 ]
[]
[]
[ "gtk", "linux", "pygtk", "python", "sigterm" ]
stackoverflow_0002490166_gtk_linux_pygtk_python_sigterm.txt