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: what does this code snippet do? can somebody give me an explanation about the following code? from twisted.internet import protocol, reactor from twisted.protocols import basic class FingerProtocol(basic.LineReceiver): def lineReceived(self, user): self.transport.write(self.factory.getUser(user)+"\r\n") self.transport.loseConnection() class FingerFactory(protocol.ServerFactory): protocol = FingerProtocol def __init__(self, **kwargs): # whats is ** ?? self.users = kwargs def getUser(self, user): return self.users.get(user, "No such user") reactor.listenTCP(1079, FingerFactory(moshez='Happy and well')) # explain call to fnger factory?? A: It's keyword argument notation. A: The call to FingerFactory (a strange name, BTW) is instantiating a FingerFactory object. The parameters to that call are passed to the __init__ function of the class, where they are accepted by the **kwargs parameter as a dictionary: {'moshez': 'Happy and well'} So this is assigned to the users attribute of the new FingerFactory instance. A: And the other question, regarding FingerFactory call. That's how you do instantiation in Python. You don't use a new keyword. You just call the class as though it were a function. The constructor of the class is __init__
what does this code snippet do?
can somebody give me an explanation about the following code? from twisted.internet import protocol, reactor from twisted.protocols import basic class FingerProtocol(basic.LineReceiver): def lineReceived(self, user): self.transport.write(self.factory.getUser(user)+"\r\n") self.transport.loseConnection() class FingerFactory(protocol.ServerFactory): protocol = FingerProtocol def __init__(self, **kwargs): # whats is ** ?? self.users = kwargs def getUser(self, user): return self.users.get(user, "No such user") reactor.listenTCP(1079, FingerFactory(moshez='Happy and well')) # explain call to fnger factory??
[ "It's keyword argument notation.\n", "The call to FingerFactory (a strange name, BTW) is instantiating a FingerFactory object. The parameters to that call are passed to the __init__ function of the class, where they are accepted by the **kwargs parameter as a dictionary: \n{'moshez': 'Happy and well'}\n\nSo this is assigned to the users attribute of the new FingerFactory instance.\n", "And the other question, regarding FingerFactory call.\nThat's how you do instantiation in Python. You don't use a new keyword. You just call the class as though it were a function. The constructor of the class is __init__\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002115578_python.txt
Q: Python 2.x vs 3.x Speed I'm a PhD student and use Python to write the code I use for my research. My workflow often consists of making a small change to the code, running the program, seeing whether the results improved, and repeating the process. Because of this, I find myself spending more time waiting for my program to run than I do actually working on it (a common experience, I know). I'm currently using the most recent version of Python 2 on my system, so my question is whether switching to Python 3 is going to give me any speed boost or not. At this point, I don't really have a compelling reason to move to Python 3, so if the execution speeds are similar, I'll probably just stick with 2.x. I know I'm going to have to modify my code a bit to get it working in Python 3, so it's not trivial to just test it on both versions to see which runs faster. I'd need to be reasonably confident I will get a speed improvement before I spend the time updating my code to Python 3. A: This article (archive.org) said that there were a few points where Python 3.0 was actually slower than Python 2.6, though I think many of these issues were resolved. That being said, Numpy hasn't been brought over to Python 3.0 yet and that's where a lot of the high performance (written in c) number functionality stuff is hiding. Hopefully it will be ready late 2009 or early 2010. You should not consider performance to be a justification to switch to Python 3; I don't think you'll see a consistent speed improvement. Edit: Versions of Numpy which support Python 3 have since been released. Edit2: This answer (and other answers to this question) are outdated. A: Right now, speed on Python 3 is more or less the same as Python 2... If you're looking for speed, it's not on Python 3 vs Python 2 but in other tools like Psyco, Cython, etc... But, very recently, there have arisen plans to merge Unladen Swallow, the Google project to implement a JIT over Python with Python 3. Of course, it won't be very soon, but, in some time, maybe the speed will increase noticeably on Python 3 over Python 2. They claim to have already increased speed on a 10% (on Python 2). Their objective is increasing the speed to 5x. For more information, see PEP 3146 EDIT: Just as Brian remarks, PEP 3146 was retired. A: Try refining the algorithms or changing the data structures used. That's usually the best way to get an increase in performance. A: I can't answer the root of your question, but if you read anything regarding the sluggish performance of the io module please disregard it. The were definitely performance issues in Python 3.0, but they were largely resolved in Python 3.1. A: I have phylogenetics analysis that takes a long time to run, and uses about a half-dozen python scripts as well as other bioinformatics software (muscle, clustal, blast, even R!). I use temp files to save intermediate results and a master script with the subprocess module to glue all the pieces together. It's easy to change the master to run only the modified parts that I want to test. But, if the changes are being made to early steps, and you only know how good it is at the end of the whole process, then this strategy wouldn't help much.
Python 2.x vs 3.x Speed
I'm a PhD student and use Python to write the code I use for my research. My workflow often consists of making a small change to the code, running the program, seeing whether the results improved, and repeating the process. Because of this, I find myself spending more time waiting for my program to run than I do actually working on it (a common experience, I know). I'm currently using the most recent version of Python 2 on my system, so my question is whether switching to Python 3 is going to give me any speed boost or not. At this point, I don't really have a compelling reason to move to Python 3, so if the execution speeds are similar, I'll probably just stick with 2.x. I know I'm going to have to modify my code a bit to get it working in Python 3, so it's not trivial to just test it on both versions to see which runs faster. I'd need to be reasonably confident I will get a speed improvement before I spend the time updating my code to Python 3.
[ "This article (archive.org) said that there were a few points where Python 3.0 was actually slower than Python 2.6, though I think many of these issues were resolved. That being said, Numpy hasn't been brought over to Python 3.0 yet and that's where a lot of the high performance (written in c) number functionality stuff is hiding. Hopefully it will be ready late 2009 or early 2010.\nYou should not consider performance to be a justification to switch to Python 3; I don't think you'll see a consistent speed improvement.\nEdit: Versions of Numpy which support Python 3 have since been released.\nEdit2: This answer (and other answers to this question) are outdated.\n", "Right now, speed on Python 3 is more or less the same as Python 2... If you're looking for speed, it's not on Python 3 vs Python 2 but in other tools like Psyco, Cython, etc...\nBut, very recently, there have arisen plans to merge Unladen Swallow, the Google project to implement a JIT over Python with Python 3. Of course, it won't be very soon, but, in some time, maybe the speed will increase noticeably on Python 3 over Python 2. They claim to have already increased speed on a 10% (on Python 2). Their objective is increasing the speed to 5x.\nFor more information, see PEP 3146\nEDIT: Just as Brian remarks, PEP 3146 was retired.\n", "Try refining the algorithms or changing the data structures used. That's usually the best way to get an increase in performance.\n", "I can't answer the root of your question, but if you read anything regarding the sluggish performance of the io module please disregard it. The were definitely performance issues in Python 3.0, but they were largely resolved in Python 3.1.\n", "I have phylogenetics analysis that takes a long time to run, and uses about a half-dozen python scripts as well as other bioinformatics software (muscle, clustal, blast, even R!). I use temp files to save intermediate results and a master script with the subprocess module to glue all the pieces together. It's easy to change the master to run only the modified parts that I want to test. But, if the changes are being made to early steps, and you only know how good it is at the end of the whole process, then this strategy wouldn't help much.\n" ]
[ 23, 5, 3, 2, 2 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0002112298_performance_python.txt
Q: assigning value to shell variable using a function return value from Python I have a Python function, fooPy() that returns some value. ( int / double or string) I want to use this value and assign it in a shell script. For example following is the python function: def fooPy(): return "some string" #return 10 .. alternatively, it can be an int fooPy() In the shell script I tried the following things but none of them work. fooShell = python fooPy.py #fooShell = $(python fooPy.py) #fooShell = echo "$(python fooPy.py)" A: You can print your value in Python, like this: print fooPy() and in your shell script: fooShell=$(python fooPy.py) Be sure not to leave spaces around the = in the shell script. A: In your Python code, you need to print the result. import sys def fooPy(): return 10 # or whatever if __name__ == '__main__': sys.stdout.write("%s\n", fooPy()) Then in the shell, you can do: fooShell=$(python fooPy.py) # note no space around the '=' Note that I added an if __name__ == '__main__' check in the Python code, to make sure that the printing is done only when your program is run from the command line, not when you import it from the Python interpreter. I also used sys.stdout.write() instead of print, because print has different behavior in Python 2 and Python 3, in "real programs", one should use sys.stdout.write() instead of print anyway :-) A: If you want the value from the Python sys.exit statement, it will be in the shell special variable $?. $ var=$(foo.py) $ returnval=$? $ echo $var Some string $ echo returnval 10 A: You should print the value returned by fooPy. The shell substitution reads from stdout. Replace the last line of your program with print fooPy() and then use the second shell pipeline you've mentioned. It should work.
assigning value to shell variable using a function return value from Python
I have a Python function, fooPy() that returns some value. ( int / double or string) I want to use this value and assign it in a shell script. For example following is the python function: def fooPy(): return "some string" #return 10 .. alternatively, it can be an int fooPy() In the shell script I tried the following things but none of them work. fooShell = python fooPy.py #fooShell = $(python fooPy.py) #fooShell = echo "$(python fooPy.py)"
[ "You can print your value in Python, like this:\nprint fooPy()\n\nand in your shell script:\nfooShell=$(python fooPy.py)\n\nBe sure not to leave spaces around the = in the shell script.\n", "In your Python code, you need to print the result.\nimport sys\ndef fooPy():\n return 10 # or whatever\n\nif __name__ == '__main__':\n sys.stdout.write(\"%s\\n\", fooPy())\n\nThen in the shell, you can do:\nfooShell=$(python fooPy.py) # note no space around the '='\n\nNote that I added an if __name__ == '__main__' check in the Python code, to make sure that the printing is done only when your program is run from the command line, not when you import it from the Python interpreter.\nI also used sys.stdout.write() instead of print, because\n\nprint has different behavior in Python 2 and Python 3,\nin \"real programs\", one should use sys.stdout.write() instead of print anyway :-)\n\n", "If you want the value from the Python sys.exit statement, it will be in the shell special variable $?.\n$ var=$(foo.py)\n$ returnval=$?\n$ echo $var\nSome string\n$ echo returnval\n10\n\n", "You should print the value returned by fooPy. The shell substitution reads from stdout. Replace the last line of your program with print fooPy() and then use the second shell pipeline you've mentioned. It should work.\n" ]
[ 34, 11, 5, 3 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0002115615_python_shell.txt
Q: Calling Python function in Django template Inside a django template I'm trying to call the split function on one of the template variables and then get the last element, so I did something like this: {{ newsletter.NewsletterPath.split('/').-1 }} Unfortunately, it doesn't like the split. Some might suggest that I do the split in the view, but I'm not sure how to do that because I need to do it for all of the records. It would be much easier if I could do it in the template. Is there a way to do this? A: From the django book: Note that you do not include parentheses in the method calls. Also, it’s not possible to pass arguments to the methods; you can only call methods that have no required arguments. So, if you want to call a method without arguments from a template, it's fine. Otherwise, you have to do it in the view. A: What do you mean by "it doesn't like the split"? How does it manifest its dislike? If I remember correctly, you can not pass any arbitrary arguments to methods, that are called from the django template and the identifiers, that can be used in the templates can only consist of a-z, A-Z, 0-9, underscores and dots (where dots signify lookup: dictionary->attribute->method->list-index). There are at least four ways to achieve what you want: make the appropriately prepared data available as an attribute of your model (or whatever that is), by pre-processing it make the data available as a method of your model and make sure, that the method takes no required arguments, besides self populate the model instances in the view for newsletter in newsletters: setattr(newsletter, 'basepath', newsletter.NewsletterPath.split('/')[-1]) (or something along these lines) implement a custom filter tag, that will handle the split (easier, than you might think) A: Templates are deliberately not able to do such stuff. The purpose is to prevent you from putting your business logic in templates, which are meant to deal only with the layout. So a possible way to do this is to define a NewsletterPathLastElement(self) function in your newsletter Model, and call that from the template. A: Yes, as others have said, you shouldn't really be doing it in the templates. But if you want to, then you need to define a filter and load it in the template and use it.
Calling Python function in Django template
Inside a django template I'm trying to call the split function on one of the template variables and then get the last element, so I did something like this: {{ newsletter.NewsletterPath.split('/').-1 }} Unfortunately, it doesn't like the split. Some might suggest that I do the split in the view, but I'm not sure how to do that because I need to do it for all of the records. It would be much easier if I could do it in the template. Is there a way to do this?
[ "From the django book:\n\nNote that you do not include parentheses in the method calls.\n Also, it’s not possible to pass arguments to the methods;\n you can only call methods that have no required arguments.\n\nSo, if you want to call a method without arguments from a template, it's fine.\n Otherwise, you have to do it in the view.\n", "What do you mean by \"it doesn't like the split\"? How does it manifest its dislike? \nIf I remember correctly, you can not pass any arbitrary arguments to methods, that are called from the django template and the identifiers, that can be used in the templates can only consist of a-z, A-Z, 0-9, underscores and dots (where dots signify lookup: dictionary->attribute->method->list-index).\nThere are at least four ways to achieve what you want:\n\nmake the appropriately prepared data available as an attribute of your model (or whatever that is), by pre-processing it\nmake the data available as a method of your model and make sure, that the method takes no required arguments, besides self\npopulate the model instances in the view\n for newsletter in newsletters:\n setattr(newsletter, 'basepath',\n newsletter.NewsletterPath.split('/')[-1])\n\n(or something along these lines)\nimplement a custom filter tag, that will handle the split (easier, than you might think)\n\n", "Templates are deliberately not able to do such stuff. The purpose is to prevent you from putting your business logic in templates, which are meant to deal only with the layout.\nSo a possible way to do this is to define a NewsletterPathLastElement(self) function in your newsletter Model, and call that from the template.\n", "Yes, as others have said, you shouldn't really be doing it in the templates.\nBut if you want to, then you need to define a filter and load it in the template and use it.\n" ]
[ 9, 6, 5, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002115869_django_django_templates_python.txt
Q: How to download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine? I have a python script running inside the Google App Engine with boto 1.9b that gets all keys inside a S3-Bucket. The output is formated as a HTML-Table. bucket_instance = conn_s3.get_bucket(bucketname) liste_keys = bucket_instance.get_all_keys() table = '<table>' for i in range(laenge_liste_keys): table = table + '<tr><td>'+str(liste_keys[i].name)+</td></tr>' table = '</table>' How can I realize the key-names as links that enable the user to download the key via the browser? Thanks in advance! A: The solution is found. generate_url(expires_in, method='GET', headers=None, query_auth=True, force_http=False) This makes it easy to create a link for every key which is valid for x seconds. A: The public URL for the file would be something like: http://s3.amazonaws.com/bucket_name/key_name So in your code, add links with their href attributes pointing to that URL.
How to download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine?
I have a python script running inside the Google App Engine with boto 1.9b that gets all keys inside a S3-Bucket. The output is formated as a HTML-Table. bucket_instance = conn_s3.get_bucket(bucketname) liste_keys = bucket_instance.get_all_keys() table = '<table>' for i in range(laenge_liste_keys): table = table + '<tr><td>'+str(liste_keys[i].name)+</td></tr>' table = '</table>' How can I realize the key-names as links that enable the user to download the key via the browser? Thanks in advance!
[ "The solution is found.\ngenerate_url(expires_in, method='GET', headers=None, query_auth=True, force_http=False)\n\nThis makes it easy to create a link for every key which is valid for x seconds. \n", "The public URL for the file would be something like: \nhttp://s3.amazonaws.com/bucket_name/key_name \n\nSo in your code, add links with their href attributes pointing to that URL. \n" ]
[ 3, 2 ]
[]
[]
[ "amazon_s3", "boto", "google_app_engine", "html", "python" ]
stackoverflow_0002113777_amazon_s3_boto_google_app_engine_html_python.txt
Q: XML to store system paths in Python with lxml I'm using an xml file to store configurations for a software. One of theese configurations would be a system path like > set_value = "c:\\test\\3 tests\\test" i can store it by using: > setting = etree.SubElement(settings, > "setting", name=tmp_set_name, type = > set_type , value= set_value) If I use doc.write(output_file, method='xml',encoding = 'utf-8', compression=0) the file would be: < setting type="str" name="MyPath" value="c:\test\3 tests\test"/> Now I read it again with the etree.parse method I obtain an etree child object with a string value, but the string contains the \3 character and if i try to use it to write again to xml it will be interpreted !!!!! So i cannot use it anymore as a path Maybe i'm only missing a simple string operation, but I cannot see it =) How would you solve it in a smart way ? This is an example, but what is the best way, you think to store paths in xml and parse them with lxml ? Thank you !! A: Now I read it again with the etree.parse method I obtain an etree child object with a string value, but the string contains the \3 character and if i try to use it to write again to xml it will be interpreted !!!!! I just tried that, and it doesn't get "interpreted". The elements attributes as returned after parsed is: {'type': 'str', 'name': 'yowza!', 'value': 'c:\\test\\3 tests\\test'} So as you see this works just as you expected it to work. If you really have this problem, you are doing something else than what you are saying. Show us the real code, or make a small example code where you demonstrate the problem and use that.
XML to store system paths in Python with lxml
I'm using an xml file to store configurations for a software. One of theese configurations would be a system path like > set_value = "c:\\test\\3 tests\\test" i can store it by using: > setting = etree.SubElement(settings, > "setting", name=tmp_set_name, type = > set_type , value= set_value) If I use doc.write(output_file, method='xml',encoding = 'utf-8', compression=0) the file would be: < setting type="str" name="MyPath" value="c:\test\3 tests\test"/> Now I read it again with the etree.parse method I obtain an etree child object with a string value, but the string contains the \3 character and if i try to use it to write again to xml it will be interpreted !!!!! So i cannot use it anymore as a path Maybe i'm only missing a simple string operation, but I cannot see it =) How would you solve it in a smart way ? This is an example, but what is the best way, you think to store paths in xml and parse them with lxml ? Thank you !!
[ "\nNow I read it again with the\n etree.parse method\nI obtain an etree child object with a\n string value, but the string contains\n the\n\\3\n\ncharacter and if i try to use it to\n write again to xml it will be\n interpreted !!!!!\n\nI just tried that, and it doesn't get \"interpreted\". The elements attributes as returned after parsed is:\n{'type': 'str', 'name': 'yowza!', 'value': 'c:\\\\test\\\\3 tests\\\\test'}\n\nSo as you see this works just as you expected it to work. If you really have this problem, you are doing something else than what you are saying. Show us the real code, or make a small example code where you demonstrate the problem and use that.\n" ]
[ 1 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0002116121_lxml_python_xml.txt
Q: Python EVT_SET_FOCUS When I run this code and focus on choice it is raise a error. I close this message but it is come back again. I want to see only one time this message. How can i do this? What is error in my code ? #! -*- coding:utf-8 -*- import wx class MyPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) sizer = wx.BoxSizer(wx.HORIZONTAL) self.my_choice = wx.Choice(self, wx.NewId()) self.my_button = wx.Button(self, wx.NewId(), label = "Procces") self.my_button.SetFocus() sizer.AddMany([(self.my_choice, 0, wx.ALL, 5), (self.my_button, 0, wx.ALL, 5)]) self.SetSizer(sizer) self.my_choice.Bind(wx.EVT_SET_FOCUS, self.my_choice_on_focus) self.my_button.Bind(wx.EVT_BUTTON, self.my_button_on_clicked) def my_choice_on_focus(self, evt): try: self.my_choice.Clear() print "Input some items in my_choice" raise RuntimeError except RuntimeError: dlg = wx.MessageDialog(self, "test EVT_SET_FOCUS", "Error", wx.ICON_ERROR|wx.OK ) dlg.ShowModal() dlg.Destroy() raise evt.Skip() def my_button_on_clicked(self, evt): print "Procces my choice value" evt.Skip() class MyApp(wx.App): def OnInit(self): frame = wx.Frame(None, title = "Test") panel = MyPanel(frame) frame.Show() self.SetTopWindow(frame) return True if __name__ == '__main__': app = MyApp(redirect = False) app.MainLoop() A: The error dialog gets the focus when it is shown. When you close the error dialog, the focus returns to the choice control, firing the event handler again, which pops up the error dialog again, et cetera. To avoid the event handler from being invoked multiple times, one solution would be to unbind the wx.EVT_SET_FOCUS. Another would be not to bind to wx.EVT_SET_FOCUS at all and do the action that you want to do in my_choice_on_focus somewhere else and/or at another moment in time. A: I solved my problem with following code. Thanks to everyone for help. #! -*- coding:utf-8 -*- import wx import wx.lib.evtmgr as em class MyPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) sizer = wx.BoxSizer(wx.HORIZONTAL) self.my_choice = wx.Choice(self, wx.NewId()) self.my_choice.Append("Make your selection") self.my_choice.Select(0) self.my_button = wx.Button(self, wx.NewId(), label = "Procces") self.my_button.SetFocus() sizer.AddMany([(self.my_choice, 0, wx.ALL, 5), (self.my_button, 0, wx.ALL, 5)]) self.SetSizer(sizer) em.eventManager.Register(self.my_choice_set_focus, wx.EVT_SET_FOCUS, self.my_choice) em.eventManager.Register(self.my_choice_on_select, wx.EVT_CHOICE, self.my_choice) em.eventManager.Register(self.my_button_on_clicked, wx.EVT_BUTTON, self.my_button) def my_choice_on_select(self, evt): if evt.GetSelection() <= 0: print "Procces false selection" em.eventManager.Register(self.my_choice_set_focus, wx.EVT_SET_FOCUS, self.my_choice) self.SetFocusIgnoringChildren() else: print "Procces true selection" evt.Skip() def my_choice_set_focus(self, evt): try: self.my_choice.Clear() self.my_choice.Append("Make your selection") raise RuntimeError except RuntimeError: em.eventManager.DeregisterListener(self.my_choice_set_focus) dlg = wx.MessageDialog(None, "test EVT_SET_FOCUS", "Error", wx.ICON_ERROR|wx.OK ) dlg.ShowModal() dlg.Destroy() self.my_choice.Clear() self.my_choice.Append("Try again...") self.my_choice.Select(0) evt.Skip() evt.Skip() def my_button_on_clicked(self, evt): print "Procces my choice value" evt.Skip() class MyApp(wx.App): def OnInit(self): frame = wx.Frame(None, title = "Test") panel = MyPanel(frame) frame.Show() self.SetTopWindow(frame) return True if __name__ == '__main__': app = MyApp(redirect = False) app.MainLoop()
Python EVT_SET_FOCUS
When I run this code and focus on choice it is raise a error. I close this message but it is come back again. I want to see only one time this message. How can i do this? What is error in my code ? #! -*- coding:utf-8 -*- import wx class MyPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) sizer = wx.BoxSizer(wx.HORIZONTAL) self.my_choice = wx.Choice(self, wx.NewId()) self.my_button = wx.Button(self, wx.NewId(), label = "Procces") self.my_button.SetFocus() sizer.AddMany([(self.my_choice, 0, wx.ALL, 5), (self.my_button, 0, wx.ALL, 5)]) self.SetSizer(sizer) self.my_choice.Bind(wx.EVT_SET_FOCUS, self.my_choice_on_focus) self.my_button.Bind(wx.EVT_BUTTON, self.my_button_on_clicked) def my_choice_on_focus(self, evt): try: self.my_choice.Clear() print "Input some items in my_choice" raise RuntimeError except RuntimeError: dlg = wx.MessageDialog(self, "test EVT_SET_FOCUS", "Error", wx.ICON_ERROR|wx.OK ) dlg.ShowModal() dlg.Destroy() raise evt.Skip() def my_button_on_clicked(self, evt): print "Procces my choice value" evt.Skip() class MyApp(wx.App): def OnInit(self): frame = wx.Frame(None, title = "Test") panel = MyPanel(frame) frame.Show() self.SetTopWindow(frame) return True if __name__ == '__main__': app = MyApp(redirect = False) app.MainLoop()
[ "The error dialog gets the focus when it is shown. When you close the error dialog, the focus returns to the choice control, firing the event handler again, which pops up the error dialog again, et cetera.\nTo avoid the event handler from being invoked multiple times, one solution would be to unbind the wx.EVT_SET_FOCUS. Another would be not to bind to wx.EVT_SET_FOCUS at all and do the action that you want to do in my_choice_on_focus somewhere else and/or at another moment in time.\n", "I solved my problem with following code.\nThanks to everyone for help.\n#! -*- coding:utf-8 -*-\nimport wx\nimport wx.lib.evtmgr as em \n\nclass MyPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.my_choice = wx.Choice(self, wx.NewId())\n self.my_choice.Append(\"Make your selection\")\n self.my_choice.Select(0)\n\n self.my_button = wx.Button(self, wx.NewId(), label = \"Procces\")\n self.my_button.SetFocus()\n\n sizer.AddMany([(self.my_choice, 0, wx.ALL, 5),\n (self.my_button, 0, wx.ALL, 5)])\n\n self.SetSizer(sizer)\n em.eventManager.Register(self.my_choice_set_focus, wx.EVT_SET_FOCUS, self.my_choice)\n em.eventManager.Register(self.my_choice_on_select, wx.EVT_CHOICE, self.my_choice)\n em.eventManager.Register(self.my_button_on_clicked, wx.EVT_BUTTON, self.my_button)\n\n\n def my_choice_on_select(self, evt):\n if evt.GetSelection() <= 0:\n print \"Procces false selection\"\n em.eventManager.Register(self.my_choice_set_focus,\n wx.EVT_SET_FOCUS,\n self.my_choice)\n self.SetFocusIgnoringChildren()\n else:\n print \"Procces true selection\"\n\n evt.Skip()\n\n def my_choice_set_focus(self, evt):\n try:\n self.my_choice.Clear()\n self.my_choice.Append(\"Make your selection\")\n raise RuntimeError\n except RuntimeError:\n em.eventManager.DeregisterListener(self.my_choice_set_focus)\n dlg = wx.MessageDialog(None, \"test EVT_SET_FOCUS\", \"Error\",\n wx.ICON_ERROR|wx.OK )\n dlg.ShowModal()\n dlg.Destroy()\n self.my_choice.Clear()\n self.my_choice.Append(\"Try again...\")\n self.my_choice.Select(0)\n evt.Skip()\n evt.Skip()\n\n def my_button_on_clicked(self, evt):\n print \"Procces my choice value\"\n evt.Skip()\n\nclass MyApp(wx.App):\n def OnInit(self):\n frame = wx.Frame(None, title = \"Test\")\n panel = MyPanel(frame)\n frame.Show()\n self.SetTopWindow(frame)\n return True\n\nif __name__ == '__main__':\n app = MyApp(redirect = False)\n app.MainLoop()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002107223_python_wxpython.txt
Q: Cannot solve mod_wsgi exception in Django setup I'm working with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end. I don't have direct access to the conf file but here's how its contents have been described to me: <IfModule mod_wsgi.c> WSGIScriptAlias /fredapp/ /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/ WSGIProcessGroup fred WSGIApplicationGroup %{GLOBAL} </IfModule> Alias /robots.txt /home/fred/public_html/fred-site/robots.txt Alias /favicon.ico /home/fred/public_html/fred-site/favicon.ico Alias /settings/media/ /home/fred/public_html/fred-site/media/ My "django.wsgi" script is nothing fancy: import os, sys sys.path.append('/home/fred/public_html/cgi-bin/') sys.path.append('/home/fred/public_html/cgi-bin/fredapp/') os.environ['DJANGO_SETTINGS_MODULE'] = 'fredapp.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() So my understanding is that all this means that if a request comes in for domain.com/fredapp/ that it should be turned over to the application via django.wsgi. However, the only response I get is: [Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/500.shtml [Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] mod_wsgi (pid=26760): Exception occurred processing WSGI script '/home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi'. [Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/404.shtml [Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain This is running under Apache on Linux. I have tried running each line of the .wsgi script in the Python interpreter on the server, and none of them return any errors. I also tried the sys.stdout = sys.stderr trick and got no further output than what is above. The File does not exist errors have to do with the rest of the site's set-up and occur on any request. I haven't finished setting all that up properly (error pages and index pages and so on) because I'm just trying to get the app itself to run. I've gotten this app up and running under Apache on my own machine, though NOT in Daemon mode, but it's my first Django app, and I don't think my hosting provider has ever configured one before, so we're flying a little blind. If anyone has any suggestions, I'd be very grateful. Thank you! A: If the quoted configuration about is what you are using, the error is rather obvious actually. You have: WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/ WSGIProcessGroup scratchf It should be: WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/ WSGIProcessGroup fred That is, the name of the process group must match. You should though have seen an error message: No WSGI daemon process called 'scratchf' has been configured This would likely be before the logged error: Exception occurred processing WSGI script This is why it is important that you supply all the error log messages and don't assume that they aren't relevant. Alternatively, you have quoted configuration different to what you are using or not all of the configuration. UPDATE 1 It looks like you may have ErrorDocument directive enabled in Apache to redirect errors to a specific URL. Because however you have mounted Django at root of web server and not excluded those error URLs from being passed through to Django, then when an error is generated Django gets the redirect for the error document but it cannot resolve the URL and subsequently generates a 404. Because Apache saw a 404 for error page redirect, it then returns a 500 default error page. The end result is that true original error and any information is lost. Thus, go into Apache configuration and comment out the ErrorDocument directives. UPDATE 2 Change configuration to: WSGIScriptAlias /fredapp /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi You should not have trailing slash on the second value on line. Missed that you were actually trying to mount at sub URL and not at root of web server. A: Is it possible that your starting directory is not the one project is in? Today I was also setting up Apache+mod_wsgi+Django app and after adding to django.wsgi: os.chdir('/home/user/my_django_project') everything started to work like a charm. A: We had the same error when the user running Apache had not the rights to read the files.
Cannot solve mod_wsgi exception in Django setup
I'm working with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end. I don't have direct access to the conf file but here's how its contents have been described to me: <IfModule mod_wsgi.c> WSGIScriptAlias /fredapp/ /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/ WSGIProcessGroup fred WSGIApplicationGroup %{GLOBAL} </IfModule> Alias /robots.txt /home/fred/public_html/fred-site/robots.txt Alias /favicon.ico /home/fred/public_html/fred-site/favicon.ico Alias /settings/media/ /home/fred/public_html/fred-site/media/ My "django.wsgi" script is nothing fancy: import os, sys sys.path.append('/home/fred/public_html/cgi-bin/') sys.path.append('/home/fred/public_html/cgi-bin/fredapp/') os.environ['DJANGO_SETTINGS_MODULE'] = 'fredapp.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() So my understanding is that all this means that if a request comes in for domain.com/fredapp/ that it should be turned over to the application via django.wsgi. However, the only response I get is: [Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/500.shtml [Fri Jan 22 18:46:08 2010] [error] [client xx.xxx.xx.xx] mod_wsgi (pid=26760): Exception occurred processing WSGI script '/home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi'. [Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain.com/404.shtml [Fri Jan 22 18:46:03 2010] [error] [client xx.xxx.xx.xx] File does not exist: /home/fred/public_html/domain This is running under Apache on Linux. I have tried running each line of the .wsgi script in the Python interpreter on the server, and none of them return any errors. I also tried the sys.stdout = sys.stderr trick and got no further output than what is above. The File does not exist errors have to do with the rest of the site's set-up and occur on any request. I haven't finished setting all that up properly (error pages and index pages and so on) because I'm just trying to get the app itself to run. I've gotten this app up and running under Apache on my own machine, though NOT in Daemon mode, but it's my first Django app, and I don't think my hosting provider has ever configured one before, so we're flying a little blind. If anyone has any suggestions, I'd be very grateful. Thank you!
[ "If the quoted configuration about is what you are using, the error is rather obvious actually. You have:\nWSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/\nWSGIProcessGroup scratchf\n\nIt should be:\nWSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/\nWSGIProcessGroup fred\n\nThat is, the name of the process group must match.\nYou should though have seen an error message:\nNo WSGI daemon process called 'scratchf' has been configured\n\nThis would likely be before the logged error:\nException occurred processing WSGI script\n\nThis is why it is important that you supply all the error log messages and don't assume that they aren't relevant.\nAlternatively, you have quoted configuration different to what you are using or not all of the configuration.\n\nUPDATE 1\nIt looks like you may have ErrorDocument directive enabled in Apache to redirect errors to a specific URL. Because however you have mounted Django at root of web server and not excluded those error URLs from being passed through to Django, then when an error is generated Django gets the redirect for the error document but it cannot resolve the URL and subsequently generates a 404. Because Apache saw a 404 for error page redirect, it then returns a 500 default error page. The end result is that true original error and any information is lost.\nThus, go into Apache configuration and comment out the ErrorDocument directives.\n\nUPDATE 2\nChange configuration to:\nWSGIScriptAlias /fredapp /home/fred/public_html/cgi-bin/fredapp/apache/django.wsgi\n\nYou should not have trailing slash on the second value on line. Missed that you were actually trying to mount at sub URL and not at root of web server.\n", "Is it possible that your starting directory is not the one project is in?\nToday I was also setting up Apache+mod_wsgi+Django app and after adding to django.wsgi:\n os.chdir('/home/user/my_django_project')\n\neverything started to work like a charm.\n", "We had the same error when the user running Apache had not the rights to read the files.\n" ]
[ 22, 1, 0 ]
[]
[]
[ "apache", "django", "python", "wsgi" ]
stackoverflow_0002113905_apache_django_python_wsgi.txt
Q: sum of bytes with unsigned long overflow in python how to translate this piece of C code into Python >=2.6 ? unsigned long memSum(unsigned char *p, unsigned long len) { unsigned long i, sum=0; for(i=0; i<len; i++) sum = sum + *p++; return sum; } of course f=open("file_to_sum",'rb') m = f.read() f.close() sum( array.array('B', m) ) does not work A: If you need to wrap around on overflow, simply take your sum modulo MAX_LONG at the end. A: A direct, Pythonic translation: def memSum(data): return sum(ord(c) for c in data) & 0xFFFFFFFF A: As I mentioned in my comment, you need to convert the string into a list of ints. This probably what you want: f=open("infile.txt",'rb') m=f.read() f.close() m=map(ord,list(m)) print sum(m) The ord function returns the ascii int corresponding to a character. A: I've tried your code, and seems to be working (it opens the data in binary, convert it to a list of unsigned char and adds all). What is your problem? Could be an overflow problem? Maybe there is a problem with the length? How are you saving the file? Sorry, but with this information we can only guess! The code is not equivalent, as the Python code seems to deal with files and the C code seems to deal with a memory array. A: You really need to give an example input and what you expect as output. Any code that uses a recent version of Python, extracts an integer in range(256) from each byte, sums those integers, and finally does total &= 0xFFFFFFFF should do the job (assuming that your unsigned long is 32 bits wide). Note that the last step ( the &=) is pointless if your file is less than about 16MB in size ... it won't overflow; 16843009 * 255 <= 0xFFFFFFFF < (16843009 + 1) * 255 That means that if your test file is smaller than 16843010 bytes, you must have a problem in your C code or your Python code or both. You said that "of course" this code: f=open("file_to_sum",'rb') m = f.read() f.close() sum( array.array('B', m) ) "doesn't work". Does it work if you replace the last line by print sum( array.array('B', m) ) ? If none of the above is of any help, and you want sensible answers instead of guesses, provide example input, expected output, C code, C output, Python code, Python output. Both the C code and the Python code should be standalone-runnable, and should include printing the size of the byte array being summed. A: first, thank you all for your help I have written successfully the C implementation and tested over 20 different files the checksum function. And then the 2 complement of the computed checksum is compared to a checksum a the file. It works perfectly in C as mentionned: with unsigned char and unsigned long. the right value of the sum is 3da4be70 (from C implementation) from your suggestions: print '%x' % ( sum( array.array('B', m[ o2+4:o2+len2 ]) ) ) and n = map(ord, list(m[ o2+4: o2+len2 ])) print '%x' % (sum(n)) give 504a022a I suppose it is because bytes here in python as interpreted as signed instead of unsigned (like in C)... update: even for i in range(o2+4, o2+len2): cchk = ( (cchk + unpack('B', m[i])[0]) & 0xffffffff) print '%x' % (cchk) does not work and gives again 504a022a A: SOLVED : MY FAULT, SORRY #include<stdio.h> unsigned long memSum(unsigned char *p, unsigned long len) { unsigned long i, sum=0; for(i=0; i<len; i++) sum = sum + *p++; return sum; } #define LEN2SUM (0xa13b10-4) int main(int argc, char *argv[] ) { FILE *f; unsigned char *buf; unsigned long sum; f=fopen("test2.dat", "rb"); fseek(f, 0x7c+4, SEEK_SET); buf = (unsigned char*)malloc(LEN2SUM); fread(buf, sizeof(char), LEN2SUM, f); sum = memSum( buf, LEN2SUM); printf("0x%08x\n", sum ); free(buf); fclose(f); } and f = open('test2.dat','rb') f.seek(0x7c+4) m = f.read(0xa13b10-4) print '%x' % ( ( sum(ord(c) for c in m) & 0xFFFFFFFF ) ) give the same answer, the good one the difference is that in C, i checksum a given memory area which contains decrypted data, where decryption has been done 'in place' in my python implementation, decryption is done in another buffer, and I still checksum the encrypted area. since my a beginner in python, I was focused on this point : bad track. i'm kicking my ass twenty times..... sorry for the stupid question and thanks again your kind help !!!
sum of bytes with unsigned long overflow in python
how to translate this piece of C code into Python >=2.6 ? unsigned long memSum(unsigned char *p, unsigned long len) { unsigned long i, sum=0; for(i=0; i<len; i++) sum = sum + *p++; return sum; } of course f=open("file_to_sum",'rb') m = f.read() f.close() sum( array.array('B', m) ) does not work
[ "If you need to wrap around on overflow, simply take your sum modulo MAX_LONG at the end.\n", "A direct, Pythonic translation:\ndef memSum(data):\n return sum(ord(c) for c in data) & 0xFFFFFFFF\n\n", "As I mentioned in my comment, you need to convert the string into a list of ints.\nThis probably what you want:\nf=open(\"infile.txt\",'rb')\nm=f.read()\nf.close()\nm=map(ord,list(m))\nprint sum(m)\n\nThe ord function returns the ascii int corresponding to a character.\n", "I've tried your code, and seems to be working (it opens the data in binary, convert it to a list of unsigned char and adds all). \nWhat is your problem? Could be an overflow problem? Maybe there is a problem with the length? How are you saving the file?\nSorry, but with this information we can only guess!\nThe code is not equivalent, as the Python code seems to deal with files and the C code seems to deal with a memory array.\n", "You really need to give an example input and what you expect as output. Any code that uses a recent version of Python, extracts an integer in range(256) from each byte, sums those integers, and finally does total &= 0xFFFFFFFF should do the job (assuming that your unsigned long is 32 bits wide).\nNote that the last step ( the &=) is pointless if your file is less than about 16MB in size ... it won't overflow; 16843009 * 255 <= 0xFFFFFFFF < (16843009 + 1) * 255\nThat means that if your test file is smaller than 16843010 bytes, you must have a problem in your C code or your Python code or both.\nYou said that \"of course\" this code:\nf=open(\"file_to_sum\",'rb')\nm = f.read()\nf.close()\nsum( array.array('B', m) )\n\n\"doesn't work\". Does it work if you replace the last line by \nprint sum( array.array('B', m) )\n\n?\nIf none of the above is of any help, and you want sensible answers instead of guesses, provide example input, expected output, C code, C output, Python code, Python output. Both the C code and the Python code should be standalone-runnable, and should include printing the size of the byte array being summed.\n", "first, thank you all for your help\nI have written successfully the C implementation and tested over 20 different files the checksum function. And then the 2 complement of the computed checksum is compared to a checksum a the file. It works perfectly in C as mentionned: with unsigned char and unsigned long.\nthe right value of the sum is 3da4be70 (from C implementation)\nfrom your suggestions:\nprint '%x' % ( sum( array.array('B', m[ o2+4:o2+len2 ]) ) )\n\nand\nn = map(ord, list(m[ o2+4: o2+len2 ]))\nprint '%x' % (sum(n))\n\ngive 504a022a\nI suppose it is because bytes here in python as interpreted as signed instead of unsigned (like in C)...\nupdate:\neven\nfor i in range(o2+4, o2+len2):\n cchk = ( (cchk + unpack('B', m[i])[0]) & 0xffffffff)\nprint '%x' % (cchk)\n\ndoes not work and gives again 504a022a\n", "SOLVED : MY FAULT, SORRY\n#include<stdio.h>\n\nunsigned long memSum(unsigned char *p, unsigned long len)\n{\n unsigned long i, sum=0;\n\n for(i=0; i<len; i++) \n sum = sum + *p++;\n\n return sum;\n} \n\n#define LEN2SUM (0xa13b10-4)\n\nint main(int argc, char *argv[] )\n{\n\n FILE *f;\n unsigned char *buf;\n unsigned long sum;\n\n f=fopen(\"test2.dat\", \"rb\");\n fseek(f, 0x7c+4, SEEK_SET); \n\n buf = (unsigned char*)malloc(LEN2SUM);\n fread(buf, sizeof(char), LEN2SUM, f);\n sum = memSum( buf, LEN2SUM);\n printf(\"0x%08x\\n\", sum );\n\n free(buf); \n fclose(f);\n\n\n}\n\nand \nf = open('test2.dat','rb')\nf.seek(0x7c+4)\n\nm = f.read(0xa13b10-4)\nprint '%x' % ( ( sum(ord(c) for c in m) & 0xFFFFFFFF ) )\n\ngive the same answer, the good one\nthe difference is that in C, i checksum a given memory area which contains decrypted data, where decryption has been done 'in place'\nin my python implementation, decryption is done in another buffer, and I still checksum the encrypted area.\nsince my a beginner in python, I was focused on this point : bad track.\ni'm kicking my ass twenty times.....\nsorry for the stupid question and thanks again your kind help !!!\n" ]
[ 3, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "byte", "overflow", "python", "sum" ]
stackoverflow_0002113118_byte_overflow_python_sum.txt
Q: Create string(s) from list(s) items I have a list, list = ['foo','bar'] and now i want to create a string from each item. Each string is named as the item and has the value of the item foo = 'foo' bar = 'bar' Thanks to all, i will use a dict instead A: Don't do that. Use a dict instead. strings = dict((x, x) for x in L) A: Ignacio Vazquez-Abrams is right, using a dict is better. But if you insist on having them available as variables, you can always do this: strings = dict((x, x) for x in L) locals().update(strings) PS: Edan Maor's version with exec has a security issue. It won't handle ["foo", "';__import__('os').system('rm -rf ~');'"], for example :) A: Try: >>> l = ["foo", "bar"] >>> for item in l: exec("%s = '%s'" % (item, item)) Note: Why do you need this? Are you sure this is the best way to do what you want to do? I ask because this is usually not such a great idea. Security Warning: As pointed out by Attila Oláh, running arbitrary code using "exec" is a very bad idea. Only use this if you're in control of the string in the list (and they're not, for example, input from the user). A: In spite of their names, variables in Python should in fact not themselves be variable. If you have data you want to associate with a 'name', you should be using a dict instead: data = {} for s in ['foo', 'bar']: data[s] = s It is sometimes(!) possible to modify locals() to introduce new variables, but since you would have no sensible way of referring to them (as you don't know their name when you write the code) there's really no value in it. All it does is make your code a lot slower and much harder to understand. A: Take a look at http://docs.python.org/library/functions.html#setattr You should be able to do something along the lines of for x in list: setattr(object, x, x) Assuming object is whatever object you wanted to add the attributes to.
Create string(s) from list(s) items
I have a list, list = ['foo','bar'] and now i want to create a string from each item. Each string is named as the item and has the value of the item foo = 'foo' bar = 'bar' Thanks to all, i will use a dict instead
[ "Don't do that. Use a dict instead.\nstrings = dict((x, x) for x in L)\n\n", "Ignacio Vazquez-Abrams is right, using a dict is better. But if you insist on having them available as variables, you can always do this:\nstrings = dict((x, x) for x in L)\nlocals().update(strings)\n\nPS: Edan Maor's version with exec has a security issue. It won't handle [\"foo\", \"';__import__('os').system('rm -rf ~');'\"], for example :)\n", "Try:\n>>> l = [\"foo\", \"bar\"]\n>>> for item in l:\n exec(\"%s = '%s'\" % (item, item))\n\nNote: Why do you need this? Are you sure this is the best way to do what you want to do? I ask because this is usually not such a great idea.\nSecurity Warning: As pointed out by Attila Oláh, running arbitrary code using \"exec\" is a very bad idea. Only use this if you're in control of the string in the list (and they're not, for example, input from the user).\n", "In spite of their names, variables in Python should in fact not themselves be variable. If you have data you want to associate with a 'name', you should be using a dict instead:\ndata = {}\nfor s in ['foo', 'bar']:\n data[s] = s\n\nIt is sometimes(!) possible to modify locals() to introduce new variables, but since you would have no sensible way of referring to them (as you don't know their name when you write the code) there's really no value in it. All it does is make your code a lot slower and much harder to understand.\n", "Take a look at http://docs.python.org/library/functions.html#setattr\nYou should be able to do something along the lines of\nfor x in list:\n setattr(object, x, x)\n\nAssuming object is whatever object you wanted to add the attributes to.\n" ]
[ 9, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002116597_python.txt
Q: Python XML Parsing Confusion I'm using xml.dom.mindom in Python and have retrieved the book node in the below XML tree. I want to get a list of all children nodes. In this case, I would think there would only be one. <Book> <Title>Why is this so hard</Title> </Book When I call: nodeList = bookNode.childNodes print "nodeList has " + str(nodeList.length) + " elements" for node in nodeList: print "Found a " + node.nodeName + " node" I get the following output: nodeList has 3 elements Found a #text node Found a Book node Found a #text node What are these random #text nodes? How do I get the tagName and value for each of the legitimate nodes? I want to get a list of key->value pairs for each of the nodes under Book. I don't want to use getElementsByName because I will not know all of the tagNames ahead of time. Book -> "Why is this so hard" Thanks- Jonathan A: The first text node is the whitespace between <Book> and <Title>. The second is the whitespace between </Title> and </Book> A: What are these random #text nodes? Hardly random, they're text nodes representing the whitespace you put between tags. XML has to remember this, or the document would be all run together in one unreadable line when it's reserialised. How do I get the tagName and value for each of the legitimate nodes? Loop over the child nodes, ignoring those that aren't elements. I want to get a list of key->value pairs for each of the nodes under Book. book= {} for child in bookNode.childNodes: if child.nodeType==child.ELEMENT_NODE: book[child.tagName]= '' if child.firstChild is None else child.firstChild.data This assumes that every element contains only a single text node.
Python XML Parsing Confusion
I'm using xml.dom.mindom in Python and have retrieved the book node in the below XML tree. I want to get a list of all children nodes. In this case, I would think there would only be one. <Book> <Title>Why is this so hard</Title> </Book When I call: nodeList = bookNode.childNodes print "nodeList has " + str(nodeList.length) + " elements" for node in nodeList: print "Found a " + node.nodeName + " node" I get the following output: nodeList has 3 elements Found a #text node Found a Book node Found a #text node What are these random #text nodes? How do I get the tagName and value for each of the legitimate nodes? I want to get a list of key->value pairs for each of the nodes under Book. I don't want to use getElementsByName because I will not know all of the tagNames ahead of time. Book -> "Why is this so hard" Thanks- Jonathan
[ "The first text node is the whitespace between <Book> and <Title>. The second is the whitespace between </Title> and </Book>\n", "\nWhat are these random #text nodes?\n\nHardly random, they're text nodes representing the whitespace you put between tags. XML has to remember this, or the document would be all run together in one unreadable line when it's reserialised.\n\nHow do I get the tagName and value for each of the legitimate nodes?\n\nLoop over the child nodes, ignoring those that aren't elements.\n\nI want to get a list of key->value pairs for each of the nodes under Book.\n\nbook= {}\nfor child in bookNode.childNodes:\n if child.nodeType==child.ELEMENT_NODE:\n book[child.tagName]= '' if child.firstChild is None else child.firstChild.data\n\nThis assumes that every element contains only a single text node.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002113917_python_xml.txt
Q: How can I check compilation errors in python? #!/usr/bin/python str = "this" if(1): print "Hi" else: print str.any_random_function() This doesn't fail when I run the program. I tried py_compile but that didn't indicate the error in the else loop either. Now how can I compile the program and detect errors reliably in python code? A: I think your best bet would be pylint. A: Python is a dynamic language, so you can't simply check for compiling errors like in static languages (C/C++/Java). If you assign str.any_random_function, the above code would be correct (okay that's a bad example...). I'd suggest you to use PyDev for Eclipse which automatically finds many common problems in your code, like missing functions/modules etc. It also supports pylint (optional).
How can I check compilation errors in python?
#!/usr/bin/python str = "this" if(1): print "Hi" else: print str.any_random_function() This doesn't fail when I run the program. I tried py_compile but that didn't indicate the error in the else loop either. Now how can I compile the program and detect errors reliably in python code?
[ "I think your best bet would be pylint.\n", "Python is a dynamic language, so you can't simply check for compiling errors like in static languages (C/C++/Java). If you assign str.any_random_function, the above code would be correct (okay that's a bad example...).\nI'd suggest you to use PyDev for Eclipse which automatically finds many common problems in your code, like missing functions/modules etc. It also supports pylint (optional).\n" ]
[ 9, 3 ]
[]
[]
[ "compilation", "python" ]
stackoverflow_0002117586_compilation_python.txt
Q: How can I query objects with a date field, using a specific month and year? I need to make a gql query against a set of some objects which have a date field. I am very new to python and also the GAE so I am a bit igorant to this. I am looking in the documentation but cannot find quite what I am looking for. Basically I have made the following class method Event.getEventsForMonth(cls, month,year): So I am trying to query my object where the month and year of the date field fall in a specified range. I have tried to create a date object and use that for the comparison but I have had no joy so far. dateto = str(year)+str(month+1)+"01" datefrom = str(year)+str(month)+"01" if month + 1 == 13: dateto = str(year+1)+"01"+"01" query = GqlQuery("SELECT * FROM Event WHERE date >= :datefrom AND date <= :dateto", dateto=dateto, datefrom=datefrom) return query This method to me looks awful, as I am not very up on the core methods I can use from Python inline with the GQL Query. Any help is appreciated Cheers, Andrew A: First, store your dates as DateProperty or DateTimeProperty instances in the datastore. Then, you can do your query something like this: def getEventsForMonth(self, month, year): start_date = datetime.datetime(year, month, 1) if month == 12: end_date = datetime.datetime(year + 1, 1, 1) else: end_date = datetime.datetime(year, month + 1, 1) return Events.all().filter('date >=', start_date).filter('date <=', end_date).fetch(1000)
How can I query objects with a date field, using a specific month and year?
I need to make a gql query against a set of some objects which have a date field. I am very new to python and also the GAE so I am a bit igorant to this. I am looking in the documentation but cannot find quite what I am looking for. Basically I have made the following class method Event.getEventsForMonth(cls, month,year): So I am trying to query my object where the month and year of the date field fall in a specified range. I have tried to create a date object and use that for the comparison but I have had no joy so far. dateto = str(year)+str(month+1)+"01" datefrom = str(year)+str(month)+"01" if month + 1 == 13: dateto = str(year+1)+"01"+"01" query = GqlQuery("SELECT * FROM Event WHERE date >= :datefrom AND date <= :dateto", dateto=dateto, datefrom=datefrom) return query This method to me looks awful, as I am not very up on the core methods I can use from Python inline with the GQL Query. Any help is appreciated Cheers, Andrew
[ "First, store your dates as DateProperty or DateTimeProperty instances in the datastore.\nThen, you can do your query something like this:\ndef getEventsForMonth(self, month, year):\n start_date = datetime.datetime(year, month, 1)\n if month == 12:\n end_date = datetime.datetime(year + 1, 1, 1)\n else:\n end_date = datetime.datetime(year, month + 1, 1)\n return Events.all().filter('date >=', start_date).filter('date <=', end_date).fetch(1000)\n\n" ]
[ 3 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002117056_django_google_app_engine_python.txt
Q: Is there any metaprogramming patterns catalog for Python? I have just read Python Cookbook. The book is amazing. I think the best use of this book is that it provides lots of examples that show python in real problem applications. Many of the idioms include metaprogramming techniques. I wonder if there is any catalog that summarizes metaprogramming idioms in Python? Python Cookbook is very rich in examples and techniques. But I think there is also a need for a pattern catalog that gives specific names for each technique and that abstracts the main features of the solution technique from the concrete application area as the Design Patterns book of Gang of Four does. A: A Primer on Python Metaclass Programming. http://www.ibm.com/developerworks/linux/library/l-pymeta.html
Is there any metaprogramming patterns catalog for Python?
I have just read Python Cookbook. The book is amazing. I think the best use of this book is that it provides lots of examples that show python in real problem applications. Many of the idioms include metaprogramming techniques. I wonder if there is any catalog that summarizes metaprogramming idioms in Python? Python Cookbook is very rich in examples and techniques. But I think there is also a need for a pattern catalog that gives specific names for each technique and that abstracts the main features of the solution technique from the concrete application area as the Design Patterns book of Gang of Four does.
[ "\nA Primer on Python Metaclass Programming.\nhttp://www.ibm.com/developerworks/linux/library/l-pymeta.html\n\n" ]
[ 4 ]
[]
[]
[ "design_patterns", "idioms", "metaprogramming", "python" ]
stackoverflow_0002117927_design_patterns_idioms_metaprogramming_python.txt
Q: Python List Exclusions I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this for y in myDict: print(y+"\t"+myDict[y]) I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok like this for x in myList: print(x) Now I want to remove occurrences of key val pairs in the dictionary where the keys are the list values. I tried this for x in myList: for y in myDict: if x != y: print(y+"\t"+myDict[y]) but on each pass through the list it lets all the others apart from the current `x to the screen Is there a nice python way to remove the key val pairs from the dictionary if the key exists in the list? A: Do you mean for key in myDict: if key not in myList: print(key+"\t"+myDict[key]) Or one of many alternatives: for key in (set(myDict)-set(myList)): print(key+"\t"+myDict[key]) A: mySet = set(myList) myNewDict = dict(((k, v) for k, v in myDict if k not in mySet)) Note that using mySet instead of myList isn't a concern unless myList has a large number of entries.
Python List Exclusions
I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this for y in myDict: print(y+"\t"+myDict[y]) I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok like this for x in myList: print(x) Now I want to remove occurrences of key val pairs in the dictionary where the keys are the list values. I tried this for x in myList: for y in myDict: if x != y: print(y+"\t"+myDict[y]) but on each pass through the list it lets all the others apart from the current `x to the screen Is there a nice python way to remove the key val pairs from the dictionary if the key exists in the list?
[ "Do you mean\nfor key in myDict:\n if key not in myList:\n print(key+\"\\t\"+myDict[key])\n\nOr one of many alternatives:\nfor key in (set(myDict)-set(myList)):\n print(key+\"\\t\"+myDict[key])\n\n", "mySet = set(myList)\nmyNewDict = dict(((k, v) for k, v in myDict if k not in mySet))\n\nNote that using mySet instead of myList isn't a concern unless myList has a large number of entries.\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002118503_python.txt
Q: Python :: How to open a page in the Non Default browser I was trying to create a simple script to open a locally hosted web site for testing the css in 2 or more browsers. The default browser is IE7 and it opens the page fine but when I try to open a non default browser such as Firefox or Arora it just fails. I am using the webbrowser module and have tried this several way as detailed in various sites across the web. Is it possible and if so how? A: Matt's right and it's a pretty useful module to know... 18.1. subprocess IDLE 2.6.2 >>> import subprocess >>> chrome = 'C:\Users\Ted\AppData\Local\Google\Chrome\Application\chrome.exe' >>> chrome_args = 'www.rit.edu' >>> spChrome = subprocess.Popen(chrome+' '+chrome_args) >>> print spChrome.pid 2124 A: The subprocess module should provide what you want if you feed subprocess the path to the browser. Note that you need Python 2.4 or later to use subprocess, but that's common nowadays. Update - code for a method to call Chrome, while opening a passed in URL: def startChrome(url): """ Calls Chrome, opening the URL contained in the url parameter. """ executable = 'path-to-chrome' # Change to fit your system cmd = ' '.join([executable, url]) browswer_proc = subprocess.Popen(cmd, shell=True) A: This basically boils down to: - run 'firefox "url"' - run 'iexplore "url"' - run 'other_browser "url"' I don't know enough python to know how the system() call is implemented there but it should be quite simple.
Python :: How to open a page in the Non Default browser
I was trying to create a simple script to open a locally hosted web site for testing the css in 2 or more browsers. The default browser is IE7 and it opens the page fine but when I try to open a non default browser such as Firefox or Arora it just fails. I am using the webbrowser module and have tried this several way as detailed in various sites across the web. Is it possible and if so how?
[ "Matt's right and it's a pretty useful module to know...\n18.1. subprocess\nIDLE 2.6.2 \n>>> import subprocess\n>>> chrome = 'C:\\Users\\Ted\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'\n>>> chrome_args = 'www.rit.edu'\n>>> spChrome = subprocess.Popen(chrome+' '+chrome_args)\n>>> print spChrome.pid\n2124\n\n", "The subprocess module should provide what you want if you feed subprocess the path to the browser. Note that you need Python 2.4 or later to use subprocess, but that's common nowadays.\nUpdate - code for a method to call Chrome, while opening a passed in URL:\ndef startChrome(url):\n \"\"\" Calls Chrome, opening the URL contained in the url parameter. \"\"\"\n executable = 'path-to-chrome' # Change to fit your system\n cmd = ' '.join([executable, url])\n browswer_proc = subprocess.Popen(cmd, shell=True)\n\n", "This basically boils down to:\n- run 'firefox \"url\"'\n- run 'iexplore \"url\"'\n- run 'other_browser \"url\"'\n\nI don't know enough python to know how the system() call is implemented there but it should be quite simple.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0002117545_browser_python.txt
Q: SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0]? How? I'm trying to help a colleague run SOATest (a web services client that makes testing SOAP services easy) on a WCF web service operation, and for "big" responses, we are seeing this error: SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0] This is perplexing, as the tool is actually able to get a response from the server that contains no SOAP faults. Furthermore, the response isn't very big at all - 22kb to be exact. I can't seem to Google this error message, and the the grammar/spelling mistake in it isn't working for my benefit either. Is this a SOATest setting? Maybe a WCF setting? Or a WS-Security setting? It certainly isn't a restriction we are imposing at the server level. Here's a screenshot for posterity. A: We were able to get an answer to this error on the SOATest forums. SECURITY.MSGSIZE is one of the default SOAP Policy rule checks available to be added to a response. Here's a screenshot of the particular rule as it was being applied. This particular rule is located at: C:\Program Files\Parasoft\SOAtest\5.5.3\rules\SOAP\SECURITY.MSGSIZE.rule If you open the default policy configuration package located at: C:\Program Files\Parasoft\SOAtest\5.5.3\rules\soa.policy you can then disable or modify the value of the SECURITY.MSGSIZE rule by if you right click on SOAP->Avoid large SOAP messages [SECURITY.MSGSIZE]->Edit->Method: def checkSize(value, context): message = XMLUtil.serialize(value) size = len(message) if size > 10240: return 1 else: return 0 The size > 10240 conditional is where this rule can be changed as needed. Or you could simply uncheck it as part of the default policy package and save the change that way instead.
SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0]? How?
I'm trying to help a colleague run SOATest (a web services client that makes testing SOAP services easy) on a WCF web service operation, and for "big" responses, we are seeing this error: SOAP Message size it greater than allowed limit [SECURITY.MSGSIZE v 1.0] This is perplexing, as the tool is actually able to get a response from the server that contains no SOAP faults. Furthermore, the response isn't very big at all - 22kb to be exact. I can't seem to Google this error message, and the the grammar/spelling mistake in it isn't working for my benefit either. Is this a SOATest setting? Maybe a WCF setting? Or a WS-Security setting? It certainly isn't a restriction we are imposing at the server level. Here's a screenshot for posterity.
[ "We were able to get an answer to this error on the SOATest forums.\nSECURITY.MSGSIZE is one of the default SOAP Policy rule checks available to be added to a response. Here's a screenshot of the particular rule as it was being applied. This particular rule is located at:\nC:\\Program Files\\Parasoft\\SOAtest\\5.5.3\\rules\\SOAP\\SECURITY.MSGSIZE.rule\n\nIf you open the default policy configuration package located at:\nC:\\Program Files\\Parasoft\\SOAtest\\5.5.3\\rules\\soa.policy\n\nyou can then disable or modify the value of the SECURITY.MSGSIZE rule by if you right click on SOAP->Avoid large SOAP messages [SECURITY.MSGSIZE]->Edit->Method:\ndef checkSize(value, context):\n message = XMLUtil.serialize(value)\n size = len(message)\n if size > 10240:\n return 1\n else:\n return 0\n\nThe size > 10240 conditional is where this rule can be changed as needed. Or you could simply uncheck it as part of the default policy package and save the change that way instead.\n" ]
[ 0 ]
[]
[]
[ "policy", "python", "rule", "soap" ]
stackoverflow_0002105037_policy_python_rule_soap.txt
Q: What are the cons of returning an Exception instance instead of raising it in Python? I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following: def update(self, documents, **options): """Perform a bulk update or insertion of the given documents using a single HTTP request. >>> server = Server('http://localhost:5984/') >>> db = server.create('python-tests') >>> for doc in db.update([ ... Document(type='Person', name='John Doe'), ... Document(type='Person', name='Mary Jane'), ... Document(type='City', name='Gotham City') ... ]): ... print repr(doc) #doctest: +ELLIPSIS (True, '...', '...') (True, '...', '...') (True, '...', '...') >>> del server['python-tests'] The return value of this method is a list containing a tuple for every element in the `documents` sequence. Each tuple is of the form ``(success, docid, rev_or_exc)``, where ``success`` is a boolean indicating whether the update succeeded, ``docid`` is the ID of the document, and ``rev_or_exc`` is either the new document revision, or an exception instance (e.g. `ResourceConflict`) if the update failed. If an object in the documents list is not a dictionary, this method looks for an ``items()`` method that can be used to convert the object to a dictionary. Effectively this means you can also use this method with `schema.Document` objects. :param documents: a sequence of dictionaries or `Document` objects, or objects providing a ``items()`` method that can be used to convert them to a dictionary :return: an iterable over the resulting documents :rtype: ``list`` :since: version 0.2 """ As you can see, this function does not raise the exceptions that have been raised by the couchdb server but it rather returns them in a tuple with the id of the document that we wanted to update. One of the reviewers went to #python on irc to ask about the matter. In #python they recommended to use sentinel values rather than exceptions. As you can imaging just an approach is not practical since there are lots of possible exceptions that can be received. My questions is, what are the cons of using Exceptions over sentinel values besides that using exceptions is uglier? A: I think it is ok to return the exceptions in this case, because some parts of the update function may succeed and some may fail. When you raise the exception, the API user has no control over what succeeded already. A: Raising an Exception is a notification that something that was expected to work did not work. It breaks the program flow, and should only be done if whatever is going on now is flawed in a way that the program doesn't know how to handle. But sometimes you want to raise a little error flag without breaking program flow. You can do this by returning special values, and these values can very well be exceptions. Python does this internally in one case. When you compare two values like foo < bar, the actual call is foo.__lt__(bar). If this method raises an exception, program flow will be broken, as expected. But if it returns NotImplemented, Python will then try bar.__ge__(foo) instead. So in this case returning the exception rather than raising it is used to flag that it didn't work, but in an expected way. It's really the difference between an expected error and an unexpected one, IMO. A: exceptions intended to be raised. It helps with debugging, handling causes of the errors and it's clear and well-established practise of other developers. I think looking at the interface of the programme, it's not clear what am I supposed to do with returned exception. raise it? from outside of the chain that actually caused it? it seems a bit convoluted. I'd suggest, returning docid, new_rev_doc tuple on success and propagating/raising exception as it is. Your approach duplicates success and type of 3rd returned value too. A: Exceptions cause the normal program flow to break; then exceptions go up the call stack until they're intercept, or they may reach the top if they aren't. Hence they're employed to mark a really special condition that should be handled by the caller. Raising an exception is useful since the program won't continue if a necessary condition has not been met. In languages that don't support exceptions (like C) you're often forced to check return values of functions to verify everything went on correctly; otherwise the program may misbehave. By the way the update() is a bit different: it takes multiple arguments; some may fail, some may succeed, hence it needs a way to communicate results for each arg. a previous failure has no relation with operations coming next, e.g. it is not a permanent error In that situation raising an exception would NOT be usueful in an API. On the other hand, if the connection to the db drops while executing the query, then an exception is the way to go (since it's a permament error and would impact all operations coming next). By the way if your business logic requires all operations to complete successfully and you don't know what to do when an update fails (i.e. your design says it should never happen), feel free to raise an exception in your own code.
What are the cons of returning an Exception instance instead of raising it in Python?
I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following: def update(self, documents, **options): """Perform a bulk update or insertion of the given documents using a single HTTP request. >>> server = Server('http://localhost:5984/') >>> db = server.create('python-tests') >>> for doc in db.update([ ... Document(type='Person', name='John Doe'), ... Document(type='Person', name='Mary Jane'), ... Document(type='City', name='Gotham City') ... ]): ... print repr(doc) #doctest: +ELLIPSIS (True, '...', '...') (True, '...', '...') (True, '...', '...') >>> del server['python-tests'] The return value of this method is a list containing a tuple for every element in the `documents` sequence. Each tuple is of the form ``(success, docid, rev_or_exc)``, where ``success`` is a boolean indicating whether the update succeeded, ``docid`` is the ID of the document, and ``rev_or_exc`` is either the new document revision, or an exception instance (e.g. `ResourceConflict`) if the update failed. If an object in the documents list is not a dictionary, this method looks for an ``items()`` method that can be used to convert the object to a dictionary. Effectively this means you can also use this method with `schema.Document` objects. :param documents: a sequence of dictionaries or `Document` objects, or objects providing a ``items()`` method that can be used to convert them to a dictionary :return: an iterable over the resulting documents :rtype: ``list`` :since: version 0.2 """ As you can see, this function does not raise the exceptions that have been raised by the couchdb server but it rather returns them in a tuple with the id of the document that we wanted to update. One of the reviewers went to #python on irc to ask about the matter. In #python they recommended to use sentinel values rather than exceptions. As you can imaging just an approach is not practical since there are lots of possible exceptions that can be received. My questions is, what are the cons of using Exceptions over sentinel values besides that using exceptions is uglier?
[ "I think it is ok to return the exceptions in this case, because some parts of the update function may succeed and some may fail. When you raise the exception, the API user has no control over what succeeded already.\n", "Raising an Exception is a notification that something that was expected to work did not work. It breaks the program flow, and should only be done if whatever is going on now is flawed in a way that the program doesn't know how to handle.\nBut sometimes you want to raise a little error flag without breaking program flow. You can do this by returning special values, and these values can very well be exceptions.\nPython does this internally in one case. When you compare two values like foo < bar, the actual call is foo.__lt__(bar). If this method raises an exception, program flow will be broken, as expected. But if it returns NotImplemented, Python will then try bar.__ge__(foo) instead. So in this case returning the exception rather than raising it is used to flag that it didn't work, but in an expected way.\nIt's really the difference between an expected error and an unexpected one, IMO.\n", "exceptions intended to be raised. It helps with debugging, handling causes of the errors and it's clear and well-established practise of other developers.\nI think looking at the interface of the programme, it's not clear what am I supposed to do with returned exception. raise it? from outside of the chain that actually caused it? it seems a bit convoluted.\nI'd suggest, returning docid, new_rev_doc tuple on success and propagating/raising exception as it is. Your approach duplicates success and type of 3rd returned value too.\n", "Exceptions cause the normal program flow to break; then exceptions go up the call stack until they're intercept, or they may reach the top if they aren't. Hence they're employed to mark a really special condition that should be handled by the caller. Raising an exception is useful since the program won't continue if a necessary condition has not been met.\nIn languages that don't support exceptions (like C) you're often forced to check return values of functions to verify everything went on correctly; otherwise the program may misbehave.\nBy the way the update() is a bit different:\n\nit takes multiple arguments; some may fail, some may succeed, hence it needs a way to communicate results for each arg.\na previous failure has no relation with operations coming next, e.g. it is not a permanent error\n\nIn that situation raising an exception would NOT be usueful in an API. On the other hand, if the connection to the db drops while executing the query, then an exception is the way to go (since it's a permament error and would impact all operations coming next).\nBy the way if your business logic requires all operations to complete successfully and you don't know what to do when an update fails (i.e. your design says it should never happen), feel free to raise an exception in your own code.\n" ]
[ 4, 2, 1, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002116972_exception_python.txt
Q: os.listdir etc fails on shared windows path (Python 2.5) I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds) I am reading text file which contains directory paths which I want to process further. In order to do so I do as below: def toWin(path): return path.replace("\\", "\\\\") for line in open(fileName): l = toWin(line).strip() if os.path.isdir(l): print l # os.listdir(l) etc.. This works for local directories but fails for paths specified on shared system. e.g. E:\Test -- works \\StorageMachine\Test -- fails [internally converts to \\\\StorageMachine\\Test] \\StorageMachine\Test\ -- fails [internally converts to \\\\StorageMachine\\Test\\] But if I open python shell, import script and invoke function with same path string then it works! It seems that parsing windows shared paths is behaving differently in both cases. Any ideas/suggestions? A: This may not be your actual issue, but your UNC paths are actually not correct - they should start with a double backslash, but internally only use a single backslash as a divider. I'm not sure why the same thing would be working within the shell. Update: I suspect that what's happening is that in the shell, your string is being interpreted by the shell (with replacements happening) while in your code it's being treated as seen for the first time - basically, specifying the string in the shell is different from reading it from an input. To get the same effect from the shell, you'd need to specify it as a raw string with r"string" A: There is simply no reason to "convert". Backslashes are only interpreted when they are contained in string literals in your code, not when you read them programmatically from a file. Therefore, you should disable your conversion function and things will probably work. A: Have to convert input to forward slash (unix-style) for os.* modules to parse correctly. changed code as below def toUnix(path): return path.replace("\\", "/") Now all modules parse correctly.
os.listdir etc fails on shared windows path (Python 2.5)
I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds) I am reading text file which contains directory paths which I want to process further. In order to do so I do as below: def toWin(path): return path.replace("\\", "\\\\") for line in open(fileName): l = toWin(line).strip() if os.path.isdir(l): print l # os.listdir(l) etc.. This works for local directories but fails for paths specified on shared system. e.g. E:\Test -- works \\StorageMachine\Test -- fails [internally converts to \\\\StorageMachine\\Test] \\StorageMachine\Test\ -- fails [internally converts to \\\\StorageMachine\\Test\\] But if I open python shell, import script and invoke function with same path string then it works! It seems that parsing windows shared paths is behaving differently in both cases. Any ideas/suggestions?
[ "This may not be your actual issue, but your UNC paths are actually not correct - they should start with a double backslash, but internally only use a single backslash as a divider.\nI'm not sure why the same thing would be working within the shell.\nUpdate:\nI suspect that what's happening is that in the shell, your string is being interpreted by the shell (with replacements happening) while in your code it's being treated as seen for the first time - basically, specifying the string in the shell is different from reading it from an input. To get the same effect from the shell, you'd need to specify it as a raw string with r\"string\"\n", "There is simply no reason to \"convert\". Backslashes are only interpreted when they are contained in string literals in your code, not when you read them programmatically from a file. Therefore, you should disable your conversion function and things will probably work.\n", "Have to convert input to forward slash (unix-style) for os.* modules to parse correctly.\nchanged code as below\ndef toUnix(path):\n return path.replace(\"\\\\\", \"/\")\n\nNow all modules parse correctly.\n" ]
[ 0, 0, -1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0002046912_path_python.txt
Q: python: convert UUID to a string which is a C unsigned char[16] initializer (in case you're curious about motivation: this will be used in a scons build to generate a C file containing a GUID) I found the question about generating a GUID in python. But I don't really know much about programming python. Could someone help me convert this to a string of the form "{0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**}" where the **'s are filled in with the GUID bytes in 2-digit hex form? def getInitializer(someUUID): hexByteList = [??? for b in someUUID.bytes] return '{'+(', '.join(hexByteList))+'}' I'm not sure what to use for the "???" above. A: hex(ord(b)) ...
python: convert UUID to a string which is a C unsigned char[16] initializer
(in case you're curious about motivation: this will be used in a scons build to generate a C file containing a GUID) I found the question about generating a GUID in python. But I don't really know much about programming python. Could someone help me convert this to a string of the form "{0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**}" where the **'s are filled in with the GUID bytes in 2-digit hex form? def getInitializer(someUUID): hexByteList = [??? for b in someUUID.bytes] return '{'+(', '.join(hexByteList))+'}' I'm not sure what to use for the "???" above.
[ "hex(ord(b))\n\n...\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002119500_python.txt
Q: Boost.Python - How to return by reference? I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references. Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference. Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a return_value_policy. However, using what seemed appropriate (doc); return_value_policy<reference_existing_object> did not seem to work. Have I misunderstood what it does? struct Foo { Foo(float x) { _x = x; } float& get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float& (Foo::*get_by_ref)(); class_<Foo>("Foo", init<float>()) .def("get", get_by_value(&Foo::get)) .def("get_ref", get_by_ref(&Foo::get), return_value_policy<reference_existing_object>())//Doesn't work ; } Note: I know it could be dangerous to reference existing object without life-time managing. Update: It looks like it works for objects but not basic data types. Take this revised example: struct Foo { Foo(float x) { _x = x; } float& get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo& self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_<Foo>("Foo", init<float>()) .def("get", get_by_value(&Foo::get)) .def("get_self", &Foo::self, return_value_policy<reference_existing_object>()) .def("set", &Foo::set); ; } Which in a test gave the expected result: >>> foo1 = Foo(123) >>> foo1.get() 123.0 >>> foo2 = foo1.get_self() >>> foo2.set(1) >>> foo1.get() 1.0 >>> id(foo1) == id(foo2) False A: In Python, there's the concept of immutable types. An immutable type can't have its value changed. Examples of built-in immutable types are int, float and str. Having said that, you can't do what you want with boost::python, because Python itself does not allow you to change the value of the float returned by the function. Your second example shows one solution, another would be to create thin-wrappers and exposing that: void Foo_set_x(Foo& self, float value) { self.get() = value; } class_<Foo>("Foo", init<float>()) ... .def("set", &Foo_set_x); ; Which is a better solution than having to change the original C++ class. A: I think you want return internal reference instead. I have used it before to do something similar. Edit: Latest doc A: I don't know much about Boost.Python, so I may misunderstand the question, in which case this is completely unhelpful. But here goes: In Python you can't choose between returning by reference or by value, the distinction doesn't make sense in Python. I find it's easiest to think of it as everything being handled by reference. You just have objects, and you have names for those objects. So foo = "ryiuy" Creates the string object "ryiuy" and then lets you refer to that string object with the name "foo". So in Python, when you get passed something, you get passed that object. There is no "values" as such, so you can't pass the value. But then again, it's also a valid viewpoint that there aren't references either, just objects and their names. So the answer is, I guess, is that when you get a reference in C, you need to pass a reference to the object that reference references into Python. And when you get a value in C, you need to pass a reference to the object that you create from that value into Python. A: Are you sure that the c++ object is being copied? You will get a new python object each time but which references the same c++ object. How are you determining that the object has been copied?
Boost.Python - How to return by reference?
I'm using Boost.Python to create Python modules from C++ classes. And I ran into a problem with references. Condider the following case where I have a class Foo with overloaded get methods that can either return by value or reference. Specifying that the return by value should be used was easy once I typedefed a signature. But I think it should be possible return a reference as well by using a return_value_policy. However, using what seemed appropriate (doc); return_value_policy<reference_existing_object> did not seem to work. Have I misunderstood what it does? struct Foo { Foo(float x) { _x = x; } float& get() { return _x; } float get() const { return _x; } private: float _x; }; // Wrapper code BOOST_PYTHON_MODULE(my_module) { using namespace boost::python; typedef float (Foo::*get_by_value)() const; typedef float& (Foo::*get_by_ref)(); class_<Foo>("Foo", init<float>()) .def("get", get_by_value(&Foo::get)) .def("get_ref", get_by_ref(&Foo::get), return_value_policy<reference_existing_object>())//Doesn't work ; } Note: I know it could be dangerous to reference existing object without life-time managing. Update: It looks like it works for objects but not basic data types. Take this revised example: struct Foo { Foo(float x) { _x = x; } float& get() { return _x; } float get() const { return _x; } void set( float f ){ _x = f;} Foo& self(){return *this;} private: float _x; }; // Wrapper code using namespace boost::python; BOOST_PYTHON_MODULE(my_module) { typedef float (Foo::*get_by_value)() const; class_<Foo>("Foo", init<float>()) .def("get", get_by_value(&Foo::get)) .def("get_self", &Foo::self, return_value_policy<reference_existing_object>()) .def("set", &Foo::set); ; } Which in a test gave the expected result: >>> foo1 = Foo(123) >>> foo1.get() 123.0 >>> foo2 = foo1.get_self() >>> foo2.set(1) >>> foo1.get() 1.0 >>> id(foo1) == id(foo2) False
[ "In Python, there's the concept of immutable types. An immutable type can't have its value changed. Examples of built-in immutable types are int, float and str.\nHaving said that, you can't do what you want with boost::python, because Python itself does not allow you to change the value of the float returned by the function. \nYour second example shows one solution, another would be to create thin-wrappers and exposing that:\nvoid Foo_set_x(Foo& self, float value) {\n self.get() = value;\n}\n\nclass_<Foo>(\"Foo\", init<float>())\n ...\n .def(\"set\", &Foo_set_x);\n;\n\nWhich is a better solution than having to change the original C++ class.\n", "I think you want return internal reference instead. I have used it before to do something similar.\nEdit: Latest doc \n", "I don't know much about Boost.Python, so I may misunderstand the question, in which case this is completely unhelpful. But here goes:\nIn Python you can't choose between returning by reference or by value, the distinction doesn't make sense in Python. I find it's easiest to think of it as everything being handled by reference. \nYou just have objects, and you have names for those objects. So\nfoo = \"ryiuy\"\n\nCreates the string object \"ryiuy\" and then lets you refer to that string object with the name \"foo\". So in Python, when you get passed something, you get passed that object. There is no \"values\" as such, so you can't pass the value. But then again, it's also a valid viewpoint that there aren't references either, just objects and their names.\nSo the answer is, I guess, is that when you get a reference in C, you need to pass a reference to the object that reference references into Python. And when you get a value in C, you need to pass a reference to the object that you create from that value into Python.\n", "Are you sure that the c++ object is being copied? You will get a new python object each time but which references the same c++ object. How are you determining that the object has been copied?\n" ]
[ 7, 3, 0, 0 ]
[]
[]
[ "boost", "boost_python", "python" ]
stackoverflow_0001571054_boost_boost_python_python.txt
Q: Returning a c++ array (pointer) from boost python I'm currently writing python bindings for a c++ library I'm working on. The library reads some binary file format and reading speed is very important. While optimizing the library for speed, I noticed that std::vector (used in the instances I'm reading) was eating up a lot of processing time, so I replaced those with simple arrays allocated with new[] (whether this was a good/wise thing to do is another question probably). Now I'm stuck with the problem of how to give python access to these arrays. There seems to be no solution built into boost::python (I haven't been able to find one at least). Example code to illustrate the situation: // Instance.cpp class Instance { int * data; int dataLength; Instance () { data = new int[10]; dataLength = 10; } }; // Class pythonBindings.cpp BOOST_PYTHON_MODULE(db) { class_<Instance>("Instance", init<>()) .add_property("data", ........) ; } I guess I could use a wrapper function that constructs a boost::python::list out of the arrays whenever python wants to access them. Since I am quite new to boost::python, I figured I should ask if there are any nice, standard or built-in solutions to this problem before I start hacking away though. So, how would you recommend wrapping Instance's data array using boost::python? A: If you change your class to work with std::vector instances, take a look at the vector indexing suite (http://www.boost.org/doc/libs/1_41_0/libs/python/doc/v2/indexing.html), which allows you to expose vectors to python with a native list interface, without creating copies from/to python. A: I will recomend a wrap data and dataLength with proxy class and returns from Instance this proxy. In our project we use this way to export data from our app to python. If you want I can give you few links to our implementation and explain how it works.
Returning a c++ array (pointer) from boost python
I'm currently writing python bindings for a c++ library I'm working on. The library reads some binary file format and reading speed is very important. While optimizing the library for speed, I noticed that std::vector (used in the instances I'm reading) was eating up a lot of processing time, so I replaced those with simple arrays allocated with new[] (whether this was a good/wise thing to do is another question probably). Now I'm stuck with the problem of how to give python access to these arrays. There seems to be no solution built into boost::python (I haven't been able to find one at least). Example code to illustrate the situation: // Instance.cpp class Instance { int * data; int dataLength; Instance () { data = new int[10]; dataLength = 10; } }; // Class pythonBindings.cpp BOOST_PYTHON_MODULE(db) { class_<Instance>("Instance", init<>()) .add_property("data", ........) ; } I guess I could use a wrapper function that constructs a boost::python::list out of the arrays whenever python wants to access them. Since I am quite new to boost::python, I figured I should ask if there are any nice, standard or built-in solutions to this problem before I start hacking away though. So, how would you recommend wrapping Instance's data array using boost::python?
[ "If you change your class to work with std::vector instances, take a look at the vector indexing suite (http://www.boost.org/doc/libs/1_41_0/libs/python/doc/v2/indexing.html), which allows you to expose vectors to python with a native list interface, without creating copies from/to python.\n", "I will recomend a wrap data and dataLength with proxy class and returns from Instance this proxy. In our project we use this way to export data from our app to python.\nIf you want I can give you few links to our implementation and explain how it works.\n" ]
[ 4, 1 ]
[]
[]
[ "binding", "boost", "boost_python", "python" ]
stackoverflow_0001410272_binding_boost_boost_python_python.txt
Q: How to separate one list in two via list comprehension or otherwise If have a list of dictionary items like so: L = [{"a":1, "b":0}, {"a":3, "b":1}...] I would like to split these entries based upon the value of "b", either 0 or 1. A(b=0) = [{"a":1, "b":1}, ....] B(b=1) = [{"a":3, "b":2}, .....] I am comfortable with using simple list comprehensions, and i am currently looping through the list L two times. A = [d for d in L if d["b"] == 0] B = [d for d in L if d["b"] != 0] Clearly this is not the most efficient way. An else clause does not seem to be available within the list comprehension functionality. Can I do what I want via list comprehension? Is there a better way to do this? I am looking for a good balance between readability and efficiency, leaning towards readability. Thanks! update: thanks everyone for the comments and ideas! the most easiest one for me to read is the one by Thomas. but i will look at Alex' suggestion as well. i had not found any reference to the collections module before. A: Don't use a list comprehension. List comprehensions are for when you want a single list result. You obviously don't :) Use a regular for loop: A = [] B = [] for item in L: if item['b'] == 0: target = A else: target = B target.append(item) You can shorten the snippet by doing, say, (A, B)[item['b'] != 0].append(item), but why bother? A: If the b value can be only 0 or 1, @Thomas's simple solution is probably best. For a more general case (in which you want to discriminate among several possible values of b -- your sample "expected results" appear to be completely divorced from and contradictory to your question's text, so it's far from obvious whether you actually need some generality;-): from collections import defaultdict separated = defaultdict(list) for x in L: separated[x['b']].append(x) When this code executes, separated ends up with a dict (actually an instance of collections.defaultdict, a dict subclass) whose keys are all values for b that actually occur in dicts in list L, the corresponding values being the separated sublists. So, for example, if b takes only the values 0 and 1, separated[0] would be what (in your question's text as opposed to the example) you want as list A, and separated[1] what you want as list B.
How to separate one list in two via list comprehension or otherwise
If have a list of dictionary items like so: L = [{"a":1, "b":0}, {"a":3, "b":1}...] I would like to split these entries based upon the value of "b", either 0 or 1. A(b=0) = [{"a":1, "b":1}, ....] B(b=1) = [{"a":3, "b":2}, .....] I am comfortable with using simple list comprehensions, and i am currently looping through the list L two times. A = [d for d in L if d["b"] == 0] B = [d for d in L if d["b"] != 0] Clearly this is not the most efficient way. An else clause does not seem to be available within the list comprehension functionality. Can I do what I want via list comprehension? Is there a better way to do this? I am looking for a good balance between readability and efficiency, leaning towards readability. Thanks! update: thanks everyone for the comments and ideas! the most easiest one for me to read is the one by Thomas. but i will look at Alex' suggestion as well. i had not found any reference to the collections module before.
[ "Don't use a list comprehension. List comprehensions are for when you want a single list result. You obviously don't :) Use a regular for loop:\nA = []\nB = []\nfor item in L:\n if item['b'] == 0:\n target = A\n else:\n target = B\n target.append(item)\n\nYou can shorten the snippet by doing, say, (A, B)[item['b'] != 0].append(item), but why bother?\n", "If the b value can be only 0 or 1, @Thomas's simple solution is probably best. For a more general case (in which you want to discriminate among several possible values of b -- your sample \"expected results\" appear to be completely divorced from and contradictory to your question's text, so it's far from obvious whether you actually need some generality;-):\nfrom collections import defaultdict\n\nseparated = defaultdict(list)\nfor x in L:\n separated[x['b']].append(x)\n\nWhen this code executes, separated ends up with a dict (actually an instance of collections.defaultdict, a dict subclass) whose keys are all values for b that actually occur in dicts in list L, the corresponding values being the separated sublists. So, for example, if b takes only the values 0 and 1, separated[0] would be what (in your question's text as opposed to the example) you want as list A, and separated[1] what you want as list B.\n" ]
[ 5, 3 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0002119112_list_list_comprehension_python.txt
Q: How do I create an extra RSS item element that contains HTML using PyRSS2Gen? I'm using PyRSS2Gen to generate an RSS feed. I've succeeded in extending it to add an extra element to each item in the RSS feed: class FullRSSItem(PyRSS2Gen.RSSItem): def __init__(self, **kwargs): if 'content' in kwargs: self.content = kwargs['content'] del kwargs['content'] else: self.content = None PyRSS2Gen.RSSItem.__init__(self, **kwargs) def publish_extensions(self, handler): PyRSS2Gen._opt_element(handler, "content:encoded", '<![CDATA[' + self.content + ']]>') However, self.content contains HTML tags and all of the angled brackets (including those in the <![CDATA part) are translated into &lt; and &gt; when the feed file is generated. How do I add an extra RSS item element that contains HTML using PyRSS2Gen? A: I eventually ditched the idea of using the CDATA wrapper and just had the full text be encoded. Seems to work.
How do I create an extra RSS item element that contains HTML using PyRSS2Gen?
I'm using PyRSS2Gen to generate an RSS feed. I've succeeded in extending it to add an extra element to each item in the RSS feed: class FullRSSItem(PyRSS2Gen.RSSItem): def __init__(self, **kwargs): if 'content' in kwargs: self.content = kwargs['content'] del kwargs['content'] else: self.content = None PyRSS2Gen.RSSItem.__init__(self, **kwargs) def publish_extensions(self, handler): PyRSS2Gen._opt_element(handler, "content:encoded", '<![CDATA[' + self.content + ']]>') However, self.content contains HTML tags and all of the angled brackets (including those in the <![CDATA part) are translated into &lt; and &gt; when the feed file is generated. How do I add an extra RSS item element that contains HTML using PyRSS2Gen?
[ "I eventually ditched the idea of using the CDATA wrapper and just had the full text be encoded. Seems to work.\n" ]
[ 0 ]
[]
[]
[ "cdata", "python", "rss" ]
stackoverflow_0002066423_cdata_python_rss.txt
Q: Is there a Python library for connecting to a PostgreSQL 8.4 server using certificate authentication? We are in the process of upgrading from PostgreSQL 8.3 to PostgreSQL 8.4, in a large part so that we can start using certificate-based authentication. We have some Python 2.x code that accesses the database that uses PyGreSQL. Is there a way to get it or any other Python library to use a cert to access PostgreSQL? Looking through the PyGreSQL source, I didn't see a way to supply a certificate. A: psycopg2 is based on libpq, so it should work there. I don't think there's a specific interface for it, so you'll have to use the environment variables (see the libpq documentation) to control it, but it should work. (disclaimer: I haven't actually tried it, but anything on top of libpq should work)
Is there a Python library for connecting to a PostgreSQL 8.4 server using certificate authentication?
We are in the process of upgrading from PostgreSQL 8.3 to PostgreSQL 8.4, in a large part so that we can start using certificate-based authentication. We have some Python 2.x code that accesses the database that uses PyGreSQL. Is there a way to get it or any other Python library to use a cert to access PostgreSQL? Looking through the PyGreSQL source, I didn't see a way to supply a certificate.
[ "psycopg2 is based on libpq, so it should work there. I don't think there's a specific interface for it, so you'll have to use the environment variables (see the libpq documentation) to control it, but it should work. (disclaimer: I haven't actually tried it, but anything on top of libpq should work)\n" ]
[ 2 ]
[]
[]
[ "authentication", "certificate", "postgresql", "python" ]
stackoverflow_0002118846_authentication_certificate_postgresql_python.txt
Q: Python extensions that can be used in all varieties of python (jython / IronPython / etc.) In the 'old days' when there was just cpython, most extensions were written in c (as platform independent as possible) and compiled into pyd's (think PyCrypto for example). Now there is Jython, IronPython and PyPy and the pyd’s do not work with any of them (Ironclad aside). It seems they all support ctypes and that the best approach MIGHT be to create a platform independent dll or shared library and then use ctypes to interface to it. But I think this approach will be a bit slower than the old fashion pyd approach. You could also program a pyd for cpython, a similar c# dll for IronPython and a java class or jar for Jython (I'm not sure about PyPy. But while this approach will appeal to platform purists it is very labor intensive. So what is the best route to take today? A: Currently, it seems the ctypes is indeed the best approach. It works today, and it's so convenient that it's gonna conquer (most of) the world. For performance-critical APIs (such as numpy), ctypes is indeed problematic. The cleanest approach would probably be to port Cython to produce native IronPython / Jython / PyPy extensions. I recall that PyPy had plans to compile ctypes code to efficient wrappers, but as far as I google, there is nothing like that yet... A: If you're wrapping an existing native library, the ctypes is absolutely the way to go. If you're trying to speed up the hot spots in a Python extension, then making a custom extension for each interpreter (and a pure-Python fallback) is tractable because the bulk of the code is pure Python that can be shared, but undesirable and labour-intensive, as you said. You could use ctypes in this case as well.
Python extensions that can be used in all varieties of python (jython / IronPython / etc.)
In the 'old days' when there was just cpython, most extensions were written in c (as platform independent as possible) and compiled into pyd's (think PyCrypto for example). Now there is Jython, IronPython and PyPy and the pyd’s do not work with any of them (Ironclad aside). It seems they all support ctypes and that the best approach MIGHT be to create a platform independent dll or shared library and then use ctypes to interface to it. But I think this approach will be a bit slower than the old fashion pyd approach. You could also program a pyd for cpython, a similar c# dll for IronPython and a java class or jar for Jython (I'm not sure about PyPy. But while this approach will appeal to platform purists it is very labor intensive. So what is the best route to take today?
[ "Currently, it seems the ctypes is indeed the best approach. It works today, and it's so convenient that it's gonna conquer (most of) the world.\nFor performance-critical APIs (such as numpy), ctypes is indeed problematic. The cleanest approach would probably be to port Cython to produce native IronPython / Jython / PyPy extensions.\nI recall that PyPy had plans to compile ctypes code to efficient wrappers, but as far as I google, there is nothing like that yet...\n", "If you're wrapping an existing native library, the ctypes is absolutely the way to go.\nIf you're trying to speed up the hot spots in a Python extension, then making a custom extension for each interpreter (and a pure-Python fallback) is tractable because the bulk of the code is pure Python that can be shared, but undesirable and labour-intensive, as you said. You could use ctypes in this case as well.\n" ]
[ 2, 1 ]
[]
[]
[ "ironpython", "jython", "python" ]
stackoverflow_0002114627_ironpython_jython_python.txt
Q: Django forms: how do I display the initial blank form? I have this view function: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): last_name = form.cleaned_data['last_name'] first_name = form.cleaned_data['first_name'] lawyers = Lawyer.objects.all() [ other if statements ] .... else: form = SearchForm() return render_to_response('search.html', {'form': form}) I would think that when the page loads the else statement will be executed with the initial blank form. But this is not the case. To have the form displayed initially I have to add it inside the first if: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): last_name = form.cleaned_data['last_name'] first_name = form.cleaned_data['first_name'] lawyers = Lawyer.objects.all() [ other if statements ] .... form = SearchForm() return render_to_response('search.html', {'form': form}) else: form = SearchForm() return render_to_response('search.html', {'form': form}) Can you help why the first if is never false? Thank you. The entire view function is here A: Every normal HTTP request (like when you go to http://stackoverflow.com) is a GET request. It is generally a good idea to use POST as the method of your forms when they change some data. You should read: When do you use POST and when do you use GET? A: When you post a form with method=GET you don't actually change the method from the initial request: it was method=GET too. You can either use method=POST in your form, and your if statement will check for that, or you could check for the existence of the required fields, first_name, last_name or both, as your form requires. if 'first_name' in request.GET or 'last_name' in request.GET: form = SearchForm(request.GET) else: form = SearchForm() You might want to abstract this into the form itself, modifying the __init__ method, but you don't have to.
Django forms: how do I display the initial blank form?
I have this view function: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): last_name = form.cleaned_data['last_name'] first_name = form.cleaned_data['first_name'] lawyers = Lawyer.objects.all() [ other if statements ] .... else: form = SearchForm() return render_to_response('search.html', {'form': form}) I would think that when the page loads the else statement will be executed with the initial blank form. But this is not the case. To have the form displayed initially I have to add it inside the first if: def search(request): if request.method == 'GET': form = SearchForm(request.GET) if form.is_valid(): last_name = form.cleaned_data['last_name'] first_name = form.cleaned_data['first_name'] lawyers = Lawyer.objects.all() [ other if statements ] .... form = SearchForm() return render_to_response('search.html', {'form': form}) else: form = SearchForm() return render_to_response('search.html', {'form': form}) Can you help why the first if is never false? Thank you. The entire view function is here
[ "Every normal HTTP request (like when you go to http://stackoverflow.com) is a GET request. It is generally a good idea to use POST as the method of your forms when they change some data.\nYou should read: When do you use POST and when do you use GET?\n", "When you post a form with method=GET you don't actually change the method from the initial request: it was method=GET too.\nYou can either use method=POST in your form, and your if statement will check for that, or you could check for the existence of the required fields, first_name, last_name or both, as your form requires.\nif 'first_name' in request.GET or 'last_name' in request.GET:\n form = SearchForm(request.GET)\nelse:\n form = SearchForm()\n\nYou might want to abstract this into the form itself, modifying the __init__ method, but you don't have to.\n" ]
[ 2, 1 ]
[]
[]
[ "django_forms", "python" ]
stackoverflow_0002119682_django_forms_python.txt
Q: What do square brackets, "[]", mean in function/class documentation? I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify. From the docmentation: class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]]) I'd appreciate a summary of the arguments to the class instantiation. Thanks A: The square brackets indicate that these arguments are optional. You can leave them out. So, in this case you are only required to pass the csvfile argument to csv.DictReader. If you would pass a second parameter, it would be interpreted as the fieldnames arguments. The third would be restkey, etc. If you only want to specify e.g. cvsfile and dialect, then you'll have to name the keyword argument explicitly, like so: csv.DictReader(file('test.csv'), dialect='excel_tab') For more on keyword arguments, see section 4.7.2 of the tutorial at python.org. A: Usually in api documentation square brackets mean optional. I would think they mean the same here. A: This is actually a subset of the widely used notation to unambiguously describe language syntax called Backus-Naur Form (see Wikipedia article for details). A: To reiterate what the others have said, the arguments are optional. If you leave out optional parts, the remaining fieldnames=, restval=, restkey= or dialect= keywords tell the function which parts are missing. The syntax doesn't suggest it, but I wouldn't be surprised if the keywords allow the arguments to be specificied in any order, except that the last two arguments must be either both specified, or both omitted.
What do square brackets, "[]", mean in function/class documentation?
I am having trouble figuring out the arguments to csv.dictreader and realized I have no clue what the square brackets signify. From the docmentation: class csv.DictReader(csvfile[, fieldnames=None[, restkey=None[, restval=None[, dialect='excel'[, *args, **kwds]]]]]) I'd appreciate a summary of the arguments to the class instantiation. Thanks
[ "The square brackets indicate that these arguments are optional. You can leave them out.\nSo, in this case you are only required to pass the csvfile argument to csv.DictReader. If you would pass a second parameter, it would be interpreted as the fieldnames arguments. The third would be restkey, etc.\nIf you only want to specify e.g. cvsfile and dialect, then you'll have to name the keyword argument explicitly, like so:\ncsv.DictReader(file('test.csv'), dialect='excel_tab')\n\nFor more on keyword arguments, see section 4.7.2 of the tutorial at python.org.\n", "Usually in api documentation square brackets mean optional. I would think they mean the same here.\n", "This is actually a subset of the widely used notation to unambiguously describe language syntax called Backus-Naur Form (see Wikipedia article for details).\n", "To reiterate what the others have said, the arguments are optional.\nIf you leave out optional parts, the remaining fieldnames=, restval=, restkey= or dialect= keywords tell the function which parts are missing.\nThe syntax doesn't suggest it, but I wouldn't be surprised if the keywords allow the arguments to be specificied in any order, except that the last two arguments must be either both specified, or both omitted.\n" ]
[ 28, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001718903_python.txt
Q: Best F/OSS IDE for Python Web Development (Windows or Linux)? Would like to know what is the best F/OSS IDE for Python Web development. I've always used vim myself, but I'm increasingly interested in having a tool that integrates syntax checking/highlighting, source control, debugging, and other IDE goodies. I use both Windows and Linux as desktops, so recommendations for either platform are welcome! Thanks, -aj A: Might take some getting used to but Eclipse with the python extension - PyDev - works for me. It took a bit of getting-used-to though as Eclipse is generally meant for Java (or perhaps because I wasn't familiar with it). But it's a good open source option. A: I am also working with mod_wsgi, python, apache software stack. I am using WingIDE as my environment, which gives you debugging capabilities. If you are vi person it has a VI/VIM personality which coupled with auto-completion makes for a very productive work environment. A: What about IDLE? It's bundled with Python distributions. A: I've been using Komodo Edit for a while now and it's quite good for Python development. It's free and I think it's also open-source now, though it wasn't always so. A: I don't know if it is powerful enough for you but you can try Komodo Edit. AFAK it has no debugging or SCM but it is lightweight ;) A: "syntax checking/highlighting, source control, debugging, and other IDE goodies" Emacs fits this criteria, if you use the right extensions. Though it does have a much steeper learning curve than any IDE I know of.
Best F/OSS IDE for Python Web Development (Windows or Linux)?
Would like to know what is the best F/OSS IDE for Python Web development. I've always used vim myself, but I'm increasingly interested in having a tool that integrates syntax checking/highlighting, source control, debugging, and other IDE goodies. I use both Windows and Linux as desktops, so recommendations for either platform are welcome! Thanks, -aj
[ "Might take some getting used to but Eclipse with the python extension - PyDev - works for me. It took a bit of getting-used-to though as Eclipse is generally meant for Java (or perhaps because I wasn't familiar with it). But it's a good open source option.\n", "I am also working with mod_wsgi, python, apache software stack. I am using WingIDE as my environment, which gives you debugging capabilities. If you are vi person it has a VI/VIM personality which coupled with auto-completion makes for a very productive work environment.\n", "What about IDLE? It's bundled with Python distributions.\n", "I've been using Komodo Edit for a while now and it's quite good for Python development. It's free and I think it's also open-source now, though it wasn't always so.\n", "I don't know if it is powerful enough for you but you can try Komodo Edit. AFAK it has no debugging or SCM but it is lightweight ;)\n", "\"syntax checking/highlighting, source control, debugging, and other IDE goodies\"\nEmacs fits this criteria, if you use the right extensions. Though it does have a much steeper learning curve than any IDE I know of.\n" ]
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0002097134_ide_python.txt
Q: ImportError: Model A references Model B, Model B references Model A I think this is more a python question than Django. But basically I'm doing at Model A: from myproject.modelb.models import ModelB and at Model B: from myproject.modela.models import ModelA Result: cannot import name ModelA Am I doing something forbidden? Thanks A: A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the ModelA class because the import of myproject.modelb.models happens before the definition of that class. In Django you can fix this by referring to a model by name instead of by class object. So, instead of saying from myproject.modela.models import ModelA class ModelB: a = models.ForeignKey(ModelA) you would use (without the import): class ModelB: a = models.ForeignKey('ModelA') A: Mutual imports usually mean you've designed your models incorrectly. When A depends on B, you should not have B also depending on A. Break B into two parts. B1 - depends on A. B2 - does not depend on A. A depends on B1. B1 depends on B2. Circularity removed.
ImportError: Model A references Model B, Model B references Model A
I think this is more a python question than Django. But basically I'm doing at Model A: from myproject.modelb.models import ModelB and at Model B: from myproject.modela.models import ModelA Result: cannot import name ModelA Am I doing something forbidden? Thanks
[ "A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the ModelA class because the import of myproject.modelb.models happens before the definition of that class.\nIn Django you can fix this by referring to a model by name instead of by class object. So, instead of saying\nfrom myproject.modela.models import ModelA\nclass ModelB:\n a = models.ForeignKey(ModelA)\n\nyou would use (without the import):\nclass ModelB:\n a = models.ForeignKey('ModelA')\n\n", "Mutual imports usually mean you've designed your models incorrectly.\nWhen A depends on B, you should not have B also depending on A.\nBreak B into two parts.\nB1 - depends on A.\nB2 - does not depend on A.\nA depends on B1. B1 depends on B2. Circularity removed.\n" ]
[ 6, 2 ]
[]
[]
[ "circular_dependency", "django", "python" ]
stackoverflow_0002120332_circular_dependency_django_python.txt
Q: Read XML with multiple top-level items using Python ElementTree? How can I read an XML file using Python ElementTree, if the XML has multiple top-level items? I have an XML file that I would like to read using Python ElementTree. Unfortunately, it has multiple top-level tags. I would wrap <doc>...</doc> around the XML, except I have to put the <doc> after the <?xml> and <!DOCTYPE> fields. But figuring out where <!DOCTYPE> ends is non-trivial. What I have: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> What I want: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <DOC> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> </DOC> NB the name of tag ARTICLE might change, so I cannot grep for it. Can anyone suggest to me how I can add the enclosing <doc>...</doc> after the XML header, or suggest another workaround? A: I wrote the following function to add a toplevel tag after the XML processing instructions. You can now find this code in my common Python library as common.myelementtree.add_toplevel_tag import re xmlprocre = re.compile("(\s*<[\?\!])") def add_toplevel_tag(string): """ After all the XML processing instructions, add an enclosing top-level <DOC> tag, and return it. e.g. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> => <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]><DOC> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE></DOC> """ def _advance_proc(string, idx): # If possible, advance over whitespace and one processing # instruction starting at string index idx, and return its index. # If not possible, return None # Find the beginning of the processing instruction m = xmlprocre.match(string[idx:]) if m is None: return None #print "Group", m.group(1) idx = idx + len(m.group(1)) #print "Remain", string[idx:] # Find closing > bracket bracketdebt = 1 while bracketdebt > 0: if string[idx] == "<": bracketdebt += 1 elif string[idx] == ">": bracketdebt -= 1 idx += 1 #print "Remain", string[idx:] return idx loc = 0 while 1: # Advance one processing instruction newloc = _advance_proc(string, loc) if newloc is None: break else: loc = newloc return string[:loc] + "<DOC>" + string[loc:] + "</DOC>"
Read XML with multiple top-level items using Python ElementTree?
How can I read an XML file using Python ElementTree, if the XML has multiple top-level items? I have an XML file that I would like to read using Python ElementTree. Unfortunately, it has multiple top-level tags. I would wrap <doc>...</doc> around the XML, except I have to put the <doc> after the <?xml> and <!DOCTYPE> fields. But figuring out where <!DOCTYPE> ends is non-trivial. What I have: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> What I want: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <DOC> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> </DOC> NB the name of tag ARTICLE might change, so I cannot grep for it. Can anyone suggest to me how I can add the enclosing <doc>...</doc> after the XML header, or suggest another workaround?
[ "I wrote the following function to add a toplevel tag after the XML processing instructions. You can now find this code in my common Python library as common.myelementtree.add_toplevel_tag\nimport re\nxmlprocre = re.compile(\"(\\s*<[\\?\\!])\")\ndef add_toplevel_tag(string):\n \"\"\"\nAfter all the XML processing instructions, add an enclosing top-level <DOC> tag, and return it.\ne.g.\n<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE FOO BAR \"foo.dtd\" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ...\n</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE>\n=>\n<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE FOO BAR \"foo.dtd\" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]><DOC> <ARTICLE> ...\n</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE></DOC>\n\"\"\"\n def _advance_proc(string, idx):\n # If possible, advance over whitespace and one processing\n # instruction starting at string index idx, and return its index.\n # If not possible, return None\n # Find the beginning of the processing instruction\n m = xmlprocre.match(string[idx:])\n if m is None: return None\n #print \"Group\", m.group(1)\n idx = idx + len(m.group(1))\n #print \"Remain\", string[idx:]\n\n # Find closing > bracket\n bracketdebt = 1\n while bracketdebt > 0:\n if string[idx] == \"<\": bracketdebt += 1\n elif string[idx] == \">\": bracketdebt -= 1\n idx += 1\n #print \"Remain\", string[idx:]\n return idx\n loc = 0\n while 1:\n # Advance one processing instruction\n newloc = _advance_proc(string, loc)\n if newloc is None: break\n else: loc = newloc\n return string[:loc] + \"<DOC>\" + string[loc:] + \"</DOC>\"\n\n" ]
[ 0 ]
[]
[]
[ "elementtree", "parsing", "python", "xml" ]
stackoverflow_0002113819_elementtree_parsing_python_xml.txt
Q: Why do Python function docs include the comma after the bracket for optional args? The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets? How they are: RegexObject.match(string[, pos[, endpos]]) I would expect one of the following: RegexObject.match(string, [pos], [endpos]) RegexObject.match(string[, pos][, endpos]) A: The square bracket means that the contents are optional, but everything outside of square brackets is compulsory. With your notation: RegexObject.match(string, [pos], [endpos]) I would expect to have to write: r.match("foo",,) The nesting is required because if you supply the third parameter then you must also supply the second parameter even though it is an optional parameter. The following non-nested alternative would be ambiguous: RegexObject.match(string[, pos][, endpos]) A: The open bracket indicates an optional argument. If the comma were outside the bracket, you would have to type it even if you didn't want to use the pos argument (for example). A: Because otherwise the correct syntax would be to include the comma even if you are ignoring the arguments. The parts inside the square brackets are optional, so by moving the commas out of the square brackets, they are no longer optional. For example, to call the function below with only a string: RegexObject.match(string, [pos], [endpos]) I would have to do: RegexObject.match("foobar",,) But, that isn't very elegant. A: If you think about the brackets enclosing all optional components of the argument list, it makes more sense. Essentially, anything inside brackets may be left out at the discretion of the user. A: The brackets mean that you can leave out the part between them. So if the docs would be written the way you suggest, it would imply that you can write RegexObject.match(string,,) by leaving everything in brackets. Or RegexObject.match(string,,endpos) by just leaving out the second one. But you can't. If you leave out endpos, you also have to leave out the comma before it. And if you leave out pos, you have to leave out the comma before it as well as endpos. So it's written in a way that makes that clear.
Why do Python function docs include the comma after the bracket for optional args?
The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets? How they are: RegexObject.match(string[, pos[, endpos]]) I would expect one of the following: RegexObject.match(string, [pos], [endpos]) RegexObject.match(string[, pos][, endpos])
[ "The square bracket means that the contents are optional, but everything outside of square brackets is compulsory.\nWith your notation:\nRegexObject.match(string, [pos], [endpos])\n\nI would expect to have to write:\nr.match(\"foo\",,)\n\nThe nesting is required because if you supply the third parameter then you must also supply the second parameter even though it is an optional parameter. The following non-nested alternative would be ambiguous:\nRegexObject.match(string[, pos][, endpos])\n\n", "The open bracket indicates an optional argument. If the comma were outside the bracket, you would have to type it even if you didn't want to use the pos argument (for example).\n", "Because otherwise the correct syntax would be to include the comma even if you are ignoring the arguments. The parts inside the square brackets are optional, so by moving the commas out of the square brackets, they are no longer optional. For example, to call the function below with only a string:\nRegexObject.match(string, [pos], [endpos])\n\nI would have to do:\nRegexObject.match(\"foobar\",,)\n\nBut, that isn't very elegant.\n", "If you think about the brackets enclosing all optional components of the argument list, it makes more sense. Essentially, anything inside brackets may be left out at the discretion of the user.\n", "The brackets mean that you can leave out the part between them. So if the docs would be written the way you suggest, it would imply that you can write RegexObject.match(string,,) by leaving everything in brackets. Or RegexObject.match(string,,endpos) by just leaving out the second one. But you can't. If you leave out endpos, you also have to leave out the comma before it. And if you leave out pos, you have to leave out the comma before it as well as endpos. So it's written in a way that makes that clear.\n" ]
[ 22, 2, 2, 0, 0 ]
[]
[]
[ "documentation", "notation", "python" ]
stackoverflow_0002120507_documentation_notation_python.txt
Q: In wxPython, What is the Standard Process of Making an Application Slightly More Complex Than a Wizard? I am attempting to create my first OS-level GUI using wxPython. I have the book wxPython in Action and have looked at the code demos. I have no experience with event-driven programming (aside from some Javascript), sizers, and all of the typical GUI elements. The book is organized a little strangely and assumes I know far more about OS GUI programming than I actually do. I'm fairly recent to object-oriented programming, as well. I'm aware that I am clearly out of my depth. My application, on the GUI side, is simple: mostly a set of reminder screens ("Turn on the scanner," "Turn on the printer," etc) and background actions in Python either in the filesystem or from hitting a web service, but it is just complex enough that the Wizard class does not quite seem to cover it. I have to change the names on the "Back" and "Next" buttons, disable them at times, and so forth. What is the standard process for an application such as mine? 1) Create a single wxFrame, then put all of my wxPanels inside of it, hiding all but one, then performing a sequence of hides and shows as the "Next" button (or the current equivalent) are triggered? 2) Create multiple wxFrames, with one wxPanel in each, then switch between them? 3) Some non-obvious fashion of changing the names of the buttons in wxWizard and disabling them? 4) Something I have not anticipated in the three categories above. A: I don't have a good understanding of your application, but trying to force wxWizard to suit your needs sounds like a bad idea. I suggest checking out the Demos available from the wxPython website. Go through each demo and I bet you'll find one that suits your needs. I've personally never used wxWizard as I find it too cumbersome. Instead, I create a sequence of dialogs that do what I need.
In wxPython, What is the Standard Process of Making an Application Slightly More Complex Than a Wizard?
I am attempting to create my first OS-level GUI using wxPython. I have the book wxPython in Action and have looked at the code demos. I have no experience with event-driven programming (aside from some Javascript), sizers, and all of the typical GUI elements. The book is organized a little strangely and assumes I know far more about OS GUI programming than I actually do. I'm fairly recent to object-oriented programming, as well. I'm aware that I am clearly out of my depth. My application, on the GUI side, is simple: mostly a set of reminder screens ("Turn on the scanner," "Turn on the printer," etc) and background actions in Python either in the filesystem or from hitting a web service, but it is just complex enough that the Wizard class does not quite seem to cover it. I have to change the names on the "Back" and "Next" buttons, disable them at times, and so forth. What is the standard process for an application such as mine? 1) Create a single wxFrame, then put all of my wxPanels inside of it, hiding all but one, then performing a sequence of hides and shows as the "Next" button (or the current equivalent) are triggered? 2) Create multiple wxFrames, with one wxPanel in each, then switch between them? 3) Some non-obvious fashion of changing the names of the buttons in wxWizard and disabling them? 4) Something I have not anticipated in the three categories above.
[ "I don't have a good understanding of your application, but trying to force wxWizard to suit your needs sounds like a bad idea.\nI suggest checking out the Demos available from the wxPython website. Go through each demo and I bet you'll find one that suits your needs.\nI've personally never used wxWizard as I find it too cumbersome. Instead, I create a sequence of dialogs that do what I need.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002119067_python_wxpython.txt
Q: Parse boolean arithmetic including parentheses with regex? Is there a single regular expression that can parse a string (in Python and/or Javascript, does not need to be the same expression) that represents simple boolean arithmetic? For example I want to parse this string: a and (b and c) and d or e and (f or g) Assuming that: * parentheses do not nest * the terms a, b, ..., z are not sub-expressions The resulting captures should be grouped by parentheses first, which I then parse again with the same or a simpler regex. I've had success writing a naive regex for parsing boolean arithmetic without parentheses. Any ideas? A: Normally you would use for example a recursive descent parser for this task, but you can grab all the parts (tokens) with a regex: x = 'a and (b and c) and d or e and (f or g)' import re matches = re.findall(r'\(.*?\)|\w+', x) print ','.join(matches) The operators usually have different precedence. Parentheses would be evaluated first, then and expressions, and finally or expressions, with left-to-right order in case of equal precedence. You say you want to return the parentheses matches first, but actually what you would normally do is to use the parts build an expression tree and evalulate that recursively. A: Assuming no nesting simplifies it to a level where regex can be used. A regex to match that would be (assuming and/or only, can be easily extended): >>> expr = 'a and (b and c) and d or e and (f or g)' >>> regex = re.compile('\((\w+)\s+(and|or)\s+(\w)\)|(\w+)') >>> results = regex.findall(expr) >>> results = [i[:3] if i[0] else i[3] for i in results] >>> results ['a', 'and', ('b', 'and', 'c'), 'and', 'd', 'or', 'e', 'and', ('f', 'or', 'g')] Now you have parenthesized parts as tuples of 3 strings (operand-operator-operand) and the rest of the string as strings for each token (operator or operand). You can walk through the list, evaluate each parenthesized expression, and replace it with the result. Once that is done, you can walk through it again and evaluate either from left to right or according to some precedence rules you set (e.g. keep evaluating ANDs only until you run out of ANDs, then start evaluating ORs). A: The Examples page on the pyparsing wiki includes a sample SimpleBool.py that will parse and evaluate expressions such as: test = ["p and not q", "not not p", "not(p and q)", "q or not p and r", "q or not (p and r)", "p or q or r", "p or q or r and False", ] (Hmmm, there aren't any examples with nested parens, but these are supported too.) The actual parser is defined in its entirety using this code: boolOperand = Word(alphas,max=1) | oneOf("True False") boolExpr = operatorPrecedence( boolOperand, [ ("not", 1, opAssoc.RIGHT, BoolNot), ("and", 2, opAssoc.LEFT, BoolAnd), ("or", 2, opAssoc.LEFT, BoolOr), ]) The remainder of the example gives the implementations of BoolNot, BoolOr, and BoolAnd. The operatorPrecedence construct defines the sequence of operations, their arity and associativity, and optionally a class to be constructed with the parsed elements. operatorPrecedence then takes care of defining the grammar, including recursive definition of boolExpr's within nested parentheses. The resulting structure is similar to a nested AST using the given BoolXxx classes. These classes in turn define eval methods so that the expressions can parsed and evaluated using this code: p = True q = False r = True for t in test: res = boolExpr.parseString(t)[0] print t,'\n', res, '=', bool(res),'\n' pyparsing itself is a somewhat longish module, but it is a single source file so its installation footprint is pretty small. MIT license permits both noncommercial and commercial use.
Parse boolean arithmetic including parentheses with regex?
Is there a single regular expression that can parse a string (in Python and/or Javascript, does not need to be the same expression) that represents simple boolean arithmetic? For example I want to parse this string: a and (b and c) and d or e and (f or g) Assuming that: * parentheses do not nest * the terms a, b, ..., z are not sub-expressions The resulting captures should be grouped by parentheses first, which I then parse again with the same or a simpler regex. I've had success writing a naive regex for parsing boolean arithmetic without parentheses. Any ideas?
[ "Normally you would use for example a recursive descent parser for this task, but you can grab all the parts (tokens) with a regex:\nx = 'a and (b and c) and d or e and (f or g)'\nimport re\n\nmatches = re.findall(r'\\(.*?\\)|\\w+', x)\nprint ','.join(matches)\n\nThe operators usually have different precedence. Parentheses would be evaluated first, then and expressions, and finally or expressions, with left-to-right order in case of equal precedence. You say you want to return the parentheses matches first, but actually what you would normally do is to use the parts build an expression tree and evalulate that recursively.\n", "Assuming no nesting simplifies it to a level where regex can be used. A regex to match that would be (assuming and/or only, can be easily extended):\n>>> expr = 'a and (b and c) and d or e and (f or g)'\n>>> regex = re.compile('\\((\\w+)\\s+(and|or)\\s+(\\w)\\)|(\\w+)')\n>>> results = regex.findall(expr)\n>>> results = [i[:3] if i[0] else i[3] for i in results]\n>>> results\n['a', 'and', ('b', 'and', 'c'), 'and', 'd', 'or', 'e', 'and', ('f', 'or', 'g')]\n\nNow you have parenthesized parts as tuples of 3 strings (operand-operator-operand) and the rest of the string as strings for each token (operator or operand).\nYou can walk through the list, evaluate each parenthesized expression, and replace it with the result. Once that is done, you can walk through it again and evaluate either from left to right or according to some precedence rules you set (e.g. keep evaluating ANDs only until you run out of ANDs, then start evaluating ORs).\n", "The Examples page on the pyparsing wiki includes a sample SimpleBool.py that will parse and evaluate expressions such as:\ntest = [\"p and not q\",\n \"not not p\",\n \"not(p and q)\",\n \"q or not p and r\",\n \"q or not (p and r)\",\n \"p or q or r\",\n \"p or q or r and False\",\n ]\n\n(Hmmm, there aren't any examples with nested parens, but these are supported too.)\nThe actual parser is defined in its entirety using this code:\nboolOperand = Word(alphas,max=1) | oneOf(\"True False\")\nboolExpr = operatorPrecedence( boolOperand,\n [\n (\"not\", 1, opAssoc.RIGHT, BoolNot),\n (\"and\", 2, opAssoc.LEFT, BoolAnd),\n (\"or\", 2, opAssoc.LEFT, BoolOr),\n ])\n\nThe remainder of the example gives the implementations of BoolNot, BoolOr, and BoolAnd. The operatorPrecedence construct defines the sequence of operations, their arity and associativity, and optionally a class to be constructed with the parsed elements. operatorPrecedence then takes care of defining the grammar, including recursive definition of boolExpr's within nested parentheses. The resulting structure is similar to a nested AST using the given BoolXxx classes. These classes in turn define eval methods so that the expressions can parsed and evaluated using this code:\np = True\nq = False\nr = True\nfor t in test:\n res = boolExpr.parseString(t)[0]\n print t,'\\n', res, '=', bool(res),'\\n'\n\npyparsing itself is a somewhat longish module, but it is a single source file so its installation footprint is pretty small. MIT license permits both noncommercial and commercial use.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "javascript", "python", "regex" ]
stackoverflow_0002118261_javascript_python_regex.txt
Q: How do I get stacktraces from epydoc when it is loading my code? When I load my code into epydoc and just load the top module it fails with: Error: TypeError: 'NoneType' object is not callable (line 10) Where the the NoneType that it is referring to is a submodule that I tried to load on line 9. How can I get epydoc to explain why it couldn't load the module on line 9 instead of just plowing ahead and hitting an error? Per nosko's request. Here is similar example, where no stack trace is given: # foo.py import bar bar.baz() # bar.py def baz(): print 'baz' import os os.environ['DOES_NOT_EXIST'] Run with: python2.6 epydoc --html foo.py Produces the less than useful: +-------------------------------------- | In /home/ross/foo.py: | Import failed (but source code parsing was successful). | Error: KeyError: 'DOES_NOT_EXIST' (line 1) I want epydoc to tell me that the failure is on line 6 of bar.py. I don't want it to complain about foo.py's import of bar.py. I can't reproduce my specific problem in a small example, but my fundamental request is that when epydoc fails, I want it to print a stack trace to point to the issue. Whether it is loading a sub-module or calling not finding a key in a dictionary. NOTE: The root of this problem is that the code I am trying to document is an input to SCons which has different environment setup issues. That's why when I run in epydoc it doesn't work, but the script still works when run with scons -f SConstruct.py. I'm also trying to generate documentation with sphinx. When I run with sphinx it actually shows the stack trace. Maybe I'll go with sphinx... A: So if I understand correctly, the module you're running epydoc on imports a module that has an error in it (not the module you want to generate docs for)? If all you need to accomplish is to see the line in the file which has the error so you can debug it, you can pass in this file as well and the line number where the error occurred will be listed for that module. So, running: epydoc --check foo.py bar.py Will output: +------------------------------------------------------------------------------------------------------------ | In /home/mark/Desktop/foo.py: | Import failed (but source code parsing was successful). | Error: KeyError: 'DOES_NOT_EXIST' (line 2) | +------------------------------------------------------------------------------------------------------------ | In /home/mark/Desktop/bar.py: | Import failed (but source code parsing was successful). | Error: KeyError: 'DOES_NOT_EXIST' (line 7) | Since Bar.py is also analyzed, the line number where the error occurred in this file is listed. Now, if you're looking for a more robust solution because this is a common problem you need to deal with then you're going to have to start hacking the epydoc internals. Having done so myself, I'd advise you to avoid running down this rabbit hole if you can. If switching to Sphinx is an option, I'd recommend this route.
How do I get stacktraces from epydoc when it is loading my code?
When I load my code into epydoc and just load the top module it fails with: Error: TypeError: 'NoneType' object is not callable (line 10) Where the the NoneType that it is referring to is a submodule that I tried to load on line 9. How can I get epydoc to explain why it couldn't load the module on line 9 instead of just plowing ahead and hitting an error? Per nosko's request. Here is similar example, where no stack trace is given: # foo.py import bar bar.baz() # bar.py def baz(): print 'baz' import os os.environ['DOES_NOT_EXIST'] Run with: python2.6 epydoc --html foo.py Produces the less than useful: +-------------------------------------- | In /home/ross/foo.py: | Import failed (but source code parsing was successful). | Error: KeyError: 'DOES_NOT_EXIST' (line 1) I want epydoc to tell me that the failure is on line 6 of bar.py. I don't want it to complain about foo.py's import of bar.py. I can't reproduce my specific problem in a small example, but my fundamental request is that when epydoc fails, I want it to print a stack trace to point to the issue. Whether it is loading a sub-module or calling not finding a key in a dictionary. NOTE: The root of this problem is that the code I am trying to document is an input to SCons which has different environment setup issues. That's why when I run in epydoc it doesn't work, but the script still works when run with scons -f SConstruct.py. I'm also trying to generate documentation with sphinx. When I run with sphinx it actually shows the stack trace. Maybe I'll go with sphinx...
[ "So if I understand correctly, the module you're running epydoc on imports a module that has an error in it (not the module you want to generate docs for)? \nIf all you need to accomplish is to see the line in the file which has the error so you can debug it, you can pass in this file as well and the line number where the error occurred will be listed for that module.\nSo, running: \nepydoc --check foo.py bar.py\n\nWill output:\n+------------------------------------------------------------------------------------------------------------\n| In /home/mark/Desktop/foo.py:\n| Import failed (but source code parsing was successful).\n| Error: KeyError: 'DOES_NOT_EXIST' (line 2)\n| \n+------------------------------------------------------------------------------------------------------------\n| In /home/mark/Desktop/bar.py:\n| Import failed (but source code parsing was successful).\n| Error: KeyError: 'DOES_NOT_EXIST' (line 7)\n| \n\nSince Bar.py is also analyzed, the line number where the error occurred in this file is listed.\nNow, if you're looking for a more robust solution because this is a common problem you need to deal with then you're going to have to start hacking the epydoc internals. Having done so myself, I'd advise you to avoid running down this rabbit hole if you can. If switching to Sphinx is an option, I'd recommend this route. \n" ]
[ 2 ]
[]
[]
[ "epydoc", "python" ]
stackoverflow_0002121268_epydoc_python.txt
Q: rstrip not removing newline char what am I doing wrong? Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence. def add_quotes( fpath ): ifile = open( fpath, 'r' ) ofile = open( 'ofile.txt', 'w' ) for line in ifile: if line == '\n': ofile.write( "\n\n" ) elif len( line ) > 1: line.rstrip('\n') convertedline = "\"" + line + "\", " ofile.write( convertedline ) ifile.close() ofile.close() A: The clue is in the signature of rstrip. It returns a copy of the string, but with the desired characters stripped, thus you'll need to assign line the new value: line = line.rstrip('\n') This allows for the sometimes very handy chaining of operations: "a string".strip().upper() As Max. S says in the comments, Python strings are immutable which means that any "mutating" operation will yield a mutated copy. This is how it works in many frameworks and languages. If you really need to have a mutable string type (usually for performance reasons) there are string buffer classes. A: you can do it like this def add_quotes( fpath ): ifile = open( fpath, 'r' ) ofile = open( 'ofile.txt', 'w' ) for line in ifile: line=line.rstrip() convertedline = '"' + line + '", ' ofile.write( convertedline + "\n" ) ifile.close() ofile.close() A: As alluded to in Skurmedel's answer and the comments, you need to do something like: stripped_line = line.rstrip() and then write out stripped_line.
rstrip not removing newline char what am I doing wrong?
Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence. def add_quotes( fpath ): ifile = open( fpath, 'r' ) ofile = open( 'ofile.txt', 'w' ) for line in ifile: if line == '\n': ofile.write( "\n\n" ) elif len( line ) > 1: line.rstrip('\n') convertedline = "\"" + line + "\", " ofile.write( convertedline ) ifile.close() ofile.close()
[ "The clue is in the signature of rstrip.\nIt returns a copy of the string, but with the desired characters stripped, thus you'll need to assign line the new value:\nline = line.rstrip('\\n')\n\nThis allows for the sometimes very handy chaining of operations:\n\"a string\".strip().upper()\n\nAs Max. S says in the comments, Python strings are immutable which means that any \"mutating\" operation will yield a mutated copy.\nThis is how it works in many frameworks and languages. If you really need to have a mutable string type (usually for performance reasons) there are string buffer classes.\n", "you can do it like this\ndef add_quotes( fpath ):\n ifile = open( fpath, 'r' )\n ofile = open( 'ofile.txt', 'w' )\n for line in ifile:\n line=line.rstrip()\n convertedline = '\"' + line + '\", '\n ofile.write( convertedline + \"\\n\" )\n ifile.close()\n ofile.close()\n\n", "As alluded to in Skurmedel's answer and the comments, you need to do something like:\nstripped_line = line.rstrip()\n\nand then write out stripped_line.\n" ]
[ 35, 3, 3 ]
[]
[]
[ "newline", "python" ]
stackoverflow_0002121839_newline_python.txt
Q: How to report a bug with Python's 'help()' function? As a hobby/learning project, I'm writing a parser generator in Python. One of my code files is named "token.py" - which contains a couple of classes for turning plain strings into Token objects. I've just discovered that using the "help()" function from the console in Python raises an error for any module defined in a directory that contains a "token.py". Here's a way to reproduce the error. Create a new directory with the following files: /New Folder main.py token.py Leave 'token.py' blank. In main.py, write a simple function - for example: def test(): pass Then, in your Python console, import 'main' and call 'help(main.test)' - here's what you'll get: C:\New Folder>python Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import main >>> help(main.test) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python31\lib\site.py", line 428, in __call__ import pydoc File "C:\Python31\lib\pydoc.py", line 55, in <module> import sys, imp, os, re, inspect, builtins, pkgutil File "C:\Python31\lib\inspect.py", line 40, in <module> import tokenize File "C:\Python31\lib\tokenize.py", line 37, in <module> COMMENT = N_TOKENS NameError: name 'N_TOKENS' is not defined >>> If you delete the 'token.py' file, help() will behave normally. Both Python 3.1 and Python 2.5 exhibit this behavior. Is this a known issue? If not, how do I report it? EDIT: Several comments state that this behavior isn't a bug. The module that defines "help" imports a module called "token" from Python's standard library. However, Python looks in the application folder before it looks in its library to find modules. In the example above, "help" tries to use my "token.py" instead of Python's, which causes the error. Since Python is defined to exhibit this behavior, I suppose it isn't a bug. But why do people think that this behavior is acceptable? It implies that adding new modules to Python's library - even without changing existing modules - could break existing applications. It also implies that programmers are expected to have memorized the names of all modules in Python's library - how is that any less ridiculous than expecting programmers to memorize every namespace in .NET or Java? Why don't Python applications get their own namespaces? Why aren't Python standard library modules in their own namespace? A: The problem is that your local token.py is being imported by help() instead of Python's actual token.py. This will occur for any number of .py files whose names collide with built-in modules. For example, try creating a pydoc.py file in the CWD and then try help() in Python. The help() function is just a built-in Python function, so it follows the same import path as any other Python code. A: Whenever you choose to name your modules in a way that mimics module names defined in Python's standard library, you're fully responsible for whatever happens as a result -- other Python standard library modules are likely to rely on those that you are hiding/overriding, and if your own modules don't carefully mimic the functionality of the modules you're hiding, that's not a bug with Python: it's a bug with your code. Of course, this applies to module token as much as to any other. If this is happening to you accidentally, and you're looking for a way to check your code for likely bugs or iffy constructs (rather than, as you say, for a way to report a nonexisting bug with the Python standard library), I think tools like pylint may be able to help. A: You can search for issues and report new ones here: http://bugs.python.org/. A: This isn't a bug with the the help() method. There is a module in the standard library named token.py which is imported by tokenize.py (where the error you're seeing originates from). from tokenize.py: from token import * So tokenize.py expects to have a bunch of variables from the standard library token.py, but since the token.py in your working directory is actually imported they are not present which is causing the NameError (one amoungst many reasons import * shouldn't be used).
How to report a bug with Python's 'help()' function?
As a hobby/learning project, I'm writing a parser generator in Python. One of my code files is named "token.py" - which contains a couple of classes for turning plain strings into Token objects. I've just discovered that using the "help()" function from the console in Python raises an error for any module defined in a directory that contains a "token.py". Here's a way to reproduce the error. Create a new directory with the following files: /New Folder main.py token.py Leave 'token.py' blank. In main.py, write a simple function - for example: def test(): pass Then, in your Python console, import 'main' and call 'help(main.test)' - here's what you'll get: C:\New Folder>python Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import main >>> help(main.test) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python31\lib\site.py", line 428, in __call__ import pydoc File "C:\Python31\lib\pydoc.py", line 55, in <module> import sys, imp, os, re, inspect, builtins, pkgutil File "C:\Python31\lib\inspect.py", line 40, in <module> import tokenize File "C:\Python31\lib\tokenize.py", line 37, in <module> COMMENT = N_TOKENS NameError: name 'N_TOKENS' is not defined >>> If you delete the 'token.py' file, help() will behave normally. Both Python 3.1 and Python 2.5 exhibit this behavior. Is this a known issue? If not, how do I report it? EDIT: Several comments state that this behavior isn't a bug. The module that defines "help" imports a module called "token" from Python's standard library. However, Python looks in the application folder before it looks in its library to find modules. In the example above, "help" tries to use my "token.py" instead of Python's, which causes the error. Since Python is defined to exhibit this behavior, I suppose it isn't a bug. But why do people think that this behavior is acceptable? It implies that adding new modules to Python's library - even without changing existing modules - could break existing applications. It also implies that programmers are expected to have memorized the names of all modules in Python's library - how is that any less ridiculous than expecting programmers to memorize every namespace in .NET or Java? Why don't Python applications get their own namespaces? Why aren't Python standard library modules in their own namespace?
[ "The problem is that your local token.py is being imported by help() instead of Python's actual token.py. This will occur for any number of .py files whose names collide with built-in modules. For example, try creating a pydoc.py file in the CWD and then try help() in Python. The help() function is just a built-in Python function, so it follows the same import path as any other Python code.\n", "Whenever you choose to name your modules in a way that mimics module names defined in Python's standard library, you're fully responsible for whatever happens as a result -- other Python standard library modules are likely to rely on those that you are hiding/overriding, and if your own modules don't carefully mimic the functionality of the modules you're hiding, that's not a bug with Python: it's a bug with your code. Of course, this applies to module token as much as to any other.\nIf this is happening to you accidentally, and you're looking for a way to check your code for likely bugs or iffy constructs (rather than, as you say, for a way to report a nonexisting bug with the Python standard library), I think tools like pylint may be able to help.\n", "You can search for issues and report new ones here: http://bugs.python.org/. \n", "This isn't a bug with the the help() method. There is a module in the standard library named token.py which is imported by tokenize.py (where the error you're seeing originates from).\nfrom tokenize.py:\nfrom token import *\n\nSo tokenize.py expects to have a bunch of variables from the standard library token.py, but since the token.py in your working directory is actually imported they are not present which is causing the NameError (one amoungst many reasons import * shouldn't be used). \n" ]
[ 5, 3, 1, 0 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0002121715_namespaces_python.txt
Q: Inline parsing in BeautifulSoup in Python I am writing an HTML document with BeautifulSoup, and I would like it to not split inline text (such as text within the <p> tag) into multiple lines. The issue that I get is that parsing the <p>a<span>b</span>c</p> with prettify gives me the output <p> a <span> b </span> c </p> and now the HTML displays spaces between a,b,c, which I do not want. How do I avoid this? A: How about not using prettify at all? BeautifulSoup.BeautifulSoup('<p>a<span>b</span>c</p>').renderContents() outputs the original HTML with no extra spaces. You can use e.g. Firebug to have a closer look at the document's structure later with no need to 'prettify' it at construction time. A: I'd just do: from BeautifulSoup import BeautifulSoup ht = '<p>a<span>b</span>c</p>' soup = BeautifulSoup(ht) print soup and avoid getting any extra whitespace. prettify's job is exactly to adjust whitespace to clearly show the HTML parse tree's structure, after all...!
Inline parsing in BeautifulSoup in Python
I am writing an HTML document with BeautifulSoup, and I would like it to not split inline text (such as text within the <p> tag) into multiple lines. The issue that I get is that parsing the <p>a<span>b</span>c</p> with prettify gives me the output <p> a <span> b </span> c </p> and now the HTML displays spaces between a,b,c, which I do not want. How do I avoid this?
[ "How about not using prettify at all?\nBeautifulSoup.BeautifulSoup('<p>a<span>b</span>c</p>').renderContents()\n\noutputs the original HTML with no extra spaces. You can use e.g. Firebug to have a closer look at the document's structure later with no need to 'prettify' it at construction time.\n", "I'd just do:\nfrom BeautifulSoup import BeautifulSoup\n\nht = '<p>a<span>b</span>c</p>'\nsoup = BeautifulSoup(ht)\nprint soup\n\nand avoid getting any extra whitespace. prettify's job is exactly to adjust whitespace to clearly show the HTML parse tree's structure, after all...!\n" ]
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0002121036_beautifulsoup_html_python.txt
Q: What side effects should one expect when method decorator replaces self? I want to execute a method with a copy of the original self passed while execution. Here is the code I'm talking about: def protect_self(func): from copy import copy from functools import wraps @wraps(func) def decorated(self, *args, **kwargs): self_copy = copy(self) return func(self_copy, *args, **kwargs) return decorated In my understanding the copy function creates a new object of the same type and copies the __dict__ of the old one to the new object (using references, so changes to actual object instances in __dict__ will still affect the original object). Does this mean I can be sure that the decorated method cannot modify __dict__ of the original instance? Just to make sure: I don't need a secure sandbox behaviour. My purpose is just to have a single object instanciated which I will use as a factory. The protected method should be possible to modify the passed self but it should be reseted afterwards. A: The copy makes it so the 'self' passed to the decorated function is a shallow copy of the original. The decorated function can't modify the original 'self' directly, although it can of course modify it through other means (if it has indirect access to it.) If any of the attributes of the object are mutable, it can effectively change the original 'self' by modifying the attributes. Additionally, any piece of (arbitrary) Python code has indirect access to pretty much any object in the program. The decorated function could gain access to the original 'self' through stack inspection, or through the gc module, for example. Your usecase seems a little convoluted; are you sure you should be using a class instance for this? A: As the OP clarified in a comment that the purpose is to be threadsafe, then there's an obvious issue -- copy.copy itself isn't threadsafe, in addition to the issue already pointed out, that copy.copy makes a shallow copy and so (while self.__dict__ itself won't be modified) mutable objects can perfectly well get altered. Using copy.deepcopy deals with this (at a potentially hefty price in terms of performance) but in a sense even worsens the issue of thread-safety (since deep-copying can take so much longer than shallow-copying, the risk of a race condition actually occurring grows by leaps and bounds -- not that I'm in any way, shape or form recommending having race conditions that occur "only rarely", mind!-). If you have to make originally-unsafe methods thread-safe, you'll have to bite the bullet and use locks (or a Queue and an auxiliary thread to serialize the operations) -- I guess that if you further need to silently ignore the methods' attempts to alter objects, you'll moreover have to deepcopy everything (why stop at self -- what if those methods were altering globals, for example?!-). Seem a very iffy proposition to me.
What side effects should one expect when method decorator replaces self?
I want to execute a method with a copy of the original self passed while execution. Here is the code I'm talking about: def protect_self(func): from copy import copy from functools import wraps @wraps(func) def decorated(self, *args, **kwargs): self_copy = copy(self) return func(self_copy, *args, **kwargs) return decorated In my understanding the copy function creates a new object of the same type and copies the __dict__ of the old one to the new object (using references, so changes to actual object instances in __dict__ will still affect the original object). Does this mean I can be sure that the decorated method cannot modify __dict__ of the original instance? Just to make sure: I don't need a secure sandbox behaviour. My purpose is just to have a single object instanciated which I will use as a factory. The protected method should be possible to modify the passed self but it should be reseted afterwards.
[ "The copy makes it so the 'self' passed to the decorated function is a shallow copy of the original. The decorated function can't modify the original 'self' directly, although it can of course modify it through other means (if it has indirect access to it.) If any of the attributes of the object are mutable, it can effectively change the original 'self' by modifying the attributes.\nAdditionally, any piece of (arbitrary) Python code has indirect access to pretty much any object in the program. The decorated function could gain access to the original 'self' through stack inspection, or through the gc module, for example. Your usecase seems a little convoluted; are you sure you should be using a class instance for this?\n", "As the OP clarified in a comment that the purpose is to be threadsafe, then there's an obvious issue -- copy.copy itself isn't threadsafe, in addition to the issue already pointed out, that copy.copy makes a shallow copy and so (while self.__dict__ itself won't be modified) mutable objects can perfectly well get altered. Using copy.deepcopy deals with this (at a potentially hefty price in terms of performance) but in a sense even worsens the issue of thread-safety (since deep-copying can take so much longer than shallow-copying, the risk of a race condition actually occurring grows by leaps and bounds -- not that I'm in any way, shape or form recommending having race conditions that occur \"only rarely\", mind!-).\nIf you have to make originally-unsafe methods thread-safe, you'll have to bite the bullet and use locks (or a Queue and an auxiliary thread to serialize the operations) -- I guess that if you further need to silently ignore the methods' attempts to alter objects, you'll moreover have to deepcopy everything (why stop at self -- what if those methods were altering globals, for example?!-). Seem a very iffy proposition to me.\n" ]
[ 2, 1 ]
[]
[]
[ "decorator", "python", "self" ]
stackoverflow_0002120563_decorator_python_self.txt
Q: Problem allocating heap space over 4 GB when calling java "from Python" I am using using os.system call from python to run jar file. The jar file requires large heap space and thus i am allocating 4 Gb heap space using Xmx. When i execute the command "java -Xms4096m -Xmx4096m -jar camXnet.jar net.txt" from command line it executes properly, however when i call it from a python program via os.system, it works only if memory allocated is less than 4Gb, otherwise it fails to execute. Any solutions? By fails to execute i mean that A command window appears indicating that os.system has been called and then it disappears, i will check for the error code if any being returned. however no problems are encountered if xmx,xms are set to lower value. Ok i checked both version and there is a difference The one being called via python is Java HotSpot Client VM mixed mode,sharing while one being called via normal command line is Java HotSpot 64 bit server How do make os.system in python call the correct one that is the 64 bit server. UPDATE: I tried using subprocess module as yet the version of java return is same as that from os.system A: It's hard to be sure without knowing more detail - like which OS you're on - but my guess is that you're using a 32-bit version of Python which means that when you launch Java, you're also getting the 32-bit version which has a heap size limit of 4GB. To test if this is the case, compare the output of java -version when run from the command line and when run from your Python script. A: I was having the same problem launching 64bit Java from 32bit python. I solved the problem using Dave Webb's suggestiong of putting the full path to 64bit Java.exe in the python script. This worked fine so it is not necessary to use 64 bit Python A: Just a suggestion, but try using subprocess.call() instead of os.system(), it is preferred and may handle the issue you are experiencing. I'm curious to know if it does...
Problem allocating heap space over 4 GB when calling java "from Python"
I am using using os.system call from python to run jar file. The jar file requires large heap space and thus i am allocating 4 Gb heap space using Xmx. When i execute the command "java -Xms4096m -Xmx4096m -jar camXnet.jar net.txt" from command line it executes properly, however when i call it from a python program via os.system, it works only if memory allocated is less than 4Gb, otherwise it fails to execute. Any solutions? By fails to execute i mean that A command window appears indicating that os.system has been called and then it disappears, i will check for the error code if any being returned. however no problems are encountered if xmx,xms are set to lower value. Ok i checked both version and there is a difference The one being called via python is Java HotSpot Client VM mixed mode,sharing while one being called via normal command line is Java HotSpot 64 bit server How do make os.system in python call the correct one that is the 64 bit server. UPDATE: I tried using subprocess module as yet the version of java return is same as that from os.system
[ "It's hard to be sure without knowing more detail - like which OS you're on - but my guess is that you're using a 32-bit version of Python which means that when you launch Java, you're also getting the 32-bit version which has a heap size limit of 4GB.\nTo test if this is the case, compare the output of java -version when run from the command line and when run from your Python script.\n", "I was having the same problem launching 64bit Java from 32bit python. I solved the problem using Dave Webb's suggestiong of putting the full path to 64bit Java.exe in the python script. This worked fine so it is not necessary to use 64 bit Python\n", "Just a suggestion, but try using subprocess.call() instead of os.system(), it is preferred and may handle the issue you are experiencing. I'm curious to know if it does...\n" ]
[ 2, 1, 0 ]
[]
[]
[ "java", "python", "ram" ]
stackoverflow_0002000331_java_python_ram.txt
Q: Can Someone Explain Threads to Me? I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? A: This is a very broad topic. But here are the things I would want to know if I knew nothing about threads: They are units of execution within a single process that happen "in parallel" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via different means. Switching is called "context switching", and there is some overhead associated with this. They can share memory! This is where problems can occur. I talk about this more in depth in a later bullet point. The benefit of parallelizing your application is that logic that uses different parts of the machine can happen simultaneously. That is, if part of your process is I/O-bound and part of it is CPU-bound, the I/O intensive operation doesn't have to wait until the CPU-intensive operation is done. Some languages also allow you to run threads at the same time if you have a multicore processor (and thus parallelize CPU-intensive operations as well), though this is not always the case. Thread-safe means that there are no race conditions, which is the term used for problems that occur when the execution of your process depends on timing (something you don't want to rely on). For example, if you have threads A and B both incrementing a shared counter C, you could see the case where A reads the value of C, then B reads the value of C, then A overwrites C with C+1, then B overwrites C with C+1. Notice that C only actually increments once! A couple of common ways avoid race conditions include synchronization, which excludes mutual access to shared state, or just not having any shared state at all. But this is just the tip of the iceberg - thread-safety is quite a broad topic. I hope that helps! Understand that this was a very quick introduction to something that requires a good bit of learning. I would recommend finding a resource about multithreading in your preferred language, whatever that happens to be, and giving it a thorough read. A: There are four things you should know about threads. Threads are like processes, but they share memory. Threads often have hardware, OS, and language support, which might make them better than processes. There are lots of fussy little things that threads need to support (like locks and semaphores) so they don't get the memory they share into an inconsistent state. This makes them a little difficult to use. Locking isn't automatic (in the languages I know), so you have to be very careful with the memory they (implicitly) share. A: Threads don't speed up applications. Algorithms speed up applications. Threads can be used in algorithms, if appropriate. A: Well someone will probably answer this better, but threads are for the purpose of having background processing that won't freeze the user interface. You don't want to stop accepting keyboard input or mouse input, and tell the user, "just a moment, I want to finish this computation, it will only be a few more seconds." (And yet its amazing how many times commercial programs do this. As far as thread safe, it means a function that does not have some internal saved state. If it did you couldn't have multiple threads using it simutaneously. As far as thread programming you just have to start doing it, and then you'll start encountering various issues unique to thread programming, for example simultaneuous access to data, in which case you have to decide to use some syncronization method such as critical sections or mutexes or something else, each one having slightly different nuances in their behavior. As far as the differences between processes and threads (which you didn't ask) processes are an OS level entity, whereas threads are associated with a program. In certain instances your program may want to create a process rather than a thread. A: Threads are simply a way of executing multiple things simultaneously (assuming that the platform on which they are being run is capable of parallel execution). Thread safety is simply (well, nothing with threads is truly simple) making sure that the threads don't affect each other in harmful ways. In general, you are unlikely to see systems use multiple threads for rendering graphics on the screen due to the multiple performance implications and complexity issues that may arise from that. Other tasks related to state management (or AI) can potentially be moved to separate threads however. A: First rule of threading: don't thread. Second rule of threading: if you have to violate rule one...don't. Third rule: OK, fine you have to use threads, so before proceeding get your head into the pitfalls, understand locking and the common thread problems such as deadlock and livelocking. Understand that threading does not speed up anything, it is only useful to background long-running processes allowing the user can do something else with the application. If you have to allow the user to interact with the application while the app does something else in the background, like poll a socket or wait for ansynchronous input from elsewhere in the application, then you may indeed require threading. The thread sections in both Effective Java and Clean Code are good introductions to threads and their pitfalls. A: Since the question is tagged with 'Java', I assume you are familiar with Java, in which case this is a great introductory tutorial http://java.sun.com/docs/books/tutorial/essential/concurrency/ A: Orm, great question to ask. I think all serious programmers should learn about threads, cause eventually you will at least consider using them and you really want to be prepared when it happens. Concurrency bugs can be incredibly subtle and the best way to avoid them is to know what idioms are safe(-ish). I highly recommend you take the time to read the book Concurrent Programming in Java: Design Principles and Patterns by Doug Lea: http://gee.cs.oswego.edu/dl/cpj/ Lea takes the time not only to teach you the concepts, but also to show you the correct and incorrect ways to use the concurrent programming primitives (in Java but also helpful for any other environment that uses shared-memory locking/signaling style concurrency). Most of all he teaches respect for the difficulty of concurrent programming. I should add that this style of concurrent programming is the most common but not the only approach. There's also message passing, which is safer but forces you to structure your algorithm differently. A: Since the original post is very broad, and also tagged with C++, I think the following pointers are relevant: Anthony Williams, maintainer of the Boost Thread Library, has been working on a book called "C++ Concurrency in Action", a description of which you can find here. The first (introductory) chapter is available for free in pdf form here. Also, Herb Sutter (known, among other things, for his "Exceptional C++" series) has been writing a book to be called "Effective Concurrency", many articles of which are available in draft form here. A: There's a nice book, Java Concurrency in Practice, http://www.javaconcurrencyinpractice.com/ .
Can Someone Explain Threads to Me?
I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here?
[ "This is a very broad topic. But here are the things I would want to know if I knew nothing about threads:\n\nThey are units of execution within a single process that happen \"in parallel\" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via different means. Switching is called \"context switching\", and there is some overhead associated with this.\nThey can share memory! This is where problems can occur. I talk about this more in depth in a later bullet point.\nThe benefit of parallelizing your application is that logic that uses different parts of the machine can happen simultaneously. That is, if part of your process is I/O-bound and part of it is CPU-bound, the I/O intensive operation doesn't have to wait until the CPU-intensive operation is done. Some languages also allow you to run threads at the same time if you have a multicore processor (and thus parallelize CPU-intensive operations as well), though this is not always the case.\nThread-safe means that there are no race conditions, which is the term used for problems that occur when the execution of your process depends on timing (something you don't want to rely on). For example, if you have threads A and B both incrementing a shared counter C, you could see the case where A reads the value of C, then B reads the value of C, then A overwrites C with C+1, then B overwrites C with C+1. Notice that C only actually increments once!\nA couple of common ways avoid race conditions include synchronization, which excludes mutual access to shared state, or just not having any shared state at all. But this is just the tip of the iceberg - thread-safety is quite a broad topic.\n\nI hope that helps! Understand that this was a very quick introduction to something that requires a good bit of learning. I would recommend finding a resource about multithreading in your preferred language, whatever that happens to be, and giving it a thorough read.\n", "There are four things you should know about threads.\n\nThreads are like processes, but they share memory.\nThreads often have hardware, OS, and language support, which might make them better than processes. \nThere are lots of fussy little things that threads need to support (like locks and semaphores) so they don't get the memory they share into an inconsistent state. This makes them a little difficult to use.\nLocking isn't automatic (in the languages I know), so you have to be very careful with the memory they (implicitly) share.\n\n", "Threads don't speed up applications. Algorithms speed up applications. Threads can be used in algorithms, if appropriate.\n", "Well someone will probably answer this better, but threads are for the purpose of having background processing that won't freeze the user interface. You don't want to stop accepting keyboard input or mouse input, and tell the user, \"just a moment, I want to finish this computation, it will only be a few more seconds.\" (And yet its amazing how many times commercial programs do this.\nAs far as thread safe, it means a function that does not have some internal saved state. If it did you couldn't have multiple threads using it simutaneously.\nAs far as thread programming you just have to start doing it, and then you'll start encountering various issues unique to thread programming, for example simultaneuous access to data, in which case you have to decide to use some syncronization method such as critical sections or mutexes or something else, each one having slightly different nuances in their behavior.\nAs far as the differences between processes and threads (which you didn't ask) processes are an OS level entity, whereas threads are associated with a program. In certain instances your program may want to create a process rather than a thread.\n", "Threads are simply a way of executing multiple things simultaneously (assuming that the platform on which they are being run is capable of parallel execution). Thread safety is simply (well, nothing with threads is truly simple) making sure that the threads don't affect each other in harmful ways.\nIn general, you are unlikely to see systems use multiple threads for rendering graphics on the screen due to the multiple performance implications and complexity issues that may arise from that. Other tasks related to state management (or AI) can potentially be moved to separate threads however.\n", "First rule of threading: don't thread. Second rule of threading: if you have to violate rule one...don't. Third rule: OK, fine you have to use threads, so before proceeding get your head into the pitfalls, understand locking and the common thread problems such as deadlock and livelocking. \nUnderstand that threading does not speed up anything, it is only useful to background long-running processes allowing the user can do something else with the application. If you have to allow the user to interact with the application while the app does something else in the background, like poll a socket or wait for ansynchronous input from elsewhere in the application, then you may indeed require threading.\nThe thread sections in both Effective Java and Clean Code are good introductions to threads and their pitfalls. \n", "Since the question is tagged with 'Java', I assume you are familiar with Java, in which case this is a great introductory tutorial\nhttp://java.sun.com/docs/books/tutorial/essential/concurrency/\n", "Orm, great question to ask. I think all serious programmers should learn about threads, cause eventually you will at least consider using them and you really want to be prepared when it happens. Concurrency bugs can be incredibly subtle and the best way to avoid them is to know what idioms are safe(-ish).\nI highly recommend you take the time to read the book Concurrent Programming in Java: Design Principles and Patterns by Doug Lea:\nhttp://gee.cs.oswego.edu/dl/cpj/\nLea takes the time not only to teach you the concepts, but also to show you the correct and incorrect ways to use the concurrent programming primitives (in Java but also helpful for any other environment that uses shared-memory locking/signaling style concurrency). Most of all he teaches respect for the difficulty of concurrent programming.\nI should add that this style of concurrent programming is the most common but not the only approach. There's also message passing, which is safer but forces you to structure your algorithm differently.\n", "Since the original post is very broad, and also tagged with C++, I think the following pointers are relevant:\nAnthony Williams, maintainer of the Boost Thread Library, has been working on a book called \"C++ Concurrency in Action\", a description of which you can find here. The first (introductory) chapter is available for free in pdf form here.\nAlso, Herb Sutter (known, among other things, for his \"Exceptional C++\" series) has been writing a book to be called \"Effective Concurrency\", many articles of which are available in draft form here.\n", "There's a nice book, Java Concurrency in Practice, http://www.javaconcurrencyinpractice.com/ .\n" ]
[ 32, 2, 1, 1, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "c++", "java", "multithreading", "perl", "python" ]
stackoverflow_0002121617_c++_java_multithreading_perl_python.txt
Q: Can someone help clarify my confusion about syncdb and import loops, 'Do you have to be explicit on imports?' I have been having a difficult time building the database with syncdb on Python2.5. I think that some of this issue is because of the use of wildcard* for importing forum.models it seems to be creating a loop. >>> import settings >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/username/webapps/username/sousvide_app/forum/managers.py", line 6, in <module> from forum.models import * File "/home/username/webapps/username/sousvide_app/forum/models.py", line 18, in <module> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager ImportError: cannot import name QuestionManager >>> from forum.models import Question, Tag >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager >>> import sys, pprint >>> pprint.pprint(sys.path) ['/home/username/webapps/username/sousvide_app', '/home/username/webapps/username/lib/python2.5', '/home/username/lib/python2.5/markdown2-1.0.1.16-py2.5.egg', '/home/username/lib/python2.5/html5lib-0.11.1-py2.5.egg', '/home/username/lib/python2.5', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/PIL'] >>> from settings import INSTALLED_APPS >>> pprint.pprint(INSTALLED_APPS) ('sousvide_app.forum', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.humanize', 'django_authopenid') I had the same issue on another install that I was able to fix by explicitly importing the managers from forum.managers . As you can see, if I load Question and Tag models into the namespace I'm able to import the managers in the shell. I made the from forum.models import * explicit: from forum.models import Question, Tag However, I'm still not able to syncdb. When I try to output the SQL the APP can't be found. $ python2.5 manage.py sql forum Error: App with label forum could not be found. Are you sure your INSTALLED_APPS setting is correct? Can anyone give me an idea what is going wrong? Is there something about Python2.5 that could contribute to this error? A: Would you happen to be using global_settings.py or local_settings.py in addition to settings.py? The proper way to import Django's settings is to use the decoupled object from django.conf import settings, NOT to import settings. See the doc page about it here: Using settings in Python code I can't say for certain if that's the fix to your problem, but it's a step in the right direction to make sure your settings are being loaded properly if you say your issue is apps not showing up in INSTALLED_APPS.
Can someone help clarify my confusion about syncdb and import loops, 'Do you have to be explicit on imports?'
I have been having a difficult time building the database with syncdb on Python2.5. I think that some of this issue is because of the use of wildcard* for importing forum.models it seems to be creating a loop. >>> import settings >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/username/webapps/username/sousvide_app/forum/managers.py", line 6, in <module> from forum.models import * File "/home/username/webapps/username/sousvide_app/forum/models.py", line 18, in <module> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager ImportError: cannot import name QuestionManager >>> from forum.models import Question, Tag >>> from forum.managers import QuestionManager, TagManager, AnswerManager, VoteManager, FlaggedItemManager, ReputeManager, AwardManager >>> import sys, pprint >>> pprint.pprint(sys.path) ['/home/username/webapps/username/sousvide_app', '/home/username/webapps/username/lib/python2.5', '/home/username/lib/python2.5/markdown2-1.0.1.16-py2.5.egg', '/home/username/lib/python2.5/html5lib-0.11.1-py2.5.egg', '/home/username/lib/python2.5', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/PIL'] >>> from settings import INSTALLED_APPS >>> pprint.pprint(INSTALLED_APPS) ('sousvide_app.forum', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.humanize', 'django_authopenid') I had the same issue on another install that I was able to fix by explicitly importing the managers from forum.managers . As you can see, if I load Question and Tag models into the namespace I'm able to import the managers in the shell. I made the from forum.models import * explicit: from forum.models import Question, Tag However, I'm still not able to syncdb. When I try to output the SQL the APP can't be found. $ python2.5 manage.py sql forum Error: App with label forum could not be found. Are you sure your INSTALLED_APPS setting is correct? Can anyone give me an idea what is going wrong? Is there something about Python2.5 that could contribute to this error?
[ "Would you happen to be using global_settings.py or local_settings.py in addition to settings.py?\nThe proper way to import Django's settings is to use the decoupled object from django.conf import settings, NOT to import settings. See the doc page about it here: Using settings in Python code\nI can't say for certain if that's the fix to your problem, but it's a step in the right direction to make sure your settings are being loaded properly if you say your issue is apps not showing up in INSTALLED_APPS.\n" ]
[ 0 ]
[]
[]
[ "django", "django_syncdb", "python" ]
stackoverflow_0002120870_django_django_syncdb_python.txt
Q: Is it acceptable to use tricks to save programmer when putting data in your code? Example: It's really annoying to type a list of strings in python: ["January", "February", "March", "April", ...] I often do something like this to save me having to type quotation marks all over the place: "January February March April May June July August ...".split() Those took the same amount of time, and I got 2x the # of months typed in. Another example: [('a', '9'), ('4', '3'), ('z', 'x')...] instead of: map(tuple, "a9 43 zx".split()) which took much less time. A: Code is usually read many times, and it is written only once. Saving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code. The second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about variable instantiation, not about algorithms! A: A good text editor can make these things a non-issue. For example, I can type the following line in my code: print `"January February March April May June July August September October November December".split()` And then using the key sequence V:!python<ENTER> I can run the line through the python interpreter, and the output is the following: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] I'm using Vim for my example, but I'm sure this is just as easy with Emacs, TextMate, etc. A: In a reasonably smart editor you could: Select the lines of interest, insert the replacement (<space> by "<space>" for the 1st ex.), check selected lines checkbox, click replace all, bam.. your done. Readable and easy to type... respect the power of the editor! A: In general, I think this is a bad idea. The first example isn't SO bad (it's sort of a substitute for python's lack of qw), but the second is much more difficult to understand. In particular, I think this sort of thing is very unpythonic, and certainly not appropriate when writing Python code, at any rate. Code readability is much more important than saving a little time writing the code. If you really have THAT much data to hardcode, write a script to generate it for you. A: How often do you really need to type ["January", "February"... etc]? Granted your approach might save you time but why add complexity to your code for no good reason other than you are a bit lazy? If you really do have to type it that often... Copy-Paste! A: In production code, do it the right way. In test code, as long as this idiom shows up more than once or twice, I think this is acceptable. If, in test code, this situation shows up once or twice, do it the right way. A: ...I often do something like this to save me having to type quotation marks all over the place... I think such a thing should be done only once per program. If you do the same "all over the place" then it doesn't matter which one do you use, you're creating a monster. Such declaration should be written only ONCE for all the code. A: It's a reasonable thing to do for data that you don't expect to change, such as months or days of the weeks. It's also reasonable to do this while mocking up or stubbing out interactions with files or databases, because it isolates your code for testing. However, this isn't a good long-term solution for production code, nor does it really save you much time. Anything big enough to allow big time-savings is big enough to require storing data someplace else, like a separate file o a database. A: I all but swear by Steve McConnell's Code Complete: one of the core insights is that bad programmers write code in order to get computers to do something, period, while good programmers write first to write code that people can understand and only second to get the computer to do things. (Having code that is written without readability as a major concern is like trying to find things in a closet or filing cabinet where people just cram stuff in without any thought to making something you can navigate and find things in.) I think you could profit a lot from reading Code Complete; I know I did. A: your quick and clever methods while nice, take more time to read which is not good. Readability comes first always. A: I don't think that type of thing should be in the source. If I were you, I'd have Python evaluate the respective second versions and then paste the results into my source code. A: I think putting statements like "January February March April May June July August ...".split() at module global level is fine. This way it is only executed once during import. I even sometimes use it in non-performance critical functions because of the reduced line noise. On a sidenote i think that Python Interpreters could be made to execute the "split()" at compile-time which would eradicate the method-call overhead. Reason being that a string is a builtin literal and Python does not allow to add/override methods on the very base string type so the compiler can know that "".split() can only refer to one specific method.
Is it acceptable to use tricks to save programmer when putting data in your code?
Example: It's really annoying to type a list of strings in python: ["January", "February", "March", "April", ...] I often do something like this to save me having to type quotation marks all over the place: "January February March April May June July August ...".split() Those took the same amount of time, and I got 2x the # of months typed in. Another example: [('a', '9'), ('4', '3'), ('z', 'x')...] instead of: map(tuple, "a9 43 zx".split()) which took much less time.
[ "Code is usually read many times, and it is written only once.\nSaving writing time at the expense of readability is not usually a good choice, unless you are doing some throw-away code.\nThe second version is less explicit, and you need some time to understand what the code is doing. And we are simply talking about variable instantiation, not about algorithms!\n", "A good text editor can make these things a non-issue. For example, I can type the following line in my code:\nprint `\"January February March April May June July August September October November December\".split()`\n\nAnd then using the key sequence V:!python<ENTER> I can run the line through the python interpreter, and the output is the following:\n['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\nI'm using Vim for my example, but I'm sure this is just as easy with Emacs, TextMate, etc.\n", "In a reasonably smart editor you could:\n\nSelect the lines of interest, \ninsert the replacement (<space> by \"<space>\" for the 1st ex.), \ncheck selected lines checkbox, \nclick replace all,\nbam.. your done.\n\nReadable and easy to type... respect the power of the editor!\n", "In general, I think this is a bad idea. The first example isn't SO bad (it's sort of a substitute for python's lack of qw), but the second is much more difficult to understand. In particular, I think this sort of thing is very unpythonic, and certainly not appropriate when writing Python code, at any rate. Code readability is much more important than saving a little time writing the code. If you really have THAT much data to hardcode, write a script to generate it for you.\n", "How often do you really need to type [\"January\", \"February\"... etc]?\nGranted your approach might save you time but why add complexity to your code for no good reason other than you are a bit lazy?\nIf you really do have to type it that often... Copy-Paste!\n", "In production code, do it the right way. In test code, as long as this idiom shows up more than once or twice, I think this is acceptable. If, in test code, this situation shows up once or twice, do it the right way. \n", "\n...I often do something like this to save me having to type quotation marks all over the place...\n\nI think such a thing should be done only once per program. If you do the same \"all over the place\" then it doesn't matter which one do you use, you're creating a monster. \nSuch declaration should be written only ONCE for all the code. \n", "It's a reasonable thing to do for data that you don't expect to change, such as months or days of the weeks. It's also reasonable to do this while mocking up or stubbing out interactions with files or databases, because it isolates your code for testing. However, this isn't a good long-term solution for production code, nor does it really save you much time. Anything big enough to allow big time-savings is big enough to require storing data someplace else, like a separate file o a database. \n", "I all but swear by Steve McConnell's Code Complete: one of the core insights is that bad programmers write code in order to get computers to do something, period, while good programmers write first to write code that people can understand and only second to get the computer to do things.\n(Having code that is written without readability as a major concern is like trying to find things in a closet or filing cabinet where people just cram stuff in without any thought to making something you can navigate and find things in.)\nI think you could profit a lot from reading Code Complete; I know I did.\n", "your quick and clever methods while nice, take more time to read which is not good. Readability comes first always. \n", "I don't think that type of thing should be in the source.\nIf I were you, I'd have Python evaluate the respective second versions and then paste the results into my source code.\n", "I think putting statements like\n\"January February March April May June July August ...\".split()\nat module global level is fine. This way it is only executed once during import. I even sometimes use it in non-performance critical functions because of the reduced line noise. \nOn a sidenote i think that Python Interpreters could be made to execute the \"split()\" at compile-time which would eradicate the method-call overhead. Reason being that a string is a builtin literal and Python does not allow to add/override methods on the very base string type so the compiler can know that \"\".split() can only refer to one specific method. \n" ]
[ 33, 19, 6, 5, 3, 3, 1, 1, 1, 1, 0, 0 ]
[ "I would find this acceptable, if a bit lazy, as long as what is being done isn't too performance critical. You could always go back and optimize it if you need more speed.\n" ]
[ -2 ]
[ "coding_style", "python" ]
stackoverflow_0001122691_coding_style_python.txt
Q: Python - uniquifying(!) dictionary keys I have data coming in from a machine (via pexpect) and I parse it using regexes into a dictionary like this for line in stream: if '/' in line: # some matching etc which results in getting the # machine name, an interface and the data for that interface key=str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2] dict[key]=str(line[3]) And that all works ok, I get lots of lines like this when I read it back machine1:fe0 <data> <data> is one string or integer I now realise that multiple data can exist for the interface, and it seems that in this case, I am overwriting the value for the key every time I encounter it. What I would like is to make the key unique in a way which highlights the fact that multiple info exists for that interface. E.g. if fe0 has 3 instances or fe1 has 4 machine1:fe0:3 <data> <data> <data> machine1:fe1:4 <data> <data> <data> <data> To that end I don't mind if a single instance has a 1 after it to tell me that. hope this is clear and someone can point me in the right direction - many thanks A: You can create a list for each key, holding all values for that key: d = collections.defaultdict(list) for line in stream: if '/' in line: #..... key = str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2] value = str(line[3]) d[key].append(value) Edit: If you want the keys/values exactly as specified in your question, you can then do something like: d2 = {} for key,values in d.iteritems(): d2['%s:%d' % (key, len(values)] = ' '.join(str(v) for v in values) I used ' '.join() here to join the values into a single string - it isn't really clear from your question if that's what you want. I don't recommend doing things this way, as it will make accessing individual values more difficult. A: for (lineno, line) in enumerate(stream): if '/' in line: # some matching etc which results in getting the # machine name, an interface and the data for that interface key=str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2] dict[key + ":" + lineno]=str(line[3]) You won't end up with it smoothly increasing this way, but each dictionary key will be unique, and the numbers associated with each hostname+interface pair will be increasing. You could make the keys lexically sortable by changing the last line to dict[key + ":" + ('%06d' % (lineno,))=str(line[3])
Python - uniquifying(!) dictionary keys
I have data coming in from a machine (via pexpect) and I parse it using regexes into a dictionary like this for line in stream: if '/' in line: # some matching etc which results in getting the # machine name, an interface and the data for that interface key=str(hostname)+":"+r.groups()[0][0:2]+r.groups()[2] dict[key]=str(line[3]) And that all works ok, I get lots of lines like this when I read it back machine1:fe0 <data> <data> is one string or integer I now realise that multiple data can exist for the interface, and it seems that in this case, I am overwriting the value for the key every time I encounter it. What I would like is to make the key unique in a way which highlights the fact that multiple info exists for that interface. E.g. if fe0 has 3 instances or fe1 has 4 machine1:fe0:3 <data> <data> <data> machine1:fe1:4 <data> <data> <data> <data> To that end I don't mind if a single instance has a 1 after it to tell me that. hope this is clear and someone can point me in the right direction - many thanks
[ "You can create a list for each key, holding all values for that key:\nd = collections.defaultdict(list)\nfor line in stream:\n if '/' in line:\n #.....\n key = str(hostname)+\":\"+r.groups()[0][0:2]+r.groups()[2]\n value = str(line[3])\n d[key].append(value)\n\nEdit: If you want the keys/values exactly as specified in your question, you can then do something like:\nd2 = {}\nfor key,values in d.iteritems():\n d2['%s:%d' % (key, len(values)] = ' '.join(str(v) for v in values)\n\nI used ' '.join() here to join the values into a single string - it isn't really clear from your question if that's what you want.\nI don't recommend doing things this way, as it will make accessing individual values more difficult.\n", "for (lineno, line) in enumerate(stream):\n if '/' in line:\n # some matching etc which results in getting the\n # machine name, an interface and the data for that interface\n key=str(hostname)+\":\"+r.groups()[0][0:2]+r.groups()[2]\n dict[key + \":\" + lineno]=str(line[3])\n\nYou won't end up with it smoothly increasing this way, but each dictionary key will be unique, and the numbers associated with each hostname+interface pair will be increasing. You could make the keys lexically sortable by changing the last line to dict[key + \":\" + ('%06d' % (lineno,))=str(line[3])\n" ]
[ 4, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002122880_dictionary_python.txt
Q: Trouble using python's gzip/"How do I know what compression is being used?" Ok, so I've got an Open Source Java client/server program that uses packets to communicate. I'm trying to write a python client for said program, but the contents of the packet seem to be compressed. A quick perusal through the source code suggested gzip as the compression schema (since that was the only compression module imported in the code that I could find), but when I saved the data from one of the packets out of wireshark and tried to do import gzip f = gzip.open('compressed_file') f.read() It told me that this wasn't a gzip file because the header was wrong. Can someone advise me what I've done wrong here? Did I change or mess up the format when I saved it out? Do I need to strip away some of the extraneous data from the packet before I try running this block on it? if (zipped) { // XML encode the data and GZIP it. ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer zipOut = new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream(baos))); PacketEncoder.encodeData(packet, zipOut); zipOut.close(); // Base64 encode the commpressed data. // Please note, I couldn't get anything other than a // straight stream-to-stream encoding to work. byte[] zipData = baos.toByteArray(); ByteArrayOutputStream base64 = new ByteArrayOutputStream( (4 * zipData.length + 2) / 3); Base64.encode(new ByteArrayInputStream(zipData), base64, false); EDIT: Ok, sorry I have the information requested here. This was gathered using Wireshark to listen in on communication between two running copies of the original program on different computers. To get the hex stream below, I used the "Copy -> Hex (Byte Stream)" option in Wireshark. 001321cdc68ff4ce46e4f00d0800450000832a85400080061e51ac102cceac102cb004f8092a9909b32c10e81cb25018f734823e00000100000000000000521f8b08000000000000005bf39681b59c85818121a0b4884138da272bb12c512f27312f5dcf3f292b35b9c47ac2b988f902c59a394c0c0c150540758c250c5c2ea5b9b9950a2e89258900aa4c201a3f000000 I know this will contain the string "Dummy Data" in it. I believe it should also contain "Jonathanb" (the player name I used to send the message) and the integer 80 (80 is the command # for "Chat" as far as I can gather from the code). A: You could try using standard library module zlib directly -- that's what gzip uses for the compress/decompress part. If the whole packet isn't liked by the decompress function, you can try using different values of wbits and/or slicing off a few bytes off the packet's front (if you could "reverse engineer" exactly how the Java code is compressing that packet -- even just understand how many wbits is using, or whether it's putting out any prefix before the compressed data -- that would help immensely, of course). The only likely "damage" you might have done to the file itself would be, on windows, if you had written it without specifying 'wb' to use binary mode -- writing it in "text mode" on windows would make the file unusable. Just saying...!-) A: It would help enormously if you divulged: (0) What leads you to the conclusion that "the contents of the packet seem to be compressed" (1) The URLs for the (a) source and (b) documentation of the package that is writing the packets (2) The contents of a sample packet (a) print repr(open('file_saved_from_wireshark', 'rb').read()) (b) just in case the long trip around via wireshark is muddying the water, insert this in your Python client: print repr(a_sample_packet) (3) the exact error message that you got (copy/paste) Update after OP supplied the hex dump of a packet This code: import binascii, sys, cStringIO, gzip, struct, zlib # guff is allegedly a "packet", formatted as 2 hex characters per byte guff = "001321cdc68ff4ce46e4f00d0800450000832a85400080061e51ac102cceac102cb004f8092a9909b32c10e81cb25018f734823e00000100000000000000521f8b08000000000000005bf39681b59c85818121a0b4884138da272bb12c512f27312f5dcf3f292b35b9c47ac2b988f902c59a394c0c0c150540758c250c5c2ea5b9b9950a2e89258900aa4c201a3f000000" guff2 = binascii.unhexlify(guff) print "raw input: len=%d repr=%r" % (len(guff2), guff2) # gzip spec: http://www.faqs.org/rfcs/rfc1952.html GZIP_HDR = "\x1F\x8B\x08" gzpos = guff2.find(GZIP_HDR) if gzpos == -1: print "Can't find gzip header" sys.exit(1) print gzpos, "bytes before gzipped data" gzipped = guff2[gzpos:] packet_crc, packet_orig_len = struct.unpack("<II", gzipped[-8:]) print "packet_crc, packet_orig_len:", hex(packet_crc), packet_orig_len fobj = cStringIO.StringIO(gzipped) zf = gzip.GzipFile(fileobj=fobj) payload = zf.read() print "payload: len=%d repr=%r" % (len(payload), payload) print "crc32(payload):", hex(zlib.crc32(payload)) produced this output (wrapped at col 80 by Windows' "Command Prompt" terminal) when run with Python 2.6.4: raw input: len=145 repr="\x00\x13!\xcd\xc6\x8f\xf4\xceF\xe4\xf0\r\x08\x00E\x00\x 00\x83*\x85@\x00\x80\x06\x1eQ\xac\x10,\xce\xac\x10,\xb0\x04\xf8\t*\x99\t\xb3,\x1 0\xe8\x1c\xb2P\x18\xf74\x82>\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00R\x1f\x8b\x0 8\x00\x00\x00\x00\x00\x00\x00[\xf3\x96\x81\xb5\x9c\x85\x81\x81!\xa0\xb4\x88A8\xd a'+\xb1,Q/'1/]\xcf?)+5\xb9\xc4z\xc2\xb9\x88\xf9\x02\xc5\x9a9L\x0c\x0c\x15\x05@u\ x8c%\x0c\\.\xa5\xb9\xb9\x95\n.\x89%\x89\x00\xaaL \x1a?\x00\x00\x00" 63 bytes before gzipped data packet_crc, packet_orig_len: 0x1a204caa 63 payload: len=63 repr='\xac\xed\x00\x05w\x04\x00\x00\x00Pur\x00\x13[Ljava.lang.Ob ject;\x90\xceX\x9f\x10s)l\x02\x00\x00xp\x00\x00\x00\x01t\x00\nDummy Data' crc32(payload): 0x1a204caa Comments/questions: This packet is 145 bytes long; what happened to the idea that a packet was about 2900 bytes? The packet is 63 bytes of as-yet-unanalysed data followed by an 82-byte gzip stream which decompresses(!) to 63 bytes. There is no data after the gzip stream -- verified by comparing the last 8 bytes of the packet with calculated gzip values. It contains the expected "Dummy Data", but userid "johnathonb" is not there (or obfuscated or encrypted). The packet structure doesn't match the code that we guessed was being used (no XML, no base64). The gunzipped data contains the string "java.lang.Object" which is probably symptomatic of some java serialisation protocol. Lasciate ogni speranza, voi qu'entrate. A: It's likely to be compliant with one of RFC 1950, 1951, or 1952. Since the name is GZIP, I'd first check 1952. Then I'd try ZLIB, 1950. Finally, DEFLATE(1951). DotNetZip is a .NET library that allows a .NET app to read data streams that comply with any of these formats. If you had a stream that complied with one of the above, you could very quickly determine which one it was, by trying to read the stream with each of DotNetZip's streams in succession; GZipStream, ZlibStream, DeflateStream. One of them will work, and the others will not. I don't know of a Java library that has those streams. Doesn't mean it doesn't exist. Just that I don't know of one. DotNetZip is free and works on Windows+Mono, Linux+Mono, as well as Windows+.NET.
Trouble using python's gzip/"How do I know what compression is being used?"
Ok, so I've got an Open Source Java client/server program that uses packets to communicate. I'm trying to write a python client for said program, but the contents of the packet seem to be compressed. A quick perusal through the source code suggested gzip as the compression schema (since that was the only compression module imported in the code that I could find), but when I saved the data from one of the packets out of wireshark and tried to do import gzip f = gzip.open('compressed_file') f.read() It told me that this wasn't a gzip file because the header was wrong. Can someone advise me what I've done wrong here? Did I change or mess up the format when I saved it out? Do I need to strip away some of the extraneous data from the packet before I try running this block on it? if (zipped) { // XML encode the data and GZIP it. ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer zipOut = new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream(baos))); PacketEncoder.encodeData(packet, zipOut); zipOut.close(); // Base64 encode the commpressed data. // Please note, I couldn't get anything other than a // straight stream-to-stream encoding to work. byte[] zipData = baos.toByteArray(); ByteArrayOutputStream base64 = new ByteArrayOutputStream( (4 * zipData.length + 2) / 3); Base64.encode(new ByteArrayInputStream(zipData), base64, false); EDIT: Ok, sorry I have the information requested here. This was gathered using Wireshark to listen in on communication between two running copies of the original program on different computers. To get the hex stream below, I used the "Copy -> Hex (Byte Stream)" option in Wireshark. 001321cdc68ff4ce46e4f00d0800450000832a85400080061e51ac102cceac102cb004f8092a9909b32c10e81cb25018f734823e00000100000000000000521f8b08000000000000005bf39681b59c85818121a0b4884138da272bb12c512f27312f5dcf3f292b35b9c47ac2b988f902c59a394c0c0c150540758c250c5c2ea5b9b9950a2e89258900aa4c201a3f000000 I know this will contain the string "Dummy Data" in it. I believe it should also contain "Jonathanb" (the player name I used to send the message) and the integer 80 (80 is the command # for "Chat" as far as I can gather from the code).
[ "You could try using standard library module zlib directly -- that's what gzip uses for the compress/decompress part. If the whole packet isn't liked by the decompress function, you can try using different values of wbits and/or slicing off a few bytes off the packet's front (if you could \"reverse engineer\" exactly how the Java code is compressing that packet -- even just understand how many wbits is using, or whether it's putting out any prefix before the compressed data -- that would help immensely, of course).\nThe only likely \"damage\" you might have done to the file itself would be, on windows, if you had written it without specifying 'wb' to use binary mode -- writing it in \"text mode\" on windows would make the file unusable. Just saying...!-)\n", "It would help enormously if you divulged:\n(0) What leads you to the conclusion that \"the contents of the packet seem to be compressed\"\n(1) The URLs for the (a) source and (b) documentation of the package that is writing the packets\n(2) The contents of a sample packet\n(a) print repr(open('file_saved_from_wireshark', 'rb').read())\n(b) just in case the long trip around via wireshark is muddying the water, insert this in your Python client:\nprint repr(a_sample_packet)\n(3) the exact error message that you got (copy/paste)\nUpdate after OP supplied the hex dump of a packet\nThis code:\nimport binascii, sys, cStringIO, gzip, struct, zlib\n# guff is allegedly a \"packet\", formatted as 2 hex characters per byte\nguff = \"001321cdc68ff4ce46e4f00d0800450000832a85400080061e51ac102cceac102cb004f8092a9909b32c10e81cb25018f734823e00000100000000000000521f8b08000000000000005bf39681b59c85818121a0b4884138da272bb12c512f27312f5dcf3f292b35b9c47ac2b988f902c59a394c0c0c150540758c250c5c2ea5b9b9950a2e89258900aa4c201a3f000000\"\nguff2 = binascii.unhexlify(guff)\nprint \"raw input: len=%d repr=%r\" % (len(guff2), guff2)\n# gzip spec: http://www.faqs.org/rfcs/rfc1952.html\nGZIP_HDR = \"\\x1F\\x8B\\x08\"\ngzpos = guff2.find(GZIP_HDR)\nif gzpos == -1:\n print \"Can't find gzip header\"\n sys.exit(1)\nprint gzpos, \"bytes before gzipped data\"\ngzipped = guff2[gzpos:]\npacket_crc, packet_orig_len = struct.unpack(\"<II\", gzipped[-8:])\nprint \"packet_crc, packet_orig_len:\", hex(packet_crc), packet_orig_len\nfobj = cStringIO.StringIO(gzipped)\nzf = gzip.GzipFile(fileobj=fobj)\npayload = zf.read()\nprint \"payload: len=%d repr=%r\" % (len(payload), payload)\nprint \"crc32(payload):\", hex(zlib.crc32(payload))\n\nproduced this output (wrapped at col 80 by Windows' \"Command Prompt\" terminal) when run with Python 2.6.4:\nraw input: len=145 repr=\"\\x00\\x13!\\xcd\\xc6\\x8f\\xf4\\xceF\\xe4\\xf0\\r\\x08\\x00E\\x00\\x\n00\\x83*\\x85@\\x00\\x80\\x06\\x1eQ\\xac\\x10,\\xce\\xac\\x10,\\xb0\\x04\\xf8\\t*\\x99\\t\\xb3,\\x1\n0\\xe8\\x1c\\xb2P\\x18\\xf74\\x82>\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00R\\x1f\\x8b\\x0\n8\\x00\\x00\\x00\\x00\\x00\\x00\\x00[\\xf3\\x96\\x81\\xb5\\x9c\\x85\\x81\\x81!\\xa0\\xb4\\x88A8\\xd\na'+\\xb1,Q/'1/]\\xcf?)+5\\xb9\\xc4z\\xc2\\xb9\\x88\\xf9\\x02\\xc5\\x9a9L\\x0c\\x0c\\x15\\x05@u\\\nx8c%\\x0c\\\\.\\xa5\\xb9\\xb9\\x95\\n.\\x89%\\x89\\x00\\xaaL \\x1a?\\x00\\x00\\x00\"\n63 bytes before gzipped data\npacket_crc, packet_orig_len: 0x1a204caa 63\npayload: len=63 repr='\\xac\\xed\\x00\\x05w\\x04\\x00\\x00\\x00Pur\\x00\\x13[Ljava.lang.Ob\nject;\\x90\\xceX\\x9f\\x10s)l\\x02\\x00\\x00xp\\x00\\x00\\x00\\x01t\\x00\\nDummy Data'\ncrc32(payload): 0x1a204caa\n\nComments/questions:\n\nThis packet is 145 bytes long; what happened to the idea that a packet was about 2900 bytes? \nThe packet is 63 bytes of as-yet-unanalysed data followed by an 82-byte gzip stream which decompresses(!) to 63 bytes. There is no data after the gzip stream -- verified by comparing the last 8 bytes of the packet with calculated gzip values. It contains the expected \"Dummy Data\", but userid \"johnathonb\" is not there (or obfuscated or encrypted).\nThe packet structure doesn't match the code that we guessed was being used (no XML, no base64).\nThe gunzipped data contains the string \"java.lang.Object\" which is probably symptomatic of some java serialisation protocol. Lasciate ogni speranza, voi qu'entrate.\n\n", "It's likely to be compliant with one of RFC 1950, 1951, or 1952.\nSince the name is GZIP, I'd first check 1952. Then I'd try ZLIB, 1950. Finally, DEFLATE(1951).\nDotNetZip is a .NET library that allows a .NET app to read data streams that comply with any of these formats. If you had a stream that complied with one of the above, you could very quickly determine which one it was, by trying to read the stream with each of DotNetZip's streams in succession; GZipStream, ZlibStream, DeflateStream. One of them will work, and the others will not.\nI don't know of a Java library that has those streams. Doesn't mean it doesn't exist. Just that I don't know of one.\nDotNetZip is free and works on Windows+Mono, Linux+Mono, as well as Windows+.NET.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "compression", "java", "python", "reverse_engineering" ]
stackoverflow_0002122190_compression_java_python_reverse_engineering.txt
Q: What is the method of doing nl2br in Genshi? hiyas. I using Genshi+Pylons. please teach me, how use \n to <br/>tag in Genshi? I hope to obtain the same result as "nl2br" in php to change line. Or, does not the solution exist? i'm assign template to some text. (genshi template) <p>${c.message}</p> Im tried. case 1: (python code) c.message = """ foo bar """ NG. display result is "foo bar" case 2: (python code) c.message = """ foo<br /> bar """ NG. display result is "foo<br />bar". displayed escaped stirings! It was a same deal as <br/> as for <br />. Postscript. I want to avoid using the pre tag. thanks. When it is not easy to read because it is not good, I'm sorry by English. A: Try this: <py:for each="line in message.split('\n')">${line}<br /></py:for>
What is the method of doing nl2br in Genshi?
hiyas. I using Genshi+Pylons. please teach me, how use \n to <br/>tag in Genshi? I hope to obtain the same result as "nl2br" in php to change line. Or, does not the solution exist? i'm assign template to some text. (genshi template) <p>${c.message}</p> Im tried. case 1: (python code) c.message = """ foo bar """ NG. display result is "foo bar" case 2: (python code) c.message = """ foo<br /> bar """ NG. display result is "foo<br />bar". displayed escaped stirings! It was a same deal as <br/> as for <br />. Postscript. I want to avoid using the pre tag. thanks. When it is not easy to read because it is not good, I'm sorry by English.
[ "Try this:\n<py:for each=\"line in message.split('\\n')\">${line}<br /></py:for>\n\n" ]
[ 2 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0002123162_genshi_pylons_python.txt
Q: What are some Pythonic ways to share variables with objects defined in a module? I'm building a module where there are a whole lot of diverse objects which need to be controlled by several variables. If this were C, I would pass the objects a pointer to the variable / object I want them to watch, have the application change the variable as it needs to, and the objects in the module would "see" the new value. In module foo.py: class foo(object): def __init__(self, varToWatch): self.varToWatch = varToWatch def DoSomething(self): print self.varToWatch In application, bar.py: import foo x = "before" y = foo.foo(x) y.DoSomething() x = "after" y.DoSomething() This doesn't work, of course, because the original value of x (or a reference to the original value of x?) is stored in y. You get "before" "before". So, I try... Passing the name of a global, and referring to the global by name in foo. No go, because the global is in the application's space, not in the module. Using a global in the foo namespace, but I don't know how to address that space by variable name, and we're currently doing import * from foo rather than import foo. Changing this would be painful. Make a dictionary in the module and pass the name of a key in the dictionary to the objects in the module. Manipulate the contents of the dictionary from the application. Basically, I'm defining a new global space and sticking variables in it. I see no reason it wouldn't work, but it feels untidy to me. Is that just me being unfamiliar with Python? I'm not finding the kind of beautiful solutions I'm used to seeing come easily with Python, so I suspect I'm missing something. Suggestions? TIA, - Tim. A: How about putting the control variables in a separate module -- say, settings -- and doing a separate import settings? You could then have your objects watch settings.bar and settings.quux while still doing from foo import * to clutter up your main namespace. ;-) You could also use a global object to store your settings, with mostly the same effect. Of course, with problems such as these, one must wonder whether restructuring things to do a import foo wouldn't help things in the long run... Impossible to judge without knowing the problem, though, so I'll leave this problem to you. A: The trick is to use a mutable type. Strings are immutable, so when you change the string, it creates a new string object in a new memory space. If, however, you referenced a list and appended to the list, the memory space won't change. Adapting your code... >>> class Foo(object): ... def __init__(self, var): ... self.var = var ... def show(self): ... print self.var ... >>> x = ['before'] >>> y = Foo(x) >>> y.show() ['before'] >>> x.append('after') >>> y.show() ['before', 'after'] A: To catch all re-bindings of a name, you need to pass both a namespace and a specific name to use as the key within it. Using a dedicated dict as the namespace is fine, but the dict for the whole module (which you can get as globals()) or for any specific object o of which you want to observe an attribute (use vars(o)) are just as fine. So: class foo(object): def __init__(self, namespace, name): self.namespaceToWatch = namespace self.nameToWatch = name def DoSomething(self): print self.namespaceToWatch[self.nameToWatch] and, for your example use, since you're at global level: import foo x = "before" y = foo.foo(globals(), 'x') y.DoSomething() x = "after" y.DoSomething() A: Your problem here is that in C variables are data are objects. In Python, variables are always references to objects (which are data). You can easily watch an object, but not a variable. For example, x = "after" actually "unlinks" the object before from x and links a new object ("after"). This means that x and foo.varToWatch no longer refer to the same object. If, on the other hand, you mutate the object referenced by x, both x and varToWatch still refer to the same object and the change is reflected. An example would be if x was a mutable type, like a dictionary - changing x in this case would reflect in varToWatch unless you actually do an assignment. A: In a comment to Alex Martelli's solution, tbroberg asks, "What if the parties agree to use the namespace of the module? How can the application get the module's namespace?" Here is how you could set the namespace (by default) to be the caller's namespace: import inspect class foo(object): def __init__(self, name, namespace=None): self.namespaceToWatch = (namespace if namespace else inspect.currentframe().f_back.f_globals) self.nameToWatch = name def DoSomething(self): print self.namespaceToWatch[self.nameToWatch] Note that I changed the order of the arguments so namespace is now an optional argument. inspect.currentframe() returns the current frame, inside foo.__init__. inspect.currentframe().f_back returns the previous frame, from which foo('x') is being called. inspect.currentframe().f_back.f_globals returns the global namespace of this frame. This makes y = test.foo('x') equivalent to y = test.foo('x', globals())
What are some Pythonic ways to share variables with objects defined in a module?
I'm building a module where there are a whole lot of diverse objects which need to be controlled by several variables. If this were C, I would pass the objects a pointer to the variable / object I want them to watch, have the application change the variable as it needs to, and the objects in the module would "see" the new value. In module foo.py: class foo(object): def __init__(self, varToWatch): self.varToWatch = varToWatch def DoSomething(self): print self.varToWatch In application, bar.py: import foo x = "before" y = foo.foo(x) y.DoSomething() x = "after" y.DoSomething() This doesn't work, of course, because the original value of x (or a reference to the original value of x?) is stored in y. You get "before" "before". So, I try... Passing the name of a global, and referring to the global by name in foo. No go, because the global is in the application's space, not in the module. Using a global in the foo namespace, but I don't know how to address that space by variable name, and we're currently doing import * from foo rather than import foo. Changing this would be painful. Make a dictionary in the module and pass the name of a key in the dictionary to the objects in the module. Manipulate the contents of the dictionary from the application. Basically, I'm defining a new global space and sticking variables in it. I see no reason it wouldn't work, but it feels untidy to me. Is that just me being unfamiliar with Python? I'm not finding the kind of beautiful solutions I'm used to seeing come easily with Python, so I suspect I'm missing something. Suggestions? TIA, - Tim.
[ "How about putting the control variables in a separate module -- say, settings -- and doing a separate import settings? You could then have your objects watch settings.bar and settings.quux while still doing from foo import * to clutter up your main namespace. ;-) You could also use a global object to store your settings, with mostly the same effect.\nOf course, with problems such as these, one must wonder whether restructuring things to do a import foo wouldn't help things in the long run... Impossible to judge without knowing the problem, though, so I'll leave this problem to you.\n", "The trick is to use a mutable type. Strings are immutable, so when you change the string, it creates a new string object in a new memory space. If, however, you referenced a list and appended to the list, the memory space won't change. Adapting your code...\n>>> class Foo(object):\n... def __init__(self, var):\n... self.var = var\n... def show(self):\n... print self.var\n... \n>>> x = ['before']\n>>> y = Foo(x)\n>>> y.show()\n['before']\n>>> x.append('after')\n>>> y.show()\n['before', 'after']\n\n", "To catch all re-bindings of a name, you need to pass both a namespace and a specific name to use as the key within it. Using a dedicated dict as the namespace is fine, but the dict for the whole module (which you can get as globals()) or for any specific object o of which you want to observe an attribute (use vars(o)) are just as fine.\nSo:\nclass foo(object):\n def __init__(self, namespace, name):\n self.namespaceToWatch = namespace\n self.nameToWatch = name\n def DoSomething(self):\n print self.namespaceToWatch[self.nameToWatch]\n\nand, for your example use, since you're at global level:\nimport foo\nx = \"before\"\ny = foo.foo(globals(), 'x')\ny.DoSomething()\nx = \"after\"\ny.DoSomething()\n\n", "Your problem here is that in C variables are data are objects. In Python, variables are always references to objects (which are data). You can easily watch an object, but not a variable. For example, x = \"after\" actually \"unlinks\" the object before from x and links a new object (\"after\"). This means that x and foo.varToWatch no longer refer to the same object.\nIf, on the other hand, you mutate the object referenced by x, both x and varToWatch still refer to the same object and the change is reflected. An example would be if x was a mutable type, like a dictionary - changing x in this case would reflect in varToWatch unless you actually do an assignment.\n", "In a comment to Alex Martelli's solution, tbroberg asks, \"What if the parties\nagree to use the namespace of the module? How can the application get the\nmodule's namespace?\"\nHere is how you could set the namespace (by default) to be the caller's namespace:\nimport inspect\nclass foo(object):\n def __init__(self, name, namespace=None):\n self.namespaceToWatch = (namespace if namespace else\n inspect.currentframe().f_back.f_globals)\n self.nameToWatch = name\n def DoSomething(self):\n print self.namespaceToWatch[self.nameToWatch]\n\nNote that I changed the order of the arguments so namespace is now an optional argument.\ninspect.currentframe() returns the current frame, inside foo.__init__.\ninspect.currentframe().f_back returns the previous frame, from which foo('x') is being called.\ninspect.currentframe().f_back.f_globals returns the global namespace of this frame.\nThis makes\ny = test.foo('x')\n\nequivalent to\ny = test.foo('x', globals())\n\n" ]
[ 3, 3, 3, 1, 1 ]
[]
[]
[ "global_variables", "module", "python" ]
stackoverflow_0002122306_global_variables_module_python.txt
Q: Changing web service url in SUDS library Using SUDS SOAP client how do I specify web service URL. I can see clearly that WSDL path is specified in Client constructor but what if I wan't to change web service url? A: Suds supports WSDL with multiple services or multiple ports (or both), and without having any detailed information on what you're working with, I am only guessing that this is what you are looking for. This question would be easier to answer if you provided more detail, such as what your Client instance looks like. After you have successfully constructed a Client, you can print it to see the available services, methods, ports, and types. The following example is straight from the suds documentation. Example from suds site: from suds.client import Client url = 'http://www.thomas-bayer.com/axis2/services/BLZService?wsdl' client = Client(url) print client Outputs this: Suds - version: 0.3.7 build: (beta) R550-20090820 Service (BLZService) tns="http://thomas-bayer.com/blz/" Prefixes (1) ns0 = "http://thomas-bayer.com/blz/" Ports (2): (soap) Methods (1): getBank(xs:string blz, ) (soap12) Methods (1): getBank(xs:string blz, ) Types (5): getBankType getBankResponseType getBankType getBankResponseType detailsType Service (OtherBLZService) tns="http://thomas-bayer.com/blz/" Prefixes (1) ns0 = "http://thomas-bayer.com/blz/" Ports (2): (soap) Methods (1): getBank(xs:string blz, ) (soap12) Methods (1): getBank(xs:string blz, ) Types (5): getBankType getBankResponseType getBankType getBankResponseType detailsType Each service can be accessed in many ways, but here is a different port from each service qualified by method: ## service: BLZService, port: soap12, method: getBank client.service['BLZService']['soap12'].getBank() ## service: OtherBLZService, port: soap, method: getBank client.service['OtherBLZService']['soap'].getBank() Is that the kind of thing you're working with? If so, visit their documentation, which I think you'll find more than adequate. If not, please consider adding as much detail as possible to your question to give us more to work with! A: You can point the client to different endpoints via two methods: 1) client.set_options(location='http://path/to/your/wsdl') -or- 2) using the client's clone() method. Then use set_options() again. It's really the same as #1 above but you end up with two clients to use, not one. This latter method is a clean way to create a lightweight clone of your client object - they'll share the parsed wsdl and will only differ on their options, which you set via set_options(). I use both methods and they both work very well. -Matt A: I think you have to create a new Client object for each different URL.
Changing web service url in SUDS library
Using SUDS SOAP client how do I specify web service URL. I can see clearly that WSDL path is specified in Client constructor but what if I wan't to change web service url?
[ "Suds supports WSDL with multiple services or multiple ports (or both), and without having any detailed information on what you're working with, I am only guessing that this is what you are looking for. This question would be easier to answer if you provided more detail, such as what your Client instance looks like.\nAfter you have successfully constructed a Client, you can print it to see the available services, methods, ports, and types.\nThe following example is straight from the suds documentation.\nExample from suds site:\nfrom suds.client import Client\nurl = 'http://www.thomas-bayer.com/axis2/services/BLZService?wsdl'\nclient = Client(url) \nprint client\n\nOutputs this:\nSuds - version: 0.3.7 build: (beta) R550-20090820\n\nService (BLZService) tns=\"http://thomas-bayer.com/blz/\"\n Prefixes (1)\n ns0 = \"http://thomas-bayer.com/blz/\"\n Ports (2):\n (soap)\n Methods (1):\n getBank(xs:string blz, )\n (soap12)\n Methods (1):\n getBank(xs:string blz, )\n Types (5):\n getBankType\n getBankResponseType\n getBankType\n getBankResponseType\n detailsType\n\nService (OtherBLZService) tns=\"http://thomas-bayer.com/blz/\"\n Prefixes (1)\n ns0 = \"http://thomas-bayer.com/blz/\"\n Ports (2):\n (soap)\n Methods (1):\n getBank(xs:string blz, )\n (soap12)\n Methods (1):\n getBank(xs:string blz, )\n Types (5):\n getBankType\n getBankResponseType\n getBankType\n getBankResponseType\n detailsType\n\nEach service can be accessed in many ways, but here is a different port from each service qualified by method:\n## service: BLZService, port: soap12, method: getBank\nclient.service['BLZService']['soap12'].getBank()\n## service: OtherBLZService, port: soap, method: getBank\nclient.service['OtherBLZService']['soap'].getBank()\n\nIs that the kind of thing you're working with? If so, visit their documentation, which I think you'll find more than adequate. If not, please consider adding as much detail as possible to your question to give us more to work with!\n", "You can point the client to different endpoints via two methods: \n1) client.set_options(location='http://path/to/your/wsdl') -or- \n2) using the client's clone() method. Then use set_options() again. It's really the same as #1 above but you end up with two clients to use, not one.\nThis latter method is a clean way to create a lightweight clone of your client object - they'll share the parsed wsdl and will only differ on their options, which you set via set_options().\nI use both methods and they both work very well.\n-Matt\n", "I think you have to create a new Client object for each different URL.\n" ]
[ 4, 4, 1 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0001670569_python_soap_suds.txt
Q: python : mysql : Return 0 when no rows found Table structure - Data present for 5 min. slots - data_point | point_date 12 | 00:00 14 | 00:05 23 | 00:10 10 | 00:15 43 | 00:25 10 | 00:40 When I run the query for say 30 mins. and if data is present I'll get 6 rows (one row for each 5 min. stamp). Simple Query - select data_point from some_table where point_date >= start_date AND point_date < end_date order by point_date Now when I don't have an entry for a particular time slot (e.g. time slot 00:20 is missing), I want the "data_point" to be returned as 0 The REPLACE, IF, IFNULL, ISNULL don't work when there no rows returned. I thought Union with a default value would work, but it failed too or maybe I didn't use it correctly. Is there a way to get this done via sql only ? Note : Python 2.6 & mysql version 5.1 A: Yes, you can do that using SQL only. A solution would be to use a Stored Routine. The bellow Stored Procedure produces following output: start cnt 00:05:00 1 00:10:00 0 00:15:00 1 00:20:00 0 00:25:00 1 00:30:00 0 00:35:00 1 00:40:00 0 00:45:00 0 00:50:00 0 00:55:00 2 The table I used: CREATE TABLE `timedata` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c1` datetime DEFAULT NULL, `c2` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ) Here the Stored Procedure (adjust for your environment): DROP PROCEDURE IF EXISTS per5min; DELIMITER // CREATE PROCEDURE per5min () BEGIN DECLARE dtMin DATETIME; DECLARE dtMax DATETIME; DECLARE dtStart DATETIME; DECLARE dtStop DATETIME; DECLARE tmDiff TIME; DECLARE result INT UNSIGNED; SET @offset = 5 * 60; SELECT MIN(c1) into dtMin FROM timedata; SELECT MAX(c1) into dtMax FROM timedata; CREATE TEMPORARY TABLE tmp_per5min ( start TIME, cnt INT UNSIGNED ); SET dtStart = dtMin; REPEAT SELECT dtStart + INTERVAL @offset SECOND into dtStop; SELECT count(c2) into result FROM timedata WHERE c1 BETWEEN dtStart and dtStop; SELECT TIME(SUBTIME(dtStop,TIME(dtMin))) into tmDiff; INSERT INTO tmp_per5min (start,cnt) VALUES (tmDiff,result); SET dtStart = dtStop; UNTIL dtStop >= dtMax END REPEAT; SELECT * FROM tmp_per5min; DROP TABLE tmp_per5min; END; // DELIMITER ; CALL per5min(); If you save the above into a file called 'per5minproc.sql', you can load it like this: shell> mysql -uroot test < per5minproc.sql In Python using MySQLdb (I didn't get this working in MySQL Connector/Python, me ashamed!): import MySQLdb as m if __name__ == '__main__': db = m.connect(user='root',db='test') c = db.cursor() c.callproc("per5min") print(c.fetchall()) c.close() db.close() The solution above works, but probably will need some tweaking, e.g. dtStart can be an argument to the SP. And, it's indeed all SQL! A: I see no easy way to create non-existing records out of thin air, but you could create yourself a point_dates table containing all the timestamps you're interested in, and left join it on your data: select pd.slot, IFNULL(data_point, 0) from point_dates pd left join some_table st on st.point_date=pd.slot where point_date >= start_date AND point_date < end_date order by point_date A: You cannot query data you do not have. You (as a thinking person) can claim that the 00:20 data is missing; but there's no easy way to define "missing" in some more formal SQL sense. The best you can do is create a table with all of the expected times. Then you can do an outer join between expected times (including a 0 for 00:20) and actual times (missing the 00:20 sample) and you'll get kind of result you're expecting.
python : mysql : Return 0 when no rows found
Table structure - Data present for 5 min. slots - data_point | point_date 12 | 00:00 14 | 00:05 23 | 00:10 10 | 00:15 43 | 00:25 10 | 00:40 When I run the query for say 30 mins. and if data is present I'll get 6 rows (one row for each 5 min. stamp). Simple Query - select data_point from some_table where point_date >= start_date AND point_date < end_date order by point_date Now when I don't have an entry for a particular time slot (e.g. time slot 00:20 is missing), I want the "data_point" to be returned as 0 The REPLACE, IF, IFNULL, ISNULL don't work when there no rows returned. I thought Union with a default value would work, but it failed too or maybe I didn't use it correctly. Is there a way to get this done via sql only ? Note : Python 2.6 & mysql version 5.1
[ "Yes, you can do that using SQL only. A solution would be to use a Stored Routine. The bellow Stored Procedure produces following output:\nstart cnt\n00:05:00 1\n00:10:00 0\n00:15:00 1\n00:20:00 0\n00:25:00 1\n00:30:00 0\n00:35:00 1\n00:40:00 0\n00:45:00 0\n00:50:00 0\n00:55:00 2\n\nThe table I used:\nCREATE TABLE `timedata` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `c1` datetime DEFAULT NULL,\n `c2` varchar(20) DEFAULT NULL,\n PRIMARY KEY (`id`)\n)\n\nHere the Stored Procedure (adjust for your environment):\nDROP PROCEDURE IF EXISTS per5min;\nDELIMITER //\nCREATE PROCEDURE per5min ()\nBEGIN\n DECLARE dtMin DATETIME;\n DECLARE dtMax DATETIME;\n DECLARE dtStart DATETIME;\n DECLARE dtStop DATETIME;\n DECLARE tmDiff TIME;\n DECLARE result INT UNSIGNED;\n SET @offset = 5 * 60;\n SELECT MIN(c1) into dtMin FROM timedata;\n SELECT MAX(c1) into dtMax FROM timedata;\n\n CREATE TEMPORARY TABLE tmp_per5min (\n start TIME,\n cnt INT UNSIGNED\n );\n\n SET dtStart = dtMin;\n REPEAT\n SELECT dtStart + INTERVAL @offset SECOND into dtStop;\n SELECT count(c2) into result FROM timedata WHERE c1 BETWEEN dtStart and dtStop;\n SELECT TIME(SUBTIME(dtStop,TIME(dtMin))) into tmDiff;\n INSERT INTO tmp_per5min (start,cnt) VALUES (tmDiff,result);\n SET dtStart = dtStop;\n UNTIL dtStop >= dtMax END REPEAT;\n\n SELECT * FROM tmp_per5min;\n DROP TABLE tmp_per5min;\nEND;\n//\nDELIMITER ;\n\nCALL per5min();\n\nIf you save the above into a file called 'per5minproc.sql', you can load it like this:\nshell> mysql -uroot test < per5minproc.sql\n\nIn Python using MySQLdb (I didn't get this working in MySQL Connector/Python, me ashamed!):\nimport MySQLdb as m\n\nif __name__ == '__main__':\n db = m.connect(user='root',db='test')\n c = db.cursor()\n c.callproc(\"per5min\")\n print(c.fetchall())\n c.close()\n db.close()\n\nThe solution above works, but probably will need some tweaking, e.g. dtStart can be an argument to the SP.\nAnd, it's indeed all SQL!\n", "I see no easy way to create non-existing records out of thin air, but you could create yourself a point_dates table containing all the timestamps you're interested in, and left join it on your data:\nselect pd.slot, IFNULL(data_point, 0)\nfrom point_dates pd\nleft join some_table st on st.point_date=pd.slot\nwhere point_date >= start_date\nAND point_date < end_date\norder by point_date\n", "You cannot query data you do not have.\nYou (as a thinking person) can claim that the 00:20 data is missing; but there's no easy way to define \"missing\" in some more formal SQL sense.\nThe best you can do is create a table with all of the expected times.\nThen you can do an outer join between expected times (including a 0 for 00:20) and actual times (missing the 00:20 sample) and you'll get kind of result you're expecting.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "mysql", "null", "python" ]
stackoverflow_0002119153_mysql_null_python.txt
Q: failed abstraction of variable in for loop I'm trying to make a 4x4 sudoku solver in Python (I'm only a beginner!) and while trying to define a function to clean up my code somewhat, I ran across some strange behavior I don't really understand. Apparently, there's a difference between this: sudoku = "0200140000230040" sudoku = map(lambda x: '1234' if x=='0' else x, list(sudoku)) for i in range(16): for j in range(4): if sudoku[i] == str(j+1): for k in range(4): if len(sudoku[i/4*4+k]) > 1: sudoku[i/4*4+k] = sudoku[i/4*4+k].translate(None, str(j+1)) for k in range(4): if len(sudoku[4*k+i%4]) > 1: sudoku[4*k+i%4] = sudoku[4*k+i%4].translate(None, str(j+1)) And this one: sudoku = "0200140000230040" def sd(l): for k in range(4): if len(sudoku[l]) > 1: sudoku[l] = sudoku[l].translate(None, str(j+1)) sudoku = map(lambda x: '1234' if x=='0' else x, list(sudoku)) for i in range(16): for j in range(4): if sudoku[i] == str(j+1): sd(i/4*4+k) sd(4*k+i%4) The strange expressions are for checking the rows and columns (boxes aren't finished yet). I'm terribly sorry for wasting your time if this kind of thing has been asked already, but try running both code snippets and observing the different results you get. Thanks in advance. (I have this weird feeling I'm going to get yelled at. Huh.) A: There is a difference... they fail with two different errors! The first gives me this error: File "test.py", line 9, in <module> sudoku[i/4*4+k] = sudoku[i/4*4+k].translate(None, str(j+1)) TypeError: expected a character buffer object The second gives me this error: File "test.py", line 12, in <module> sd(i/4*4+k) NameError: name 'k' is not defined I think the main problem is you assume that the expression tree for 'i/4*4+k' will be passed as a parameter to the function, but actually it is evaluated before the function call is made and this fails because k is not defined. You could use this instead: sd(lambda k: i/4*4+k) and inside the function sd you can replace l with calls to l(k). Now you get the same error for both programs.
failed abstraction of variable in for loop
I'm trying to make a 4x4 sudoku solver in Python (I'm only a beginner!) and while trying to define a function to clean up my code somewhat, I ran across some strange behavior I don't really understand. Apparently, there's a difference between this: sudoku = "0200140000230040" sudoku = map(lambda x: '1234' if x=='0' else x, list(sudoku)) for i in range(16): for j in range(4): if sudoku[i] == str(j+1): for k in range(4): if len(sudoku[i/4*4+k]) > 1: sudoku[i/4*4+k] = sudoku[i/4*4+k].translate(None, str(j+1)) for k in range(4): if len(sudoku[4*k+i%4]) > 1: sudoku[4*k+i%4] = sudoku[4*k+i%4].translate(None, str(j+1)) And this one: sudoku = "0200140000230040" def sd(l): for k in range(4): if len(sudoku[l]) > 1: sudoku[l] = sudoku[l].translate(None, str(j+1)) sudoku = map(lambda x: '1234' if x=='0' else x, list(sudoku)) for i in range(16): for j in range(4): if sudoku[i] == str(j+1): sd(i/4*4+k) sd(4*k+i%4) The strange expressions are for checking the rows and columns (boxes aren't finished yet). I'm terribly sorry for wasting your time if this kind of thing has been asked already, but try running both code snippets and observing the different results you get. Thanks in advance. (I have this weird feeling I'm going to get yelled at. Huh.)
[ "There is a difference... they fail with two different errors!\nThe first gives me this error:\n File \"test.py\", line 9, in <module>\n sudoku[i/4*4+k] = sudoku[i/4*4+k].translate(None, str(j+1))\nTypeError: expected a character buffer object\n\nThe second gives me this error:\n File \"test.py\", line 12, in <module>\n sd(i/4*4+k)\nNameError: name 'k' is not defined\n\nI think the main problem is you assume that the expression tree for 'i/4*4+k' will be passed as a parameter to the function, but actually it is evaluated before the function call is made and this fails because k is not defined. You could use this instead:\n sd(lambda k: i/4*4+k)\n\nand inside the function sd you can replace l with calls to l(k). Now you get the same error for both programs. \n" ]
[ 2 ]
[]
[]
[ "function", "python", "sudoku" ]
stackoverflow_0002123408_function_python_sudoku.txt
Q: Python: creating a grid Is it possible to create a grid like below? I didn't found anything in the forum. #euler-project problem number 11 #In the 20 times 20 grid below, #four numbers along a diagonal line have been marked in red. #The product of these numbers is 26 times 63 times 78 times 14 = 1788696. #What is the greatest product of four adjacent numbers in any direction #(up, down, left, right, or diagonally) in the 20 times 20 grid? import numpy number = numpy.array([[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08] [49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00] [81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65] [52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91] [22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80] [24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50] [32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70] [67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21] [24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72] [21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95] [78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92] [16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57] [86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58] [19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40] [04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66] [88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69] [04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36] [20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16] [20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54] [01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48]]) EDIT no.1: I found numpy-array now. x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) Is there a way to do it without the commas? EDIT no.2: I also found a new problem. Python: Invalid Token Invalid token in number 08! :) A: You can define the numbers in a string and split it easily in row/columns: nums = """\ 1 2 3 4 5 6 7 8 9 10 """ rows = [map(int, row.split()) for row in nums.splitlines()] print rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] A: Check out NumPy - specifically, the N-dimensional array object. A: Your code example won't compile unless you put commas between the list elements. For example, this will compile: value = [ [ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12] ] If you're interested in taking strings like you show, and parsing them into a list of lists (or numpy multi-dimensional array), or if you have a list of lists or numpy array and want to print them out like you describe, you can do that too with a clever couple of list comprehensions. A: What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get: SyntaxError: invalid token Again, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you realize that fact. Edit: I see...we only get "invalid syntax" if we avoid the "invalid token" error caused by the "08" >>> import numpy >>> number = numpy.array([[08 02 22 97]]) File "<stdin>", line 1 number = numpy.array([[08 02 22 97]]) ^ SyntaxError: invalid token >>> number = numpy.array([[18 12 22 97]]) File "<stdin>", line 1 number = numpy.array([[18 12 22 97]]) ^ SyntaxError: invalid syntax A: As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this: s = """[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08] ...etc """ s = s.replace("]", "").replace("[", "").split() numbers = [int(x) for x in s] Then you got a 1d array of numbers, which you can have fun with.
Python: creating a grid
Is it possible to create a grid like below? I didn't found anything in the forum. #euler-project problem number 11 #In the 20 times 20 grid below, #four numbers along a diagonal line have been marked in red. #The product of these numbers is 26 times 63 times 78 times 14 = 1788696. #What is the greatest product of four adjacent numbers in any direction #(up, down, left, right, or diagonally) in the 20 times 20 grid? import numpy number = numpy.array([[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08] [49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00] [81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65] [52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91] [22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80] [24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50] [32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70] [67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21] [24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72] [21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95] [78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92] [16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57] [86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58] [19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40] [04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66] [88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69] [04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36] [20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16] [20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54] [01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48]]) EDIT no.1: I found numpy-array now. x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) Is there a way to do it without the commas? EDIT no.2: I also found a new problem. Python: Invalid Token Invalid token in number 08! :)
[ "You can define the numbers in a string and split it easily in row/columns:\nnums = \"\"\"\\\n1 2 3\n4 5 6\n7 8 9 10\n\"\"\"\nrows = [map(int, row.split()) for row in nums.splitlines()]\nprint rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]\n\n", "Check out NumPy - specifically, the N-dimensional array object.\n", "Your code example won't compile unless you put commas between the list elements.\nFor example, this will compile:\nvalue = [\n [ 1, 2, 3, 4],\n [ 5, 6, 7, 8],\n [ 9,10,11,12]\n ]\n\nIf you're interested in taking strings like you show, and parsing them into a list of lists (or numpy multi-dimensional array), or if you have a list of lists or numpy array and want to print them out like you describe, you can do that too with a clever couple of list comprehensions.\n", "What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get: \nSyntaxError: invalid token\n\nAgain, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you realize that fact. \nEdit: I see...we only get \"invalid syntax\" if we avoid the \"invalid token\" error caused by the \"08\"\n>>> import numpy\n>>> number = numpy.array([[08 02 22 97]])\n File \"<stdin>\", line 1\n number = numpy.array([[08 02 22 97]])\n ^\nSyntaxError: invalid token\n>>> number = numpy.array([[18 12 22 97]])\n File \"<stdin>\", line 1\n number = numpy.array([[18 12 22 97]])\n ^\nSyntaxError: invalid syntax\n\n", "As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this:\ns = \"\"\"[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]\n...etc\n\"\"\"\n\ns = s.replace(\"]\", \"\").replace(\"[\", \"\").split()\n\nnumbers = [int(x) for x in s]\n\nThen you got a 1d array of numbers, which you can have fun with.\n" ]
[ 3, 2, 2, 0, 0 ]
[]
[]
[ "datagrid", "grid", "python" ]
stackoverflow_0002112632_datagrid_grid_python.txt
Q: python threading/fork? I'm making a python script that needs to do 3 things simultaneously. What is a good way to achieve this as do to what i've heard about the GIL i'm not so lean into using threads anymore. 2 of the things that the script needs to do will be heavily active, they will have lots of work to do and then i need to have the third thing reporting to the user over a socket when he asks (so it will be like a tiny server) about the status of the other 2 processes. Now my question is what would be a good way to achieve this? I don't want to have three different script and also due to GIL using threads i think i won't get much performance and i'll make things worse. Is there a fork() for python like in C so from my script so fork 2 processes that will do their job and from the main process to report to the user? And how can i communicate from the forked processes with the main process? LE:: to be more precise 1thread should get email from a imap server and store them into a database, another thread should get messages from db that needs to be sent and then send them and the main thread should be a tiny http server that will just accept one url and will show the status of those two threads in json format. So are threads oK? will the work be done simultaneously or due to the gil there will be performance issues? A: I think you could use the multiprocessing package that has an API similar to the threading package and will allow you to get a better performance with multiple cores on a single CPU. To view the gain of performance using multiprocessing instead threading, check on this link about the average time comparison of the same program using multiprocessing x threading. A: The GIL is really only something to care about if you want to do multiprocessing, that is spread the load over several cores/processors. If that is the case, and it kinda sounds like it from your description, use multiprocessing. If you just need to do three things "simultaneously" in that way that you need to wait in the background for things to happen, then threads are just fine. That's what threads are for in the first place. 8-I)
python threading/fork?
I'm making a python script that needs to do 3 things simultaneously. What is a good way to achieve this as do to what i've heard about the GIL i'm not so lean into using threads anymore. 2 of the things that the script needs to do will be heavily active, they will have lots of work to do and then i need to have the third thing reporting to the user over a socket when he asks (so it will be like a tiny server) about the status of the other 2 processes. Now my question is what would be a good way to achieve this? I don't want to have three different script and also due to GIL using threads i think i won't get much performance and i'll make things worse. Is there a fork() for python like in C so from my script so fork 2 processes that will do their job and from the main process to report to the user? And how can i communicate from the forked processes with the main process? LE:: to be more precise 1thread should get email from a imap server and store them into a database, another thread should get messages from db that needs to be sent and then send them and the main thread should be a tiny http server that will just accept one url and will show the status of those two threads in json format. So are threads oK? will the work be done simultaneously or due to the gil there will be performance issues?
[ "I think you could use the multiprocessing package that has an API similar to the threading package and will allow you to get a better performance with multiple cores on a single CPU. \nTo view the gain of performance using multiprocessing instead threading, check on this link about the average time comparison of the same program using multiprocessing x threading.\n", "The GIL is really only something to care about if you want to do multiprocessing, that is spread the load over several cores/processors. If that is the case, and it kinda sounds like it from your description, use multiprocessing.\nIf you just need to do three things \"simultaneously\" in that way that you need to wait in the background for things to happen, then threads are just fine. That's what threads are for in the first place. 8-I)\n" ]
[ 4, 2 ]
[]
[]
[ "multiprocess", "multithreading", "python" ]
stackoverflow_0002123269_multiprocess_multithreading_python.txt
Q: Python: multiple properties, one setter/getter Consider the following class definitions class of2010(object): def __init__(self): self._a = 1 self._b = 2 self._c = 3 def set_a(self,value): print('setting a...') self._a = value def set_b(self,value): print('setting b...') self._b = value def set_c(self,value): print('setting c...') self._c = value a = property(fset=self.set_a) b = property(fset=self.set_b) c = property(fset=self.set_c) note that set_[a|b|c]() do the same thing. is there a way do define: def set_magic(self,value): print('setting <???>...') self._??? = value once and use it for a,b,c as follows a = property(fset=self.set_magic) b = property(fset=self.set_magic) c = property(fset=self.set_magic) A: def attrsetter(attr): def set_any(self, value): setattr(self, attr, value) return set_any a = property(fset=attrsetter('_a')) b = property(fset=attrsetter('_b')) c = property(fset=attrsetter('_c')) A: I see that your setters just log a message and then simply assign the value - in fact, your accepted answer just assigns the value. Are you using this pattern because it is the Accepted Practice / Conventional Wisdom in some other language, perhaps one whose name starts with "J"? If so, then please learn that the Pythonic approach to this same design is the much simpler: class Of2010(object): def __init__(self): self.a = 1 self.b = 2 self.c = 3 No do-nothing setters, no intermediate function calls just to assign a value. "What?!", you say? "Public exposure to member variables?!!" Well, yes actually. Look at these classes from the standpoint of client code. To use your class, clients create an object, and then assign property "a" using: obj = Of2010() obj.a = 42 Remarkably, this is the exact same code for the 5-liner class I posted above. Why does the J-language encourage the more verbose property style? To preserve the class interface in the event of future change in requirements. If at some point in time, some other value of the object must change in concert with any changes to a, then you must implement the property mechanism. Sadly, the J-language exposes the nature of the attribute access mechanism to the client code, so that to introduce a property at some point in the future is an intrusive refactoring task that will require a rebuild of all clients that make use of that class and its "a" attribute. In Python, such is not the case. Access to the object's "a" attribute is determined at runtime in the caller. Since direct access and property access both "look" the same, your Python class preserves this interface even though the actual mechanism is different. What matters is that it is identical as far as the client code is concerned. So in Java, one introduces this property complexity right from the inception of this class (and in fact, by Accepted Practice, of all classes), on the off-chance that it may become necessary some day in the future. With Python, one can start by implementing the Simplest Thing That Could Possibly Work, that is, direct access to simple member variables, leaving the complex approach for the time in the future that the extra stuff is actually required and of value. Since that day may never actually come, this is a huge jump forward in getting that first working version of your code out the door. A: May be you're looking for __setattr__(self, name, value) Take a look here A: class... def __setattr__(self, name, value): print 'setting', name self.__dict__[name] = value That's it.
Python: multiple properties, one setter/getter
Consider the following class definitions class of2010(object): def __init__(self): self._a = 1 self._b = 2 self._c = 3 def set_a(self,value): print('setting a...') self._a = value def set_b(self,value): print('setting b...') self._b = value def set_c(self,value): print('setting c...') self._c = value a = property(fset=self.set_a) b = property(fset=self.set_b) c = property(fset=self.set_c) note that set_[a|b|c]() do the same thing. is there a way do define: def set_magic(self,value): print('setting <???>...') self._??? = value once and use it for a,b,c as follows a = property(fset=self.set_magic) b = property(fset=self.set_magic) c = property(fset=self.set_magic)
[ "def attrsetter(attr):\n def set_any(self, value):\n setattr(self, attr, value)\n return set_any\n\na = property(fset=attrsetter('_a'))\nb = property(fset=attrsetter('_b'))\nc = property(fset=attrsetter('_c'))\n\n", "I see that your setters just log a message and then simply assign the value - in fact, your accepted answer just assigns the value. Are you using this pattern because it is the Accepted Practice / Conventional Wisdom in some other language, perhaps one whose name starts with \"J\"? If so, then please learn that the Pythonic approach to this same design is the much simpler:\nclass Of2010(object):\n def __init__(self):\n self.a = 1\n self.b = 2\n self.c = 3\n\nNo do-nothing setters, no intermediate function calls just to assign a value. \"What?!\", you say? \"Public exposure to member variables?!!\" Well, yes actually.\nLook at these classes from the standpoint of client code. To use your class, clients create an object, and then assign property \"a\" using:\nobj = Of2010()\nobj.a = 42\n\nRemarkably, this is the exact same code for the 5-liner class I posted above.\nWhy does the J-language encourage the more verbose property style? To preserve the class interface in the event of future change in requirements. If at some point in time, some other value of the object must change in concert with any changes to a, then you must implement the property mechanism. Sadly, the J-language exposes the nature of the attribute access mechanism to the client code, so that to introduce a property at some point in the future is an intrusive refactoring task that will require a rebuild of all clients that make use of that class and its \"a\" attribute.\nIn Python, such is not the case. Access to the object's \"a\" attribute is determined at runtime in the caller. Since direct access and property access both \"look\" the same, your Python class preserves this interface even though the actual mechanism is different. What matters is that it is identical as far as the client code is concerned.\nSo in Java, one introduces this property complexity right from the inception of this class (and in fact, by Accepted Practice, of all classes), on the off-chance that it may become necessary some day in the future. With Python, one can start by implementing the Simplest Thing That Could Possibly Work, that is, direct access to simple member variables, leaving the complex approach for the time in the future that the extra stuff is actually required and of value. Since that day may never actually come, this is a huge jump forward in getting that first working version of your code out the door.\n", "May be you're looking for \n__setattr__(self, name, value)\nTake a look here\n", "class...\n def __setattr__(self, name, value):\n print 'setting', name\n self.__dict__[name] = value\n\nThat's it.\n" ]
[ 21, 7, 3, 1 ]
[]
[]
[ "getter_setter", "properties", "python", "setter" ]
stackoverflow_0002123585_getter_setter_properties_python_setter.txt
Q: Google App Engine and Django templates: why do these two cases differ? I'm new to Python, and I'm using Google App Engine to build a simple blog to help me learn it. I have the following test code: entries = db.Query(Entry).order("-published").get() comments = db.Query(Comment).order("published").get() self.response.out.write(template.render(templatePath + 'test.django.html', { 'entries': entries, 'comments': comments, })) And a Django template that looks like this: {% extends "master.django.html" %} {% block pagetitle %}Test Page{% endblock pagetitle %} {% block content %} {% for e in entries %} <p><a href="/post/{{ e.slug }}/">{{ e.title|escape }} - {{ e.published|date:"jS o\f F Y" }}</p> {% endfor %} {% for c in comments.all %} <p>{{ c.authorname }} {{ c.published|date:"d/m/Y h:i" }}</p> {% endfor %} {% endblock content %} When I view this templated page in the browser, I get: TypeError: 'Entry' object is not iterable Changing the line {% for e in entries %} to {% for e in entries.all %} solves this problem, which is great. However, this is the bit I don't understand; in another template (for the archive page), I pass in the same thing, a list of Entry objects: entries = db.Query(Entry).order("-published").fetch(limit=100) self.response.out.write(template.render(templatePath + 'archive.django.html', { 'entries': entries, })) With the template as follows: {% extends "master.django.html" %} {% block pagetitle %}Home Page{% endblock pagetitle %} {% block content %} <ul> {% for entry in entries %} <li><a href="/post/{{ entry.slug }}/">{{ entry.title|escape }} <span>{{ entry.published|date:"jS o\f F Y" }}</a>{% if admin %} - <a href="/compose/?key={{ entry.key }}">Edit Post</a>{% endif %}</span></li> {% endfor %} {% endblock content %} This code works fine, without changing entries to entries.all; indeed if I do change it to that I get no output (no errors, just nothing at all). Can someone explain why this is please? Edit: I originally pasted the wrong piece of query code for the second example, which would probably have made things easier for people to give me an answer... changed it now. A: You want to use .fetch(), not get(): entries = db.Query(Entry).order("-published").fetch() comments = db.Query(Comment).order("published").fetch() get() returns only the first item that matches the query criteria, so instead of an iterable collection, you'll get one instance, and Entry object. I can not explain why the second version does work. It really looks like it shouldn't.
Google App Engine and Django templates: why do these two cases differ?
I'm new to Python, and I'm using Google App Engine to build a simple blog to help me learn it. I have the following test code: entries = db.Query(Entry).order("-published").get() comments = db.Query(Comment).order("published").get() self.response.out.write(template.render(templatePath + 'test.django.html', { 'entries': entries, 'comments': comments, })) And a Django template that looks like this: {% extends "master.django.html" %} {% block pagetitle %}Test Page{% endblock pagetitle %} {% block content %} {% for e in entries %} <p><a href="/post/{{ e.slug }}/">{{ e.title|escape }} - {{ e.published|date:"jS o\f F Y" }}</p> {% endfor %} {% for c in comments.all %} <p>{{ c.authorname }} {{ c.published|date:"d/m/Y h:i" }}</p> {% endfor %} {% endblock content %} When I view this templated page in the browser, I get: TypeError: 'Entry' object is not iterable Changing the line {% for e in entries %} to {% for e in entries.all %} solves this problem, which is great. However, this is the bit I don't understand; in another template (for the archive page), I pass in the same thing, a list of Entry objects: entries = db.Query(Entry).order("-published").fetch(limit=100) self.response.out.write(template.render(templatePath + 'archive.django.html', { 'entries': entries, })) With the template as follows: {% extends "master.django.html" %} {% block pagetitle %}Home Page{% endblock pagetitle %} {% block content %} <ul> {% for entry in entries %} <li><a href="/post/{{ entry.slug }}/">{{ entry.title|escape }} <span>{{ entry.published|date:"jS o\f F Y" }}</a>{% if admin %} - <a href="/compose/?key={{ entry.key }}">Edit Post</a>{% endif %}</span></li> {% endfor %} {% endblock content %} This code works fine, without changing entries to entries.all; indeed if I do change it to that I get no output (no errors, just nothing at all). Can someone explain why this is please? Edit: I originally pasted the wrong piece of query code for the second example, which would probably have made things easier for people to give me an answer... changed it now.
[ "You want to use .fetch(), not get():\nentries = db.Query(Entry).order(\"-published\").fetch()\ncomments = db.Query(Comment).order(\"published\").fetch()\n\nget() returns only the first item that matches the query criteria, so instead of an iterable collection, you'll get one instance, and Entry object.\nI can not explain why the second version does work. It really looks like it shouldn't.\n" ]
[ 2 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0002123695_django_templates_google_app_engine_python.txt
Q: How to prevent JPEG compression when uploading image through Picasa API? I'm using the Python client library for the Picasa Web Albums API to upload some JPEG images to an album. But the photos appear very compressed once uploaded. In Picasa 3.6 there is an option to upload images in their original quality without any compression, but is there are similar option I can use from within the API? This is some of the code I use to create the photo and insert it into the album: upload_photo = gdata.photos.PhotoEntry() upload_photo.summary = atom.Summary(text=title) upload_photo.title = atom.Title(text=file_name) upload_photo.text = atom.Text(text='Test') upload_photo.author = atom.Author(atom.Name(text='Test Author')) upload_photo.timestamp = gdata.photos.Timestamp(text='%i' % int(time.mktime(photo_date.timetuple()) * 1000)) upload_photo.geo = gdata.geo.Where() upload_photo.geo.Point = gdata.geo.Point() upload_photo.geo.Point.pos = gdata.geo.Pos(text='%f %f' % (lat, lon)) imgContent = StringIO.StringIO(urlfetch.fetch('http://url.com/image1.jpg').content) gpclient.InsertPhoto(album_or_uri=album_url, photo=upload_photo, filename_or_handle=imgContent, content_type='image/jpeg') A: I managed to solve this problem myself, and it turned out to be a weird one :-) I asked around on the Google Group for the Picasa data API and people there were saying that the API does not do any compression when uploading new images. That led me to look at the other code, namely the urlfetch. It turned out that the urlfetch was getting the compressed JPEG image. But why? Was there a parameter I forgot to set? I looked through the documentation and couldn't find any limitations. And then it suddenly dawned on me what was happening. I was testing this on my local machine using the Google App Engine SDK, which is connected to the internet using mobile broadband from T-Mobile. And T-Mobile uses a proxy to compress images when you download them. For my Firefox browser I use an extension to modify the HTTP headers to prevent this compression during browsing, but of course the urlfetch was not doing this. After changing this it is downloading the original quality JPEG and uploads it to Picasa with no problem.
How to prevent JPEG compression when uploading image through Picasa API?
I'm using the Python client library for the Picasa Web Albums API to upload some JPEG images to an album. But the photos appear very compressed once uploaded. In Picasa 3.6 there is an option to upload images in their original quality without any compression, but is there are similar option I can use from within the API? This is some of the code I use to create the photo and insert it into the album: upload_photo = gdata.photos.PhotoEntry() upload_photo.summary = atom.Summary(text=title) upload_photo.title = atom.Title(text=file_name) upload_photo.text = atom.Text(text='Test') upload_photo.author = atom.Author(atom.Name(text='Test Author')) upload_photo.timestamp = gdata.photos.Timestamp(text='%i' % int(time.mktime(photo_date.timetuple()) * 1000)) upload_photo.geo = gdata.geo.Where() upload_photo.geo.Point = gdata.geo.Point() upload_photo.geo.Point.pos = gdata.geo.Pos(text='%f %f' % (lat, lon)) imgContent = StringIO.StringIO(urlfetch.fetch('http://url.com/image1.jpg').content) gpclient.InsertPhoto(album_or_uri=album_url, photo=upload_photo, filename_or_handle=imgContent, content_type='image/jpeg')
[ "I managed to solve this problem myself, and it turned out to be a weird one :-)\nI asked around on the Google Group for the Picasa data API and people there were saying that the API does not do any compression when uploading new images. That led me to look at the other code, namely the urlfetch.\nIt turned out that the urlfetch was getting the compressed JPEG image. But why? Was there a parameter I forgot to set? I looked through the documentation and couldn't find any limitations.\nAnd then it suddenly dawned on me what was happening. I was testing this on my local machine using the Google App Engine SDK, which is connected to the internet using mobile broadband from T-Mobile. And T-Mobile uses a proxy to compress images when you download them. For my Firefox browser I use an extension to modify the HTTP headers to prevent this compression during browsing, but of course the urlfetch was not doing this.\nAfter changing this it is downloading the original quality JPEG and uploads it to Picasa with no problem.\n" ]
[ 3 ]
[]
[]
[ "gdata_api", "jpeg", "picasa", "python" ]
stackoverflow_0002100001_gdata_api_jpeg_picasa_python.txt
Q: Convert string in Class name (from appengine datastore to class) Possible Duplicate: Does python have an equivalent to Java Class.forName()? I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this: class Recipe(db.Model): ingredients = db.ListProperty(type) quantities = db.ListProperty(int) However it seems that you cannot use "type" as the class value in ListProperty. I was thinking of instead of using ListProperty, using ListStringProperty and save the class names as strings. However, how do I convert a string to a class name, so I can write like this: str = "A" # convert str to class name in var class_str class_str().call_some_method() Thanks in advance, Jose A: I suggest you make ingredient a list of strings, populate it with the pickle.dumps of the types you're saving, and, upon retrieval, use pickle.loads to get a type object back. pickle serializes types "by name", so there are some constraints (essentially, the types must live at the top level of some module), but that's way handier than doing your own serialization (and, especially, deserializaton) of the type names, which would essentially entail you repeating a bit of the work that pickle can already do on your behalf!-) A: Maybe you can use eval, like this? class Juice(object): def amount(self): print "glass of juice" juice = "Juice" eval(juice)().amount() # prints "glass of juice"
Convert string in Class name (from appengine datastore to class)
Possible Duplicate: Does python have an equivalent to Java Class.forName()? I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this: class Recipe(db.Model): ingredients = db.ListProperty(type) quantities = db.ListProperty(int) However it seems that you cannot use "type" as the class value in ListProperty. I was thinking of instead of using ListProperty, using ListStringProperty and save the class names as strings. However, how do I convert a string to a class name, so I can write like this: str = "A" # convert str to class name in var class_str class_str().call_some_method() Thanks in advance, Jose
[ "I suggest you make ingredient a list of strings, populate it with the pickle.dumps of the types you're saving, and, upon retrieval, use pickle.loads to get a type object back.\npickle serializes types \"by name\", so there are some constraints (essentially, the types must live at the top level of some module), but that's way handier than doing your own serialization (and, especially, deserializaton) of the type names, which would essentially entail you repeating a bit of the work that pickle can already do on your behalf!-)\n", "Maybe you can use eval, like this?\nclass Juice(object):\n def amount(self):\n print \"glass of juice\"\n\njuice = \"Juice\"\neval(juice)().amount()\n# prints \"glass of juice\"\n\n" ]
[ 1, 0 ]
[]
[]
[ "eval", "google_app_engine", "metaprogramming", "python" ]
stackoverflow_0002122571_eval_google_app_engine_metaprogramming_python.txt
Q: Reading corrupted file in python I've got a file, that looks like this alt text http://img40.imageshack.us/img40/4581/crapq.png Now there are 5 lines shown. However running this script with open('hello.txt', 'r') as hello: for line in hello: print line, gives num 1 ctl00$header1$Login1$txtUserName=ыют;CBШ▌ and that's all. How can I read entire file? TIA A: entire_file = open('hello.txt', 'rb').read() print 'number of \\n: %d, number of bytes %d' % ( entire_file.count('\n'), len(entire_file))
Reading corrupted file in python
I've got a file, that looks like this alt text http://img40.imageshack.us/img40/4581/crapq.png Now there are 5 lines shown. However running this script with open('hello.txt', 'r') as hello: for line in hello: print line, gives num 1 ctl00$header1$Login1$txtUserName=ыют;CBШ▌ and that's all. How can I read entire file? TIA
[ "entire_file = open('hello.txt', 'rb').read()\n\nprint 'number of \\\\n: %d, number of bytes %d' % (\n entire_file.count('\\n'), len(entire_file))\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002124238_python.txt
Q: Enabling overriding of app template in django? I'm writing a simple site to display statistics for some data, and I've got an app called "stats", that I'd like to write default templates for (places in stats/templates/stats), but I'd like these to be overridable in the same way that the templates for the admin app are. IE: If I put a stats/view.html in my project's templates directory, it would be used rather than the one in my apps directory. I can't seem to quite figure out how to do this. How can I get Django to search the project's TEMPLATE_DIRS before it hits up the apps? Edit: Found the problem, saw someone's tutorial for setting the template directories using the os module. They had: TEMPLATE_DIRS = ( os.path.join(os.path.basename(__file__), 'templates') ) Which should be: TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates') ) A: You need to put filesystem loader before app_directories loader in your TEMPLATE_LOADERS setting. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source' ) The order of TEMPLATE_LOADERS matter.
Enabling overriding of app template in django?
I'm writing a simple site to display statistics for some data, and I've got an app called "stats", that I'd like to write default templates for (places in stats/templates/stats), but I'd like these to be overridable in the same way that the templates for the admin app are. IE: If I put a stats/view.html in my project's templates directory, it would be used rather than the one in my apps directory. I can't seem to quite figure out how to do this. How can I get Django to search the project's TEMPLATE_DIRS before it hits up the apps? Edit: Found the problem, saw someone's tutorial for setting the template directories using the os module. They had: TEMPLATE_DIRS = ( os.path.join(os.path.basename(__file__), 'templates') ) Which should be: TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates') )
[ "You need to put filesystem loader before app_directories loader in your TEMPLATE_LOADERS setting.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source'\n)\n\nThe order of TEMPLATE_LOADERS matter.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002124399_django_python_templates.txt
Q: Python3 http.server POST example I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manual it appears that I must use a CGI server class instead and also map the scripts to that directory. I'd rather not have to do this but I cannot find another way. Am I missing something? def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.get('content-type')) if ctype == 'multipart/form-data': query = cgi.parse_multipart(self.rfile, pdict) self.send_response(301) self.end_headers() upfilecontent = query.get('upfile') print("filecontent", upfilecontent[0]) self.wfile.write("<HTML>POST OK.<BR><BR>"); self.wfile.write(upfilecontent[0]); A: After poking and a few more hours of googling I've found the following works. def do_POST(self): length = int(self.headers['Content-Length']) post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8')) # You now have a dictionary of the post data self.wfile.write("Lorem Ipsum".encode("utf-8")) I'm surprised at how easy this was.
Python3 http.server POST example
I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manual it appears that I must use a CGI server class instead and also map the scripts to that directory. I'd rather not have to do this but I cannot find another way. Am I missing something? def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.get('content-type')) if ctype == 'multipart/form-data': query = cgi.parse_multipart(self.rfile, pdict) self.send_response(301) self.end_headers() upfilecontent = query.get('upfile') print("filecontent", upfilecontent[0]) self.wfile.write("<HTML>POST OK.<BR><BR>"); self.wfile.write(upfilecontent[0]);
[ "After poking and a few more hours of googling I've found the following works.\ndef do_POST(self):\n length = int(self.headers['Content-Length'])\n post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))\n # You now have a dictionary of the post data\n\n self.wfile.write(\"Lorem Ipsum\".encode(\"utf-8\"))\n\nI'm surprised at how easy this was.\n" ]
[ 25 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002121481_python_python_3.x.txt
Q: Paramiko equvalent of pipline controls and input/output pipes I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as: ssh server "cat remote_file" > local_file with paramiko channels? Can paramiko.Transport.open_channel() or Message() do the job? I am unsure of how to proceed. A: If the limitation, as you say, is only in your client, you can easily implement a SFTP client directly with paramiko -- e.g., look at this example code. A: pyfilesystem implements an sftp filesystem on top of paramiko.
Paramiko equvalent of pipline controls and input/output pipes
I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as: ssh server "cat remote_file" > local_file with paramiko channels? Can paramiko.Transport.open_channel() or Message() do the job? I am unsure of how to proceed.
[ "If the limitation, as you say, is only in your client, you can easily implement a SFTP client directly with paramiko -- e.g., look at this example code.\n", "pyfilesystem implements an sftp filesystem on top of paramiko. \n" ]
[ 1, 1 ]
[]
[]
[ "file", "paramiko", "python", "transfer" ]
stackoverflow_0002123581_file_paramiko_python_transfer.txt
Q: How does Timer in Python work, regarding multithreading? If I call Timer(.1, some_function, [some_arguments]).start() multiple times, what exactly happens behind the scenes? The source of our problem is ... We have a method that's essentially: def move(target): force = calculateForce(target-getCurrentPosition()) if(force != 0) setForce(force) Timer(.1, moveCursor, [tx]).start() else: setForce(0) After setting the force, we need to check after a certain amount of time whether it should be stopped. (This information is to/from an external physical device that doesn't fire events.) There's weird issues in how much time this function is taking, and also we're getting "can't start new thread" errors after a certain amount of time. This leads me to believe that Timer(...) does not reuse threads but creates a new one every time. Combined with a belief that the library we're using isn't threadsafe, these errors would make some sense.... A: Right: each call to Timer does start a new thread. Indeed, class threading.Timer is documented as being "a thread". You can confirm this by reading the source code, line 707. A good alternative is to run a scheduler in a single thread, receiving requests through a Queue.Queue instance (intrinsically threadsafe) and intrinsically serializing them (which may also take care of your "non-thread-safe-library" problems without needing further locking or synchronization, depending how you arrange your overall architecture of course).
How does Timer in Python work, regarding multithreading?
If I call Timer(.1, some_function, [some_arguments]).start() multiple times, what exactly happens behind the scenes? The source of our problem is ... We have a method that's essentially: def move(target): force = calculateForce(target-getCurrentPosition()) if(force != 0) setForce(force) Timer(.1, moveCursor, [tx]).start() else: setForce(0) After setting the force, we need to check after a certain amount of time whether it should be stopped. (This information is to/from an external physical device that doesn't fire events.) There's weird issues in how much time this function is taking, and also we're getting "can't start new thread" errors after a certain amount of time. This leads me to believe that Timer(...) does not reuse threads but creates a new one every time. Combined with a belief that the library we're using isn't threadsafe, these errors would make some sense....
[ "Right: each call to Timer does start a new thread. Indeed, class threading.Timer is documented as being \"a thread\". You can confirm this by reading the source code, line 707.\nA good alternative is to run a scheduler in a single thread, receiving requests through a Queue.Queue instance (intrinsically threadsafe) and intrinsically serializing them (which may also take care of your \"non-thread-safe-library\" problems without needing further locking or synchronization, depending how you arrange your overall architecture of course).\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002124540_multithreading_python.txt
Q: Pythonic way of summing lists and lists of lists I'm trying to find a neat way of summing a list and a list of lists in the same function, so far I've got: import operator """ Fails late for item = ['a', 'b'] """ def validate(item): try: return sum(item) == sum(range(1, 10)) except TypeError: return sum(reduce(operator.add, item)) == sum(range(1, 10)) """ Not valid for item = [1,2,[3,4,5]] """ def validate2(item): if isinstance(item[0], int): return sum(item) == sum(range(1, 10)) else: return sum(reduce(operator.add, item)) == sum(range(1, 10)) print validate([1, 2, 3, 4, 5, 6, 7, 8, 9]) print validate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print validate2([1, 2, 3, 4, 5, 6, 7, 8, 9]) print validate2([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ...but neither of these seem quite right to me (reasons in the doc strings). What I want to know is if there is a better way of summing lists and lists of lists that doesn't require me to catch exceptions or actually analyse the list before the function decides what to do. Obviously, I'm still expecting ['a', 'b'] to be invalid. A: Perhaps you'd find it easier to flatten the list first? def flatten(xs): for x in xs: try: sub = iter(x) except TypeError: yield x else: for y in flatten(sub): yield y With the above, you can do this: In [4]: fs = flatten([1,2,[3,4,[5,6],7],8,[9,10]]) In [5]: list(fs) Out[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] A: Don't forget to describe exactly what you're trying to do. I'm assuming you mean to sum all values to a single value, and not to get eg. [[1,2],[3,4]] -> [3,7]. Here's simple recursion; five lines of code if you skip the tests: def sums(it): """ >>> sums(1) 1 >>> sums([1,2,3]) 6 >>> sums([1,2,3,[4,5]]) 15 >>> sums(['a','b']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'int' and 'str' """ if getattr(it, "__iter__", None): return sum(map(sums, it)) else: return it if __name__ == "__main__": import doctest doctest.testmod() A: The external numpy module has many operations (including sum()) which work similarly on scalars, vectors, matrices and even higher-dimensional arrays... Note however that it doesn't work on mixed lists like [1,2,[3,4,5]], only square matrices! So it doesn't exactly answer your question.
Pythonic way of summing lists and lists of lists
I'm trying to find a neat way of summing a list and a list of lists in the same function, so far I've got: import operator """ Fails late for item = ['a', 'b'] """ def validate(item): try: return sum(item) == sum(range(1, 10)) except TypeError: return sum(reduce(operator.add, item)) == sum(range(1, 10)) """ Not valid for item = [1,2,[3,4,5]] """ def validate2(item): if isinstance(item[0], int): return sum(item) == sum(range(1, 10)) else: return sum(reduce(operator.add, item)) == sum(range(1, 10)) print validate([1, 2, 3, 4, 5, 6, 7, 8, 9]) print validate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print validate2([1, 2, 3, 4, 5, 6, 7, 8, 9]) print validate2([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ...but neither of these seem quite right to me (reasons in the doc strings). What I want to know is if there is a better way of summing lists and lists of lists that doesn't require me to catch exceptions or actually analyse the list before the function decides what to do. Obviously, I'm still expecting ['a', 'b'] to be invalid.
[ "Perhaps you'd find it easier to flatten the list first?\ndef flatten(xs):\n for x in xs:\n try:\n sub = iter(x)\n except TypeError:\n yield x\n else:\n for y in flatten(sub):\n yield y\n\nWith the above, you can do this:\nIn [4]: fs = flatten([1,2,[3,4,[5,6],7],8,[9,10]])\n\nIn [5]: list(fs)\nOut[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n", "Don't forget to describe exactly what you're trying to do. I'm assuming you mean to sum all values to a single value, and not to get eg. [[1,2],[3,4]] -> [3,7]. Here's simple recursion; five lines of code if you skip the tests:\ndef sums(it):\n \"\"\"\n >>> sums(1)\n 1\n >>> sums([1,2,3])\n 6\n >>> sums([1,2,3,[4,5]])\n 15\n >>> sums(['a','b'])\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for +: 'int' and 'str'\n \"\"\"\n if getattr(it, \"__iter__\", None):\n return sum(map(sums, it))\n else:\n return it\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n", "The external numpy module has many operations (including sum()) which work similarly on scalars, vectors, matrices and even higher-dimensional arrays...\nNote however that it doesn't work on mixed lists like [1,2,[3,4,5]], only square matrices! So it doesn't exactly answer your question.\n" ]
[ 5, 3, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0002106996_algorithm_python.txt
Q: Renaming a file on a remote file server in C# / Python I need to rename a whole heap of files on a Windows file server - I don't mind what language I use really as long it's quick and easy! I know it's basic but just to clarify - in pseudo-code... server = login (fileserver, creds) foreach (file in server.navigateToDir(dir)) rename(file) I know how to do this in Python/C# if I was a local user but have no idea if it's even possible to do this remotely using Python. I've searched for code snippets/help but have found none yet. Thanks. A: Use \\servername\sharename\somefile.foo for filenames - provided you have access to connect to it and are running on windows. You could also map up a network drive and treat it as any other local drive (y:\sharename\somefile.foo) A: You could also use PSEXEC to execute the code remotely on the server if you need the performance of locally executed code. See http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx A: Have a look at pyfilesytem, it provides a consistent interface for local and remote filesystems. A: The following renames a file in each of the sub-directories of the folder path given. It renames the file from the given filename (eg."blah.txt") to foldername+extension. NB. Z can be either a local or network drive (ie. if folder is on file server map network drive to it). For example from a shell... python renamer.py "Z:\\FolderCollectionInHere" blah.txt csv ... will rename a file 'blah.txt' in each immediate sub-directory of "Z:\FolderCollectionHere" to .csv. import os import sys class Renamer: def start(self, args): os.chdir(args[1]) dirs = os.listdir(".") for dir in dirs: try: os.rename(dir + "\\" + args[2], dir + "\\" + dir + "." + args[3]) print "Renamed file in directory: " + dir except Exception: print "Couldn't find file to rename in directory: " + dir Renamer().start(sys.argv)
Renaming a file on a remote file server in C# / Python
I need to rename a whole heap of files on a Windows file server - I don't mind what language I use really as long it's quick and easy! I know it's basic but just to clarify - in pseudo-code... server = login (fileserver, creds) foreach (file in server.navigateToDir(dir)) rename(file) I know how to do this in Python/C# if I was a local user but have no idea if it's even possible to do this remotely using Python. I've searched for code snippets/help but have found none yet. Thanks.
[ "Use \\\\servername\\sharename\\somefile.foo for filenames - provided you have access to connect to it and are running on windows.\nYou could also map up a network drive and treat it as any other local drive (y:\\sharename\\somefile.foo)\n", "You could also use PSEXEC to execute the code remotely on the server if you need the performance of locally executed code. See http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx\n", "Have a look at pyfilesytem, it provides a consistent interface for local and remote filesystems.\n", "The following renames a file in each of the sub-directories of the folder path given. It renames the file from the given filename (eg.\"blah.txt\") to foldername+extension.\nNB. Z can be either a local or network drive (ie. if folder is on file server map network drive to it).\nFor example from a shell...\npython renamer.py \"Z:\\\\FolderCollectionInHere\" blah.txt csv\n\n... will rename a file 'blah.txt' in each immediate sub-directory of \"Z:\\FolderCollectionHere\" to .csv.\nimport os\nimport sys\n\nclass Renamer:\n def start(self, args):\n os.chdir(args[1])\n dirs = os.listdir(\".\")\n\n for dir in dirs:\n try:\n os.rename(dir + \"\\\\\" + args[2], dir + \"\\\\\" + dir + \".\" + args[3])\n print \"Renamed file in directory: \" + dir\n except Exception:\n print \"Couldn't find file to rename in directory: \" + dir\n\nRenamer().start(sys.argv)\n\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "c#", "file", "fileserver", "python", "rename" ]
stackoverflow_0002109988_c#_file_fileserver_python_rename.txt
Q: Pretty printing a list of list of floats? Basically i have to dump a series of temperature readings, into a text file. This is a space delimited list of elements, where each row represents something (i don't know, and it just gets forced into a fortran model, shudder). I am more or less handling it from our groups side, which is extracting those temperature readings and dumping them into a text file. Basically a quick example is i have a list like this(but with alot more elements): temperature_readings = [ [1.343, 348.222, 484844.3333], [12349.000002, -2.43333]] In the past we just dumped this into a file, unfortunately there is some people who have this irritating knack of wanting to look directly at the text file, and picking out certain columns and changing some things (for testing.. i don't really know..). But they always complain about the columns not lining up properly, they pretty much the above list to be printed like this: 1.343 348.222 484844.333 12349.000002 -2.433333 So those wonderful decimals line up. Is there an easy way to do this? A: you can right-pad like this: str = '%-10f' % val to left pad: set = '%10f' % val or in combination pad and set the precision to 4 decimal places: str = '%-10.4f' % val : import sys rows = [[1.343, 348.222, 484844.3333], [12349.000002, -2.43333]] for row in rows: for val in row: sys.stdout.write('%20f' % val) sys.stdout.write("\n") 1.343000 348.222000 484844.333300 12349.000002 -2.433330 A: The % (String formatting) operator is deprecated now. You can use str.format to do pretty printing in Python. Something like this might work for you: for set in temperature_readings: for temp in set: print "{0:10.4f}\t".format(temp), print Which prints out the following: 1.3430 348.2220 484844.3333 12349.0000 -2.4333 You can read more about this here: http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting A: If you also want to display a fixed number of decimals (which probably makes sense if the numbers are really temperature readings), something like this gives quite nice output: for line in temperature_readings: for value in line: print '%10.2f' % value, print Output: 1.34 348.22 484844.33 12349.00 -2.43 A: In Python 2.*, for sublist in temperature_readings: for item in sublist: print '%15.6f' % item, print emits 1.343000 348.222000 484844.333300 12349.000002 -2.433330 for your example. Tweak the lengths and number of decimals as you prefer, of course!
Pretty printing a list of list of floats?
Basically i have to dump a series of temperature readings, into a text file. This is a space delimited list of elements, where each row represents something (i don't know, and it just gets forced into a fortran model, shudder). I am more or less handling it from our groups side, which is extracting those temperature readings and dumping them into a text file. Basically a quick example is i have a list like this(but with alot more elements): temperature_readings = [ [1.343, 348.222, 484844.3333], [12349.000002, -2.43333]] In the past we just dumped this into a file, unfortunately there is some people who have this irritating knack of wanting to look directly at the text file, and picking out certain columns and changing some things (for testing.. i don't really know..). But they always complain about the columns not lining up properly, they pretty much the above list to be printed like this: 1.343 348.222 484844.333 12349.000002 -2.433333 So those wonderful decimals line up. Is there an easy way to do this?
[ "you can right-pad like this:\nstr = '%-10f' % val\n\nto left pad:\nset = '%10f' % val\n\nor in combination pad and set the precision to 4 decimal places:\nstr = '%-10.4f' % val\n\n:\nimport sys\nrows = [[1.343, 348.222, 484844.3333], [12349.000002, -2.43333]]\nfor row in rows:\n for val in row:\n sys.stdout.write('%20f' % val)\n sys.stdout.write(\"\\n\")\n\n 1.343000 348.222000 484844.333300\n 12349.000002 -2.433330\n\n", "The % (String formatting) operator is deprecated now.\nYou can use str.format to do pretty printing in Python.\nSomething like this might work for you:\nfor set in temperature_readings:\n for temp in set:\n print \"{0:10.4f}\\t\".format(temp),\n print\n\nWhich prints out the following:\n 1.3430 348.2220 484844.3333\n12349.0000 -2.4333\nYou can read more about this here: http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting\n", "If you also want to display a fixed number of decimals (which probably makes sense if the numbers are really temperature readings), something like this gives quite nice output:\nfor line in temperature_readings:\n for value in line:\n print '%10.2f' % value,\n print\n\nOutput:\n\n 1.34 348.22 484844.33\n 12349.00 -2.43\n\n", "In Python 2.*,\nfor sublist in temperature_readings:\n for item in sublist:\n print '%15.6f' % item,\n print\n\nemits\n 1.343000 348.222000 484844.333300\n 12349.000002 -2.433330\n\nfor your example. Tweak the lengths and number of decimals as you prefer, of course!\n" ]
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002124645_python.txt
Q: Why am I getting dups with random.shuffle in Python? For a list of 10 ints, there are 10! possible orders or permutations. Why does random.shuffle give duplicates after only 5000 tries? >>> L = range(10) >>> rL = list() >>> for i in range(5000): ... random.shuffle(L) ... rL.append(L[:]) ... >>> rL = [tuple(e) for e in rL] >>> len(set(rL)) 4997 >>> for i,t in enumerate(rL): ... if rL.count(t) > 1: ... print i,t ... 102 (7, 5, 2, 4, 0, 6, 9, 3, 1, 8) 258 (1, 4, 0, 2, 7, 3, 5, 9, 6, 8) 892 (1, 4, 0, 2, 7, 3, 5, 9, 6, 8) 2878 (7, 5, 2, 4, 0, 6, 9, 3, 1, 8) 4123 (5, 8, 0, 1, 7, 3, 2, 4, 6, 9) 4633 (5, 8, 0, 1, 7, 3, 2, 4, 6, 9) >>> 10*9*8*7*6*5*4*3*2 3628800 >>> 2**19937 - 1 431542479738816264805523551633791983905393 [snip] >>> L = list() >>> for i in range(5000): ... L.append(random.choice(xrange(3628800))) ... >>> len(set(L)) 4997 Edit: FWIW, if the probability of not having two the same for a single pair is: p = (10! - 1) / 10! and the number of combinations is: C = 5000! / 4998! * 2! = 5000 * 4999 / 2 then the probability of having a duplicate is: >>> import math >>> f = math.factorial(10) >>> p = 1.0*(f-1)/f >>> C = 5000.0*4999/2 >>> 1 - p**C 0.96806256495611798 A: It's called the Birthday Paradox. According to this formula from Wikipedia: but replacing 365 with 10! you would only need about 2200 examples to have a 50% chance of a collision, and you are way above that. A: Because it's... random! If you want all permutations just use itertools.permutations. A: maybe because is RANDOM? Random does not mean does not repeat, it means it is RANDOM, which means theoretically it could return the exact same answer every time, not likely but possible.
Why am I getting dups with random.shuffle in Python?
For a list of 10 ints, there are 10! possible orders or permutations. Why does random.shuffle give duplicates after only 5000 tries? >>> L = range(10) >>> rL = list() >>> for i in range(5000): ... random.shuffle(L) ... rL.append(L[:]) ... >>> rL = [tuple(e) for e in rL] >>> len(set(rL)) 4997 >>> for i,t in enumerate(rL): ... if rL.count(t) > 1: ... print i,t ... 102 (7, 5, 2, 4, 0, 6, 9, 3, 1, 8) 258 (1, 4, 0, 2, 7, 3, 5, 9, 6, 8) 892 (1, 4, 0, 2, 7, 3, 5, 9, 6, 8) 2878 (7, 5, 2, 4, 0, 6, 9, 3, 1, 8) 4123 (5, 8, 0, 1, 7, 3, 2, 4, 6, 9) 4633 (5, 8, 0, 1, 7, 3, 2, 4, 6, 9) >>> 10*9*8*7*6*5*4*3*2 3628800 >>> 2**19937 - 1 431542479738816264805523551633791983905393 [snip] >>> L = list() >>> for i in range(5000): ... L.append(random.choice(xrange(3628800))) ... >>> len(set(L)) 4997 Edit: FWIW, if the probability of not having two the same for a single pair is: p = (10! - 1) / 10! and the number of combinations is: C = 5000! / 4998! * 2! = 5000 * 4999 / 2 then the probability of having a duplicate is: >>> import math >>> f = math.factorial(10) >>> p = 1.0*(f-1)/f >>> C = 5000.0*4999/2 >>> 1 - p**C 0.96806256495611798
[ "It's called the Birthday Paradox.\nAccording to this formula from Wikipedia:\n\nbut replacing 365 with 10! you would only need about 2200 examples to have a 50% chance of a collision, and you are way above that.\n", "Because it's... random! If you want all permutations just use itertools.permutations.\n", "maybe because is RANDOM? Random does not mean does not repeat, it means it is RANDOM, which means theoretically it could return the exact same answer every time, not likely but possible.\n" ]
[ 19, 6, 2 ]
[]
[]
[ "birthday_paradox", "probability", "python", "random" ]
stackoverflow_0002124748_birthday_paradox_probability_python_random.txt
Q: python imaplib ssl error using celeryd queue I'm having a problem using imaplib on python 2.6 with the latest django svn. I want to download imap emails in a queue (using celeryd). I'm able to connect/download emails from the command line, but when i offload the task through django to celeryd i get this error: "SSLError: [Errno 1] _ssl.c:1325: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number". Imaplib docs don't mention how to specify a version of SSL. I'm trying to pull emails from gmail. I don't understand why offloading the task to a queue using celeryd would cause the task to fail. Any help would be much appreciated. Edit: here is a stack trace: File "/usr/lib/python2.6/imaplib.py", line 643, in select typ, dat = self._simple_command(name, mailbox) File "/usr/lib/python2.6/imaplib.py", line 1059, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/usr/lib/python2.6/imaplib.py", line 889, in _command_complete typ, data = self._get_tagged_response(tag) File "/usr/lib/python2.6/imaplib.py", line 990, in _get_tagged_response self._get_response() File "/usr/lib/python2.6/imaplib.py", line 907, in _get_response resp = self._get_line() File "/usr/lib/python2.6/imaplib.py", line 1000, in _get_line line = self.readline() File "/usr/lib/python2.6/imaplib.py", line 1170, in readline char = self.sslobj.read(1) File "/usr/lib/python2.6/ssl.py", line 136, in read return self._sslobj.read(len) SSLError: [Errno 1] _ssl.c:1325: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number Edit: Here is the task i'm trying to run, where imap_parser is a module that wraps imaplib and loads emails into my db. class DumpIMAPData(Task): def run(self, user, username, password, imap_address, **kwargs): logger = self.get_logger(**kwargs) celery.log.redirect_stdouts_to_logger(logger, loglevel=None) #imap_address is e.g. 'imap.gmail.com' parser = imap_parser.IMAPFetcher(imap_address, username, password, user\ ) parser.load_all_emails() return True I have noticed the task will actually run using celery UNLESS I daemonize the task using the --detach flag. I don't know why the task would fail only when run as a daemon. I have tried setting the same userid and groupid with the -u and -g flags, the same umask, and ensuring the path and working directories are the same for both the daemon and the non-daemonized version, but the task still will not run in celery when celery is running as a daemon. I"m using the latest version of celery (0.9.4). A: If it only breaks when run inside the celery worker, there might be something with amqplib (which uses the ssl module) or it could be something with multiprocessing and forking (a global variable that was initialized before the fork that is no longer alive) Could you please include the task you're trying to run? Do you connect to the server inside the task itself, or is it some kind of shared object? A: According to the creator of celeryd: Celery no longer does its own detaching as of 01a8a0e. There has been far too many problems with it, and since it works when detaching using start-stop-daemon, supervisord, launchd and so on, you are encouraged to use those tools instead. A: You're connecting to a port that is not speaking TLS. Are you trying to talk to a TLS/SSL enabled mail server, or is celery trying to use TLS for its AMQP connection?
python imaplib ssl error using celeryd queue
I'm having a problem using imaplib on python 2.6 with the latest django svn. I want to download imap emails in a queue (using celeryd). I'm able to connect/download emails from the command line, but when i offload the task through django to celeryd i get this error: "SSLError: [Errno 1] _ssl.c:1325: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number". Imaplib docs don't mention how to specify a version of SSL. I'm trying to pull emails from gmail. I don't understand why offloading the task to a queue using celeryd would cause the task to fail. Any help would be much appreciated. Edit: here is a stack trace: File "/usr/lib/python2.6/imaplib.py", line 643, in select typ, dat = self._simple_command(name, mailbox) File "/usr/lib/python2.6/imaplib.py", line 1059, in _simple_command return self._command_complete(name, self._command(name, *args)) File "/usr/lib/python2.6/imaplib.py", line 889, in _command_complete typ, data = self._get_tagged_response(tag) File "/usr/lib/python2.6/imaplib.py", line 990, in _get_tagged_response self._get_response() File "/usr/lib/python2.6/imaplib.py", line 907, in _get_response resp = self._get_line() File "/usr/lib/python2.6/imaplib.py", line 1000, in _get_line line = self.readline() File "/usr/lib/python2.6/imaplib.py", line 1170, in readline char = self.sslobj.read(1) File "/usr/lib/python2.6/ssl.py", line 136, in read return self._sslobj.read(len) SSLError: [Errno 1] _ssl.c:1325: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number Edit: Here is the task i'm trying to run, where imap_parser is a module that wraps imaplib and loads emails into my db. class DumpIMAPData(Task): def run(self, user, username, password, imap_address, **kwargs): logger = self.get_logger(**kwargs) celery.log.redirect_stdouts_to_logger(logger, loglevel=None) #imap_address is e.g. 'imap.gmail.com' parser = imap_parser.IMAPFetcher(imap_address, username, password, user\ ) parser.load_all_emails() return True I have noticed the task will actually run using celery UNLESS I daemonize the task using the --detach flag. I don't know why the task would fail only when run as a daemon. I have tried setting the same userid and groupid with the -u and -g flags, the same umask, and ensuring the path and working directories are the same for both the daemon and the non-daemonized version, but the task still will not run in celery when celery is running as a daemon. I"m using the latest version of celery (0.9.4).
[ "If it only breaks when run inside the celery worker, there might be something with amqplib (which uses the ssl module) or it could be something with multiprocessing and forking (a global variable that was initialized before the fork that is no longer alive)\nCould you please include the task you're trying to run?\nDo you connect to the server inside the task itself, or is it some kind of shared object?\n", "According to the creator of celeryd:\nCelery no longer does its own detaching as of 01a8a0e. There has been far too many problems with it, and since it works when detaching using start-stop-daemon, supervisord, launchd and so on, you are encouraged to use those tools instead.\n", "You're connecting to a port that is not speaking TLS. Are you trying to talk to a TLS/SSL enabled mail server, or is celery trying to use TLS for its AMQP connection?\n" ]
[ 1, 1, 0 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0002016516_celery_django_python.txt
Q: (Py)GTK StatusIcon notifications on Windows I'm currently writing a screen capture app for Windows and Linux using PyGTK, and I've hit a slight problem with displaying notifications. On Linux, I've been using the libnotify bindings to provide notifications, which has been working very well; however, this has no equivalent on Windows. I'd use the Win32 APIs directly to display the notification if I could, but I can't seem to find any way to get the tray icon ID from either GTK or PyGTK. So should I bite the bullet and write a new Windows-specific staus icon class using the Win32 APIs? Or is there a way to initiate a Win32 notification from (Py)GTK that I've missed? If anyone has any other ideas for displaying simple notifications on Windows, I'd love to hear those too. A: Looking at the GtkStatusIcon source code I don't see the NOTIFYICONDATA exposed anywhere. For X11 there is get_x11_window_id, which has no equivalent and just returns 0 in Windows. Perhaps you could file a bug to request similar functionality. For now, you'll have to create your own tray icon. A quick search at comp.lang.python gives useful result.
(Py)GTK StatusIcon notifications on Windows
I'm currently writing a screen capture app for Windows and Linux using PyGTK, and I've hit a slight problem with displaying notifications. On Linux, I've been using the libnotify bindings to provide notifications, which has been working very well; however, this has no equivalent on Windows. I'd use the Win32 APIs directly to display the notification if I could, but I can't seem to find any way to get the tray icon ID from either GTK or PyGTK. So should I bite the bullet and write a new Windows-specific staus icon class using the Win32 APIs? Or is there a way to initiate a Win32 notification from (Py)GTK that I've missed? If anyone has any other ideas for displaying simple notifications on Windows, I'd love to hear those too.
[ "Looking at the GtkStatusIcon source code I don't see the NOTIFYICONDATA exposed anywhere. For X11 there is get_x11_window_id, which has no equivalent and just returns 0 in Windows. Perhaps you could file a bug to request similar functionality.\nFor now, you'll have to create your own tray icon. A quick search at comp.lang.python gives useful result.\n" ]
[ 2 ]
[]
[]
[ "gtk", "notifications", "pygtk", "python", "winapi" ]
stackoverflow_0002124683_gtk_notifications_pygtk_python_winapi.txt
Q: Network IPC With Authentication (in Python) I am looking for a way to connect a frontend server (running Django) with a backend server. I want to avoid inventing my own protocol on top of a socket, so my plan was to use SimpleHTTPServer + JSON or XML. However, we also require some security (authentication + encryption) for the connection, which isn't quite as simple to implement. Any ideas for alternatives? What mechanisms would you use? I definitely want to avoid CORBA (we have used it before, and it's way too complex for what we need). A: Use a client side certificate for the connection. This is a good monetization technique to get more income for your client side app.
Network IPC With Authentication (in Python)
I am looking for a way to connect a frontend server (running Django) with a backend server. I want to avoid inventing my own protocol on top of a socket, so my plan was to use SimpleHTTPServer + JSON or XML. However, we also require some security (authentication + encryption) for the connection, which isn't quite as simple to implement. Any ideas for alternatives? What mechanisms would you use? I definitely want to avoid CORBA (we have used it before, and it's way too complex for what we need).
[ "Use a client side certificate for the connection. This is a good monetization technique to get more income for your client side app.\n" ]
[ 1 ]
[]
[]
[ "ipc", "json", "networking", "python" ]
stackoverflow_0002125149_ipc_json_networking_python.txt
Q: Python: how so fast? The period of the Mersenne Twister used in the module random is (I am told) 2**19937 - 1. As a binary number, that is 19937 '1's in a row (if I'm not mistaken). Python converts it to decimal pretty darned fast: $ python -m timeit '2**19937' 10000000 loops, best of 3: 0.0271 usec per loop $ python -m timeit -s 'result = 0' 'result += 2**19937' 100000 loops, best of 3: 2.09 usec per loop I guess the second version is the one that requires conversion? And it's not just binary. This is also fast. (Rather than show the numbers, I show the length of the decimal converted to a string): >>> import math >>> N = 1000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 10787 >>> N = 5000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 64921 Timing: python -m timeit -s 'import math' -s 'N=1000' 's = str((int(N*math.e))**(int(N*math.pi)))' 10 loops, best of 3: 51.2 msec per loop The question is: how is this actually done? Am I just naive to be impressed? I find the sight of the Python shell generating a number of 5000 or so places in an instant truly spectacular. Edit: Additional timings suggested by @dalke and @truppo $ python -m timeit 'x=2' 'x**19937' 1000 loops, best of 3: 230 usec per loop $ python -m timeit 'x=2' 'int(x**19937)' 1000 loops, best of 3: 232 usec per loop $ python -m timeit 'x=2' 'str(x**19937)' 100 loops, best of 3: 16.6 msec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 1000 loops, best of 3: 237 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'int(result)' 1000 loops, best of 3: 238 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'str(result)' 100 loops, best of 3: 16.6 msec per loop So it looks to me like result = 0; result += 2**19937 probably does force the conversion. A: Hate to rain on your parade, but the reason it's so fast is because the math module is actually not implemented in Python. Python supports loading shared libraries that export Python APIs, but are implemented in other languages. math.so, which provides the module you get from import math, happens to be one of those (and so is _random.so). A: When compiling to byte code, constant expressions such as 2**19937 will optimized down to a single constant: >>> def foo(): return 2**10 ... >>> import dis >>> dis.dis(foo) 1 0 LOAD_CONST 3 (1024) 3 RETURN_VALUE >>> Consider instead: [~] python -m timeit 'x=2' 'x**19937' 1000 loops, best of 3: 210 usec per loop A: Python converts it to decimal pretty darned fast. I don't know Python, but no, it needn't to do that. 2^19937 don't need computations, it is simply a binary shift ("<<") with 19937, so it is very fast. Only if you print that in decimal the actual conversion is necessary and that is much slower. EDIT: Exponentiation can be the same as shifting (=moving the point) if the number base is identical to the exponent base. 10^-1 = 0.1 10^0 = 1 10^1 = 10 10^2 = 100 10^3 = 1000 10^n = 1 (n zeroes) You see that exponentiation of 10 with the exponent n simply shifts the number. Now computers mostly use the internal base 2 (bits) , so calculating 2^19937 is setting a bit in position 19937 (counting bit positions from zero). As additional information: The conversion to decimal is normally implemented by a conquer-and-divide algorithm which successively divides the number by powers of ten. As you see, the actual conversion is slower by a factor of half a million. The second example is more interesting: As you are computing m^n with large integers m,n the fastest way is multiplying it in succession and store the temporary results. Example: 10^345 a = 10^2 b = aa = 10^4 c = bb = 10^16 d = c*c = 10^256 result = dccccccccbb*10 (Can be further optimized: see Knuth, Seminumerical Algorithms) So you only need long multiplications and they can be computed pretty effectively. EDIT: The exact implementation of multiplication depends: Besides the normal school multiplication Karatsuba, Tom-Cooke and Schoenhagen-Strasse (FFT) multiplication is used. A: I know little to nothing about how this is actually implemented in Python, but given that this is basically primitive multiplication and logarithms, I'm not terribly surprised that it's reasonably fast even on quite large numbers. There are arbitrary precision math libraries such as GMP that implement a wide variety of operations in a very effective manner, optimized in assembly, for just this purpose.
Python: how so fast?
The period of the Mersenne Twister used in the module random is (I am told) 2**19937 - 1. As a binary number, that is 19937 '1's in a row (if I'm not mistaken). Python converts it to decimal pretty darned fast: $ python -m timeit '2**19937' 10000000 loops, best of 3: 0.0271 usec per loop $ python -m timeit -s 'result = 0' 'result += 2**19937' 100000 loops, best of 3: 2.09 usec per loop I guess the second version is the one that requires conversion? And it's not just binary. This is also fast. (Rather than show the numbers, I show the length of the decimal converted to a string): >>> import math >>> N = 1000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 10787 >>> N = 5000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 64921 Timing: python -m timeit -s 'import math' -s 'N=1000' 's = str((int(N*math.e))**(int(N*math.pi)))' 10 loops, best of 3: 51.2 msec per loop The question is: how is this actually done? Am I just naive to be impressed? I find the sight of the Python shell generating a number of 5000 or so places in an instant truly spectacular. Edit: Additional timings suggested by @dalke and @truppo $ python -m timeit 'x=2' 'x**19937' 1000 loops, best of 3: 230 usec per loop $ python -m timeit 'x=2' 'int(x**19937)' 1000 loops, best of 3: 232 usec per loop $ python -m timeit 'x=2' 'str(x**19937)' 100 loops, best of 3: 16.6 msec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 1000 loops, best of 3: 237 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'int(result)' 1000 loops, best of 3: 238 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'str(result)' 100 loops, best of 3: 16.6 msec per loop So it looks to me like result = 0; result += 2**19937 probably does force the conversion.
[ "Hate to rain on your parade, but the reason it's so fast is because the math module is actually not implemented in Python.\nPython supports loading shared libraries that export Python APIs, but are implemented in other languages. math.so, which provides the module you get from import math, happens to be one of those (and so is _random.so).\n", "When compiling to byte code, constant expressions such as 2**19937 will optimized down to a single constant:\n>>> def foo(): return 2**10\n... \n>>> import dis\n>>> dis.dis(foo)\n 1 0 LOAD_CONST 3 (1024)\n 3 RETURN_VALUE \n>>> \n\nConsider instead:\n[~] python -m timeit 'x=2' 'x**19937'\n1000 loops, best of 3: 210 usec per loop\n\n", "\nPython converts it to decimal pretty darned fast.\n\nI don't know Python, but no, it needn't to do that. 2^19937 don't need computations, it is simply a binary shift (\"<<\") with 19937, so it is very fast. Only if you print that in decimal the actual conversion is necessary and that is much slower.\nEDIT: \nExponentiation can be the same as shifting (=moving the point) if the number base is identical to the exponent base. \n10^-1 = 0.1\n10^0 = 1\n10^1 = 10\n10^2 = 100\n10^3 = 1000\n10^n = 1 (n zeroes)\nYou see that exponentiation of 10 with the exponent n simply shifts the number. Now computers mostly use the internal base 2 (bits) , so calculating 2^19937 is setting a bit in position 19937 (counting bit positions from zero).\nAs additional information: The conversion to decimal is normally implemented by a conquer-and-divide algorithm which successively divides the number by powers of ten. As you see,\nthe actual conversion is slower by a factor of half a million.\nThe second example is more interesting: As you are computing m^n with large integers m,n the fastest way is multiplying it in succession and store the temporary results.\nExample: 10^345\na = 10^2\nb = aa = 10^4\nc = bb = 10^16\nd = c*c = 10^256 \nresult = dccccccccbb*10\n(Can be further optimized: see Knuth, Seminumerical Algorithms)\nSo you only need long multiplications and they can be computed pretty\neffectively.\nEDIT: The exact implementation of multiplication depends: Besides the normal school multiplication Karatsuba, Tom-Cooke and Schoenhagen-Strasse (FFT) multiplication is \nused.\n", "I know little to nothing about how this is actually implemented in Python, but given that this is basically primitive multiplication and logarithms, I'm not terribly surprised that it's reasonably fast even on quite large numbers.\nThere are arbitrary precision math libraries such as GMP that implement a wide variety of operations in a very effective manner, optimized in assembly, for just this purpose.\n" ]
[ 6, 5, 4, 0 ]
[]
[]
[ "computation", "largenumber", "python" ]
stackoverflow_0002125159_computation_largenumber_python.txt
Q: iPhone app with Google App Engine I've prototyped an iPhone app that uses (internally) SQLite as its data base. The intent was to ultimately have it communicate with a server via PHP, which would use MySQL as the back-end database. I just discovered Google App Engine, however, but know very little about it. I think it'd be nice to use the Python interface to write to the data store - but I know very little about GQL's capability. I've basically written all the working database code using MySQL, testing internally on the iPhone with SQLite. Will GQL offer the same functionality that SQL can? I read on the site that it doesn't support join queries. Also is it truly relational? Basically I guess my question is can an app that typically uses SQL backend work just as well with Google's App Engine, with GQL? I hope that's clear... any guidance is great. A: True, Google App Engine is a very cool product, but the datastore is a different beast than a regular mySQL database. That's not to say that what you need can't be done with the GAE datastore; however it may take some reworking on your end. The most prominent different that you notice right off the start is that GAE uses an object-relational mapping for its data storage scheme. Essentially object graphs are persisted in the database, maintaining there attributes and relationships to other objects. In many cases ORM (object relational mappings) map fairly well on top of a relational database (this is how Hibernate works). The mapping is not perfect though and you will find that you need to make alterations to persist your data. Also, GAE has some unique contraints that complicate things a bit. One contraint that bothers me a lot is not being able to query for attribute paths: e.g. "select ... where dog.owner.name = 'bob' ". It is these rules that force you to read and understand how GAE data store works before you jump in. I think GAE could work well in your situation. It just may take some time to understand ORM persistence in general, and GAE datastore in specifics. A: GQL offers almost no functionality at all; it's only used for SELECT queries, and it only exists to make writing SELECT queries easier for SQL programmers. Behind the scenes, it converts your queries to db.Query objects. The App Engine datastore isn't a relational database at all. You can do some stuff that looks relational, but my advice for anyone coming from an SQL background is to avoid GQL at all costs to avoid the trap of thinking the datastore is anything at all like an RDBMS, and to forget everything you know about database design. Specifically, if you're normalizing anything, you'll soon wish you hadn't. A: I think this article should help you. Summary: Cloud computing and software development for handheld devices are two very hot technologies that are increasingly being combined to create hybrid solutions. With this article, learn how to connect Google App Engine, Google's cloud computing offering, with the iPhone, Apple's mobile platform. You'll also see how to use the open source library, TouchEngine, to dynamically control application data on the iPhone by connecting to the App Engine cloud and caching that data for offline use. A: That's a pretty generic question :) Short answer: yes. It's going to involve some rethinking of your data model, but yes, changes are you can support it with the GAE Datastore API. When you create your Python models (think of these as tables), you can certainly define references to other models (so now we have a foreign key). When you select this model, you'll get back the referencing models (pretty much like a join). It'll most likely work, but it's not a drop in replacement for a mySQL server.
iPhone app with Google App Engine
I've prototyped an iPhone app that uses (internally) SQLite as its data base. The intent was to ultimately have it communicate with a server via PHP, which would use MySQL as the back-end database. I just discovered Google App Engine, however, but know very little about it. I think it'd be nice to use the Python interface to write to the data store - but I know very little about GQL's capability. I've basically written all the working database code using MySQL, testing internally on the iPhone with SQLite. Will GQL offer the same functionality that SQL can? I read on the site that it doesn't support join queries. Also is it truly relational? Basically I guess my question is can an app that typically uses SQL backend work just as well with Google's App Engine, with GQL? I hope that's clear... any guidance is great.
[ "True, Google App Engine is a very cool product, but the datastore is a different beast than a regular mySQL database. That's not to say that what you need can't be done with the GAE datastore; however it may take some reworking on your end. \nThe most prominent different that you notice right off the start is that GAE uses an object-relational mapping for its data storage scheme. Essentially object graphs are persisted in the database, maintaining there attributes and relationships to other objects. In many cases ORM (object relational mappings) map fairly well on top of a relational database (this is how Hibernate works). The mapping is not perfect though and you will find that you need to make alterations to persist your data. Also, GAE has some unique contraints that complicate things a bit. One contraint that bothers me a lot is not being able to query for attribute paths: e.g. \"select ... where dog.owner.name = 'bob' \". It is these rules that force you to read and understand how GAE data store works before you jump in. \nI think GAE could work well in your situation. It just may take some time to understand ORM persistence in general, and GAE datastore in specifics. \n", "GQL offers almost no functionality at all; it's only used for SELECT queries, and it only exists to make writing SELECT queries easier for SQL programmers. Behind the scenes, it converts your queries to db.Query objects.\nThe App Engine datastore isn't a relational database at all. You can do some stuff that looks relational, but my advice for anyone coming from an SQL background is to avoid GQL at all costs to avoid the trap of thinking the datastore is anything at all like an RDBMS, and to forget everything you know about database design. Specifically, if you're normalizing anything, you'll soon wish you hadn't.\n", "I think this article should help you.\n\nSummary: Cloud computing and software development for handheld devices are two very hot technologies that are increasingly being combined to create hybrid solutions. With this article, learn how to connect Google App Engine, Google's cloud computing offering, with the iPhone, Apple's mobile platform. You'll also see how to use the open source library, TouchEngine, to dynamically control application data on the iPhone by connecting to the App Engine cloud and caching that data for offline use.\n\n", "That's a pretty generic question :)\nShort answer: yes. It's going to involve some rethinking of your data model, but yes, changes are you can support it with the GAE Datastore API.\nWhen you create your Python models (think of these as tables), you can certainly define references to other models (so now we have a foreign key). When you select this model, you'll get back the referencing models (pretty much like a join).\nIt'll most likely work, but it's not a drop in replacement for a mySQL server.\n" ]
[ 2, 2, 1, 1 ]
[]
[]
[ "google_app_engine", "gql", "iphone", "python" ]
stackoverflow_0002124688_google_app_engine_gql_iphone_python.txt
Q: Python, Source-Code Encoding Problem I'm using Notepad++ editor on windows with format set to ASCII, I've read "PEP 263: Source Code Encodings" and amended my code accordingly (I think), but there are characters still printing in hex... #!/usr/bin/python # -*- coding: UTF-8 -*- import os, sys a_munge = [ "A", "4", "/\\", "\@", "/-\\", "^", "aye", "?" ] b_munge = [ "B", "8", "13", "I3", "|3" , "P>", "|:", "!3", "(3", "/3", "3","]3" ] c_munge = [ "C", "<", "(", "{", "(c)" ] d_munge = [ "D", "|)", "|o", "?", "])", "[)", "I>", "|>", " ?", "T)", "0", "cl" ] e_munge = [ "E", "3", "&", "€", "£", "[-", "|=-", "?" ] . . . A: Perhaps you should be using unicode literals (e.g. u'€') instead. A: The line: # -*- coding: UTF-8 -*- declares that the source file is saved in UTF-8. Anything else is an error. When you declare byte strings in your source code: e_munge = [ "E", "3", "&", "€", "£", "[-", "|=-", "?" ] then byte strings like "€" will actually contain the encoded bytes used to save the source file. When you use Unicode strings instead: e_munge = [ u"E", u"3", u"&", u"€", u"£", u"[-", u"|=-", u"?" ] then when u followed by the byte-string "€" is read by Python from a source file, it uses the declared encoding to decode that character into Unicode. An illustration: # coding: utf-8 bs = '€' us = u'€' print repr(bs) print repr(us) OUTPUT: '\xe2\x82\xac' u'\u20ac' A: print some_list is in effect print repr(some_list) -- that's why you see \u20ac instead of a Euro character. For debugging purposes, the "unicode hex" is exactly what you need for unambiguous display of your data. You appear to have perfectly OK unicode objects in your list; I suggest that you don't "print" the list to Tkinter.
Python, Source-Code Encoding Problem
I'm using Notepad++ editor on windows with format set to ASCII, I've read "PEP 263: Source Code Encodings" and amended my code accordingly (I think), but there are characters still printing in hex... #!/usr/bin/python # -*- coding: UTF-8 -*- import os, sys a_munge = [ "A", "4", "/\\", "\@", "/-\\", "^", "aye", "?" ] b_munge = [ "B", "8", "13", "I3", "|3" , "P>", "|:", "!3", "(3", "/3", "3","]3" ] c_munge = [ "C", "<", "(", "{", "(c)" ] d_munge = [ "D", "|)", "|o", "?", "])", "[)", "I>", "|>", " ?", "T)", "0", "cl" ] e_munge = [ "E", "3", "&", "€", "£", "[-", "|=-", "?" ] . . .
[ "Perhaps you should be using unicode literals (e.g. u'€') instead.\n", "The line:\n# -*- coding: UTF-8 -*-\n\ndeclares that the source file is saved in UTF-8. Anything else is an error.\nWhen you declare byte strings in your source code:\ne_munge = [ \"E\", \"3\", \"&\", \"€\", \"£\", \"[-\", \"|=-\", \"?\" ]\n\nthen byte strings like \"€\" will actually contain the encoded bytes used to save the source file.\nWhen you use Unicode strings instead:\n e_munge = [ u\"E\", u\"3\", u\"&\", u\"€\", u\"£\", u\"[-\", u\"|=-\", u\"?\" ]\n\nthen when u followed by the byte-string \"€\" is read by Python from a source file, it uses the declared encoding to decode that character into Unicode.\nAn illustration:\n# coding: utf-8\nbs = '€'\nus = u'€'\nprint repr(bs)\nprint repr(us)\n\nOUTPUT:\n'\\xe2\\x82\\xac'\nu'\\u20ac'\n\n", "print some_list is in effect print repr(some_list) -- that's why you see \\u20ac instead of a Euro character. For debugging purposes, the \"unicode hex\" is exactly what you need for unambiguous display of your data.\nYou appear to have perfectly OK unicode objects in your list; I suggest that you don't \"print\" the list to Tkinter.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0002123283_character_encoding_python.txt
Q: Reassembling Python bytecode to the original code? This might be a silly question, but, given the output of, say.. >>> from dis import dis >>> def myfunc(x): ... print x ** 2 ... >>> dis(myfunc) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (2) 6 BINARY_POWER 7 PRINT_ITEM 8 PRINT_NEWLINE 9 LOAD_CONST 0 (None) 12 RETURN_VALUE ..or a .pyc file - is it possible to reassembling this into a valid piece of Python source code? I.e where reassemble(dis(myfunc)) == "def reassembled_function(x):\n print x ** 2" Not for any particular practical reason, I'm just curious if this is possible, or has been attempted.. Related Free Python decompiler that is not an online service? A: http://sourceforge.net/projects/decompyle/
Reassembling Python bytecode to the original code?
This might be a silly question, but, given the output of, say.. >>> from dis import dis >>> def myfunc(x): ... print x ** 2 ... >>> dis(myfunc) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (2) 6 BINARY_POWER 7 PRINT_ITEM 8 PRINT_NEWLINE 9 LOAD_CONST 0 (None) 12 RETURN_VALUE ..or a .pyc file - is it possible to reassembling this into a valid piece of Python source code? I.e where reassemble(dis(myfunc)) == "def reassembled_function(x):\n print x ** 2" Not for any particular practical reason, I'm just curious if this is possible, or has been attempted.. Related Free Python decompiler that is not an online service?
[ "http://sourceforge.net/projects/decompyle/\n" ]
[ 5 ]
[]
[]
[ "bytecode", "bytecode_manipulation", "python" ]
stackoverflow_0002124202_bytecode_bytecode_manipulation_python.txt
Q: How can I see error logs of Django views I'm coding a small application with Django. But I can't see any error logs in the console when an error (e.g. Python syntax error, etc.) occurs in one of my views -no action at all. How can I see the error logs of my views? Debugging like a blind is really annoying. A: Django does not print any errors to the console by default. Instead it provides very helpful error pages that are displayed for any errors that occur in your views. Please check what your DEBUG setting is set to. In development this should be True which will give you the nice error pages for 404 and 500 errors. The pretty error page will look like this: (source: linkaider.com) I can also recommend the talk What the Heck Went Wrong? from DjangoCon2009 for some more information on basic debugging technics with django.
How can I see error logs of Django views
I'm coding a small application with Django. But I can't see any error logs in the console when an error (e.g. Python syntax error, etc.) occurs in one of my views -no action at all. How can I see the error logs of my views? Debugging like a blind is really annoying.
[ "Django does not print any errors to the console by default. Instead it provides very helpful error pages that are displayed for any errors that occur in your views. Please check what your DEBUG setting is set to. In development this should be True which will give you the nice error pages for 404 and 500 errors.\nThe pretty error page will look like this:\n\n(source: linkaider.com) \nI can also recommend the talk What the Heck Went Wrong? from DjangoCon2009 for some more information on basic debugging technics with django.\n" ]
[ 5 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002125080_django_logging_python.txt
Q: Compress data before storage on Google App Engine I im trying to store 30 second user mp3 recordings as Blobs in my app engine data store. However, in order to enable this feature (App Engine has a 1MB limit per upload) and to keep the costs down I would like to compress the file before upload and decompress the file every time it is requested. How would you suggest I accomplish this (It can happen in the background by the way via a task queue but an efficient solution is always good) Based on my own tests and research - I see two possible approaches to accomplish this Zlib For this I need to compress a certain number of blocks at a time using a While loop. However, App Engine doesnt allow you to write to the file system. I thought about using a Temporary File to accomplish this but I havent had luck with this approach when trying to decompress the content from a Temporary File Gzip From reading around the web, it appears that the app engine url fetch function requests content gzipped already and then decompresses it. Is there a way to stop the function from decompressing the content so that I can just put it in the datastore in gzipped format and then decompress it when I need to play it back to a user on demand? Let me know how you would suggest using zlib or gzip or some other solution to accmoplish this. Thanks A: "Compressing before upload" implies doing it in the user's browser -- but no text in your question addresses that! It seems to be about compression in your GAE app, where of course the data will only be after the upload. You could do it with a Firefox extension (or other browsers' equivalents), if you can develop those and convince your users to install them, but that has nothing much to do with GAE!-) Not to mention that, as @RageZ's comment mentions, MP3 is, essentially, already compressed, so there's little or nothing to gain (though maybe you could, again with a browser extension for the user, reduce the MP3's bit rate and thus the file's dimension, that could impact the audio quality, depending on your intended use for those audio files). So, overall, I have to second @jldupont's suggestion (also in a comment) -- use a different server for storage of large files (S3, Amazon's offering, is surely a possibility though not the only one). A: While the technical limitations (mentioned in other answers) of compressing MP3 files via standard compression or reencoding at a lower bitrate are correct, your aim is to store 30 seconds of MP3 encoded data. Assuming that you can enforce that on your users, you should be alright without applying additional compression techniques if the MP3 bitrate is 256kbit constant bitrate (CBR) or lower. At 256kbit CBR, 30 seconds of audio would require: (((256 * 1000) / 8) * 30) / 1048576 = 0.91MB The maximum standard bitrate is 320kbit which equates to 1.14MB, so you'd have to use 256 or less. The most commonly used bitrate in the wild is 128kbits. There are additional overheads that will increase the final file size such as ID3 tags and framing, but you should be OK. If not, drop down to 224kbits as your maximum (30 secs = 0.80MB). There are other complexities such as variable bit rate encoding for which the file size is not so predictable and I am ignoring these. So your problem is no longer how to compress MP3 files, but how to ensure that your users are aware that they can not upload more than 30 seconds encoded at 256kbits CBR, and how to enforce that policy. A: You could try the new Blobstore API allowing the storage and serving of files up to 50MB http://www.cloudave.com/link/the-new-google-app-engine-blobstore-api-first-thoughts http://code.google.com/appengine/docs/python/blobstore/ http://code.google.com/appengine/docs/java/blobstore/ A: As Aneto mentions in a comment, you will not be able to compress MP3 data with a standard compression library like gzip or zlib. However, you could reencode the MP3 at a MUCH lower bitrate, possible with LAME. A: You can store up to 10Mb with a list of Blobs. Search for google file service. It's much more versatile than BlobStore in my opinion, since I just started using BlobStore Api yesterday and I'm still figuring out if it is possible to access the data bytewise.. as in changing doc to pdf, jpeg to gif.. You can storage Blobs of 1Mb * 10 = 10 Mb (max entity size I think), or you can use BlobStore API and get the same 10Mb or get 50Mb if you enable billing (you can enable it but if you don't pass the free quota you don't pay).
Compress data before storage on Google App Engine
I im trying to store 30 second user mp3 recordings as Blobs in my app engine data store. However, in order to enable this feature (App Engine has a 1MB limit per upload) and to keep the costs down I would like to compress the file before upload and decompress the file every time it is requested. How would you suggest I accomplish this (It can happen in the background by the way via a task queue but an efficient solution is always good) Based on my own tests and research - I see two possible approaches to accomplish this Zlib For this I need to compress a certain number of blocks at a time using a While loop. However, App Engine doesnt allow you to write to the file system. I thought about using a Temporary File to accomplish this but I havent had luck with this approach when trying to decompress the content from a Temporary File Gzip From reading around the web, it appears that the app engine url fetch function requests content gzipped already and then decompresses it. Is there a way to stop the function from decompressing the content so that I can just put it in the datastore in gzipped format and then decompress it when I need to play it back to a user on demand? Let me know how you would suggest using zlib or gzip or some other solution to accmoplish this. Thanks
[ "\"Compressing before upload\" implies doing it in the user's browser -- but no text in your question addresses that! It seems to be about compression in your GAE app, where of course the data will only be after the upload. You could do it with a Firefox extension (or other browsers' equivalents), if you can develop those and convince your users to install them, but that has nothing much to do with GAE!-) Not to mention that, as @RageZ's comment mentions, MP3 is, essentially, already compressed, so there's little or nothing to gain (though maybe you could, again with a browser extension for the user, reduce the MP3's bit rate and thus the file's dimension, that could impact the audio quality, depending on your intended use for those audio files).\nSo, overall, I have to second @jldupont's suggestion (also in a comment) -- use a different server for storage of large files (S3, Amazon's offering, is surely a possibility though not the only one).\n", "While the technical limitations (mentioned in other answers) of compressing MP3 files via standard compression or reencoding at a lower bitrate are correct, your aim is to store 30 seconds of MP3 encoded data. Assuming that you can enforce that on your users, you should be alright without applying additional compression techniques if the MP3 bitrate is 256kbit constant bitrate (CBR) or lower. At 256kbit CBR, 30 seconds of audio would require:\n(((256 * 1000) / 8) * 30) / 1048576 = 0.91MB\n\nThe maximum standard bitrate is 320kbit which equates to 1.14MB, so you'd have to use 256 or less. The most commonly used bitrate in the wild is 128kbits.\nThere are additional overheads that will increase the final file size such as ID3 tags and framing, but you should be OK. If not, drop down to 224kbits as your maximum (30 secs = 0.80MB). There are other complexities such as variable bit rate encoding for which the file size is not so predictable and I am ignoring these.\nSo your problem is no longer how to compress MP3 files, but how to ensure that your users are aware that they can not upload more than 30 seconds encoded at 256kbits CBR, and how to enforce that policy.\n", "You could try the new Blobstore API allowing the storage and serving of files up to 50MB\nhttp://www.cloudave.com/link/the-new-google-app-engine-blobstore-api-first-thoughts\nhttp://code.google.com/appengine/docs/python/blobstore/\nhttp://code.google.com/appengine/docs/java/blobstore/\n", "As Aneto mentions in a comment, you will not be able to compress MP3 data with a standard compression library like gzip or zlib. However, you could reencode the MP3 at a MUCH lower bitrate, possible with LAME.\n", "You can store up to 10Mb with a list of Blobs. Search for google file service.\nIt's much more versatile than BlobStore in my opinion, since I just started using BlobStore Api yesterday and I'm still figuring out if it is possible to access the data bytewise.. as in changing doc to pdf, jpeg to gif.. \nYou can storage Blobs of 1Mb * 10 = 10 Mb (max entity size I think), or you can use BlobStore API and get the same 10Mb or get 50Mb if you enable billing (you can enable it but if you don't pass the free quota you don't pay).\n" ]
[ 2, 2, 2, 0, 0 ]
[]
[]
[ "compression", "google_app_engine", "gzip", "python", "zlib" ]
stackoverflow_0001739543_compression_google_app_engine_gzip_python_zlib.txt
Q: Hudson build failed using Python & Coverage I completed this tutorial from Joe Heck to set up Hudson for Python. Everything worked perfectly except the Coverage section. My build failed with this output: [workspace] $ /bin/sh -xe /tmp/hudson6222564272447222496.sh + coverage run tests/run.py --with-xunit You must specify at least one of -e, -x, -c, -r, or -a. I tried to include the Execute argument, -x, but got an exception that was ultimately caused by a permissions failure: IOError: [Errno 13] Permission denied: 'nosetests.xml' Has anyone gotten Coverage working successfully with Hudson? A: You have an old version of coverage.py, it looks like 2.x of some sort. "coverage run" is new syntax with coverage.py 3.x. Download the latest coverage.py at http://pypi.python.org/pypi/coverage, and you should be good to go.
Hudson build failed using Python & Coverage
I completed this tutorial from Joe Heck to set up Hudson for Python. Everything worked perfectly except the Coverage section. My build failed with this output: [workspace] $ /bin/sh -xe /tmp/hudson6222564272447222496.sh + coverage run tests/run.py --with-xunit You must specify at least one of -e, -x, -c, -r, or -a. I tried to include the Execute argument, -x, but got an exception that was ultimately caused by a permissions failure: IOError: [Errno 13] Permission denied: 'nosetests.xml' Has anyone gotten Coverage working successfully with Hudson?
[ "You have an old version of coverage.py, it looks like 2.x of some sort. \"coverage run\" is new syntax with coverage.py 3.x. Download the latest coverage.py at http://pypi.python.org/pypi/coverage, and you should be good to go.\n" ]
[ 4 ]
[]
[]
[ "code_coverage", "continuous_integration", "hudson", "python", "python_coverage" ]
stackoverflow_0002125164_code_coverage_continuous_integration_hudson_python_python_coverage.txt
Q: Good looking Python GUI toolkit for Snow Leopard(64 bit) I'm looking for a GUI toolkit/framework to create applications that run on Mac Snow Leopard and preferably other systems(Windows, Linux). Deal breakers: X11 based Non-native widgets 32 bit/Carbon Bad Mac look and feel As far as I know Tkinter runs X11 and wxWidgets and PyQT do not run 64 bit. Is there anything usable for good looking Mac applications? [edit] http://wiki.python.org/moin/GuiProgramming Lists a lot of unusable stuff, but has a few interesting ones. Lucid... rings a bell, but the site has nothing about Python whatsoever. PyGUI, looks like a cool one-man project, just like uxpython. It seems QT, WX and TK are really the big ones... All of them might have 64 bit or Cocoa ports in a few years, but a the moment none of them seems to run out of the box. [edit] So far there is no perfect solution. Tkinter works, but is un-cool for me PyObjC works, but is not cross-platform PyQT and wxWidgets might work someday... I'm not yet sure which to use, but I accepted PyQT for now. A: Maybe PyQt works on Snow Leopard 64 bits. Look at this link and try it. A: Your list doesn't specifically rule out CocoaPython/PyObjC, which would be completely native on Mac OS X. It wouldn't run on anything else, though, A: The Apple-supplied Tk, Aqua Tk, on OS X has not been X11-based since at least OS X 10.4. Apple ships a 64-bit version of Aqua Tk in OS X 10.6 and the Tkinter in the Apple-supplied Python 2.6 is linked with it. There have been some reported problems using IDLE and other test applications with it, though. Your mileage may vary.
Good looking Python GUI toolkit for Snow Leopard(64 bit)
I'm looking for a GUI toolkit/framework to create applications that run on Mac Snow Leopard and preferably other systems(Windows, Linux). Deal breakers: X11 based Non-native widgets 32 bit/Carbon Bad Mac look and feel As far as I know Tkinter runs X11 and wxWidgets and PyQT do not run 64 bit. Is there anything usable for good looking Mac applications? [edit] http://wiki.python.org/moin/GuiProgramming Lists a lot of unusable stuff, but has a few interesting ones. Lucid... rings a bell, but the site has nothing about Python whatsoever. PyGUI, looks like a cool one-man project, just like uxpython. It seems QT, WX and TK are really the big ones... All of them might have 64 bit or Cocoa ports in a few years, but a the moment none of them seems to run out of the box. [edit] So far there is no perfect solution. Tkinter works, but is un-cool for me PyObjC works, but is not cross-platform PyQT and wxWidgets might work someday... I'm not yet sure which to use, but I accepted PyQT for now.
[ "Maybe PyQt works on Snow Leopard 64 bits. Look at this link and try it.\n", "Your list doesn't specifically rule out CocoaPython/PyObjC, which would be completely native on Mac OS X. It wouldn't run on anything else, though,\n", "The Apple-supplied Tk, Aqua Tk, on OS X has not been X11-based since at least OS X 10.4. Apple ships a 64-bit version of Aqua Tk in OS X 10.6 and the Tkinter in the Apple-supplied Python 2.6 is linked with it. There have been some reported problems using IDLE and other test applications with it, though. Your mileage may vary.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "user_interface" ]
stackoverflow_0002123335_macos_osx_snow_leopard_python_user_interface.txt
Q: how do I change 'username-password login' to 'email-password login' on django-registration how do I change 'username-password login' to 'email-password login' on django-registration A: You can't easily store emails in django.contrib.auth.model.User's username field, so you'll need a different auth backend. Put the following somewhere and add its path to AUTHENTICATION_BACKENDS. See http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend from django.contrib.auth.models import User class EmailBackend(object): """ Authenticates against the email field of django.contrib.auth.models.User """ def authenticate(self, email=None, password=None): # Try using the email if it is given if email: for user in User.objects.filter(email=email): if user.check_password(password): return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None Then, in your views, authenticate by calling django.contrib.auth.authenticate. Two things to note: You will probably want to keep the default AUTHENTICATION_BACKEND there, especially if you want to use the Django admin. If users are signing themselves up without a username, you'll need to create one for them. I use the base64 version of a uuid for that Set the username in a save method somewhere (eg in your new user form): import uuid, binascii username = binascii.b2a_base64(uuid.uuid4().bytes)
how do I change 'username-password login' to 'email-password login' on django-registration
how do I change 'username-password login' to 'email-password login' on django-registration
[ "You can't easily store emails in django.contrib.auth.model.User's username field, so you'll need a different auth backend. Put the following somewhere and add its path to AUTHENTICATION_BACKENDS. See http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend\nfrom django.contrib.auth.models import User\n\nclass EmailBackend(object):\n \"\"\" Authenticates against the email field of django.contrib.auth.models.User\n \"\"\"\n\n def authenticate(self, email=None, password=None):\n # Try using the email if it is given\n if email:\n for user in User.objects.filter(email=email):\n if user.check_password(password):\n return user\n\n def get_user(self, user_id):\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None\n\nThen, in your views, authenticate by calling django.contrib.auth.authenticate.\nTwo things to note:\n\nYou will probably want to keep the default AUTHENTICATION_BACKEND there, especially if you want to use the Django admin.\nIf users are signing themselves up without a username, you'll need to create one for them. I use the base64 version of a uuid for that\n\nSet the username in a save method somewhere (eg in your new user form):\nimport uuid, binascii\nusername = binascii.b2a_base64(uuid.uuid4().bytes)\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002125724_django_python.txt
Q: How to properly escape output (for XHTML) in mako? Despite offering a nice way to escape output using filters, none of them do the right thing. Taking the string: x=u"&\u0092" The filters do the following: x Turns the & into an entity but not the \u0092 (valid XML but not XHTML) h Exactly the same u Escapes both, but obviously uses url escaping entities Only converts named entities, so again only the & is escaped decode.latin1 The same HTML uses the standard UNICODE Consortium character repertoire, and it leaves undefined (among others) 65 character codes (0 to 31 inclusive and 127 to 159 inclusive) These seem to be the characters missed. Any ideas? EDIT It seems to validate if I use the file offline. Could this be a Content-Type problem? A: It is not necessary to convert Unicode characters to the &#xxxx; form to work in HTML unless you're deliberately using the ASCII charset. It's simpler and more efficient to escape named entities, then encode the whole string to UTF-8 and write it out like that. You should probably declare the encoding being used in the HTTP headers or in a <meta> tag. EDIT: It seems to validate if I use the file offline. Could this be a Content-Type problem? Yes. You can either use HTTP headers to enforce a UTF-8 charset or specify it in the HTML directly via a meta tag: <meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8" /> A: Validation issues aside, it's useful to be able to remove these characters (which don't display reliably anyway) without necessarily escaping anything else. To this end I added the following function to `lib/helpers.py': __sgml_invalid = re.compile(r'[\x82-\x8c\x91-\x9c\x9f]', re.UNICODE) def sgmlsafe(text): lookup = { 130:"&#8218;", #Single Low-9 Quotation Mark 131: "&#402;", #Latin Small Letter F With Hook 132:"&#8222;", #Double Low-9 Quotation Mark 133:"&#8230;", #Horizontal Ellipsis 134:"&#8224;", #Dagger 135:"&#8225;", #Double Dagger 136: "&#710;", #Modifier Letter Circumflex Accent 137:"&#8240;", #Per Mille Sign 138: "&#352;", #Latin Capital Letter S With Caron 139:"&#8249;", #Single Left-Pointing Angle Quotation Mark 140: "&#338;", #Latin Capital Ligature OE 145:"&#8216;", #Left Single Quotation Mark 146:"&#8217;", #Right Single Quotation Mark 147:"&#8220;", #Left Double Quotation Mark 148:"&#8221;", #Right Double Quotation Mark 149:"&#8226;", #Bullet 150:"&#8211;", #En Dash 151:"&#8212;", #Em Dash 152: "&#732;", #Small Tilde 153:"&#8482;", #Trade Mark Sign 154: "&#353;", #Latin Small Letter S With Caron 155:"&#8250;", #Single Right-Pointing Angle Quotation Mark 156: "&#339;", #Latin Small Ligature OE 159: "&#376;" #Latin Capital Letter Y With Diaeresis } return __sgml_invalid.sub(lambda x: lookup[ord(x.group())], text) And you can make this available as a filter by editing environment.py: config['pylons.app_globals'].mako_lookup = TemplateLookup( ... imports=[....,'from appname.lib.helpers import sgmlsafe',...] It should then be available to your templates: ${c.content|n,sgmlsafe}
How to properly escape output (for XHTML) in mako?
Despite offering a nice way to escape output using filters, none of them do the right thing. Taking the string: x=u"&\u0092" The filters do the following: x Turns the & into an entity but not the \u0092 (valid XML but not XHTML) h Exactly the same u Escapes both, but obviously uses url escaping entities Only converts named entities, so again only the & is escaped decode.latin1 The same HTML uses the standard UNICODE Consortium character repertoire, and it leaves undefined (among others) 65 character codes (0 to 31 inclusive and 127 to 159 inclusive) These seem to be the characters missed. Any ideas? EDIT It seems to validate if I use the file offline. Could this be a Content-Type problem?
[ "It is not necessary to convert Unicode characters to the &#xxxx; form to work in HTML unless you're deliberately using the ASCII charset. It's simpler and more efficient to escape named entities, then encode the whole string to UTF-8 and write it out like that. You should probably declare the encoding being used in the HTTP headers or in a <meta> tag.\nEDIT:\n\nIt seems to validate if I use the file offline. Could this be a Content-Type problem?\n\nYes. You can either use HTTP headers to enforce a UTF-8 charset or specify it in the HTML directly via a meta tag:\n<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml;charset=utf-8\" />\n\n", "Validation issues aside, it's useful to be able to remove these characters (which don't display reliably anyway) without necessarily escaping anything else. To this end I added the following function to `lib/helpers.py':\n__sgml_invalid = re.compile(r'[\\x82-\\x8c\\x91-\\x9c\\x9f]', re.UNICODE)\n\ndef sgmlsafe(text):\n lookup = {\n 130:\"&#8218;\", #Single Low-9 Quotation Mark\n 131: \"&#402;\", #Latin Small Letter F With Hook\n 132:\"&#8222;\", #Double Low-9 Quotation Mark\n 133:\"&#8230;\", #Horizontal Ellipsis\n 134:\"&#8224;\", #Dagger\n 135:\"&#8225;\", #Double Dagger\n 136: \"&#710;\", #Modifier Letter Circumflex Accent\n 137:\"&#8240;\", #Per Mille Sign\n 138: \"&#352;\", #Latin Capital Letter S With Caron\n 139:\"&#8249;\", #Single Left-Pointing Angle Quotation Mark\n 140: \"&#338;\", #Latin Capital Ligature OE\n 145:\"&#8216;\", #Left Single Quotation Mark\n 146:\"&#8217;\", #Right Single Quotation Mark\n 147:\"&#8220;\", #Left Double Quotation Mark\n 148:\"&#8221;\", #Right Double Quotation Mark\n 149:\"&#8226;\", #Bullet\n 150:\"&#8211;\", #En Dash\n 151:\"&#8212;\", #Em Dash\n 152: \"&#732;\", #Small Tilde\n 153:\"&#8482;\", #Trade Mark Sign\n 154: \"&#353;\", #Latin Small Letter S With Caron\n 155:\"&#8250;\", #Single Right-Pointing Angle Quotation Mark\n 156: \"&#339;\", #Latin Small Ligature OE\n 159: \"&#376;\" #Latin Capital Letter Y With Diaeresis\n }\n\n return __sgml_invalid.sub(lambda x: lookup[ord(x.group())], text)\n\nAnd you can make this available as a filter by editing environment.py:\nconfig['pylons.app_globals'].mako_lookup = TemplateLookup(\n ...\n imports=[....,'from appname.lib.helpers import sgmlsafe',...]\n\nIt should then be available to your templates:\n${c.content|n,sgmlsafe}\n\n" ]
[ 2, 1 ]
[]
[]
[ "escaping", "mako", "python", "unicode", "xhtml" ]
stackoverflow_0002125788_escaping_mako_python_unicode_xhtml.txt
Q: After breaking a python program into functions, how do I make one the main function? This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "main" but I have no clue. A: Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects. If you put a print statement at the top or middle of your program, it will run normally without being in any function. What this means is that you could just put all the main code at the end of the file and it will run when the script is run. However, if your script is ever imported rather than run directly, that code will also run. This is usually not what you want so you would want to avoid that. Python provides the __name__ global variable to differentiate when a script is imported and run directly - it is set to the name under which the script runs. If the script is imported, it will be the name of the script file. If it is run directly, it'll be "__main__". So, you can put an if __name__ == '__main__': at the bottom of your program, and everything inside this if block will run only if the script is run directly. Example. if __name__ == "__main__": the_function_I_think_of_as_main() A: When a python module is being imported for the first time, it's main block is run. You can distinguish between being run by itself and being imported into another program: if __name__ == "__main__": function1() function2() else: # loaded from another module A: if __name__ == '__main__': run_main() A: It's the following idiom: if __name__ == "__main__": yourfoo() Also read this. A: As I read your question, you're asking about how to define a main function. That actually would be done with something like: def main(): function1() function2() return 0 And then you would put code something like this outside all your main file's functions: if __name__ == "__main__": sys.exit(main()) (Of course you need an import sys somewhere for the above to work.) A (now kind of old, but still relevant) post from Guido tells more.
After breaking a python program into functions, how do I make one the main function?
This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "main" but I have no clue.
[ "Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects.\nIf you put a print statement at the top or middle of your program, it will run normally without being in any function. What this means is that you could just put all the main code at the end of the file and it will run when the script is run. However, if your script is ever imported rather than run directly, that code will also run. This is usually not what you want so you would want to avoid that.\nPython provides the __name__ global variable to differentiate when a script is imported and run directly - it is set to the name under which the script runs. If the script is imported, it will be the name of the script file. If it is run directly, it'll be \"__main__\". So, you can put an if __name__ == '__main__': at the bottom of your program, and everything inside this if block will run only if the script is run directly.\nExample.\nif __name__ == \"__main__\":\n the_function_I_think_of_as_main()\n\n", "When a python module is being imported for the first time, it's main block is run. You can distinguish between being run by itself and being imported into another program:\nif __name__ == \"__main__\":\n function1()\n function2()\nelse:\n # loaded from another module\n\n", "if __name__ == '__main__':\n run_main()\n\n", "It's the following idiom:\nif __name__ == \"__main__\":\n yourfoo()\n\nAlso read this.\n", "As I read your question, you're asking about how to define a main function. That actually would be done with something like:\ndef main():\n function1()\n function2()\n return 0\n\nAnd then you would put code something like this outside all your main file's functions:\nif __name__ == \"__main__\":\n sys.exit(main())\n\n(Of course you need an import sys somewhere for the above to work.)\nA (now kind of old, but still relevant) post from Guido tells more.\n" ]
[ 12, 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002125825_python.txt
Q: How to organize an app-engine application I want to create a directory structure like the following. How can I get the account.py and game.py to handle the requests that go to \account\ and \game\ respectfully. All the app-engine examples I have seen have all the logic in on main.py that handle all urls. app\account\ \account.py \game\ \ game.py \static\css \js \images \app.yaml \main.py I tried the following in app.yaml but it didn't work application: mefirst version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /account script: account.py - url: .* script: main.py A: You need the following in your app.yaml: - url: /account script: account/account.py - url: /game script: game/game.py - url: .* script: main.py BTW, I suggest you try to forget backslashes (characters like this: \ ) -- think normal slashes (characters like this: / ). Backslashes are a Windows anomaly (and mostly unneeded even there -- Python will happily accept normal slashes in lieu of backslashes in filepaths), not used as path separators in URLs nor on Unix-y operating systems (including Linux and MacOSX). I mention this because you speak of "requests that go to \account\ and \game\ respectfully" and there are no such things -- no request goes to a path with backslashes, it will always be forward slashes. A: Take a look at MVCEngine, a framework for AppEngine that provides a Ruby on Rails-like structure for building apps. It may or may not be overkill for what you are looking to do, but if you take a look in the main project file, MVCEngine.py, you should be able to see how it goes about providing for a project directory structure somewhat like you want. It's not too difficult.
How to organize an app-engine application
I want to create a directory structure like the following. How can I get the account.py and game.py to handle the requests that go to \account\ and \game\ respectfully. All the app-engine examples I have seen have all the logic in on main.py that handle all urls. app\account\ \account.py \game\ \ game.py \static\css \js \images \app.yaml \main.py I tried the following in app.yaml but it didn't work application: mefirst version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /account script: account.py - url: .* script: main.py
[ "You need the following in your app.yaml:\n- url: /account\n script: account/account.py\n\n- url: /game\n script: game/game.py\n\n- url: .*\n script: main.py\n\nBTW, I suggest you try to forget backslashes (characters like this: \\ ) -- think normal slashes (characters like this: / ). Backslashes are a Windows anomaly (and mostly unneeded even there -- Python will happily accept normal slashes in lieu of backslashes in filepaths), not used as path separators in URLs nor on Unix-y operating systems (including Linux and MacOSX). I mention this because you speak of \"requests that go to \\account\\ and \\game\\ respectfully\" and there are no such things -- no request goes to a path with backslashes, it will always be forward slashes.\n", "Take a look at MVCEngine, a framework for AppEngine that provides a Ruby on Rails-like structure for building apps. It may or may not be overkill for what you are looking to do, but if you take a look in the main project file, MVCEngine.py, you should be able to see how it goes about providing for a project directory structure somewhat like you want. It's not too difficult.\n" ]
[ 11, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002125951_google_app_engine_python.txt
Q: Python property The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing? class Base: def __init__(self): self.s = "BaseStr" def getstr(self): print "get in Base" return self.s def setstr(self, s): print "set in Base" self.s = s str = property(getstr, setstr) b = Base() print b.str b.str = "Foo" print b.str Output: get in Base BaseStr Foo A: You need to use new-style classes for properties to work correctly. To do so derive your class from object: class Base(object): ... A: Whenever creating a new class, derive it from the object type.
Python property
The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing? class Base: def __init__(self): self.s = "BaseStr" def getstr(self): print "get in Base" return self.s def setstr(self, s): print "set in Base" self.s = s str = property(getstr, setstr) b = Base() print b.str b.str = "Foo" print b.str Output: get in Base BaseStr Foo
[ "You need to use new-style classes for properties to work correctly. To do so derive your class from object:\nclass Base(object):\n ...\n\n", "Whenever creating a new class, derive it from the object type.\n" ]
[ 18, 0 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0002125166_properties_python.txt
Q: Python os.path is ntpath, how? Can someone tell me how Python "aliases" os.path to ntpath? >>> import os.path >>> os.path <module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'> >>> A: Look at os.py, lines 55-67: elif 'nt' in _names: name = 'nt' linesep = '\r\n' from nt import * try: from nt import _exit except ImportError: pass import ntpath as path import nt __all__.extend(_get_exports_list(nt)) del nt The import ntpath as path is the specific statement that causes os.path to be ntpath on your platforms (doubtlessly Windows). A: >>> import os as my_aliased_module >>> my_aliased_module <module 'os' from 'C:\Program Files\Python 2.6\lib\os.pyc'> EDIT: And since import is a simple statement in Python, you can do neat stuff like: import sys if sys.platform == 'win32': import windows_module as my_module else: import unix_module as my_module
Python os.path is ntpath, how?
Can someone tell me how Python "aliases" os.path to ntpath? >>> import os.path >>> os.path <module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'> >>>
[ "Look at os.py, lines 55-67:\nelif 'nt' in _names:\n name = 'nt'\n linesep = '\\r\\n'\n from nt import *\n try:\n from nt import _exit\n except ImportError:\n pass\n import ntpath as path\n\n import nt\n __all__.extend(_get_exports_list(nt))\n del nt\n\nThe import ntpath as path is the specific statement that causes os.path to be ntpath on your platforms (doubtlessly Windows).\n", ">>> import os as my_aliased_module\n>>> my_aliased_module\n<module 'os' from 'C:\\Program Files\\Python 2.6\\lib\\os.pyc'>\n\nEDIT: And since import is a simple statement in Python, you can do neat stuff like:\nimport sys\n\nif sys.platform == 'win32':\n import windows_module as my_module\nelse:\n import unix_module as my_module\n\n" ]
[ 13, 7 ]
[]
[]
[ "alias", "module", "path", "python" ]
stackoverflow_0002126301_alias_module_path_python.txt
Q: GAE Python optimization: Django filter for language support I have a filter that I use for lang support in my webapp. But when I publish it to GAE it keeps telling me that it the usage of CPU is to high. I think I located the problem to my filters I use for support. I use this in my templates: <h1>{{ "collection.header"|translate:lang }}</h1> The filter code looks like this: import re from google.appengine.ext import webapp from util import dictionary register = webapp.template.create_template_register() def translate(key, lang): d = dictionary.GetDictionaryKey(lang, key) if d == False: return "no key for " + key else: return d.value register.filter(translate) I'm to new to Python to see what's wrong with it. Or is the the entire wrong approach? ..fredrik Little more about what I'm trying to do: I'm trying to find away to handle language support. A user needs to be able to update text elements via an admin page. As of now I have all text elements stored in a db.model. And use a filter to get the right key based on language. After a lot of testing I still can't get to work well enough. When published I still get error messages in the logs about to much CPU usage. A typical page has about 30-50 text elements. And according to the logs it uses about 1500ms (900ms API) for each page load. I'm starting to think this might not be the best approach? I've tried using both memcache and indexes to get around the CPU usage. It helps a little. Should one use memcache and manually added indexes? This is how my filter looks like: import re from google.appengine.ext import webapp from google.appengine.api import memcache from util import dictionary register = webapp.template.create_template_register() def translate(key, lang): re = "no key for " + key data = memcache.get("dictionary" + lang) if data is None: data = dictionary.GetDictionaryKey(lang) memcache.add("dictionary" + lang, data, 60) if key in data: return data[key] else: return "no key for " + key register.filter(translate) And util.dictionary looks like this: from google.appengine.ext import db class DictionaryEntries(db.Model): lang = db.StringProperty() dkey = db.StringProperty() value = db.TextProperty() params = db.StringProperty() @property def itemid(self): return self.key().id() def GetDictionaryKey(lang): entries = DictionaryEntries.all().filter("lang = ", lang) if entries.count() > 0: langObj = {} for entry in entries: langObj[entry.dkey] = entry.value return langObj else: return False A: Your initial question is about high cpu usage, the answer i think is simple, with GAE and databases like BigTable (non-relational) the code with entries.count() is expensive and the for entry in entrie too if you have a lot of data. I think you must have to do a couple of things: in your utils.py def GetDictionaryKey(lang, key): chache_key = 'dictionary_%s_%s' % (lang, key) data = memcache.get(cache_key) if not data: entry = DictionaryEntries.all().filter("lang = ", lang).filter("value =", key).get() if entry: data = memcache.add(cache_key, entry.value, 60) else: data = 'no result for %s' % key return data and in your filter: def translate(key, lang): return dictionary.GetDictionaryKey(lang, key) This approach is better because: You don't make the expensive query of count You respect the MVC pattern, because a filter is part of the Template (View in the pattern) and the method GetDictionaryKey is part of the Controler. Besides, if you are using django i suggest you slugify your cache_key: from django.template.defaultfilters import slugify def GetDictionaryKey(lang, key): chache_key = 'dictionary_%s_%s' % (slugify(lang), slugify(key)) data = memcache.get(cache_key) if not data: entry = DictionaryEntries.all().filter("lang = ", lang).filter("value =", key).get() if entry: data = memcache.add(cache_key, entry.value, 60) else: data = 'no result for %s' % key return data A: Have you considered switching to standard gettext methods? Gettext is a widely spread approach for internationalization and very well embedded in the Python (and the Django) world. Some links: Python's gettext module Django's support for gettext with special attention to unicode PoEdit, an editor for .po-files produced by pygettext Your template would then look like this: {% load i18n %} <h1>{% trans "Header of my Collection" %}</h1> The files for translations can be generated by manage.py: manage.py makemessages -l fr for generating french (fr) messages, for example. Gettext is quite performant, so I doubt that you will experience a significant slow-down with this approach compared to your storage of the translation table in memcache. And what's more, it let's you work with "real" messages instead of abstract dictionary keys, which is, at least in my experience, ways better, if you have to read and understand the code (or if you have to find and change a certain message).
GAE Python optimization: Django filter for language support
I have a filter that I use for lang support in my webapp. But when I publish it to GAE it keeps telling me that it the usage of CPU is to high. I think I located the problem to my filters I use for support. I use this in my templates: <h1>{{ "collection.header"|translate:lang }}</h1> The filter code looks like this: import re from google.appengine.ext import webapp from util import dictionary register = webapp.template.create_template_register() def translate(key, lang): d = dictionary.GetDictionaryKey(lang, key) if d == False: return "no key for " + key else: return d.value register.filter(translate) I'm to new to Python to see what's wrong with it. Or is the the entire wrong approach? ..fredrik Little more about what I'm trying to do: I'm trying to find away to handle language support. A user needs to be able to update text elements via an admin page. As of now I have all text elements stored in a db.model. And use a filter to get the right key based on language. After a lot of testing I still can't get to work well enough. When published I still get error messages in the logs about to much CPU usage. A typical page has about 30-50 text elements. And according to the logs it uses about 1500ms (900ms API) for each page load. I'm starting to think this might not be the best approach? I've tried using both memcache and indexes to get around the CPU usage. It helps a little. Should one use memcache and manually added indexes? This is how my filter looks like: import re from google.appengine.ext import webapp from google.appengine.api import memcache from util import dictionary register = webapp.template.create_template_register() def translate(key, lang): re = "no key for " + key data = memcache.get("dictionary" + lang) if data is None: data = dictionary.GetDictionaryKey(lang) memcache.add("dictionary" + lang, data, 60) if key in data: return data[key] else: return "no key for " + key register.filter(translate) And util.dictionary looks like this: from google.appengine.ext import db class DictionaryEntries(db.Model): lang = db.StringProperty() dkey = db.StringProperty() value = db.TextProperty() params = db.StringProperty() @property def itemid(self): return self.key().id() def GetDictionaryKey(lang): entries = DictionaryEntries.all().filter("lang = ", lang) if entries.count() > 0: langObj = {} for entry in entries: langObj[entry.dkey] = entry.value return langObj else: return False
[ "Your initial question is about high cpu usage, the answer i think is simple, with GAE and databases like BigTable (non-relational) the code with entries.count() is expensive and the for entry in entrie too if you have a lot of data.\nI think you must have to do a couple of things:\nin your utils.py\ndef GetDictionaryKey(lang, key):\n chache_key = 'dictionary_%s_%s' % (lang, key)\n data = memcache.get(cache_key)\n if not data:\n entry = DictionaryEntries.all().filter(\"lang = \", lang).filter(\"value =\", key).get()\n if entry:\n data = memcache.add(cache_key, entry.value, 60)\n else:\n data = 'no result for %s' % key\n return data\n\nand in your filter: \n def translate(key, lang):\n return dictionary.GetDictionaryKey(lang, key)\n\nThis approach is better because:\n\nYou don't make the expensive query of count\nYou respect the MVC pattern, because a filter is part of the Template (View in the pattern) and the method GetDictionaryKey is part of the Controler.\n\nBesides, if you are using django i suggest you slugify your cache_key:\nfrom django.template.defaultfilters import slugify\ndef GetDictionaryKey(lang, key):\n chache_key = 'dictionary_%s_%s' % (slugify(lang), slugify(key))\n data = memcache.get(cache_key)\n if not data:\n entry = DictionaryEntries.all().filter(\"lang = \", lang).filter(\"value =\", key).get()\n if entry:\n data = memcache.add(cache_key, entry.value, 60)\n else:\n data = 'no result for %s' % key\n return data\n\n", "Have you considered switching to standard gettext methods? Gettext is a widely spread approach for internationalization and very well embedded in the Python (and the Django) world.\nSome links:\n\nPython's gettext module\nDjango's support for gettext with special attention to unicode\nPoEdit, an editor for .po-files produced by pygettext\n\nYour template would then look like this:\n{% load i18n %}\n<h1>{% trans \"Header of my Collection\" %}</h1>\n\nThe files for translations can be generated by manage.py:\nmanage.py makemessages -l fr\n\nfor generating french (fr) messages, for example.\nGettext is quite performant, so I doubt that you will experience a significant slow-down with this approach compared to your storage of the translation table in memcache. And what's more, it let's you work with \"real\" messages instead of abstract dictionary keys, which is, at least in my experience, ways better, if you have to read and understand the code (or if you have to find and change a certain message).\n" ]
[ 3, 2 ]
[]
[]
[ "django", "filter", "google_app_engine", "python" ]
stackoverflow_0001873704_django_filter_google_app_engine_python.txt
Q: Machine learning issue for negative instances I had to build a concept analyzer for computer science field and I used for this machine learning, the orange library for Python. I have the examples of concepts, where the features are lemma and part of speech, like algorithm|NN|concept. The problem is that any other word, that in fact is not a concept, is classified as a concept, due to the lack of negative examples. It is not feasable to put all the other words in learning file, classified as simple words not concepts(this will work, but is not quite a solution). Any idea? Thanks. A: The question is very unclear, but assuming what you mean is that your machine learning algorithm is not working without negative examples and you can't give it every possible negative example, then it's perfectly alright to give it some negative examples. The point of data mining (a.k.a. machine learning) is to try coming up with general rules based on a relatively small samples of data and then applying them to larger data. In real life problems you will never have all the data. If you had all possible inputs, you could easily create a simple sequence of if-then rules which would always be correct. If it was that simple, robots would be doing all our thinking for us by now.
Machine learning issue for negative instances
I had to build a concept analyzer for computer science field and I used for this machine learning, the orange library for Python. I have the examples of concepts, where the features are lemma and part of speech, like algorithm|NN|concept. The problem is that any other word, that in fact is not a concept, is classified as a concept, due to the lack of negative examples. It is not feasable to put all the other words in learning file, classified as simple words not concepts(this will work, but is not quite a solution). Any idea? Thanks.
[ "The question is very unclear, but assuming what you mean is that your machine learning algorithm is not working without negative examples and you can't give it every possible negative example, then it's perfectly alright to give it some negative examples.\nThe point of data mining (a.k.a. machine learning) is to try coming up with general rules based on a relatively small samples of data and then applying them to larger data. In real life problems you will never have all the data. If you had all possible inputs, you could easily create a simple sequence of if-then rules which would always be correct. If it was that simple, robots would be doing all our thinking for us by now.\n" ]
[ 2 ]
[]
[]
[ "artificial_intelligence", "data_mining", "machine_learning", "python" ]
stackoverflow_0002126383_artificial_intelligence_data_mining_machine_learning_python.txt
Q: Processing a simple workflow in Python I am working on a code which takes a dataset and runs some algorithms on it. User uploads a dataset, and then selects which algorithms will be run on this dataset and creates a workflow like this: workflow = {0: {'dataset': 'some dataset'}, 1: {'algorithm1': "parameters"}, 2: {'algorithm2': "parameters"}, 3: {'algorithm3': "parameters"} } Which means I'll take workflow[0] as my dataset, and I will run algorithm1 on it. Then, I will take its results and I will run algorithm2 on this results as my new dataset. And I will take the new results and run algorithm3 on it. It goes like this until the last item and there is no length limit for this workflow. I am writing this in Python. Can you suggest some strategies about processing this workflow? A: You want to run a pipeline on some dataset. That sounds like a reduce operation (fold in some languages). No need for anything complicated: result = reduce(lambda data, (aname, p): algo_by_name(aname)(p, data), workflow) This assumes workflow looks like (text-oriented so you can load it with YAML/JSON): workflow = ['data', ('algo0', {}), ('algo1', {'param': value}), … ] And that your algorithms look like: def algo0(p, data): … return output_data.filename algo_by_name takes a name and gives you an algo function; for example: def algo_by_name(name): return {'algo0': algo0, 'algo1': algo1, }[name] (old edit: if you want a framework for writing pipelines, you could use Ruffus. It's like a make tool, but with progress support and pretty flow charts.) A: If each algorithm works on each element on dataset, map() would be an elegant option: dataset=workflow[0] for algorithm in workflow[1:]: dataset=map(algorithm, dataset) e.g. for the square roots of odd numbers only, use, >>> algo1=lambda x:0 if x%2==0 else x >>> algo2=lambda x:x*x >>> dataset=range(10) >>> workflow=(dataset, algo1, algo2) >>> for algo in workflow[1:]: dataset=map(algo, dataset) >>> dataset [0, 1, 0, 9, 0, 25, 0, 49, 0, 81] A: The way you want to do it seems sound to me, or you need to post more informations about what you are trying to accomplish. And advice: I would put the workflow structure in a list with tuples rather than a dictionary workflow = [ ('dataset', 'some dataset'), ('algorithm1', "parameters"), ('algorithm2', "parameters"), ('algorithm3', "parameters")] A: Define a Dataset class that tracks... data... for your set. Define methods in this class. Something like this: class Dataset: # Some member fields here that define your data, and a constructor def algorithm1(self, param1, param2, param3): # Update member fields based on algorithm def algorithm2(self, param1, param2): # More updating/processing Now, iterate over your "workflow" dict. For the first entry, simply instantiate your Dataset class. myDataset = Dataset() # Whatever actual construction you need to do For each subsequent entry... Extract the key/value somehow (I'd recommend changing your workflow data structure if possible, dict is inconvenient here) Parse the param string to a tuple of arguments (this step is up to you). Assuming you now have the string algorithm and the tuple params for the current iteration... getattr(myDataset, algorithm)(*params) This will call the function on myDataset with the name specified by "algorithm" with the argument list contained in "params". A: Here is how I would do this (all code untested): Step 1: You need to create the algorithms. The Dataset could look like this: class Dataset(object): def __init__(self, dataset): self.dataset = dataset def __iter__(self): for x in self.dataset: yield x Notice that you make an iterator out of it, so you iterate over it one item at a time. There's a reason for that, you'll see later: Another algorithm could look like this: class Multiplier(object): def __init__(self, previous, multiplier): self.previous = previous self.multiplier = multiplier def __iter__(self): for x in previous: yield x * self.multiplier Step 2 Your user would then need to make a chain of this somehow. Now if he had access to Python directly, you can just do this: dataset = Dataset(range(100)) multiplier = Multiplier(dataset, 5) and then get the results by: for x in multiplier: print x And it would ask the multiplier for one piece of data at a time, and the multiplier would in turn as the dataset. If you have a chain, then this means that one piece of data is handled at a time. This means you can handle huge amounts of data without using a lot of memory. Step 3 Probably you want to specify the steps in some other way. For example a text file or a string (sounds like this may be web-based?). Then you need a registry over the algorithms. The easiest way is to just create a module called "registry.py" like this: algorithms = {} Easy, eh? You would register a new algorithm like so: from registry import algorithms algorithms['dataset'] = Dataset algorithms['multiplier'] = Multiplier You'd also need a method that creates the chain from specifications in a text file or something. I'll leave that up to you. ;) (I would probably use the Zope Component Architecture and make algorithms components and register them in the component registry. But that is all strictly speaking overkill).
Processing a simple workflow in Python
I am working on a code which takes a dataset and runs some algorithms on it. User uploads a dataset, and then selects which algorithms will be run on this dataset and creates a workflow like this: workflow = {0: {'dataset': 'some dataset'}, 1: {'algorithm1': "parameters"}, 2: {'algorithm2': "parameters"}, 3: {'algorithm3': "parameters"} } Which means I'll take workflow[0] as my dataset, and I will run algorithm1 on it. Then, I will take its results and I will run algorithm2 on this results as my new dataset. And I will take the new results and run algorithm3 on it. It goes like this until the last item and there is no length limit for this workflow. I am writing this in Python. Can you suggest some strategies about processing this workflow?
[ "You want to run a pipeline on some dataset. That sounds like a reduce operation (fold in some languages). No need for anything complicated:\nresult = reduce(lambda data, (aname, p): algo_by_name(aname)(p, data), workflow)\n\nThis assumes workflow looks like (text-oriented so you can load it with YAML/JSON):\nworkflow = ['data', ('algo0', {}), ('algo1', {'param': value}), … ]\n\nAnd that your algorithms look like:\ndef algo0(p, data):\n …\n return output_data.filename\n\nalgo_by_name takes a name and gives you an algo function; for example:\ndef algo_by_name(name):\n return {'algo0': algo0, 'algo1': algo1, }[name]\n\n(old edit: if you want a framework for writing pipelines, you could use Ruffus. It's like a make tool, but with progress support and pretty flow charts.)\n", "If each algorithm works on each element on dataset, map() would be an elegant option:\ndataset=workflow[0]\nfor algorithm in workflow[1:]:\n dataset=map(algorithm, dataset)\n\ne.g. for the square roots of odd numbers only, use,\n>>> algo1=lambda x:0 if x%2==0 else x\n>>> algo2=lambda x:x*x\n>>> dataset=range(10)\n>>> workflow=(dataset, algo1, algo2)\n>>> for algo in workflow[1:]:\n dataset=map(algo, dataset)\n>>> dataset\n[0, 1, 0, 9, 0, 25, 0, 49, 0, 81]\n\n", "The way you want to do it seems sound to me, or you need to post more informations about what you are trying to accomplish.\nAnd advice: I would put the workflow structure in a list with tuples rather than a dictionary\nworkflow = [ ('dataset', 'some dataset'),\n ('algorithm1', \"parameters\"),\n ('algorithm2', \"parameters\"),\n ('algorithm3', \"parameters\")]\n\n", "Define a Dataset class that tracks... data... for your set. Define methods in this class. Something like this:\nclass Dataset:\n # Some member fields here that define your data, and a constructor\n\n def algorithm1(self, param1, param2, param3):\n # Update member fields based on algorithm\n\n def algorithm2(self, param1, param2):\n # More updating/processing\n\nNow, iterate over your \"workflow\" dict. For the first entry, simply instantiate your Dataset class.\nmyDataset = Dataset() # Whatever actual construction you need to do\n\nFor each subsequent entry...\n\nExtract the key/value somehow (I'd recommend changing your workflow data structure if possible, dict is inconvenient here)\nParse the param string to a tuple of arguments (this step is up to you).\nAssuming you now have the string algorithm and the tuple params for the current iteration...\ngetattr(myDataset, algorithm)(*params)\nThis will call the function on myDataset with the name specified by \"algorithm\" with the argument list contained in \"params\". \n\n", "Here is how I would do this (all code untested):\nStep 1: You need to create the algorithms. The Dataset could look like this:\nclass Dataset(object):\n def __init__(self, dataset):\n self.dataset = dataset\n\n def __iter__(self):\n for x in self.dataset:\n yield x\n\nNotice that you make an iterator out of it, so you iterate over it one item at a time. There's a reason for that, you'll see later:\nAnother algorithm could look like this:\nclass Multiplier(object):\n def __init__(self, previous, multiplier):\n self.previous = previous\n self.multiplier = multiplier\n def __iter__(self):\n for x in previous:\n yield x * self.multiplier\n\nStep 2\nYour user would then need to make a chain of this somehow. Now if he had access to Python directly, you can just do this:\ndataset = Dataset(range(100))\nmultiplier = Multiplier(dataset, 5)\n\nand then get the results by:\nfor x in multiplier:\n print x\n\nAnd it would ask the multiplier for one piece of data at a time, and the multiplier would in turn as the dataset. If you have a chain, then this means that one piece of data is handled at a time. This means you can handle huge amounts of data without using a lot of memory.\nStep 3\nProbably you want to specify the steps in some other way. For example a text file or a string (sounds like this may be web-based?). Then you need a registry over the algorithms. The easiest way is to just create a module called \"registry.py\" like this:\nalgorithms = {}\n\nEasy, eh? You would register a new algorithm like so:\nfrom registry import algorithms\nalgorithms['dataset'] = Dataset\nalgorithms['multiplier'] = Multiplier\n\nYou'd also need a method that creates the chain from specifications in a text file or something. I'll leave that up to you. ;)\n(I would probably use the Zope Component Architecture and make algorithms components and register them in the component registry. But that is all strictly speaking overkill).\n" ]
[ 10, 4, 2, 2, 1 ]
[]
[]
[ "python", "workflow" ]
stackoverflow_0002126811_python_workflow.txt
Q: How to play sound in Python WITHOUT interrupting music/other sounds from playing I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code: from wave import open as wave_open from ossaudiodev import open as oss_open def _play_chime(): """ Play a sound file once. """ sound_file = wave_open('chime.wav','rb') (nc,sw,fr,nf,comptype, compname) = sound_file.getparams( ) dsp = oss_open('/dev/dsp','w') try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp.setparameters(AFMT_S16_NE, nc, fr) data = sound_file.readframes(nf) sound_file.close() dsp.write(data) dsp.close() It works pretty good, unless any other device is already outputing sound. How could I do basically the same (under linux) without having the prerequisite that no sound is being played? If you think the process would require an API to ensure software mixing, please suggest a method :) Thx for the support :) A: The easy answer is "Switch from OSS to PulseAudio." (Or set up ALSA to use dmix, or get a soundcard with better Linux drivers...) The more complicated answer is, your code already works the way you want it to... on some soundcards. OSS drivers can expose hardware mixers so that you can have multiple audio streams playing simultaneously, or they can expose a single stream which results in the blocking audio you see on your system. The only correct solution here is to use an API that ensures software mixing. A: Modern hardware and drivers supports multiple streams. So unless you are running with ancient hardware or a crappy driver, it should work anyway. Having said that, ALSA may give you more control than OSS. Most kernels shipped nowadays support both.
How to play sound in Python WITHOUT interrupting music/other sounds from playing
I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code: from wave import open as wave_open from ossaudiodev import open as oss_open def _play_chime(): """ Play a sound file once. """ sound_file = wave_open('chime.wav','rb') (nc,sw,fr,nf,comptype, compname) = sound_file.getparams( ) dsp = oss_open('/dev/dsp','w') try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp.setparameters(AFMT_S16_NE, nc, fr) data = sound_file.readframes(nf) sound_file.close() dsp.write(data) dsp.close() It works pretty good, unless any other device is already outputing sound. How could I do basically the same (under linux) without having the prerequisite that no sound is being played? If you think the process would require an API to ensure software mixing, please suggest a method :) Thx for the support :)
[ "The easy answer is \"Switch from OSS to PulseAudio.\" (Or set up ALSA to use dmix, or get a soundcard with better Linux drivers...)\nThe more complicated answer is, your code already works the way you want it to... on some soundcards. OSS drivers can expose hardware mixers so that you can have multiple audio streams playing simultaneously, or they can expose a single stream which results in the blocking audio you see on your system. The only correct solution here is to use an API that ensures software mixing.\n", "Modern hardware and drivers supports multiple streams. So unless you are running with ancient hardware or a crappy driver, it should work anyway.\nHaving said that, ALSA may give you more control than OSS. Most kernels shipped nowadays support both.\n" ]
[ 8, 1 ]
[]
[]
[ "audio", "linux", "python", "timer" ]
stackoverflow_0002125547_audio_linux_python_timer.txt
Q: Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py) Django only allows you to use one database in settings.py. Does that prevent you from scaling up? (millions of users) A: Django now has support for multiple databases. A: The database isn't your bottleneck. Check your browser carefully. For each page of HTML you're sending (on average) 8 other files, some of which may be quite large. These are your JS, CSS, graphics, etc. The actual performance bottleneck is the browser requesting those files and accepting the bytes s... l... o... w... l... y... To scale, then, do this. Use multiple front-ends balanced with a pure software solution like wackamole. http://www.backhand.org/wackamole/ Use proxy servers like squid to send the "other" files. They're largely static. This is where 7/8ths of the work is done downloading to the client. Don't scrimp on getting these right. Use multiple, concurrent mod_wsgi/Django to create the -- rare -- piece of dynamic HTML based on DB queries. Be sure that mod_wsgi is in daemon mode so that you can have multiple Django servers available to Apache. Build as many of these as you need. They're all identical, all in parallel, and all shared by Wackamole. Use a single, fast database like MySQL for the few things that must come from a database. MySQL will make use of multiple cores on it's server, so it will scale reasonably well without you having to do anything other than buy memory. Put this on a separate box, all by itself, dedicated and tuned for just this. You'll find that this scales nicely. You'll find that the load is shared nicely between squid, apache, the Django daemons and the actual database. You'll also find that each part of the load (from the boring static parts to the interesting database query) happens separately and concurrently. Finally, buy Schlossnagle's book. http://www.amazon.com/Scalable-Internet-Architectures-Theo-Schlossnagle/dp/067232699X A: Read scaling to millions of users is not a database problem, but is fixed with load balancing and caching, etc, see S. Lott above. Write scaling can indeed be a database problem. "Sharding" and having multiple databases can be one solution, but that's hard with SQL while still retaining the relationality of the database. Popular solutions there are the new types of "nosql" databases. But if you really have those problems, then you need serious expert help, not just answers from dudes Stackoverflow. :) A: Some great answers already (S. Lott for example), however I thought I should pipe in with some more things: Make sure not to use the database for logical operations I understand the attractiveness of Order By or SQL Procedures however you only have one database but you have multiple django servers, let the servers handle this if you can. Of course, if you only want the last ten rows according to a certain criterion (date), then by all means do precise it in the request ;) Just make sure not to overload your database with operations that could be handled elsewhere. Throw more hardware to the problem MySQL and Oracle scale quite well with hardware, if you have a small problem of performance you could begin by adding more hardware. Split your database I know that for relationships and all you have to manage some tables together, however if you ever have a load problem, try to group your tables, for example if you have a "history" group of tables, perhaps that it could work without the others and be on a separate server. Do consider tuning, and watch out for your requests/index You would need experts advises here, but I can tell from experience that even a single badly tuned request can wreak havoc... and it's quite difficult to find out. You can consider the Ask Tom website for example of diagnosis / fine tuning. Don't decide on your tables architecture in isolation, but do consider the requests Hierarchical requests and multiple joins can be really costly. You don't have to build a fully normalized relations schema and may consider some denormalization in order to better accomodate the type of requests the database will face. Just a couple of thoughts :) A: A few miscellaneous pieces of advice: I'm surprised no one's mentioned this yet. Use memcached. If you're getting a lot of repetitive types of queries (which most webapps do), this can make a huge difference. Consider using Oracle's failover and load balancing. It allows you to add support for multiple databases on a single db connection. Another thing to consider is using a system similar to FriendFeed's. This solves the problem of "how do we make changes to the database without halting the world?" more than anything else. A: If you find out that the DB is the bottlenck of your app, and their is now way around it (like using caching) then you should scale your DB as well. Django has nothing to do with this
Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py)
Django only allows you to use one database in settings.py. Does that prevent you from scaling up? (millions of users)
[ "Django now has support for multiple databases.\n", "The database isn't your bottleneck.\nCheck your browser carefully.\nFor each page of HTML you're sending (on average) 8 other files, some of which may be quite large. These are your JS, CSS, graphics, etc.\nThe actual performance bottleneck is the browser requesting those files and accepting the bytes s... l... o... w... l... y...\nTo scale, then, do this.\n\nUse multiple front-ends balanced with a pure software solution like wackamole. http://www.backhand.org/wackamole/\nUse proxy servers like squid to send the \"other\" files. They're largely static. This is where 7/8ths of the work is done downloading to the client. Don't scrimp on getting these right.\nUse multiple, concurrent mod_wsgi/Django to create the -- rare -- piece of dynamic HTML based on DB queries. Be sure that mod_wsgi is in daemon mode so that you can have multiple Django servers available to Apache. Build as many of these as you need. They're all identical, all in parallel, and all shared by Wackamole.\nUse a single, fast database like MySQL for the few things that must come from a database. MySQL will make use of multiple cores on it's server, so it will scale reasonably well without you having to do anything other than buy memory. Put this on a separate box, all by itself, dedicated and tuned for just this.\n\nYou'll find that this scales nicely. You'll find that the load is shared nicely between squid, apache, the Django daemons and the actual database. You'll also find that each part of the load (from the boring static parts to the interesting database query) happens separately and concurrently.\nFinally, buy Schlossnagle's book. http://www.amazon.com/Scalable-Internet-Architectures-Theo-Schlossnagle/dp/067232699X\n", "Read scaling to millions of users is not a database problem, but is fixed with load balancing and caching, etc, see S. Lott above.\nWrite scaling can indeed be a database problem. \"Sharding\" and having multiple databases can be one solution, but that's hard with SQL while still retaining the relationality of the database. Popular solutions there are the new types of \"nosql\" databases. But if you really have those problems, then you need serious expert help, not just answers from dudes Stackoverflow. :)\n", "Some great answers already (S. Lott for example), however I thought I should pipe in with some more things:\nMake sure not to use the database for logical operations\nI understand the attractiveness of Order By or SQL Procedures however you only have one database but you have multiple django servers, let the servers handle this if you can.\nOf course, if you only want the last ten rows according to a certain criterion (date), then by all means do precise it in the request ;) Just make sure not to overload your database with operations that could be handled elsewhere.\nThrow more hardware to the problem\nMySQL and Oracle scale quite well with hardware, if you have a small problem of performance you could begin by adding more hardware.\nSplit your database\nI know that for relationships and all you have to manage some tables together, however if you ever have a load problem, try to group your tables, for example if you have a \"history\" group of tables, perhaps that it could work without the others and be on a separate server.\nDo consider tuning, and watch out for your requests/index\nYou would need experts advises here, but I can tell from experience that even a single badly tuned request can wreak havoc... and it's quite difficult to find out. You can consider the Ask Tom website for example of diagnosis / fine tuning.\nDon't decide on your tables architecture in isolation, but do consider the requests\nHierarchical requests and multiple joins can be really costly. You don't have to build a fully normalized relations schema and may consider some denormalization in order to better accomodate the type of requests the database will face.\nJust a couple of thoughts :)\n", "A few miscellaneous pieces of advice:\n\nI'm surprised no one's mentioned this yet. Use memcached. If you're getting a lot of repetitive types of queries (which most webapps do), this can make a huge difference.\nConsider using Oracle's failover and load balancing. It allows you to add support for multiple databases on a single db connection.\nAnother thing to consider is using a system similar to FriendFeed's. This solves the problem of \"how do we make changes to the database without halting the world?\" more than anything else.\n\n", "If you find out that the DB is the bottlenck of your app, and their is now way around it (like using caching) then you should scale your DB as well. Django has nothing to do with this\n" ]
[ 11, 7, 3, 1, 1, 0 ]
[]
[]
[ "django", "python", "scalability", "web_services" ]
stackoverflow_0002127067_django_python_scalability_web_services.txt
Q: Set auto-incrementing attribute in XML node I'm trying to set an attribute in one of the nodes for my XML as below: rank = 1 for photo in s: image = feed.createElement('Image') images.appendChild(image) image.setAttribute("rank", rank) p = feed.createTextNode(str(main_url+photo.display.url)) image.appendChild(p) rank += 1 This however results in the error: 'int' object has no attribute 'replace' in reference to the line: image.setAttribute("rank", rank) What am I missing? A: The .setAttribute method expects a string, so you will have to convert it: image.setAttribute("rank", str(rank))
Set auto-incrementing attribute in XML node
I'm trying to set an attribute in one of the nodes for my XML as below: rank = 1 for photo in s: image = feed.createElement('Image') images.appendChild(image) image.setAttribute("rank", rank) p = feed.createTextNode(str(main_url+photo.display.url)) image.appendChild(p) rank += 1 This however results in the error: 'int' object has no attribute 'replace' in reference to the line: image.setAttribute("rank", rank) What am I missing?
[ "The .setAttribute method expects a string, so you will have to convert it:\nimage.setAttribute(\"rank\", str(rank))\n\n" ]
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002127291_python_xml.txt
Q: How to resolve case problems for non-english languages in django admin panel? I need to resolve problem with word endings in django admin panel. The language I'm using is russian (using utf-8 charset), so some problems occur, for example, there is a problem with the right endings on the "Add" button for some model names. The simplest thing I found is using jQuery to correct endings "on the fly", but this solution is too radical. Maybe there is a simple answer? Just don't want to dig again into deepness of django's sources... A: If I understood the problem correctly, you should just add an appropriate attribute in the meta section of the class. English example: class Man(models.Model): [...your fields...] class Meta: verbose_name_plural = "men" More info can be found in the documentation for Django model options
How to resolve case problems for non-english languages in django admin panel?
I need to resolve problem with word endings in django admin panel. The language I'm using is russian (using utf-8 charset), so some problems occur, for example, there is a problem with the right endings on the "Add" button for some model names. The simplest thing I found is using jQuery to correct endings "on the fly", but this solution is too radical. Maybe there is a simple answer? Just don't want to dig again into deepness of django's sources...
[ "If I understood the problem correctly, you should just add an appropriate attribute in the meta section of the class.\nEnglish example:\nclass Man(models.Model):\n [...your fields...]\n\n class Meta:\n verbose_name_plural = \"men\"\n\nMore info can be found in the documentation for Django model options\n" ]
[ 1 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0002127362_django_internationalization_python.txt
Q: tricky string matching I want to find the first index of substrings in a larger string. I only want it to match whole words and I'd like it to be case-insensitive, except that I want it to treat CamelCase as separate words. The code below does the trick, but it's slow. I'd like to speed it up. Any suggestions? I was trying some regex stuff, but couldn't find one that handled all the edge cases. def word_start_index(text, seek_word): start_index = 0 curr_word = "" def case_change(): return curr_word and ch.isupper() and curr_word[-1].islower() def is_match(): return curr_word.lower() == seek_word.lower() for i, ch in enumerate(text): if case_change() or not ch.isalnum(): if is_match(): return start_index curr_word = "" start_index = None if ch.isalnum(): if start_index is None: start_index = i curr_word += ch if is_match(): return start_index if __name__ == "__main__": # 01234567890123456789012345 test_text = "a_foobar_FooBar baz golf_CART" test_words = ["a", "foo", "bar", "baz", "golf", "cart", "fred"] for word in test_words: match_start = word_start_index(test_text, word) print match_start, word Output: 0 a 9 foo 12 bar 16 baz 20 golf 25 cart None fred A: word_emitter (below) takes a text string and yields lowercase "words" as they are found, one at a time (along with their positions). It replaces all underscores with spaces. It then splits the text into a list. For example, "a_foobar_FooBar baz golf_CART Foo" becomes ['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo'] Of course, you also want camelCase words to be treated as separate words. So for each piece in the above list, we use the regex pattern '(.*[a-z])(?=[A-Z])' to split camelCase words. This regex uses the re module's look-forward operator (?=...). Perhaps that is the trickiest part to the whole thing. word_emitter then yields the words one at a time, along with their associated positions. Once you have a function which splits the text into "words", the rest is easy. I've also switch the order of your loops, so you only loop through the test_text once. This will speed things up if test_text is very long compared to test_words. import re import string import itertools nonspace=re.compile('(\S+)') table = string.maketrans( '_.,!?;:"(){}@#$%^&*-+='+"'", ' ', ) def piece_emitter(text): # This generator splits text into 2-tuples of (positions,pieces). # Given "a_foobar_FooBar" it returns # ((0,'a'), # (2,'foobar'), # (9,'FooBar'), # ) pos=0 it=itertools.groupby(text,lambda w: w.isspace()) for k,g in it: w=''.join(g) w=w.translate(table) it2=itertools.groupby(w,lambda w: w.isspace()) for isspace,g2 in it2: word=''.join(g2) if not isspace: yield pos,word pos+=len(word) def camel_splitter(word): # Given a word like 'FooBar', this generator yields # 'Foo', then 'Bar'. it=itertools.groupby(word,lambda w: w.isupper()) for k,g in it: w=''.join(g) if len(w)==1: try: k1,g1=next(it) w+=''.join(g1) except StopIteration: pass yield w def word_emitter(piece): # Given 'getFooBar', this generator yields in turn the elements of the sequence # ((0,'get'), # (0,'getFoo'), # (0,'getFooBar'), # (3,'Foo'), # (3,'FooBar'), # (6,'Bar'), # ) # In each 2-tuple, the number is the starting position of the string, # followed by the fragment of camelCase word generated by camel_splitter. words=list(camel_splitter(piece)) num_words=len(words) for i in range(0,num_words+1): prefix=''.join(words[:i]) for step in range(1,num_words-i+1): word=''.join(words[i:i+step]) yield len(prefix),word def camel_search(text,words): words=dict.fromkeys(words,False) for pos,piece in piece_emitter(text): if not all(words[test_word] for test_word in words): for subpos,word in word_emitter(piece): for test_word in words: if not words[test_word] and word.lower() == test_word.lower(): yield pos+subpos,word words[test_word]=True break else: break for word in words: if not words[word]: yield None,word if __name__ == "__main__": # 01234567890123456789012345 test_text = "a_foobar_FooBar baz golf_CART" test_words = ["a", "foo", "bar", "baz", "golf", "cart", "fred"] for pos,word in camel_search(test_text,test_words): print pos,word.lower() Here are the unit tests I used to check the program: import unittest import sys import camel import itertools class Test(unittest.TestCase): def check(self,result,answer): for r,a in itertools.izip_longest(result,answer): if r!=a: print('%s != %s'%(r,a)) self.assertTrue(r==a) def test_piece_emitter(self): tests=(("a_foobar_FooBar baz? golf_CART Foo 'food' getFooBaz", ((0,'a'), (2,'foobar'), (9,'FooBar'), (16,'baz'), (21,'golf'), (26,'CART'), (31,'Foo'), (36,'food'), (42,'getFooBaz'), ) ), ) for text,answer in tests: result=list(camel.piece_emitter(text)) print(result) self.check(result,answer) def test_camel_splitter(self): tests=(('getFooBar',('get','Foo','Bar')), ('getFOObar',('get','FOO','bar')), ('Foo',('Foo',)), ('getFoo',('get','Foo')), ('foobar',('foobar',)), ('fooBar',('foo','Bar')), ('FooBar',('Foo','Bar')), ('a',('a',)), ('fooB',('foo','B')), ('FooB',('Foo','B')), ('FOOb',('FOO','b')), ) for word,answer in tests: result=camel.camel_splitter(word) self.check(result,answer) def test_word_emitter(self): tests=(("a", ((0,'a'),) ), ('getFooBar', ((0,'get'), (0,'getFoo'), (0,'getFooBar'), (3,'Foo'), (3,'FooBar'), (6,'Bar'), ) ) ) for text,answer in tests: result=list(camel.word_emitter(text)) print(result) self.check(result,answer) def test_camel_search(self): tests=(("a_foobar_FooBar baz? golf_CART Foo 'food' getFooBaz", ("a", "foo", "bar", "baz", "golf", "cart", "fred", "food", 'FooBaz'), ((0,'a'), (9,'Foo'), (12,'Bar'), (16,'baz'), (21,'golf'), (26,'CART'), (36,'food'), (45,'FooBaz'), (None,'fred') ) ), ("\"Foo\"",('Foo',),((1,'Foo'),)), ("getFooBar",('FooBar',),((3,'FooBar'),)), ) for text,search_words,answer in tests: result=list(camel.camel_search(text,search_words)) print(result) self.check(result,answer) if __name__ == '__main__': unittest.main(argv = unittest.sys.argv + ['--verbose']) A: If I were doing this with regular expressions I'd probably do it like this: def word_start_index2(text, seek_word): camel_case = seek_word[0].upper() + seek_word[1:].lower() seek_word_i = ''.join('[' + c.lower() + c.upper() + ']' for c in seek_word) regex1 = r'(?:(?<=[^a-zA-Z])|^)' + seek_word_i + r'(?=$|[^a-zA-Z])' regex2 = r'(?:(?<=[a-z]|[^A-Z])|^)' + camel_case + r'(?=$|[A-Z]|[^a-z])' regex = '%s|%s' % (regex1, regex2) import re m = re.search(regex, text) if not m: return None else: return m.start() I haven't performance tested this against your version though, but you could try it to see if it is better or worse and let us know. My answer might give different output from yours on some edge cases but in your comments you said that you don't care about these cases. Also, I tried to use the notation (?i) to mark part of the regex as case-insensitive but for some reason this fails to work correctly. I cannot explain why. Final self-nitpick: the function needs to validate its arguments but this code is omitted for clarity. You should add checks at least for the following: text should be a string seek_word should be a string matching '[a-zA-Z]+' A: With a index to speed up searching :-) from collections import defaultdict class IndexedText(object): """ a indexed text """ def __init__(self, text): self.text = text self._index() def word_start_index(self, word): l = len(word) w = word.lower() return self.index[word] def _index(self): self.index = defaultdict( list ) def index( word, pos): self.index[word.lower()].append( pos ) start = 0 it = enumerate(self.text) lpos, lchar = it.next() WS = (' ','_') for pos, char in it: if lchar in WS and char not in WS: index( self.text[start:lpos], start ) start = pos elif lchar.islower() and char.isupper(): # camelcase index( self.text[start:pos], start ) start = pos lpos, lchar = pos, char # last word is missing index( self.text[start:], start ) if __name__ == "__main__": # 01234567890123456789012345 test_text = "a_foobar_FooBar baz golf_CART" test_words = ["a", "foo", "bar", "baz", "golf", "cart", "fred"] index = IndexedText( test_text ) for word in test_words: match_start = index.word_start_index( word ) print match_start, word
tricky string matching
I want to find the first index of substrings in a larger string. I only want it to match whole words and I'd like it to be case-insensitive, except that I want it to treat CamelCase as separate words. The code below does the trick, but it's slow. I'd like to speed it up. Any suggestions? I was trying some regex stuff, but couldn't find one that handled all the edge cases. def word_start_index(text, seek_word): start_index = 0 curr_word = "" def case_change(): return curr_word and ch.isupper() and curr_word[-1].islower() def is_match(): return curr_word.lower() == seek_word.lower() for i, ch in enumerate(text): if case_change() or not ch.isalnum(): if is_match(): return start_index curr_word = "" start_index = None if ch.isalnum(): if start_index is None: start_index = i curr_word += ch if is_match(): return start_index if __name__ == "__main__": # 01234567890123456789012345 test_text = "a_foobar_FooBar baz golf_CART" test_words = ["a", "foo", "bar", "baz", "golf", "cart", "fred"] for word in test_words: match_start = word_start_index(test_text, word) print match_start, word Output: 0 a 9 foo 12 bar 16 baz 20 golf 25 cart None fred
[ "word_emitter (below) takes a text string and yields lowercase \"words\" as they are found, one at a time (along with their positions). \nIt replaces all underscores with spaces. It then splits the text into a list. For example,\n\"a_foobar_FooBar baz golf_CART Foo\"\n\nbecomes\n['a', 'foobar', 'FooBar', 'baz', 'golf', 'CART', 'Foo']\n\nOf course, you also want camelCase words to be treated as separate words.\nSo for each piece in the above list, we use the regex pattern '(.*[a-z])(?=[A-Z])'\nto split camelCase words. This regex uses the re module's look-forward operator (?=...).\nPerhaps that is the trickiest part to the whole thing.\nword_emitter then yields the words one at a time, along with their associated positions.\nOnce you have a function which splits the text into \"words\", the rest is easy.\nI've also switch the order of your loops, so you only loop through the test_text once. This will speed things up if test_text is very long compared to test_words.\nimport re\nimport string\nimport itertools\n\nnonspace=re.compile('(\\S+)')\ntable = string.maketrans(\n '_.,!?;:\"(){}@#$%^&*-+='+\"'\",\n ' ',\n )\n\ndef piece_emitter(text):\n # This generator splits text into 2-tuples of (positions,pieces).\n # Given \"a_foobar_FooBar\" it returns\n # ((0,'a'),\n # (2,'foobar'),\n # (9,'FooBar'),\n # )\n pos=0\n it=itertools.groupby(text,lambda w: w.isspace())\n for k,g in it:\n w=''.join(g)\n w=w.translate(table)\n it2=itertools.groupby(w,lambda w: w.isspace())\n for isspace,g2 in it2:\n word=''.join(g2)\n if not isspace:\n yield pos,word\n pos+=len(word)\n\ndef camel_splitter(word):\n # Given a word like 'FooBar', this generator yields\n # 'Foo', then 'Bar'.\n it=itertools.groupby(word,lambda w: w.isupper())\n for k,g in it:\n w=''.join(g)\n if len(w)==1:\n try:\n k1,g1=next(it)\n w+=''.join(g1)\n except StopIteration:\n pass\n yield w\n\ndef word_emitter(piece):\n # Given 'getFooBar', this generator yields in turn the elements of the sequence\n # ((0,'get'),\n # (0,'getFoo'),\n # (0,'getFooBar'),\n # (3,'Foo'),\n # (3,'FooBar'),\n # (6,'Bar'), \n # )\n # In each 2-tuple, the number is the starting position of the string,\n # followed by the fragment of camelCase word generated by camel_splitter.\n words=list(camel_splitter(piece))\n num_words=len(words)\n for i in range(0,num_words+1):\n prefix=''.join(words[:i])\n for step in range(1,num_words-i+1):\n word=''.join(words[i:i+step])\n yield len(prefix),word\n\ndef camel_search(text,words):\n words=dict.fromkeys(words,False)\n for pos,piece in piece_emitter(text): \n if not all(words[test_word] for test_word in words):\n for subpos,word in word_emitter(piece):\n for test_word in words:\n if not words[test_word] and word.lower() == test_word.lower(): \n yield pos+subpos,word\n words[test_word]=True\n break\n else:\n break\n for word in words:\n if not words[word]:\n yield None,word\n\nif __name__ == \"__main__\": \n # 01234567890123456789012345\n test_text = \"a_foobar_FooBar baz golf_CART\"\n test_words = [\"a\", \"foo\", \"bar\", \"baz\", \"golf\", \"cart\", \"fred\"]\n for pos,word in camel_search(test_text,test_words):\n print pos,word.lower()\n\nHere are the unit tests I used to check the program:\nimport unittest\nimport sys\nimport camel\nimport itertools\n\nclass Test(unittest.TestCase):\n def check(self,result,answer):\n for r,a in itertools.izip_longest(result,answer):\n if r!=a:\n print('%s != %s'%(r,a))\n self.assertTrue(r==a)\n\n def test_piece_emitter(self):\n tests=((\"a_foobar_FooBar baz? golf_CART Foo 'food' getFooBaz\",\n ((0,'a'),\n (2,'foobar'),\n (9,'FooBar'),\n (16,'baz'),\n (21,'golf'),\n (26,'CART'),\n (31,'Foo'),\n (36,'food'),\n (42,'getFooBaz'),\n )\n ),\n )\n for text,answer in tests:\n result=list(camel.piece_emitter(text))\n print(result)\n self.check(result,answer)\n def test_camel_splitter(self):\n tests=(('getFooBar',('get','Foo','Bar')),\n ('getFOObar',('get','FOO','bar')),\n ('Foo',('Foo',)),\n ('getFoo',('get','Foo')),\n ('foobar',('foobar',)),\n ('fooBar',('foo','Bar')),\n ('FooBar',('Foo','Bar')),\n ('a',('a',)),\n ('fooB',('foo','B')),\n ('FooB',('Foo','B')), \n ('FOOb',('FOO','b')), \n )\n for word,answer in tests:\n result=camel.camel_splitter(word)\n self.check(result,answer) \n def test_word_emitter(self):\n tests=((\"a\",\n ((0,'a'),) ),\n ('getFooBar',\n ((0,'get'),\n (0,'getFoo'),\n (0,'getFooBar'),\n (3,'Foo'),\n (3,'FooBar'),\n (6,'Bar'), \n ) \n )\n )\n for text,answer in tests:\n result=list(camel.word_emitter(text))\n print(result)\n self.check(result,answer)\n\n def test_camel_search(self):\n tests=((\"a_foobar_FooBar baz? golf_CART Foo 'food' getFooBaz\",\n (\"a\", \"foo\", \"bar\", \"baz\", \"golf\", \"cart\", \"fred\", \"food\",\n 'FooBaz'),\n ((0,'a'),\n (9,'Foo'),\n (12,'Bar'),\n (16,'baz'),\n (21,'golf'),\n (26,'CART'),\n (36,'food'),\n (45,'FooBaz'),\n (None,'fred')\n )\n ),\n (\"\\\"Foo\\\"\",('Foo',),((1,'Foo'),)),\n (\"getFooBar\",('FooBar',),((3,'FooBar'),)), \n )\n for text,search_words,answer in tests:\n result=list(camel.camel_search(text,search_words))\n print(result)\n self.check(result,answer)\n\nif __name__ == '__main__':\n unittest.main(argv = unittest.sys.argv + ['--verbose'])\n\n", "If I were doing this with regular expressions I'd probably do it like this:\ndef word_start_index2(text, seek_word):\n camel_case = seek_word[0].upper() + seek_word[1:].lower()\n seek_word_i = ''.join('[' + c.lower() + c.upper() + ']'\n for c in seek_word)\n regex1 = r'(?:(?<=[^a-zA-Z])|^)' + seek_word_i + r'(?=$|[^a-zA-Z])'\n regex2 = r'(?:(?<=[a-z]|[^A-Z])|^)' + camel_case + r'(?=$|[A-Z]|[^a-z])'\n regex = '%s|%s' % (regex1, regex2)\n import re\n m = re.search(regex, text)\n if not m:\n return None\n else:\n return m.start()\n\nI haven't performance tested this against your version though, but you could try it to see if it is better or worse and let us know.\nMy answer might give different output from yours on some edge cases but in your comments you said that you don't care about these cases.\nAlso, I tried to use the notation (?i) to mark part of the regex as case-insensitive but for some reason this fails to work correctly. I cannot explain why.\nFinal self-nitpick: the function needs to validate its arguments but this code is omitted for clarity. You should add checks at least for the following:\n\ntext should be a string\nseek_word should be a string matching '[a-zA-Z]+'\n\n", "With a index to speed up searching :-)\nfrom collections import defaultdict\n\nclass IndexedText(object):\n \"\"\" a indexed text \"\"\"\n def __init__(self, text):\n self.text = text\n self._index()\n\n\n def word_start_index(self, word):\n l = len(word)\n w = word.lower()\n return self.index[word]\n\n def _index(self):\n self.index = defaultdict( list )\n\n def index( word, pos):\n self.index[word.lower()].append( pos )\n\n start = 0\n it = enumerate(self.text)\n lpos, lchar = it.next()\n WS = (' ','_')\n\n for pos, char in it:\n if lchar in WS and char not in WS:\n index( self.text[start:lpos], start )\n start = pos\n elif lchar.islower() and char.isupper(): # camelcase\n index( self.text[start:pos], start )\n start = pos\n lpos, lchar = pos, char\n\n # last word is missing\n index( self.text[start:], start ) \n\nif __name__ == \"__main__\":\n # 01234567890123456789012345\n test_text = \"a_foobar_FooBar baz golf_CART\"\n test_words = [\"a\", \"foo\", \"bar\", \"baz\", \"golf\", \"cart\", \"fred\"]\n\n index = IndexedText( test_text )\n\n for word in test_words:\n match_start = index.word_start_index( word )\n print match_start, word\n\n" ]
[ 3, 2, 1 ]
[]
[]
[ "find", "python", "regex", "string" ]
stackoverflow_0002127188_find_python_regex_string.txt
Q: Easy to use time-stamps in Python I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal. As of now, I use the time.ctime() function to generate time-stamps that are visually friendly. The journal entries thus look like: Thu Jan 21 19:59:47 2010 Did something Thu Jan 21 20:01:07 2010 Did something else Now, I would like to be able to use these time-stamps to do some searching/querying. I need to be able to search, for example, for "2010", or "feb 2010", or "23 feb 2010". My questions are: 1) What time module(s) should I use: time vs datetime? 2) What would be an appropriate way of creating and using the time-stamp objects? Many thanks! A: You might want to consider changing to ISO 8601. Will help with sorting for example, or transferring data between different systems. A: Option 1: Don't change anything. Use time.strptime to parse your timestamps. Option 2: Change to datetime. You can format the timestamps the same way, and use datetime.strptime to parse them. It doesn't much matter, since the code will be similar. Searching will involve matching months, days or years or some such. Use time tuples for this. Or datetime.datetime objects. Or, searching will involve comparing ranges of times; use time in seconds for this. Or use datetime objects. They will both work and -- for this -- they will be similar in complexity. Doing date calculations (90 days in the future, 3 months in the past, etc.) is the strong suit of datetime. In general, you'll often be happier with datetime because it does more and doesn't involve switching between simple double time and time tuple time.
Easy to use time-stamps in Python
I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal. As of now, I use the time.ctime() function to generate time-stamps that are visually friendly. The journal entries thus look like: Thu Jan 21 19:59:47 2010 Did something Thu Jan 21 20:01:07 2010 Did something else Now, I would like to be able to use these time-stamps to do some searching/querying. I need to be able to search, for example, for "2010", or "feb 2010", or "23 feb 2010". My questions are: 1) What time module(s) should I use: time vs datetime? 2) What would be an appropriate way of creating and using the time-stamp objects? Many thanks!
[ "You might want to consider changing to ISO 8601. Will help with sorting for example, or transferring data between different systems.\n", "Option 1: Don't change anything. Use time.strptime to parse your timestamps.\nOption 2: Change to datetime. You can format the timestamps the same way, and use datetime.strptime to parse them.\nIt doesn't much matter, since the code will be similar. Searching will involve matching months, days or years or some such. Use time tuples for this. Or datetime.datetime objects. Or, searching will involve comparing ranges of times; use time in seconds for this. Or use datetime objects. They will both work and -- for this -- they will be similar in complexity.\nDoing date calculations (90 days in the future, 3 months in the past, etc.) is the strong suit of datetime. \nIn general, you'll often be happier with datetime because it does more and doesn't involve switching between simple double time and time tuple time.\n" ]
[ 9, 7 ]
[]
[]
[ "datetime", "python", "time", "timestamp" ]
stackoverflow_0002127447_datetime_python_time_timestamp.txt
Q: An equivalent to string.ascii_letters for unicode strings in python 2.x? In the "string" module of the standard library, string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Is there a similar constant which would include everything that is considered a letter in unicode? A: You can construct your own constant of Unicode upper and lower case letters with: import unicodedata as ud all_unicode = ''.join(unichr(i) for i in xrange(65536)) unicode_letters = ''.join(c for c in all_unicode if ud.category(c)=='Lu' or ud.category(c)=='Ll') This makes a string 2153 characters long (narrow Unicode Python build). For code like letter in unicode_letters it would be faster to use a set instead: unicode_letters = set(unicode_letters) A: There's no string, but you can check whether a character is a letter using the unicodedata module, in particular its category() function. >>> unicodedata.category(u'a') 'Ll' >>> unicodedata.category(u'A') 'Lu' >>> unicodedata.category(u'5') 'Nd' >>> unicodedata.category(u'ф') # Cyrillic f. 'Ll' >>> unicodedata.category(u'٢') # Arabic-indic numeral for 2. 'Nd' Ll means "letter, lowercase". Lu means "letter, uppercase". Nd means "numeric, digit". A: That would be a pretty massive constant. Unicode currently covers over 100.000 different characters. So the answer is no. The question is why you would need it? There might be some other way of solving whatever your problem is with the unicodedata module, for example. Update: You can download files with all unicode datapoint names and other information from ftp://ftp.unicode.org/, and do loads of interesting stuff with that.
An equivalent to string.ascii_letters for unicode strings in python 2.x?
In the "string" module of the standard library, string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Is there a similar constant which would include everything that is considered a letter in unicode?
[ "You can construct your own constant of Unicode upper and lower case letters with:\nimport unicodedata as ud\nall_unicode = ''.join(unichr(i) for i in xrange(65536))\nunicode_letters = ''.join(c for c in all_unicode\n if ud.category(c)=='Lu' or ud.category(c)=='Ll')\n\nThis makes a string 2153 characters long (narrow Unicode Python build). For code like letter in unicode_letters it would be faster to use a set instead:\nunicode_letters = set(unicode_letters)\n\n", "There's no string, but you can check whether a character is a letter using the unicodedata module, in particular its category() function.\n>>> unicodedata.category(u'a')\n'Ll'\n>>> unicodedata.category(u'A')\n'Lu'\n>>> unicodedata.category(u'5')\n'Nd'\n>>> unicodedata.category(u'ф') # Cyrillic f.\n'Ll'\n>>> unicodedata.category(u'٢') # Arabic-indic numeral for 2.\n'Nd'\n\nLl means \"letter, lowercase\". Lu means \"letter, uppercase\". Nd means \"numeric, digit\".\n", "That would be a pretty massive constant. Unicode currently covers over 100.000 different characters. So the answer is no.\nThe question is why you would need it? There might be some other way of solving whatever your problem is with the unicodedata module, for example.\nUpdate: You can download files with all unicode datapoint names and other information from ftp://ftp.unicode.org/, and do loads of interesting stuff with that.\n" ]
[ 11, 7, 0 ]
[ "As mentioned in previous answers, the string would indeed be way too long. So, you have to target (a) specific language(s).\n[EDIT: I realized it was the case for my original intended use, and for most uses, I guess. However, in the meantime, Mark Tolonen gave a good answer to the question as it was asked, so I chose his answer, although I used the following solution]\nThis is easily done with the \"locale\" module:\nimport locale\nimport string\ncode = 'fr_FR' ## Do NOT specify encoding (see below)\nlocale.setlocale(locale.LC_CTYPE, code)\nencoding = locale.getlocale()[1]\nletters = string.letters.decode(encoding)\n\nwith \"letters\" being a 117-character-long unicode string.\nApparently, string.letters is dependant on the default encoding for the selected language code, rather than on the language itself. Setting the locale to fr_FR or de_DE or es_ES will update string.letters to the same value (since they are all encoded in ISO8859-1 by default).\nIf you add an encoding to the language code (de_DE.UTF-8), the default encoding will be used instead for string.letters. That would cause a UnicodeDecodeError if you used the rest of the above code.\n" ]
[ -1 ]
[ "python", "python_2.x", "unicode" ]
stackoverflow_0002126551_python_python_2.x_unicode.txt
Q: Finding fast default aliases in Python Is there a faster way to do the following for much larger dicts? aliases = { 'United States': 'USA', 'United Kingdom': 'UK', 'Russia': 'RUS', } if countryname in aliases: countryname = aliases[countryname] A: Your solution is fine, as "in" is 0(1) for dictionaries. You could do something like this to save some typing: countryname = aliases.get(countryname, countryname) (But I find your code a lot easier to read than that) When it comes to speed, what solution is best would depend on if there will be a majority of "hits" or "misses". But that would probably be in the nanosecond range when it comes to difference. A: If your list fits in memory, dicts are the fastest way to go. As S.Mark points out, you are doing two lookups where one will do, either with: countryname = aliases.get(countryname, countryname) (which will leave countryname unchanged if it isn't in the dictionary), or: try: countryname = aliases[countryname] except KeyError: pass A: Accessing with .get could be faster than checking and assigning in variable aliases.get(countryname) And if countryname is not exists in aliases it will return None. A: If your dictionary is very large and you expect many of your checks not to find a match, then you might want to consider a Bloom filter or one of it's derivatives and allow false positives. Alternatively, because your keys can be sorted (and/or have a derived values), you could implement a bisection or other root-finding algorithm. First, I'd figure out exactly how Python implements dictionary look-ups, so you are not just re-inventing the wheel. Also, a pure-Python implementation of these could be quite slow if it involves a lot of iteration. Consider Cython, Numpy, or F2Py to get truly optimized. (if you are dealing with just country names, then I don't think you are dealing with mappings large enough to warrant any of my suggestions), but if you are looking at doing some kind of spell-check implementation, then.. Good luck.
Finding fast default aliases in Python
Is there a faster way to do the following for much larger dicts? aliases = { 'United States': 'USA', 'United Kingdom': 'UK', 'Russia': 'RUS', } if countryname in aliases: countryname = aliases[countryname]
[ "Your solution is fine, as \"in\" is 0(1) for dictionaries.\nYou could do something like this to save some typing:\ncountryname = aliases.get(countryname, countryname)\n\n(But I find your code a lot easier to read than that)\nWhen it comes to speed, what solution is best would depend on if there will be a majority of \"hits\" or \"misses\". But that would probably be in the nanosecond range when it comes to difference.\n", "If your list fits in memory, dicts are the fastest way to go. As S.Mark points out, you are doing two lookups where one will do, either with:\ncountryname = aliases.get(countryname, countryname)\n\n(which will leave countryname unchanged if it isn't in the dictionary), or:\ntry:\n countryname = aliases[countryname]\nexcept KeyError:\n pass\n\n", "Accessing with .get could be faster than checking and assigning in variable\naliases.get(countryname)\n\nAnd if countryname is not exists in aliases it will return None.\n", "If your dictionary is very large and you expect many of your checks not to find a match, then you might want to consider a Bloom filter or one of it's derivatives and allow false positives.\nAlternatively, because your keys can be sorted (and/or have a derived values), you could implement a bisection or other root-finding algorithm. \nFirst, I'd figure out exactly how Python implements dictionary look-ups, so you are not just re-inventing the wheel.\nAlso, a pure-Python implementation of these could be quite slow if it involves a lot of iteration. Consider Cython, Numpy, or F2Py to get truly optimized.\n(if you are dealing with just country names, then I don't think you are dealing with mappings large enough to warrant any of my suggestions), but if you are looking at doing some kind of spell-check implementation, then..\nGood luck.\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002127202_python.txt
Q: Python Syntax Error but looks fine to me. Help? Right now I'm working on a Tetris Game (sorta, I found a Tetris example for Python on a website, I've been copying it but adding some of my own stuff), and just finished writing all the code but have had a couple syntax errors. I've been able to fix all of them but this last syntax error is confusing to me. def pieceDropped(self): for i in range(4): x = self.curX + self.curPiece.x(i) y = self.curY - self.curPiece.y(i) self.setShapeAt(x, y, self.curPiece.shape() self.removeFullLines() The specific syntax error is on the last line of the function and I don't understand why, the indentation and whitespace all seems correct. So could someone explain how this is a syntax error? A: You didn't close the parenthesis of self.setShapeAt. A: There's an extra whitespace on the last line - just ahead self.removeFullLines(). Its indenting is thus not the same as the for line's indenting. EDIT: Seems to be corrected now. Always use the same indent sequence - choose either tabs, or n whitespaces. But be consistent. Some editors (such as VIM) are able to insert the appropriate number of whitespaces whenever you hit tab.
Python Syntax Error but looks fine to me. Help?
Right now I'm working on a Tetris Game (sorta, I found a Tetris example for Python on a website, I've been copying it but adding some of my own stuff), and just finished writing all the code but have had a couple syntax errors. I've been able to fix all of them but this last syntax error is confusing to me. def pieceDropped(self): for i in range(4): x = self.curX + self.curPiece.x(i) y = self.curY - self.curPiece.y(i) self.setShapeAt(x, y, self.curPiece.shape() self.removeFullLines() The specific syntax error is on the last line of the function and I don't understand why, the indentation and whitespace all seems correct. So could someone explain how this is a syntax error?
[ "You didn't close the parenthesis of self.setShapeAt.\n", "There's an extra whitespace on the last line - just ahead self.removeFullLines(). Its indenting is thus not the same as the for line's indenting. EDIT: Seems to be corrected now.\nAlways use the same indent sequence - choose either tabs, or n whitespaces. But be consistent. Some editors (such as VIM) are able to insert the appropriate number of whitespaces whenever you hit tab. \n" ]
[ 7, 0 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0002127735_python_syntax_error.txt
Q: Python sqlite3 "unable to open database file" on windows I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts some rows into the db. However, at some point in the insertion process, the program dies with this message: sqlite3.OperationalError: unable to open database file However, before it dies, there are several rows that are properly added to the database. Here is the code which specifically handles the insertion: idx = 0 lst_to_ins = [] for addl_img in all_jpegs: lst_to_ins.append((addl_img['col1'], addl_img['col2'])) idx = idx + 1 if idx % 10 == 0: logging.debug('adding rows [%s]', lst_to_ins) conn.executemany(ins_sql, lst_to_ins) conn.commit() lst_to_ins = [] logging.debug('added 10 rows [%d]', idx) if len(lst_to_ins) > 0: conn.executemany(ins_sql, lst_to_ins) conn.commit() logging.debug('adding the last few rows to the db') This code inserts anywhere from 10 to 400 rows, then dies with the error message conn.executemany(ins_sql, lst_to_ins) sqlite3.OperationalError: unable to open database file How is it possible that I can insert some rows, but then get this error? A: SQLite does not have record locking; it uses a simple locking mechanism that locks the entire database file briefly during a write. It sounds like you are running into a lock that hasn't cleared yet. The author of SQLite recommends that you create a transaction prior to doing your inserts, and then complete the transaction at the end. This causes SQLite to queue the insert requests, and perform them using a single file lock when the transaction is committed. In the newest version of SQLite, the locking mechanism has been enhanced, so it might not require a full file lock anymore. A: same error here on windows 7 (python 2.6, django 1.1.1 and sqllite) after some records inserted correctly: sqlite3.OperationalError: unable to open database file I ran my script from Eclipse different times and always got that error. But as I ran it from the command line (after setting PYTHONPATH and DJANGO_SETTINGS_MODULE) it worked as a charm... just my 2 cents!
Python sqlite3 "unable to open database file" on windows
I am working on a windows vista machine in python 3.1.1. I am trying to insert a large number of rows into a SQLite3 db. The file exists, and my program properly inserts some rows into the db. However, at some point in the insertion process, the program dies with this message: sqlite3.OperationalError: unable to open database file However, before it dies, there are several rows that are properly added to the database. Here is the code which specifically handles the insertion: idx = 0 lst_to_ins = [] for addl_img in all_jpegs: lst_to_ins.append((addl_img['col1'], addl_img['col2'])) idx = idx + 1 if idx % 10 == 0: logging.debug('adding rows [%s]', lst_to_ins) conn.executemany(ins_sql, lst_to_ins) conn.commit() lst_to_ins = [] logging.debug('added 10 rows [%d]', idx) if len(lst_to_ins) > 0: conn.executemany(ins_sql, lst_to_ins) conn.commit() logging.debug('adding the last few rows to the db') This code inserts anywhere from 10 to 400 rows, then dies with the error message conn.executemany(ins_sql, lst_to_ins) sqlite3.OperationalError: unable to open database file How is it possible that I can insert some rows, but then get this error?
[ "SQLite does not have record locking; it uses a simple locking mechanism that locks the entire database file briefly during a write. It sounds like you are running into a lock that hasn't cleared yet.\nThe author of SQLite recommends that you create a transaction prior to doing your inserts, and then complete the transaction at the end. This causes SQLite to queue the insert requests, and perform them using a single file lock when the transaction is committed.\nIn the newest version of SQLite, the locking mechanism has been enhanced, so it might not require a full file lock anymore.\n", "same error here on windows 7 (python 2.6, django 1.1.1 and sqllite) after some records inserted correctly: sqlite3.OperationalError: unable to open database file\nI ran my script from Eclipse different times and always got that error. But as I ran it from the command line (after setting PYTHONPATH and DJANGO_SETTINGS_MODULE) it worked as a charm...\njust my 2 cents!\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sqlite", "windows_vista" ]
stackoverflow_0001529527_python_sqlite_windows_vista.txt
Q: Python - Moving entire text between two .doc files I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target .doc file is not the only one but can be many of them. All the target .doc files are always in the same folder (same path) but all of them don't have the same name. The .doc file FROM where I want to move entire text is only one, always in the same folder (same path) and always with the same file name. Names of the target are only similar but as I have said before, not the same. Here is the point of whole script: Target .doc files have the names: HD1.doc HD2.doc HD3.doc HD4.doc and so on What I would like to have is moved the entire (but really all of the text, must be 100% all) text into the .doc file with the highest ( ! ) number. The target .doc files will always start with ''HD'' and always be similar to above examples. It is possible that the doc file (target file) is only one, so only HD1.doc. Therefore ''1'' is the maximum number and the text is moved into this file. Sometimes the target file is empty but usually won't be. If it won't be then the text should be moved to the end of the text, into first new line (no empty lines inbetween). So for example in the target file which has the maximum number in its name is the following text: a b c In the file from which I want to move the text is: d This means I need in the target file this: a b c d But no empty lines anywhere. I have found (showing three different codes): http://paste.pocoo.org/show/169309/ But neither of them make any sense to me. I know I would need to begin with finding the correct target file (correct HDX file where X is the highest number - again all HD files are and will be in the same folder) but no idea how to do this. I meant microsoft office word .doc files. They have "pure text". What I mean with pure text is that Im also able to see them in notepad (.txt). But I need to work with .doc extensions. Python is because I need this as automated system, so I wouldn't even need to open any file. Why exsactly python and not any other programming language? The reason for this is because recently I have started learning python and need this script for my work - Python is the "only" programming language that Im interested for and thats why I would like to make this script with it. By "really 100%" I meant that entire text (everything in source file - every single line, no matter if there are 2 or several thousands) would be moved to correct (which one is correct is described in my first post) target file. I cannot move the whole file because I need to move entire text (everything gathered - source file will be always the same but contest of text will be always different - different words in lines) and not whole file because I need the text in correct .doc file with correct name and together (with "together" i mean inside the same file) with already exsisting text IF is there anything already in the target file. Because its possible that the correct target file is empty also. If someone could suggest me anything, I would really appreciate it. Thank you, best wishes. I have tried to ask on openoffice forum but they don't answer. Seen the code could be something like this: from time import sleep import win32com.client from win32com.client import Dispatch wordApp = win32com.client.Dispatch('Word.Application') wordApp.Visible=False wordApp.Documents.Open('C:\\test.doc') sleep(5) HD1 = wordApp.Documents.Open('C:\\test.doc') #HD1 word document as object. HD1.Content.Select.Copy() #Selects entire document and copies it. ` But I have no idea what does that mean. Also I cannot use the .doc file like that because I never know what is the correct filename (HDX.doc where X is maximum integer number, all HD are in same directory path) of the file and therefore I cannot use its name - the script should find the correct file. Also ''filename'' = wordApp.Documents.open... would for sure give me syntax error. :-( A: Openoffice ships with full python scripting support, have a look: http://wiki.services.openoffice.org/wiki/Python Might be easier than trying to mess around with MS Word and COM apis. A: So you want to take the text from a doc file, and append it to the end of the text in another doc file. And the problem here is that's MS Word files. It's a proprietary format, and as far as I know there is not module to access them from Python. But if you are on Windows, you can access them via the COM API, but that's pretty complicated. But look into that. Otehrwise I recommend you to not us MS Word files. The above sounds like some sort of logging facility, and it sounds like a bad idea to use Word files for this, it's too fragile.
Python - Moving entire text between two .doc files
I have been having this issue for a while and cannot figure how should I start to do this with python. My OS is windows xp pro. I need the script that moves entire (100% of the text) text from one .doc file to another. But its not so easy as it sounds. The target .doc file is not the only one but can be many of them. All the target .doc files are always in the same folder (same path) but all of them don't have the same name. The .doc file FROM where I want to move entire text is only one, always in the same folder (same path) and always with the same file name. Names of the target are only similar but as I have said before, not the same. Here is the point of whole script: Target .doc files have the names: HD1.doc HD2.doc HD3.doc HD4.doc and so on What I would like to have is moved the entire (but really all of the text, must be 100% all) text into the .doc file with the highest ( ! ) number. The target .doc files will always start with ''HD'' and always be similar to above examples. It is possible that the doc file (target file) is only one, so only HD1.doc. Therefore ''1'' is the maximum number and the text is moved into this file. Sometimes the target file is empty but usually won't be. If it won't be then the text should be moved to the end of the text, into first new line (no empty lines inbetween). So for example in the target file which has the maximum number in its name is the following text: a b c In the file from which I want to move the text is: d This means I need in the target file this: a b c d But no empty lines anywhere. I have found (showing three different codes): http://paste.pocoo.org/show/169309/ But neither of them make any sense to me. I know I would need to begin with finding the correct target file (correct HDX file where X is the highest number - again all HD files are and will be in the same folder) but no idea how to do this. I meant microsoft office word .doc files. They have "pure text". What I mean with pure text is that Im also able to see them in notepad (.txt). But I need to work with .doc extensions. Python is because I need this as automated system, so I wouldn't even need to open any file. Why exsactly python and not any other programming language? The reason for this is because recently I have started learning python and need this script for my work - Python is the "only" programming language that Im interested for and thats why I would like to make this script with it. By "really 100%" I meant that entire text (everything in source file - every single line, no matter if there are 2 or several thousands) would be moved to correct (which one is correct is described in my first post) target file. I cannot move the whole file because I need to move entire text (everything gathered - source file will be always the same but contest of text will be always different - different words in lines) and not whole file because I need the text in correct .doc file with correct name and together (with "together" i mean inside the same file) with already exsisting text IF is there anything already in the target file. Because its possible that the correct target file is empty also. If someone could suggest me anything, I would really appreciate it. Thank you, best wishes. I have tried to ask on openoffice forum but they don't answer. Seen the code could be something like this: from time import sleep import win32com.client from win32com.client import Dispatch wordApp = win32com.client.Dispatch('Word.Application') wordApp.Visible=False wordApp.Documents.Open('C:\\test.doc') sleep(5) HD1 = wordApp.Documents.Open('C:\\test.doc') #HD1 word document as object. HD1.Content.Select.Copy() #Selects entire document and copies it. ` But I have no idea what does that mean. Also I cannot use the .doc file like that because I never know what is the correct filename (HDX.doc where X is maximum integer number, all HD are in same directory path) of the file and therefore I cannot use its name - the script should find the correct file. Also ''filename'' = wordApp.Documents.open... would for sure give me syntax error. :-(
[ "Openoffice ships with full python scripting support, have a look: http://wiki.services.openoffice.org/wiki/Python\nMight be easier than trying to mess around with MS Word and COM apis.\n", "So you want to take the text from a doc file, and append it to the end of the text in another doc file. And the problem here is that's MS Word files. It's a proprietary format, and as far as I know there is not module to access them from Python.\nBut if you are on Windows, you can access them via the COM API, but that's pretty complicated. But look into that. Otehrwise I recommend you to not us MS Word files. The above sounds like some sort of logging facility, and it sounds like a bad idea to use Word files for this, it's too fragile.\n" ]
[ 3, 1 ]
[]
[]
[ ".doc", "python", "text" ]
stackoverflow_0002127410_.doc_python_text.txt
Q: Django, making a page activate for a fixed time Greetings I am hacking Django and trying to test something such as: Like woot.com , I want to sell "an item per day", so only one item will be available for that day (say the default www.mysite.com will be redirected to that item), Assume my urls for calling these items will be such: www.mysite.com/item/<number> my model for item: class Item(models.Model): item_name = models.CharField(max_length=30) price = models.FloatField() content = models.TextField() #keeps all the html content start_time = models.DateTimeField() end_time = models.DateTimeField() And my view for rendering this: def results(request, item_id): item = get_object_or_404(Item, pk=item_id) now = datetime.now() if item.start_time > now: #render and return some "not started yet" error templete elif item.end_time < now: #render and return some "item selling ended" error templete else: # render the real templete for selling this item What would be the efficient and clever model & templete for achieving this ? A: It seems you've got the basics figured out, so I'm assuming you're asking for polishing suggestions... A few ideas in this vein: I think I'd have a separate URL like /items/today/ for this, or perhaps just /today/. You'll want to use the date components of datime.datetime.now() only. The whole thing is an object containing the current time specified to a microsecond's precision. How about using a single base template for all three cases and inheriting from it to change a block containing either the button to click on when buying, the price etc., or a note saying that the item is not being sold yet / any more. Then people can still use the numbered URLs when saying things like See what I bought yesterday, you have to go to that site in an e-mail. ;-) A: I have a photo of the day feature on my site. I have a model that represents today's photo, and a cron job runs a custom management command at midnight to update it with the next photo in the sequence (also a model). So all my view has to do is retrieve the current photo from the database.
Django, making a page activate for a fixed time
Greetings I am hacking Django and trying to test something such as: Like woot.com , I want to sell "an item per day", so only one item will be available for that day (say the default www.mysite.com will be redirected to that item), Assume my urls for calling these items will be such: www.mysite.com/item/<number> my model for item: class Item(models.Model): item_name = models.CharField(max_length=30) price = models.FloatField() content = models.TextField() #keeps all the html content start_time = models.DateTimeField() end_time = models.DateTimeField() And my view for rendering this: def results(request, item_id): item = get_object_or_404(Item, pk=item_id) now = datetime.now() if item.start_time > now: #render and return some "not started yet" error templete elif item.end_time < now: #render and return some "item selling ended" error templete else: # render the real templete for selling this item What would be the efficient and clever model & templete for achieving this ?
[ "It seems you've got the basics figured out, so I'm assuming you're asking for polishing suggestions... A few ideas in this vein:\n\nI think I'd have a separate URL like /items/today/ for this, or perhaps just /today/.\nYou'll want to use the date components of datime.datetime.now() only. The whole thing is an object containing the current time specified to a microsecond's precision.\nHow about using a single base template for all three cases and inheriting from it to change a block containing either the button to click on when buying, the price etc., or a note saying that the item is not being sold yet / any more. Then people can still use the numbered URLs when saying things like See what I bought yesterday, you have to go to that site in an e-mail. ;-)\n\n", "I have a photo of the day feature on my site. I have a model that represents today's photo, and a cron job runs a custom management command at midnight to update it with the next photo in the sequence (also a model). So all my view has to do is retrieve the current photo from the database.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002128093_django_django_models_django_views_python.txt
Q: Google App Engine: Add task to queue from a task I need to track data from another website. Since it's spread over 60+ pages, I intend to use a daily cron job to add a task to the queue. This task then should take care of one page and depending on some checks, put another instance of itself on the queue for the next page. Now a simple taskqueue.add(url='/path/to_self', params=control) in the get of my webapp.RequestHandler class for this task leads to a "POST /path/to_self HTTP/1.1" 405 - Is there a way to get this to work, or is it simply not possible to add tasks to the queue from within tasks? A: It's possible to add tasks from within tasks. I'm doing it in my application. It's very useful when you want to migrate a large set of entities : one task processes a small chunk of entities then adds itself to the queue in order to process the rest until the migration is over. I am not sure what is the problem with your code. Have you implemented the post(self) method in your RequestHandler class ? Task calls default to the POST method.
Google App Engine: Add task to queue from a task
I need to track data from another website. Since it's spread over 60+ pages, I intend to use a daily cron job to add a task to the queue. This task then should take care of one page and depending on some checks, put another instance of itself on the queue for the next page. Now a simple taskqueue.add(url='/path/to_self', params=control) in the get of my webapp.RequestHandler class for this task leads to a "POST /path/to_self HTTP/1.1" 405 - Is there a way to get this to work, or is it simply not possible to add tasks to the queue from within tasks?
[ "It's possible to add tasks from within tasks. I'm doing it in my application.\nIt's very useful when you want to migrate a large set of entities : one task processes a small chunk of entities then adds itself to the queue in order to process the rest until the migration is over.\nI am not sure what is the problem with your code.\nHave you implemented the post(self) method in your RequestHandler class ? Task calls default to the POST method.\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "python", "task", "task_queue" ]
stackoverflow_0002127981_google_app_engine_python_task_task_queue.txt
Q: python automate ffmpeg conversion from upload directory I have a upload script done. But i need to figure out how to make a script that I can run as a daemon in python to handle the conversion part and moving the file thats converted to its final resting place. heres what I have so far for the directory watcher script: #!/usr/bin/python import os import pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventCodes import sys, time, syslog, config from os import system from daemon import Daemon class myLog(ProcessEvent): def process_IN_CREATE(self, event): syslog.syslog("creating: " + event.pathname) def process_IN_DELETE(self, event): syslog.syslog("deleting: " + event.pathname) def process_default(self, event): syslog.syslog("default: " + event.pathname) class MyDaemon(Daemon): def loadConfig(self): """Load user configuration file""" self.config = {} self.parser = ConfigParser.ConfigParser() if not os.path.isfile(self.configfile): self.parser.write(open(self.configfile, 'w')) self.parser.readfp(open(self.configfile, 'r')) variables = { \ 'mplayer': ['paths', self.findProgram("mplayer")], \ 'mencoder': ['paths', self.findProgram("mencoder")], \ 'tcprobe': ['paths', self.findProgram("tcprobe")], \ 'transcode': ['paths', self.findProgram("transcode")], \ 'ogmmerge': ['paths', self.findProgram("ogmmerge")], \ 'outputdir': ['paths', os.path.expanduser("~")], \ } for key in variables.keys(): self.cautiousLoad(variables[key][0], key, variables[key][1]) def cautiousLoad(self, section, var, default): """Load a configurable variable within an exception clause, in case variable is not in configuration file""" try: self.config[var] = int(self.parser.get(section, var)) except: self.config[var] = default try: self.parser.set(section, var, default) except: self.parser.add_section(section) self.parser.set(section, var, default) self.parser.write(open(self.configfile, 'w')) def findProgram(self, program): """Looks for program in path, and returns full path if found""" for path in config.paths: if os.path.isfile(os.path.join(path, program)): return os.path.join(path, program) self.ui_configError(program) def run(self): syslog.openlog('mediaConvertor', syslog.LOG_PID,syslog.LOG_DAEMON) syslog.syslog('daemon started, entering loop') wm = WatchManager() mask = IN_DELETE | IN_CREATE notifier = ThreadedNotifier(wm, myLog()) notifier.start() wdd = wm.add_watch(self.config['outputdir'], mask, rec=True) while True: time.sleep(1) wm.rm_watch(wdd.values()) notifier.stop() syslog.syslog('exiting media convertor') syslog.closelog() if __name__ == "__main__": daemon = MyDaemon('/tmp/mediaconvertor.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.run() if 'stop' == sys.argv[1]: daemon.stop() if 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown Command" sys.exit(2) sys.exit(0) else: print "Usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) not sure where to go from here. A: I don't run on Linux and have never used the inotify capabilities you are using here. I'll describe how I would do things generically. In the simplest case, you need to check if there's a new file in the upload directory and when there is one, start doing the conversion notification. To check if there are new files you can do something like: import os import time def watch_directory(dirname="."): old_files = set(os.listdir(dirname)) while 1: time.sleep(1) new_files = set(os.listdir(dirname)) diff = new_files - old_files if diff: print "New files", diff old_files = new_files watch_directory() You may be able to minimize some filesystem overhead by first stat'ing the directory to see if there are any changes. def watch_directory(dirname="."): old_files = set(os.listdir(dirname)) old_stat = os.stat(dirname) while 1: time.sleep(1) new_stat = os.stat(dirname) if new_stat == old_stat: continue new_files = set(os.listdir(dirname)) diff = new_files - old_files if diff: print "New files", diff old_stat = new_stat old_files = new_files With inotify I think this is all handled for you, and you put your code into process_IN_CREATE() which gets called when a new file is available. One bit of trickiness - how does the watcher know that the upload is complete? What happens if the upload is canceled part-way through uploading? This could be as simple as having the web server do a rename() to use one extension during upload and another extension when done. Once you know the file, use subprocess.Popen(conversion_program, "new_filename") or os.system("conversion_program new_filename &") to spawn off the conversion in a new process which does the conversion. You'll need to handle things like error reporting, as when the input isn't in the right format. It should also clean up, meaning that once the conversion is done it should remove the input file from consideration. This might be as easy as deleting the file. You'll also need to worry about restarting any conversions which were killed. If the machine does down, how does the restarted watcher know which data file conversions were also killed and need to be restarted. But this might be doable as a manual step.
python automate ffmpeg conversion from upload directory
I have a upload script done. But i need to figure out how to make a script that I can run as a daemon in python to handle the conversion part and moving the file thats converted to its final resting place. heres what I have so far for the directory watcher script: #!/usr/bin/python import os import pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventCodes import sys, time, syslog, config from os import system from daemon import Daemon class myLog(ProcessEvent): def process_IN_CREATE(self, event): syslog.syslog("creating: " + event.pathname) def process_IN_DELETE(self, event): syslog.syslog("deleting: " + event.pathname) def process_default(self, event): syslog.syslog("default: " + event.pathname) class MyDaemon(Daemon): def loadConfig(self): """Load user configuration file""" self.config = {} self.parser = ConfigParser.ConfigParser() if not os.path.isfile(self.configfile): self.parser.write(open(self.configfile, 'w')) self.parser.readfp(open(self.configfile, 'r')) variables = { \ 'mplayer': ['paths', self.findProgram("mplayer")], \ 'mencoder': ['paths', self.findProgram("mencoder")], \ 'tcprobe': ['paths', self.findProgram("tcprobe")], \ 'transcode': ['paths', self.findProgram("transcode")], \ 'ogmmerge': ['paths', self.findProgram("ogmmerge")], \ 'outputdir': ['paths', os.path.expanduser("~")], \ } for key in variables.keys(): self.cautiousLoad(variables[key][0], key, variables[key][1]) def cautiousLoad(self, section, var, default): """Load a configurable variable within an exception clause, in case variable is not in configuration file""" try: self.config[var] = int(self.parser.get(section, var)) except: self.config[var] = default try: self.parser.set(section, var, default) except: self.parser.add_section(section) self.parser.set(section, var, default) self.parser.write(open(self.configfile, 'w')) def findProgram(self, program): """Looks for program in path, and returns full path if found""" for path in config.paths: if os.path.isfile(os.path.join(path, program)): return os.path.join(path, program) self.ui_configError(program) def run(self): syslog.openlog('mediaConvertor', syslog.LOG_PID,syslog.LOG_DAEMON) syslog.syslog('daemon started, entering loop') wm = WatchManager() mask = IN_DELETE | IN_CREATE notifier = ThreadedNotifier(wm, myLog()) notifier.start() wdd = wm.add_watch(self.config['outputdir'], mask, rec=True) while True: time.sleep(1) wm.rm_watch(wdd.values()) notifier.stop() syslog.syslog('exiting media convertor') syslog.closelog() if __name__ == "__main__": daemon = MyDaemon('/tmp/mediaconvertor.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.run() if 'stop' == sys.argv[1]: daemon.stop() if 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown Command" sys.exit(2) sys.exit(0) else: print "Usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) not sure where to go from here.
[ "I don't run on Linux and have never used the inotify capabilities you are using here. I'll describe how I would do things generically.\nIn the simplest case, you need to check if there's a new file in the upload directory and when there is one, start doing the conversion notification.\nTo check if there are new files you can do something like:\nimport os\nimport time\n\ndef watch_directory(dirname=\".\"):\n old_files = set(os.listdir(dirname))\n while 1:\n time.sleep(1)\n new_files = set(os.listdir(dirname))\n diff = new_files - old_files\n if diff:\n print \"New files\", diff\n old_files = new_files\n\nwatch_directory()\n\nYou may be able to minimize some filesystem overhead by first stat'ing the directory to see if there are any changes.\ndef watch_directory(dirname=\".\"):\n old_files = set(os.listdir(dirname))\n old_stat = os.stat(dirname)\n while 1:\n time.sleep(1)\n new_stat = os.stat(dirname)\n if new_stat == old_stat:\n continue\n new_files = set(os.listdir(dirname))\n diff = new_files - old_files\n if diff:\n print \"New files\", diff\n old_stat = new_stat\n old_files = new_files\n\nWith inotify I think this is all handled for you, and you put your code into process_IN_CREATE() which gets called when a new file is available.\nOne bit of trickiness - how does the watcher know that the upload is complete? What happens if the upload is canceled part-way through uploading? This could be as simple as having the web server do a rename() to use one extension during upload and another extension when done.\nOnce you know the file, use subprocess.Popen(conversion_program, \"new_filename\") or os.system(\"conversion_program new_filename &\") to spawn off the conversion in a new process which does the conversion. You'll need to handle things like error reporting, as when the input isn't in the right format. It should also clean up, meaning that once the conversion is done it should remove the input file from consideration. This might be as easy as deleting the file.\nYou'll also need to worry about restarting any conversions which were killed. If the machine does down, how does the restarted watcher know which data file conversions were also killed and need to be restarted. But this might be doable as a manual step.\n" ]
[ 3 ]
[]
[]
[ "ffmpeg", "inotify", "python" ]
stackoverflow_0002123435_ffmpeg_inotify_python.txt
Q: Preferred way to store/retrieve python data I would like to include data files with a Python package. Is the best place to put them inside the actual package as suggested here, i.e. setup.py src/ mypkg/ __init__.py module.py data/ tables.dat spoons.dat forks.dat or is there a better way to do this? What is the best way to retrieve a datafile from inside python? Should I use mypkg.__path__ + 'data/tables.dat' for example, or should I use pkgutil.getdata('mypkg','tables.dat') or again, is there another better way to do this? Generally speaking, what is the current preferred way to deal with data inside Python packages? A: pkgutil means you can load the data even if the package is installed in a ZIP file, so it's preferable if you want to support that. Storing it in a data directory like that is fine, I do that all the time. :)
Preferred way to store/retrieve python data
I would like to include data files with a Python package. Is the best place to put them inside the actual package as suggested here, i.e. setup.py src/ mypkg/ __init__.py module.py data/ tables.dat spoons.dat forks.dat or is there a better way to do this? What is the best way to retrieve a datafile from inside python? Should I use mypkg.__path__ + 'data/tables.dat' for example, or should I use pkgutil.getdata('mypkg','tables.dat') or again, is there another better way to do this? Generally speaking, what is the current preferred way to deal with data inside Python packages?
[ "pkgutil means you can load the data even if the package is installed in a ZIP file, so it's preferable if you want to support that. Storing it in a data directory like that is fine, I do that all the time. :)\n" ]
[ 3 ]
[ "You should store your data as a Python data structure vía the Pickle module. That way, when you call it (load it) the data is ready to be used, and you dont need to process it in every script. \nAs for the location, it makes sense that you store it in a way that is transparent and clear to the user, the following seems intuitive to me: \nfrom package import data\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0002128399_python.txt