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: How to embed the Python interpreter in a Qt app? Is there a straightforward way to embed the Python interpreter in a Qt application? I am hoping for a cross-platform solution if possible. A: This is the purpose of PythonQt. It supports Windows, Linux, and Mac OS.
How to embed the Python interpreter in a Qt app?
Is there a straightforward way to embed the Python interpreter in a Qt application? I am hoping for a cross-platform solution if possible.
[ "This is the purpose of PythonQt. It supports Windows, Linux, and Mac OS.\n" ]
[ 3 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0002742636_python_qt.txt
Q: dropEvent not being called on custom view in PyQt4? I'm trying to create a custom QTableView that will respond to drag and drop actions. So far, I have something like the following: from PyQt4.QtCore import * from PyQt4.QtGui import * class FooTableView(QTableView): def __init__(self, parent = None): QTableView.__init__(self, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): print "dragged!" def dropEvent(self, event): print "dropped!" The problem is that when I drag a file into this view, I see "dragged!" but upon releasing the file over the view, I do not see "dropped!". Is there something else I need to do in order to make this functionality work? A: Ok, I think I figured it out. The event must be accepted in dragEnterEvent in order for it to make it to dropEvent.
dropEvent not being called on custom view in PyQt4?
I'm trying to create a custom QTableView that will respond to drag and drop actions. So far, I have something like the following: from PyQt4.QtCore import * from PyQt4.QtGui import * class FooTableView(QTableView): def __init__(self, parent = None): QTableView.__init__(self, parent) self.setAcceptDrops(True) def dragEnterEvent(self, event): print "dragged!" def dropEvent(self, event): print "dropped!" The problem is that when I drag a file into this view, I see "dragged!" but upon releasing the file over the view, I do not see "dropped!". Is there something else I need to do in order to make this functionality work?
[ "Ok, I think I figured it out. The event must be accepted in dragEnterEvent in order for it to make it to dropEvent.\n" ]
[ 0 ]
[]
[]
[ "drag_and_drop", "pyqt4", "python" ]
stackoverflow_0002742368_drag_and_drop_pyqt4_python.txt
Q: How do I use a ListProperty(users.user) in a djangoforms.ModelForm on Google AppEngine? I have been looking around a bit for info on how to do this. Essentially I have a Model: class SharableUserAsset(db.Model): name = StringProperty() users = ListProperty(users.User) My questions are: What is the best way to associate users to this value where they are not authenticated, visa vi invite from contacts list etc.? Is there a reasonable way to present a list control easily in a djangoforms.ModelForm? Once a user logs in I want to be able to check if that user is in the list for any number of SharableUserAsset class "records", how do I do that? Does user evaluate as a match to an email address or is there a way to look up a valid user against an email address? A: In a query, comparing a list property to a value performs the test against the list members: list_property = value tests if the value appears anywhere in the list http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ListProperty So to find all the SharableUserAssets associated with the current user just query like: user = users.get_current_user() assets = SharableUserAsset.gql("WHERE users = :1", user) Here's another reference dealing with ListProperty objects. An App Engine User object contains an email address, and the email address can be retireved using the .email() method.
How do I use a ListProperty(users.user) in a djangoforms.ModelForm on Google AppEngine?
I have been looking around a bit for info on how to do this. Essentially I have a Model: class SharableUserAsset(db.Model): name = StringProperty() users = ListProperty(users.User) My questions are: What is the best way to associate users to this value where they are not authenticated, visa vi invite from contacts list etc.? Is there a reasonable way to present a list control easily in a djangoforms.ModelForm? Once a user logs in I want to be able to check if that user is in the list for any number of SharableUserAsset class "records", how do I do that? Does user evaluate as a match to an email address or is there a way to look up a valid user against an email address?
[ "\nIn a query, comparing a list property\n to a value performs the test against\n the list members: list_property =\n value tests if the value appears\n anywhere in the list\n\nhttp://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ListProperty\nSo to find all the SharableUserAssets associated with the current user just query like:\nuser = users.get_current_user()\nassets = SharableUserAsset.gql(\"WHERE users = :1\", user)\n\nHere's another reference dealing with ListProperty objects.\nAn App Engine User object contains an email address, and the email address can be retireved using the .email() method.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "single_sign_on" ]
stackoverflow_0002742864_google_app_engine_python_single_sign_on.txt
Q: Creating a simple command line interface (CLI) using a python server (TCP sock) and few scripts I have a Linux box and I want to be able to telnet into it (port 77557) and run few required commands without having to access to the whole Linux box. So, I have a server listening on that port, and echos the entered command on the screen. (for now) Telnet 192.168.1.100 77557 Trying 192.168.1.100... Connected to 192.168.1.100. Escape character is '^]'. hello<br /> You typed: "hello"<br /> NOW: I want to create lot of commands that each take some args and have error codes. Anyone has done this before? It would be great if I can have the server upon initialization go through each directory and execute the init.py file and in turn, the init.py file of each command call into a main template lib API (e.g. RegisterMe()) and register themselves with the server as function call backs. At least this is how I would do it in C/C++. But I want the best Pythonic way of doing this. /cmd/ /cmd/myreboot/ /cmd/myreboot/ini.py (note underscore don't show for some reason) /cmd/mylist/ /cmd/mylist/init.py ... etc IN: /cmd/myreboot/__ini__.py: from myMainCommand import RegisterMe RegisterMe(name="reboot",args=Arglist, usage="Use this to reboot the box", desc="blabla") So, repeating this creates a list of commands and when you enter the command in the telnet session, then the server goes through the list, matches the command and passed the args to that command and the command does the job and print the success or failure to stdout. Thx A: Twisted's web server does something kinda-sorta like what you're looking to do. The general approach used is to have a loadable python file define an object of a specific name in the loaded module's global namespace. Upon loading the module, the server checks for this object, makes sure that it derives from the proper type (and hence has the needed interface) then uses it to handle the requested URL. In your case, the same approach would probably work pretty well. Upon seeing a command name, import the module on the fly (check the built-in import function's documentation for how to do this), look for an instance of "command", and then use it to parse your argument list, do the processing, and return the result code. There likely wouldn't be much need to pre-process the directory on startup though you certainly could do this if you prefer it to on-the-fly loading. A: I would build this app using combination of cmd2 and RPyC modules.
Creating a simple command line interface (CLI) using a python server (TCP sock) and few scripts
I have a Linux box and I want to be able to telnet into it (port 77557) and run few required commands without having to access to the whole Linux box. So, I have a server listening on that port, and echos the entered command on the screen. (for now) Telnet 192.168.1.100 77557 Trying 192.168.1.100... Connected to 192.168.1.100. Escape character is '^]'. hello<br /> You typed: "hello"<br /> NOW: I want to create lot of commands that each take some args and have error codes. Anyone has done this before? It would be great if I can have the server upon initialization go through each directory and execute the init.py file and in turn, the init.py file of each command call into a main template lib API (e.g. RegisterMe()) and register themselves with the server as function call backs. At least this is how I would do it in C/C++. But I want the best Pythonic way of doing this. /cmd/ /cmd/myreboot/ /cmd/myreboot/ini.py (note underscore don't show for some reason) /cmd/mylist/ /cmd/mylist/init.py ... etc IN: /cmd/myreboot/__ini__.py: from myMainCommand import RegisterMe RegisterMe(name="reboot",args=Arglist, usage="Use this to reboot the box", desc="blabla") So, repeating this creates a list of commands and when you enter the command in the telnet session, then the server goes through the list, matches the command and passed the args to that command and the command does the job and print the success or failure to stdout. Thx
[ "Twisted's web server does something kinda-sorta like what you're looking to do. The general approach used is to have a loadable python file define an object of a specific name in the loaded module's global namespace. Upon loading the module, the server checks for this object, makes sure that it derives from the proper type (and hence has the needed interface) then uses it to handle the requested URL. In your case, the same approach would probably work pretty well.\nUpon seeing a command name, import the module on the fly (check the built-in import function's documentation for how to do this), look for an instance of \"command\", and then use it to parse your argument list, do the processing, and return the result code.\nThere likely wouldn't be much need to pre-process the directory on startup though you certainly could do this if you prefer it to on-the-fly loading.\n", "I would build this app using combination of cmd2 and RPyC modules.\n" ]
[ 0, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0002739056_command_line_python.txt
Q: What Python based Dashboard options exist? I want to create a Dashboard on each server to show it's health and the results of some daily processing. I plan to hook up shell scripts and Python programs to collect the data. Instead of writing a web-based interface, I thought it would be good to use a python based web dashboard that could render the results in various business user and manager friendly formats. What are my options to do this? I am primarily interested in Python RedHat Linux, but other platforms are interesting too. I'm also open to Perl and Ruby based solutions especially if the plugins can be language neutral. A: Have you tried ZenOSS , it is written in python and you can extend it using python.
What Python based Dashboard options exist?
I want to create a Dashboard on each server to show it's health and the results of some daily processing. I plan to hook up shell scripts and Python programs to collect the data. Instead of writing a web-based interface, I thought it would be good to use a python based web dashboard that could render the results in various business user and manager friendly formats. What are my options to do this? I am primarily interested in Python RedHat Linux, but other platforms are interesting too. I'm also open to Perl and Ruby based solutions especially if the plugins can be language neutral.
[ "Have you tried ZenOSS , it is written in python and you can extend it using python.\n" ]
[ 0 ]
[]
[]
[ "dashboard", "health_monitoring", "monitoring", "python", "ruby" ]
stackoverflow_0002742097_dashboard_health_monitoring_monitoring_python_ruby.txt
Q: How to change User-Agent on Google App Engine UrlFetch service? Is it possible to change User-Agent of Google App Engine UrlFetch service? A: Ok found it, it's possible since SDK 1.2.1 was released (Issue 342). You just have to specify the User-Agent header: urlfetch.fetch(url, headers = {'User-Agent': "MyApplication_User-Agent"})
How to change User-Agent on Google App Engine UrlFetch service?
Is it possible to change User-Agent of Google App Engine UrlFetch service?
[ "Ok found it, it's possible since SDK 1.2.1 was released (Issue 342).\nYou just have to specify the User-Agent header:\nurlfetch.fetch(url, headers = {'User-Agent': \"MyApplication_User-Agent\"}) \n\n" ]
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002743521_google_app_engine_python.txt
Q: Calculating time until 1st or 15th of the month in python I'm trying to write a little budget program in python. This is my first program I'm writing to learn python. The first step is to calculate how many days until either the 1st or 15th (paydays) depending on today's date. Can someone help me out a little? A: Interesting question, and here's a complete solution. I'll start with my function definition, I've put this in a file named payday.py: def nexypayday(fromdate=None): """ @param fromdate: An instance of datetime.date that is the day to go from. If not specified, todays date is used. @return: The first payday on or after the date specified. """ Next we need some tests. This is to clearly define the behaviour of our method. Because you're new to python, I'm going to go all out and give you an example of using unittests. from unittest import TestCase, main import payday import datetime class TestPayday(TestCase): def test_first_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 1)), datetime.date(2010, 1, 1)) def test_second_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 2)), datetime.date(2010, 1, 15)) def test_fifteenth_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 15)), datetime.date(2010, 1, 15)) def test_thirty_one_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 31)), datetime.date(2010, 2, 1)) def test_today(self): self.assertTrue(payday.nextpayday() >= datetime.date.today()) if __name__ == '__main__': main() This is a runnable python module. You can go ahead and name that test_payday.py and run it with python test_payday.py. This should immediately fail with various error messages because we've not got the right code written yet. After some fiddling with how datetime.date works, I've worked out: mydatetime.day is the day of the month, mydatetime + datetime.timedelta(days=1) will create a new datetime one day on in the year. Thus I can throw together this in payday.py. import datetime def nextpayday(fromdate=None): """ @param fromdate: An instance of datetime.date that is the day to go from. If not specified, todays date is used. @return: The first payday on or after the date specified. """ if fromdate is None: fromdate = datetime.date.today() # while the day of the month isn't 1 or 15, increase the day by 1 while fromdate.day not in (1, 15): fromdate = fromdate + datetime.timedelta(days=1) return fromdate Run the unit tests and it should be all golden. Note that in my tests I've made it that if I check what the 'next' payday is from a payday, it returns its own day. Changing that to returning the 'next' payday is left as an exercise for the reader. A: I don't want to entirely spoil your learning experience by just typing the answer, but the Python library makes this quite easy. Have a look at the datetime module, particularly the date and timedelta classes. A: The classes in the datetime module will help. You just need to check whether it's after the 15th of the month. If it is, find the 1st of the next month. If it isn't, find the 15th of the current month. A: Ugly with no docstrings, but quite a bit lighter than brute-forcing with timedelta in a while loop at the end of the month... import datetime from itertools import cycle PAYDAYS = (1, 8, 15, 22, 20, 25, 30) def calculate_days_difference(date_, day=None, next_month=False): day = day or date_.day year = date_.year month = date_.month if next_month: if month == 12: year = year + 1 month = 1 else: month = month + 1 return (datetime.date(year, month, day) - date_).days def calculate_days_to_payday(date_, paydays=PAYDAYS): day = date_.day if day in paydays: return 0 if day > max(paydays): return calculate_days_difference(date_, paydays[0], True) for payday in cycle(paydays): if (day > payday): continue return calculate_days_difference(date_, payday) Usage: test_data = ( ((2010,04,28), 2), ((2010,04,01), 0), ((2010,04,30), 0), ) for _input, _output in test_data: d = datetime.date(*input) for i in xrange(1000000): assert calculate_days_to_payday(d) == _output A: This will work with any reasonable paydays ... sorted, and all(1 <= payday <= 28 for payday in paydays) # otherwise workers strike every February. from datetime import date def calculate_days_to_payday(start_date=None, paydays=(1, 15)): if start_date is None: start_date = date.today() day = start_date.day for payday in paydays: if payday >= day: return payday - day # next payday is in next month month = start_date.month + 1 year = start_date.year if month == 13: month = 1 year += 1 return (date(year, month, paydays[0]) - start_date).days if __name__ == "__main__": tests = ( (1, 12, 0), (2, 12, 13), (14, 12, 1), (15, 12, 0), (16, 12, 16), (31, 12, 1), ) for d, m, expected in tests: actual = calculate_days_to_payday(date(2009, m, d)) print "%5s" * 5 % (d, m, expected, actual, actual == expected)
Calculating time until 1st or 15th of the month in python
I'm trying to write a little budget program in python. This is my first program I'm writing to learn python. The first step is to calculate how many days until either the 1st or 15th (paydays) depending on today's date. Can someone help me out a little?
[ "Interesting question, and here's a complete solution. I'll start with my function definition, I've put this in a file named payday.py:\ndef nexypayday(fromdate=None):\n \"\"\"\n @param fromdate: An instance of datetime.date that is the day to go from. If\n not specified, todays date is used.\n @return: The first payday on or after the date specified.\n \"\"\"\n\nNext we need some tests. This is to clearly define the behaviour of our method. Because you're new to python, I'm going to go all out and give you an example of using unittests.\nfrom unittest import TestCase, main\nimport payday\nimport datetime\n\nclass TestPayday(TestCase):\n def test_first_jan(self):\n self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 1)),\n datetime.date(2010, 1, 1))\n\n def test_second_jan(self):\n self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 2)),\n datetime.date(2010, 1, 15))\n\n def test_fifteenth_jan(self):\n self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 15)),\n datetime.date(2010, 1, 15))\n\n def test_thirty_one_jan(self):\n self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 31)),\n datetime.date(2010, 2, 1))\n\n def test_today(self):\n self.assertTrue(payday.nextpayday() >= datetime.date.today())\n\nif __name__ == '__main__':\n main()\n\nThis is a runnable python module. You can go ahead and name that test_payday.py and run it with python test_payday.py. This should immediately fail with various error messages because we've not got the right code written yet.\nAfter some fiddling with how datetime.date works, I've worked out: mydatetime.day is the day of the month, mydatetime + datetime.timedelta(days=1) will create a new datetime one day on in the year. Thus I can throw together this in payday.py.\nimport datetime\n\ndef nextpayday(fromdate=None):\n \"\"\"\n @param fromdate: An instance of datetime.date that is the day to go from. If\n not specified, todays date is used.\n @return: The first payday on or after the date specified.\n \"\"\"\n if fromdate is None:\n fromdate = datetime.date.today()\n\n # while the day of the month isn't 1 or 15, increase the day by 1\n while fromdate.day not in (1, 15):\n fromdate = fromdate + datetime.timedelta(days=1)\n\n return fromdate\n\nRun the unit tests and it should be all golden. Note that in my tests I've made it that if I check what the 'next' payday is from a payday, it returns its own day. Changing that to returning the 'next' payday is left as an exercise for the reader. \n", "I don't want to entirely spoil your learning experience by just typing the answer, but the Python library makes this quite easy. Have a look at the datetime module, particularly the date and timedelta classes.\n", "The classes in the datetime module will help.\nYou just need to check whether it's after the 15th of the month. If it is, find the 1st of the next month. If it isn't, find the 15th of the current month.\n", "Ugly with no docstrings, but quite a bit lighter than brute-forcing with timedelta in a while loop at the end of the month...\nimport datetime\nfrom itertools import cycle\n\nPAYDAYS = (1, 8, 15, 22, 20, 25, 30)\n\ndef calculate_days_difference(date_, day=None, next_month=False):\n day = day or date_.day\n year = date_.year\n month = date_.month\n if next_month:\n if month == 12:\n year = year + 1\n month = 1\n else:\n month = month + 1 \n return (datetime.date(year, month, day) - date_).days\n\ndef calculate_days_to_payday(date_, paydays=PAYDAYS):\n day = date_.day\n if day in paydays:\n return 0\n if day > max(paydays):\n return calculate_days_difference(date_, paydays[0], True)\n for payday in cycle(paydays):\n if (day > payday):\n continue\n return calculate_days_difference(date_, payday)\n\nUsage:\ntest_data = (\n ((2010,04,28), 2),\n ((2010,04,01), 0),\n ((2010,04,30), 0),\n)\n\nfor _input, _output in test_data:\n d = datetime.date(*input)\n for i in xrange(1000000):\n assert calculate_days_to_payday(d) == _output\n\n", "This will work with any reasonable paydays ... sorted, and all(1 <= payday <= 28 for payday in paydays) # otherwise workers strike every February.\nfrom datetime import date\n\ndef calculate_days_to_payday(start_date=None, paydays=(1, 15)):\n if start_date is None:\n start_date = date.today()\n day = start_date.day\n for payday in paydays:\n if payday >= day:\n return payday - day\n # next payday is in next month\n month = start_date.month + 1\n year = start_date.year\n if month == 13:\n month = 1\n year += 1\n return (date(year, month, paydays[0]) - start_date).days\n\nif __name__ == \"__main__\":\n tests = (\n (1, 12, 0),\n (2, 12, 13),\n (14, 12, 1),\n (15, 12, 0),\n (16, 12, 16),\n (31, 12, 1),\n )\n for d, m, expected in tests:\n actual = calculate_days_to_payday(date(2009, m, d))\n print \"%5s\" * 5 % (d, m, expected, actual, actual == expected)\n\n" ]
[ 6, 2, 2, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002742329_datetime_python.txt
Q: To stop returning through SSH using Pexpect I am trying to use pexpect to ssh into a computer but I do not want to return back to the original computer. The code I have is: #!/usr/bin/python2.6 import pexpect, os def ssh(): # Logs into computer through SSH ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line p=pexpect.spawn('ssh build@10.51.11.10') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) p.sendline("password") i=p.expect('-bash-3.2') print os.getcwd() ssh() This allows me to ssh into the computer but when I run the os.getcwd() the pexpect has returned me to the original computer. You see I want to ssh into another computer and use their environment not drag my environment using pexpect. Can anyone suggest how to get this working or an alternative way. Thanks A: The process that launches ssh is never going to leave the computer it runs on. When you ssh into another computer, you start a new process there. That process is an entirely separate thing, a separate program to run. If you want to do anything on the remote machine, you have to either send the commands to execute over the connection, or copy over the program you want to run and execute it remotely. A: your instance to the other machine is p. p.sendline what you want on the other machine and p.expect the result. in the case outlined p.sendline("pwd && hostname") p.expect("-bash-3.2") # although its better to set the prompt yourself so that this can be ported to any machine response = p.before print "received response [[" + response + "]]" Try that. Also try module pxssh to use ssh with python. This module uses pexpect and has all of the methods in it to do exactly what you want here
To stop returning through SSH using Pexpect
I am trying to use pexpect to ssh into a computer but I do not want to return back to the original computer. The code I have is: #!/usr/bin/python2.6 import pexpect, os def ssh(): # Logs into computer through SSH ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line p=pexpect.spawn('ssh build@10.51.11.10') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) p.sendline("password") i=p.expect('-bash-3.2') print os.getcwd() ssh() This allows me to ssh into the computer but when I run the os.getcwd() the pexpect has returned me to the original computer. You see I want to ssh into another computer and use their environment not drag my environment using pexpect. Can anyone suggest how to get this working or an alternative way. Thanks
[ "The process that launches ssh is never going to leave the computer it runs on. When you ssh into another computer, you start a new process there. That process is an entirely separate thing, a separate program to run. If you want to do anything on the remote machine, you have to either send the commands to execute over the connection, or copy over the program you want to run and execute it remotely.\n", "your instance to the other machine is p. p.sendline what you want on the other machine and p.expect the result. in the case outlined \np.sendline(\"pwd && hostname\")\np.expect(\"-bash-3.2\") # although its better to set the prompt yourself so that this can be ported to any machine\nresponse = p.before\nprint \"received response [[\" + response + \"]]\"\n\nTry that. Also try module pxssh to use ssh with python. This module uses pexpect and has all of the methods in it to do exactly what you want here\n" ]
[ 1, 0 ]
[]
[]
[ "pexpect", "python", "ssh" ]
stackoverflow_0002736659_pexpect_python_ssh.txt
Q: Programmatically check whether a drive letter is a shared/network drive Is there a way to check whether a drive letter stands for a shared drive/network drive or a local disc in python? I guess there is some windows api function that gives me that info, but I can't find it. Perhaps there is even a method already integrated in python? What I am looking for is something with this or similar behaviour: someMagicMethod("C:\\") #outputs True 'is a local drive' someMagicMethod("Z:\\") #outputs False 'is a shared drive' That would help me as well: someMagicMethod2() #outputs list of shared drive letters A: The GetDriveType function in win32file module may help you - it's a wrapper for the GetDriveType WINAPI function. import win32file isNetworkDrive = win32file.GetDriveType("Z:\\") == win32file.DRIVE_REMOTE You'd be able to enumerate all with the GetLogicalDriveStrings() function in the win32api module, then use a loop to pick out only the network drives.
Programmatically check whether a drive letter is a shared/network drive
Is there a way to check whether a drive letter stands for a shared drive/network drive or a local disc in python? I guess there is some windows api function that gives me that info, but I can't find it. Perhaps there is even a method already integrated in python? What I am looking for is something with this or similar behaviour: someMagicMethod("C:\\") #outputs True 'is a local drive' someMagicMethod("Z:\\") #outputs False 'is a shared drive' That would help me as well: someMagicMethod2() #outputs list of shared drive letters
[ "The GetDriveType function in win32file module may help you - it's a wrapper for the GetDriveType WINAPI function.\nimport win32file\nisNetworkDrive = win32file.GetDriveType(\"Z:\\\\\") == win32file.DRIVE_REMOTE\n\nYou'd be able to enumerate all with the GetLogicalDriveStrings() function in the win32api module, then use a loop to pick out only the network drives.\n" ]
[ 13 ]
[]
[]
[ "drive_letter", "network_drive", "python", "winapi" ]
stackoverflow_0002743716_drive_letter_network_drive_python_winapi.txt
Q: Performing non-blocking requests? - Django I have been playing with other frameworks, such as NodeJS, lately. I love the possibility to return a response, and still being able to do further operations. e.g. def view(request): do_something() return HttpResponse() do_more_stuff() #not possible!!! Maybe Django already offers a way to perform operations after returning a request, if that is the case that would be great. Help would be very much appreciated! =D A: not out of the box as you've already returned out of the method. You could use something like Celery which would pass the do_more_stuff task onto a queue and then have it run do_more_stuff() outside of http request / response flow. A: Django lets you accomplish this with Signals, more information can be found here. (Please note, as I said in comments below, signals aren't non-blocking, but they do allow you to execute code after returning a response in a view.) If you're looking into doing many, many asynchronous requests and need them to be non-blocking, you may want to check out Tornado. A: Because you're returning from the function, do_more_stuff will never be called. If you're looking at doing heavy lifting stuff queuing up something before you return as Ross suggests (+1 for Celery). if however you're looking at returning some content... then doing something and returning more content to the user streaming is probably what you're looking for. You can pass an iterator or a generator to HttpResponse, and it'll iterate and push out the content in a trickle fashion. It feels a bit yuck, but if you're a generator rockstar you may be able to do enough in various states to accomplish what you want. Or I guess you could simply redesign your page to use a lot of ajax to do what you need, including firing off events to django views, reading data from views, etc. It kind of comes down to where the burden of async is going to sit: client, server or response. I'm not that familiar with node.js yet, but it would be interesting to see the use case you're talking about. EDIT: I did a little more looking into signals, and while they do occur in process, there is a built in signal for request_finished after the request has been handled by django, though it's more of a catchall than something specific.
Performing non-blocking requests? - Django
I have been playing with other frameworks, such as NodeJS, lately. I love the possibility to return a response, and still being able to do further operations. e.g. def view(request): do_something() return HttpResponse() do_more_stuff() #not possible!!! Maybe Django already offers a way to perform operations after returning a request, if that is the case that would be great. Help would be very much appreciated! =D
[ "not out of the box as you've already returned out of the method. You could use something like Celery which would pass the do_more_stuff task onto a queue and then have it run do_more_stuff() outside of http request / response flow.\n", "Django lets you accomplish this with Signals, more information can be found here. (Please note, as I said in comments below, signals aren't non-blocking, but they do allow you to execute code after returning a response in a view.)\nIf you're looking into doing many, many asynchronous requests and need them to be non-blocking, you may want to check out Tornado.\n", "Because you're returning from the function, do_more_stuff will never be called.\nIf you're looking at doing heavy lifting stuff queuing up something before you return as Ross suggests (+1 for Celery).\nif however you're looking at returning some content... then doing something and returning more content to the user streaming is probably what you're looking for. You can pass an iterator or a generator to HttpResponse, and it'll iterate and push out the content in a trickle fashion. It feels a bit yuck, but if you're a generator rockstar you may be able to do enough in various states to accomplish what you want.\nOr I guess you could simply redesign your page to use a lot of ajax to do what you need, including firing off events to django views, reading data from views, etc.\nIt kind of comes down to where the burden of async is going to sit: client, server or response.\nI'm not that familiar with node.js yet, but it would be interesting to see the use case you're talking about.\nEDIT: I did a little more looking into signals, and while they do occur in process, there is a built in signal for request_finished after the request has been handled by django, though it's more of a catchall than something specific.\n" ]
[ 10, 9, 2 ]
[]
[]
[ "asynchronous", "django", "nonblocking", "python" ]
stackoverflow_0002743331_asynchronous_django_nonblocking_python.txt
Q: python iterators and thread-safety I have a class which is being operated on by two functions. One function creates a list of widgets and writes it into the class: def updateWidgets(self): widgets = self.generateWidgetList() self.widgets = widgets the other function deals with the widgets in some way: def workOnWidgets(self): for widget in self.widgets: self.workOnWidget(widget) each of these functions runs in it's own thread. the question is, what happens if the updateWidgets() thread executes while the workOnWidgets() thread is running? I am assuming that the iterator created as part of the for...in loop will keep some kind of reference to the old self.widgets object? So I will finish iterating over the old list... but I'd love to know for sure. A: updateWidgets() doesn't alter self.widgets in place (which would have been a problem) but rather replaces it with a new list. The references to the old one are kept at least until the for loop in workOnWidgets() has finished, so this should not be a problem. Simplified, what you're doing is kind of like this: >>> l=[1,2,3] >>> for i in l: ... l=[] ... print(i) ... 1 2 3 However, you'd be running into problems if you modified the list you're iterating over: >>> l=[1,2,3] >>> for i in l: ... l[2]=0 ... print(i) ... 1 2 0
python iterators and thread-safety
I have a class which is being operated on by two functions. One function creates a list of widgets and writes it into the class: def updateWidgets(self): widgets = self.generateWidgetList() self.widgets = widgets the other function deals with the widgets in some way: def workOnWidgets(self): for widget in self.widgets: self.workOnWidget(widget) each of these functions runs in it's own thread. the question is, what happens if the updateWidgets() thread executes while the workOnWidgets() thread is running? I am assuming that the iterator created as part of the for...in loop will keep some kind of reference to the old self.widgets object? So I will finish iterating over the old list... but I'd love to know for sure.
[ "updateWidgets() doesn't alter self.widgets in place (which would have been a problem) but rather replaces it with a new list. The references to the old one are kept at least until the for loop in workOnWidgets() has finished, so this should not be a problem.\nSimplified, what you're doing is kind of like this:\n>>> l=[1,2,3]\n>>> for i in l:\n... l=[]\n... print(i)\n...\n1\n2\n3\n\nHowever, you'd be running into problems if you modified the list you're iterating over:\n>>> l=[1,2,3]\n>>> for i in l:\n... l[2]=0\n... print(i)\n...\n1\n2\n0\n\n" ]
[ 4 ]
[]
[]
[ "atomic", "iterator", "multithreading", "python", "thread_safety" ]
stackoverflow_0002744036_atomic_iterator_multithreading_python_thread_safety.txt
Q: setting the header of a response in python / django This is my code: template = loader.get_template('blog/post.html') c = Context(parameterDict) return HttpResponse(template.render(c)) I am using this to render data into a template(contained in parameterDict). The problem is that parameterDict contains certain UTF characters like ®. This is causing a problem in my template and the particular blocks with the UTF characters are not being rendered. Will setting the HttpResponse charset=utf-8 help? If so, how do I do this? A: Is the content of parameterDict unicode? parameterDict = {'title':u'® by blah'} return render_to_response('blog/post.html', parameterDict, context_instance=RequestContext(request))
setting the header of a response in python / django
This is my code: template = loader.get_template('blog/post.html') c = Context(parameterDict) return HttpResponse(template.render(c)) I am using this to render data into a template(contained in parameterDict). The problem is that parameterDict contains certain UTF characters like ®. This is causing a problem in my template and the particular blocks with the UTF characters are not being rendered. Will setting the HttpResponse charset=utf-8 help? If so, how do I do this?
[ "Is the content of parameterDict unicode?\nparameterDict = {'title':u'® by blah'}\n\nreturn render_to_response('blog/post.html',\n parameterDict,\n context_instance=RequestContext(request))\n\n" ]
[ 0 ]
[]
[]
[ "httpresponse", "python", "templates", "utf_8" ]
stackoverflow_0002744134_httpresponse_python_templates_utf_8.txt
Q: Minimal Python build for my application's scripting needs? what are your advices on building a very minimalistic version of Python(2.x) for my application's scripting needs. My main motive here is to keep the foot print (both memory and disk wise) as low as possible so that my native application won't suffer from any major performance hit. Even the Python DLL size is in consideration because of the possibility of increasing boot up time of my application. Can we go as low as Lua or other lightweight solutions? A: Have you tried Tiny Python?
Minimal Python build for my application's scripting needs?
what are your advices on building a very minimalistic version of Python(2.x) for my application's scripting needs. My main motive here is to keep the foot print (both memory and disk wise) as low as possible so that my native application won't suffer from any major performance hit. Even the Python DLL size is in consideration because of the possibility of increasing boot up time of my application. Can we go as low as Lua or other lightweight solutions?
[ "Have you tried Tiny Python?\n" ]
[ 7 ]
[ "You can use only the dll\n" ]
[ -1 ]
[ "python", "python_embedding", "scripting" ]
stackoverflow_0000356452_python_python_embedding_scripting.txt
Q: OpenCV Python and a webcam I'm working with OpenCV on a BeagleBoard with Ubuntu and OpenCV 1.1 interfaced via Python. I'm trying to set something up to capture a feed from a UVC compatible webcam (Logitech C250). I have tested the webcam with luvcview, and it works, but only if I set the input format to YUV. If I run it in 'normal' mode I am getting back JPEG frames and something - somewhere is not happy! I'm trying to connect with the webcam in OpenCV as I want to get the image back from the webcam and run some analysis on it. As I have a limited device this seems to be the most efficient way of doing it - however I need to instruct the capturing system to capture in YUV and not JPEG. Is there a way of doing this (for example luvcview allow me to enter luvcview -f YUVY)? A: I've cracked this partly. If you compile OpenCV with the flag WITH_JPEG=OFF then the camera will not try to use MJPEG.
OpenCV Python and a webcam
I'm working with OpenCV on a BeagleBoard with Ubuntu and OpenCV 1.1 interfaced via Python. I'm trying to set something up to capture a feed from a UVC compatible webcam (Logitech C250). I have tested the webcam with luvcview, and it works, but only if I set the input format to YUV. If I run it in 'normal' mode I am getting back JPEG frames and something - somewhere is not happy! I'm trying to connect with the webcam in OpenCV as I want to get the image back from the webcam and run some analysis on it. As I have a limited device this seems to be the most efficient way of doing it - however I need to instruct the capturing system to capture in YUV and not JPEG. Is there a way of doing this (for example luvcview allow me to enter luvcview -f YUVY)?
[ "I've cracked this partly. If you compile OpenCV with the flag WITH_JPEG=OFF then the camera will not try to use MJPEG.\n" ]
[ 1 ]
[]
[]
[ "beagleboard", "linux", "opencv", "python", "webcam" ]
stackoverflow_0002682313_beagleboard_linux_opencv_python_webcam.txt
Q: Dynamic Spacer in ReportLab I'm automatically generating a PDF-file with Platypus that has dynamic content. This means that it might happen that the length of the text content (which is directly at the bottom of the pdf-file) may vary. However, it might happen that a page break is done in cases where the content is too long. This is because i use a "static" spacer: s = Spacer(width=0, height=23.5*cm) as i always want to have only one page, I somehow need to dynamically set the height of the Spacer, so that the "rest" of the space that is left on the page is taken by the Spacer as its height. Now, how do i get the "rest" of height that is left on my page? A: I sniffed around in the reportlab library a bit and found the following: Basically, I decided to use a frame into which the flowables will be printed. f._aH returns the height of the Frame (we could also calculate this by hand). Subtracting the heights of the other two flowables, which we get through wrap, we get the remaining height which is the height of the Spacer. elements.append(Flowable1) elements.append(Flowable2) c = Canvas(path) f = Frame(fx, fy,fw,fh,showBoundary=0) # compute the available height for the spacer sheight = f._aH - (Flowable1.wrap(f._aW,f._aH)[1] + Flowable2.wrap(f._aW,f._aH)[1]) # create spacer s = Spacer(width=0, height=sheight) # insert the spacer between the two flowables elements.insert(1,s) # create a frame from the list of elements f.addFromList(elements,c) c.save() tested and works fine. A: As far as i can see you want to have footer, right? Then you should do it like: def _laterPages(canvas, doc): canvas.drawImage(os.path.join(settings.PROJECT_ROOT, 'templates/documents/pics/footer.png'), left_margin, bottom_margin - 0.5*cm, frame_width, 0.5*cm) doc = BaseDocTemplate(filename,showBoundary=False) doc.multiBuild(flowble elements, _firstPage, _laterPages)
Dynamic Spacer in ReportLab
I'm automatically generating a PDF-file with Platypus that has dynamic content. This means that it might happen that the length of the text content (which is directly at the bottom of the pdf-file) may vary. However, it might happen that a page break is done in cases where the content is too long. This is because i use a "static" spacer: s = Spacer(width=0, height=23.5*cm) as i always want to have only one page, I somehow need to dynamically set the height of the Spacer, so that the "rest" of the space that is left on the page is taken by the Spacer as its height. Now, how do i get the "rest" of height that is left on my page?
[ "I sniffed around in the reportlab library a bit and found the following:\nBasically, I decided to use a frame into which the flowables will be printed. f._aH returns the height of the Frame (we could also calculate this by hand). Subtracting the heights of the other two flowables, which we get through wrap, we get the remaining height which is the height of the Spacer.\nelements.append(Flowable1)\nelements.append(Flowable2)\n\nc = Canvas(path)\nf = Frame(fx, fy,fw,fh,showBoundary=0)\n\n# compute the available height for the spacer\nsheight = f._aH - (Flowable1.wrap(f._aW,f._aH)[1] + Flowable2.wrap(f._aW,f._aH)[1])\n\n# create spacer\ns = Spacer(width=0, height=sheight)\n\n# insert the spacer between the two flowables\nelements.insert(1,s)\n\n# create a frame from the list of elements\nf.addFromList(elements,c)\n\nc.save()\n\ntested and works fine.\n", "As far as i can see you want to have footer, right?\nThen you should do it like:\ndef _laterPages(canvas, doc):\n canvas.drawImage(os.path.join(settings.PROJECT_ROOT, 'templates/documents/pics/footer.png'), left_margin, bottom_margin - 0.5*cm, frame_width, 0.5*cm)\n\ndoc = BaseDocTemplate(filename,showBoundary=False)\ndoc.multiBuild(flowble elements, _firstPage, _laterPages)\n\n" ]
[ 3, 0 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0002722386_python_reportlab.txt
Q: Django admin: Add a "remove file" field for Image- or FileFields I was hunting around the Internet for a way to easily allow users to blank out imagefield/filefields they have set in the admin. I found this: http://www.djangosnippets.org/snippets/894/. What was really interesting to me here was the code posted in the comment by rfugger: remove_the_file = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_the_file'): object.the_file = '' return object When I try to use this in my own form I basically added this to my admin.py which already had a BlahAdmin. class BlahModelForm(forms.ModelForm): class Meta: model = Blah remove_img01 = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_img01'): object.img01 = '' return object When I run it I get the error maximum recursion depth exceeded while calling a Python object at this line: object = super(self.__class__, self).save(*args, **kwargs) When I think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is I can't figure out what is the correct way I should be doing this. Any suggestions? Additional information as requested: Model of blah: class Blah(models.Model): blah_name = models.CharField(max_length=25, unique=True) slug = models.SlugField() img01 = models.ImageField(upload_to='scenes/%Y/%m', blank=True) def __unicode__(self): return self.blah_name A: Never use super(self.__class__, self)! Try the following example: class A(object): def m(self): super(self.__class__, self).m() class B(A): pass B().m() It will fail with the same error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in m ... repeated a lot of times ... RuntimeError: maximum recursion depth exceeded while calling a Python object Let's see what's going on. You call A.m method for B instance, so self.__class__ is B and super(self.__class__, self).m refers to the same method A.m, so A.m calls itself instead of calling the method of base class. This leads to infinite recursion. A: I have tested it on my machine and it works :-) . I used exactly your piece of code. The problem has to be outside of this code. Please post a snippet how you call/save the form and the declaration of the Model Blah. Did you overwrite the save method of Model Blah?
Django admin: Add a "remove file" field for Image- or FileFields
I was hunting around the Internet for a way to easily allow users to blank out imagefield/filefields they have set in the admin. I found this: http://www.djangosnippets.org/snippets/894/. What was really interesting to me here was the code posted in the comment by rfugger: remove_the_file = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_the_file'): object.the_file = '' return object When I try to use this in my own form I basically added this to my admin.py which already had a BlahAdmin. class BlahModelForm(forms.ModelForm): class Meta: model = Blah remove_img01 = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_img01'): object.img01 = '' return object When I run it I get the error maximum recursion depth exceeded while calling a Python object at this line: object = super(self.__class__, self).save(*args, **kwargs) When I think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is I can't figure out what is the correct way I should be doing this. Any suggestions? Additional information as requested: Model of blah: class Blah(models.Model): blah_name = models.CharField(max_length=25, unique=True) slug = models.SlugField() img01 = models.ImageField(upload_to='scenes/%Y/%m', blank=True) def __unicode__(self): return self.blah_name
[ "Never use super(self.__class__, self)! Try the following example:\nclass A(object):\n def m(self):\n super(self.__class__, self).m()\n\nclass B(A): pass\n\nB().m()\n\nIt will fail with the same error:\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 4, in m\n ... repeated a lot of times ...\nRuntimeError: maximum recursion depth exceeded while calling a Python object\n\nLet's see what's going on. You call A.m method for B instance, so self.__class__ is B and super(self.__class__, self).m refers to the same method A.m, so A.m calls itself instead of calling the method of base class. This leads to infinite recursion.\n", "I have tested it on my machine and it works :-) . I used exactly your piece of code.\nThe problem has to be outside of this code.\nPlease post a snippet how you call/save the form and the declaration of the Model Blah.\nDid you overwrite the save method of Model Blah?\n" ]
[ 3, 0 ]
[]
[]
[ "django", "django_admin", "django_forms", "django_models", "python" ]
stackoverflow_0002657149_django_django_admin_django_forms_django_models_python.txt
Q: Django: Unicode Filenames with ASCII headers? I have a list of strangely encoded files: 02 - Charlie, Woody and You/Study #22.mp3 which I suppose isn't so bad but there are a few particular characters which Django OR nginx seem to be snagging on. >>> test = u'02 - Charlie, Woody and You/Study #22.mp3' >>> test u'02 - Charlie, Woody and You\uff0fStudy #22.mp3' I am using nginx as a reverse proxy to connect to django's built in webserver (still in development stages) and postgresql for my database. My database and tables are all en_US.UTF-8 and I am using pgadmin3 to view my tables outside of django. My issue goes a little beyond my title, firstly how should I be saving possibly whacky filenames in my database? My current method is 'path': smart_unicode(path.lstrip(MUSIC_PATH)), 'filename': smart_unicode(file) and when I pprint out the values they do show u'whateverthecrap' I am not sure if that is how I should be doing it but assuming it is now I have issues trying to spit out the download. My download view looks something like this: def song_download(request, song_id): song = get_object_or_404(Song, pk=song_id) url = u'/static_music/%s/%s' % (song.path, song.filename) print url response = HttpResponse() response['X-Accel-Redirect'] = url response['Content-Type'] = 'audio/mpeg' response['Content-Disposition'] = "attachment; filename=test.mp3" return response and most files will download but when I get to 02 - Charlie, Woody and You/Study #22.mp3 I receive this from django: 'ascii' codec can't encode character u'\uff0f' in position 118: ordinal not in range(128), HTTP response headers must be in US-ASCII format. How can I use an ASCII acceptable string if my filename is out of bounds? 02 - Charlie, Woody and You\uff0fStudy #22.mp3 doesn't seem to work... EDIT 1 I am using Ubuntu for my OS. A: Although / is an unusual and undesirable character, your script will break for any non-ASCII character. response['X-Accel-Redirect'] = url url is Unicode (and it isn't a URL, it's a filepath). Response headers are bytes. You'll need to encode it. response['X-Accel-Redirect'] = url.encode('utf-8') that's assuming you're running on a server with UTF-8 as the filesystem encoding. (Now, how to encode the filename in the Content-Disposition header... that's an altogether trickier question!)
Django: Unicode Filenames with ASCII headers?
I have a list of strangely encoded files: 02 - Charlie, Woody and You/Study #22.mp3 which I suppose isn't so bad but there are a few particular characters which Django OR nginx seem to be snagging on. >>> test = u'02 - Charlie, Woody and You/Study #22.mp3' >>> test u'02 - Charlie, Woody and You\uff0fStudy #22.mp3' I am using nginx as a reverse proxy to connect to django's built in webserver (still in development stages) and postgresql for my database. My database and tables are all en_US.UTF-8 and I am using pgadmin3 to view my tables outside of django. My issue goes a little beyond my title, firstly how should I be saving possibly whacky filenames in my database? My current method is 'path': smart_unicode(path.lstrip(MUSIC_PATH)), 'filename': smart_unicode(file) and when I pprint out the values they do show u'whateverthecrap' I am not sure if that is how I should be doing it but assuming it is now I have issues trying to spit out the download. My download view looks something like this: def song_download(request, song_id): song = get_object_or_404(Song, pk=song_id) url = u'/static_music/%s/%s' % (song.path, song.filename) print url response = HttpResponse() response['X-Accel-Redirect'] = url response['Content-Type'] = 'audio/mpeg' response['Content-Disposition'] = "attachment; filename=test.mp3" return response and most files will download but when I get to 02 - Charlie, Woody and You/Study #22.mp3 I receive this from django: 'ascii' codec can't encode character u'\uff0f' in position 118: ordinal not in range(128), HTTP response headers must be in US-ASCII format. How can I use an ASCII acceptable string if my filename is out of bounds? 02 - Charlie, Woody and You\uff0fStudy #22.mp3 doesn't seem to work... EDIT 1 I am using Ubuntu for my OS.
[ "Although / is an unusual and undesirable character, your script will break for any non-ASCII character.\nresponse['X-Accel-Redirect'] = url\n\nurl is Unicode (and it isn't a URL, it's a filepath). Response headers are bytes. You'll need to encode it.\nresponse['X-Accel-Redirect'] = url.encode('utf-8')\n\nthat's assuming you're running on a server with UTF-8 as the filesystem encoding.\n(Now, how to encode the filename in the Content-Disposition header... that's an altogether trickier question!)\n" ]
[ 8 ]
[]
[]
[ "ascii", "django", "nginx", "python", "unicode" ]
stackoverflow_0002732268_ascii_django_nginx_python_unicode.txt
Q: Python: Plot some data (matplotlib) without GIL my problem is the GIL of course. While I'm analysing data it would be nice to present some plots in between (so it's not too boring waiting for results) But the GIL prevents this (and this is bringing me to the point of asking myself if Python was such a good idea in the first place). I can only display the plot, wait till the user closes it and commence calculations after that. A waste of time obviously. I already tried the subprocess and multiprocessing modules but can't seem to get them to work. Any thoughts on this one? Thanks Edit: Ok so it's not the GIL but show(). A: This is not a problem from matplotlib or the GIL. In matplotlib You can open as many figures as you want and have them in the screen while your application continues doing other things. You must use matplotlib in interactive mode. This probably is your problem. from matplotlib import interactive interactive(True) this should be at the top of your imports A: This has nothing to do with the GIL, just modify your analysis code to make it update the graph from time to time (for example every N iterations). Only then if you see that drawing the graph slows the analysis code too much, put the graph update code in a subprocess with multiprocessing. A: I think you'll need to put the graph into a proper Windowing system, rather than relying on the built-in show code. Maybe sticking the .show() in another thread would be sufficient? The GIL is irrelevant - you've got a blocking show() call, so you need to handle that first. A: It seems like the draw() method can circumvent the need for show(). The only reason left for .show() in the script is to let it do the blocking part so that the images don't disapear when the script reaches its end.
Python: Plot some data (matplotlib) without GIL
my problem is the GIL of course. While I'm analysing data it would be nice to present some plots in between (so it's not too boring waiting for results) But the GIL prevents this (and this is bringing me to the point of asking myself if Python was such a good idea in the first place). I can only display the plot, wait till the user closes it and commence calculations after that. A waste of time obviously. I already tried the subprocess and multiprocessing modules but can't seem to get them to work. Any thoughts on this one? Thanks Edit: Ok so it's not the GIL but show().
[ "This is not a problem from matplotlib or the GIL.\nIn matplotlib You can open as many figures as you want and have them in the screen while your application continues doing other things. \nYou must use matplotlib in interactive mode. This probably is your problem.\nfrom matplotlib import interactive\ninteractive(True)\n\nthis should be at the top of your imports\n", "This has nothing to do with the GIL, just modify your analysis code to make it update the graph from time to time (for example every N iterations).\nOnly then if you see that drawing the graph slows the analysis code too much, put the graph update code in a subprocess with multiprocessing.\n", "I think you'll need to put the graph into a proper Windowing system, rather than relying on the built-in show code.\nMaybe sticking the .show() in another thread would be sufficient?\nThe GIL is irrelevant - you've got a blocking show() call, so you need to handle that first.\n", "It seems like the draw() method can circumvent the need for show(). \nThe only reason left for .show() in the script is to let it do the blocking part so that the images don't disapear when the script reaches its end.\n" ]
[ 6, 3, 3, 2 ]
[]
[]
[ "gil", "matplotlib", "parallel_processing", "python" ]
stackoverflow_0002744530_gil_matplotlib_parallel_processing_python.txt
Q: Is there anyway to get pdb and Mac Terminal to play nicely? When debugging my django apps I use pdb for interactive debugging with pdb.set_trace(). However, when I amend a file the local django webserver restarts and then I cant see what I type in the terminal, until I type reset. Is there anyway for this to happen automatically? It can be real annoying, having to cancel the runserver and reset and restart it all the time. I'm told it doesn't happen on other OS's (ubuntu) so is there anyway to make it not happen on the Mac? (I'm using Snow Leopard). A: OK - this works for me I created a ~/.pdbrc and added import os os.system("stty sane") Now each time pdb is run it sets the line settings back to sane. If I fall out to the terminal then I still have to do it manually - but it solves having to quit runserver and reset all the time. A: Try to [q]uit pdb before you save changes to a file. This will keep the console from wigging out on you but only for that one run of pdb.set_trace(). You will still have to fallback to the old ^C + reset + ./manage.py runserver when you forget to quit pdb. One thing that can make the reset a little less annoying is to put the reset and runserver onto one line. That way the reset is just a quick ^Rreset or up-arrow away. [ ... ] Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ^C$ reset && ./manage.py runserver A: The best I've found is doing a reset inside pdb like so: import os; os.system("reset");
Is there anyway to get pdb and Mac Terminal to play nicely?
When debugging my django apps I use pdb for interactive debugging with pdb.set_trace(). However, when I amend a file the local django webserver restarts and then I cant see what I type in the terminal, until I type reset. Is there anyway for this to happen automatically? It can be real annoying, having to cancel the runserver and reset and restart it all the time. I'm told it doesn't happen on other OS's (ubuntu) so is there anyway to make it not happen on the Mac? (I'm using Snow Leopard).
[ "OK - this works for me I created a ~/.pdbrc and added\n\nimport os\n os.system(\"stty sane\")\n\nNow each time pdb is run it sets the line settings back to sane.\nIf I fall out to the terminal then I still have to do it manually - but it solves having to quit runserver and reset all the time.\n", "Try to [q]uit pdb before you save changes to a file. This will keep the console from wigging out on you but only for that one run of pdb.set_trace(). \nYou will still have to fallback to the old ^C + reset + ./manage.py runserver when you forget to quit pdb. One thing that can make the reset a little less annoying is to put the reset and runserver onto one line. That way the reset is just a quick ^Rreset or up-arrow away.\n[ ... ]\nDevelopment server is running at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n^C$ reset && ./manage.py runserver\n\n", "The best I've found is doing a reset inside pdb like so:\n\nimport os; os.system(\"reset\");\n\n" ]
[ 8, 1, 1 ]
[]
[]
[ "django", "macos", "pdb", "python", "terminal" ]
stackoverflow_0002735828_django_macos_pdb_python_terminal.txt
Q: Basic Python: Exception raising and local variable scope / binding I have a basic "best practices" Python question. I see that there are already StackOverflow answers tangentially related to this question but they're mired in complicated examples or involve multiple factors. Given this code: #!/usr/bin/python def test_function(): try: a = str(5) raise b = str(6) except: print b test_function() what is the best way to avoid the inevitable "UnboundLocalError: local variable 'b' referenced before assignment" that I'm going to get in the exception handler? Does python have an elegant way to handle this? If not, what about an inelegant way? In a complicated function I'd prefer to avoid testing the existence of every local variable before I, for example, printed debug information about them. A: Does python have an elegant way to handle this? To avoid exceptions from printing unbound names, the most elegant way is not to print them; the second most elegant is to ensure the names do get bound, e.g. by binding them at the start of the function (the placeholder None is popular for this purpose). If not, what about an inelegant way? try: print 'b is', b except NameError: print 'b is not bound' In a complicated function I'd prefer to avoid testing the existence of every local variable before I, for example, printed debug information about them Keeping your functions simple (i.e., not complicated) is highly recommended, too. As Hoare wrote 30 years ago (in his Turing acceptance lecture "The Emperor's old clothes", reprinted e.g. in this PDF): There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult. Achieving and maintaining simplicity is indeed difficult: given that you have to implement a certain total functionality X, it's the most natural temptation in the world to do so via complicated accretion into a few complicated classes and functions of sundry bits and pieces, "clever" hacks, copy-and-paste-and-edit-a-bit episodes of "drive-by coding", etc, etc. However, it's a worthwhile effort to strive instead to keep your functions "so simple that there are obviously no deficiencies". If a function's hard to completely unit-test, it's too complicated: break it up (i.e., refactor it) into its natural components, even though it will take work to unearth them. (That's actually one of the way in which a strong focus on unit testing helps code quality: by spurring you relentlessly to keep all the code perfectly testable, it's at the same time spurring you to make it simple in its structure). A: You can initialize your variables outside of the try block a = None b = None try: a = str(5) raise b = str(6) except: print b A: You could check to see if the variable is defined in local scope using the built-in method locals() http://docs.python.org/library/functions.html#locals #!/usr/bin/python def test_function(): try: a = str(5) raise b = str(6) except: if 'b' in locals(): print b test_function() A: def test_function(): try: a = str(5) raise b = str(6) except: print b b = str(6) is never run; the program exits try block just after raise. If you want to print some variable in the except block, evaluate it before raising an exception and put them into the exception you throw. class MyException(Exception): def __init__(self, var): self.var = var def test_function(): try: a = str(5) b = str(6) raise MyException(b) except MyException,e: print e.var
Basic Python: Exception raising and local variable scope / binding
I have a basic "best practices" Python question. I see that there are already StackOverflow answers tangentially related to this question but they're mired in complicated examples or involve multiple factors. Given this code: #!/usr/bin/python def test_function(): try: a = str(5) raise b = str(6) except: print b test_function() what is the best way to avoid the inevitable "UnboundLocalError: local variable 'b' referenced before assignment" that I'm going to get in the exception handler? Does python have an elegant way to handle this? If not, what about an inelegant way? In a complicated function I'd prefer to avoid testing the existence of every local variable before I, for example, printed debug information about them.
[ "\nDoes python have an elegant way to\n handle this?\n\nTo avoid exceptions from printing unbound names, the most elegant way is not to print them; the second most elegant is to ensure the names do get bound, e.g. by binding them at the start of the function (the placeholder None is popular for this purpose).\n\nIf not, what about an inelegant way?\n\ntry: print 'b is', b\nexcept NameError: print 'b is not bound'\n\n\nIn a complicated function I'd prefer\n to avoid testing the existence of\n every local variable before I, for\n example, printed debug information\n about them\n\nKeeping your functions simple (i.e., not complicated) is highly recommended, too. As Hoare wrote 30 years ago (in his Turing acceptance lecture \"The Emperor's old clothes\", reprinted e.g. in this PDF):\n\nThere are two ways of constructing a\n software design: One way is to make it\n so simple that there are obviously no\n deficiencies, and the other way is to\n make it so complicated that there are\n no obvious deficiencies. The first\n method is far more difficult.\n\nAchieving and maintaining simplicity is indeed difficult: given that you have to implement a certain total functionality X, it's the most natural temptation in the world to do so via complicated accretion into a few complicated classes and functions of sundry bits and pieces, \"clever\" hacks, copy-and-paste-and-edit-a-bit episodes of \"drive-by coding\", etc, etc.\nHowever, it's a worthwhile effort to strive instead to keep your functions \"so simple that there are obviously no deficiencies\". If a function's hard to completely unit-test, it's too complicated: break it up (i.e., refactor it) into its natural components, even though it will take work to unearth them. (That's actually one of the way in which a strong focus on unit testing helps code quality: by spurring you relentlessly to keep all the code perfectly testable, it's at the same time spurring you to make it simple in its structure).\n", "You can initialize your variables outside of the try block\na = None\nb = None \ntry:\n a = str(5)\n raise\n b = str(6)\nexcept:\n print b\n\n", "You could check to see if the variable is defined in local scope using the built-in method locals()\nhttp://docs.python.org/library/functions.html#locals\n#!/usr/bin/python\n\ndef test_function():\n try:\n a = str(5)\n raise\n b = str(6)\n except:\n if 'b' in locals(): print b\n\ntest_function()\n\n", "def test_function():\n try:\n a = str(5)\n raise\n b = str(6)\n except:\n print b\n\nb = str(6) is never run; the program exits try block just after raise. If you want to print some variable in the except block, evaluate it before raising an exception and put them into the exception you throw.\nclass MyException(Exception):\n def __init__(self, var):\n self.var = var\n\ndef test_function():\n try:\n a = str(5)\n b = str(6)\n raise MyException(b)\n except MyException,e:\n print e.var\n\n" ]
[ 10, 6, 2, 1 ]
[]
[]
[ "exception_handling", "python", "scope" ]
stackoverflow_0002744820_exception_handling_python_scope.txt
Q: Python - 2 Questions: Editing a variable in a function and changing the order of if else statements internally/during runtime First of all, I should explain what I'm trying to do first. I'm creating a dungeon crawler-like game, and I'm trying to program the movement of computer characters/monsters in the map. The map is basically a Cartesian coordinate grid. The locations of characters are represented by tuples of the x and y values, (x,y). The game works by turns, and in a turn a character can only move up, down, left or right 1 space. I'm creating a very simple movement system where the character will simply make decisions to move on a turn by turn basis. Essentially a 'forgetful' movement system. A basic flow chart of what I'm intending to do: Find direction towards destination Make a priority list of movements to be done using the direction eg.('r','u','d','l') means it would try to move right first, then up, then down, then left. Try each of the possibilities following the priority order. If the first movement fails (blocked by obstacle etc.), then it would successively try the movements until the first one that is successful, then it would stop. At step 3, the way I'm trying to do it is like this: def move(direction,location): try: -snip- # Tries to move, raises the exception Movementerror if cannot move in the direction return 1 # Indicates movement successful except Movementerror: return 0 # Indicates movement unsuccessful (thus character has not moved yet) prioritylist = ('r','u','d','l') if move('r',location): pass elif move('u',location): pass elif move('d',location): pass elif move('l',location): pass else: pass In the if/else block, the program would try the first movement on the priority on the priority list. At the move function, the character would try to move. If the character is not blocked and does move, it returns 1, leading to the pass where it would stop. If the character is blocked, it returns 0, then it tries the next movement. However, this results in 2 problems: 1.How do I edit a variable passed into a function inside the function itself, while returning if the edit is successful? I have been told that you can't edit a variable inside a function as it won't really change the value of the variable, it just makes the variable inside the function refer to something else while the original variable remain unchanged. So, the solution is to return the value and then assign the variable to the returned value. However, I want it to return another value indicating if this edit is successful, so I want to edit this variable inside the function itself. How do I do so? 2.How do I change the order of the if/else statements to follow the order of the priority list? It needs to be able to change during runtime as the priority list can change resulting in a different order of movement to try. A: Re 2., I would change your relatively-big if/elif tree to a simple loop: prioritylist = ('r','u','d','l') for direction in prioritylist: if move(direction, location): break less repetitious, easier to extend in the future if you want to allow diagonal steps or whatever -- and automatically "follows the priority list" in whatever order it's in, without any need to change your code itself. Re 1., you can return multiple values from a function: def move(direction,location): try: -snip- return True, newlocation except Movementerror: return False, location and you would then change the above loop to, e.g.: prioritylist = ('r','u','d','l') for direction in prioritylist: success, newlocation = move(direction, location) if success: break else: newlocation = location using the else branch of the for, which executes if no break happens in the for, to deal with the case in which no attempt produced a success. A: You can use a for-loop, and break out of the loop at the first successful choice: for option in prioritylist: if move(option,location): # succeeded break You should also return True or False, instead of a 1 or 0, as it makes the intention clearer. Also, I should add that the statement about not editing a parameter is not entirely true... you cannot edit the parameter, itself, but you can edit the contents of that parameter assuming it is a mutable object. Tuples, which you are using, are immutable and so cannot be modified, but lists can be modified: positions = ['N','S','E','W'] def mutate_list(p): p.reverse() print positions # prints ['N', 'S', 'E', 'W'] mutate_list(positions) print positions # prints ['w', 'E', 'S', 'N']
Python - 2 Questions: Editing a variable in a function and changing the order of if else statements internally/during runtime
First of all, I should explain what I'm trying to do first. I'm creating a dungeon crawler-like game, and I'm trying to program the movement of computer characters/monsters in the map. The map is basically a Cartesian coordinate grid. The locations of characters are represented by tuples of the x and y values, (x,y). The game works by turns, and in a turn a character can only move up, down, left or right 1 space. I'm creating a very simple movement system where the character will simply make decisions to move on a turn by turn basis. Essentially a 'forgetful' movement system. A basic flow chart of what I'm intending to do: Find direction towards destination Make a priority list of movements to be done using the direction eg.('r','u','d','l') means it would try to move right first, then up, then down, then left. Try each of the possibilities following the priority order. If the first movement fails (blocked by obstacle etc.), then it would successively try the movements until the first one that is successful, then it would stop. At step 3, the way I'm trying to do it is like this: def move(direction,location): try: -snip- # Tries to move, raises the exception Movementerror if cannot move in the direction return 1 # Indicates movement successful except Movementerror: return 0 # Indicates movement unsuccessful (thus character has not moved yet) prioritylist = ('r','u','d','l') if move('r',location): pass elif move('u',location): pass elif move('d',location): pass elif move('l',location): pass else: pass In the if/else block, the program would try the first movement on the priority on the priority list. At the move function, the character would try to move. If the character is not blocked and does move, it returns 1, leading to the pass where it would stop. If the character is blocked, it returns 0, then it tries the next movement. However, this results in 2 problems: 1.How do I edit a variable passed into a function inside the function itself, while returning if the edit is successful? I have been told that you can't edit a variable inside a function as it won't really change the value of the variable, it just makes the variable inside the function refer to something else while the original variable remain unchanged. So, the solution is to return the value and then assign the variable to the returned value. However, I want it to return another value indicating if this edit is successful, so I want to edit this variable inside the function itself. How do I do so? 2.How do I change the order of the if/else statements to follow the order of the priority list? It needs to be able to change during runtime as the priority list can change resulting in a different order of movement to try.
[ "Re 2., I would change your relatively-big if/elif tree to a simple loop:\nprioritylist = ('r','u','d','l')\nfor direction in prioritylist:\n if move(direction, location): break\n\nless repetitious, easier to extend in the future if you want to allow diagonal steps or whatever -- and automatically \"follows the priority list\" in whatever order it's in, without any need to change your code itself.\nRe 1., you can return multiple values from a function:\ndef move(direction,location):\n try:\n -snip-\n return True, newlocation\n except Movementerror:\n return False, location\n\nand you would then change the above loop to, e.g.:\nprioritylist = ('r','u','d','l')\nfor direction in prioritylist:\n success, newlocation = move(direction, location)\n if success: break\n\nelse:\n newlocation = location\nusing the else branch of the for, which executes if no break happens in the for, to deal with the case in which no attempt produced a success.\n", "You can use a for-loop, and break out of the loop at the first successful choice:\nfor option in prioritylist:\n if move(option,location): # succeeded\n break\n\nYou should also return True or False, instead of a 1 or 0, as it makes the intention clearer.\nAlso, I should add that the statement about not editing a parameter is not entirely true... you cannot edit the parameter, itself, but you can edit the contents of that parameter assuming it is a mutable object. Tuples, which you are using, are immutable and so cannot be modified, but lists can be modified:\npositions = ['N','S','E','W']\n\ndef mutate_list(p):\n p.reverse()\n\nprint positions # prints ['N', 'S', 'E', 'W']\nmutate_list(positions)\nprint positions # prints ['w', 'E', 'S', 'N']\n\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002745547_python.txt
Q: Sorting objects in Python I want to sort objects using by one of their attributes. As of now, I am doing it in the following way USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True) This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort? I tried, keyFunc=operator.attrgetter('utility[chosenCar]') USpeople.sort(key=keyFunc,reverse=True) However, I get an error saying that there is no attribute 'utility[chosenCar]'. The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form: utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500} I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this? Thanks in advance. A: No, attrgetter will not be any faster than the lambda - it's really just another way of doing the same thing. You may have been confused by a recommendation to use key instead of cmp, which is indeed significantly faster, but you're already doing that. A: to access chosenCar item you'd have to use: >>> P.utility={'chosenCar':25000,'anotherCar':24000,'yetAnotherCar':24500} >>> operator.itemgetter('chosenCar')(operator.attrgetter('utility')(P)) 25000 for the key function you'll have to do the following: >>> def keyfunc(P): util = operator.attrgetter('utility')(P) return operator.itemgetter('chosenCar')(util) >>> USpeople.sort(key=keyfunc,reverse=True) However, your main claim re the better performance of this approach seems poorly researched. I'd suggest to use timeit module to test performance of both approaches for your own data. A: Never, ever, ever optimize based on something you've read. Going into your code and making random changes from what you have to something you think should be faster is not a working optimization strategy. Here is how you optimize if you want to improve your code. Don't. It's often a waste of time. Make a working, testable program. Determine performance metrics—be able to answer "Is this code fast enough?" Realize that your code is already fast enough. If you weren't able to do step (4), profile your code for realistic input to determine where it spends its time. In Python you can use http://docs.python.org/library/profile.html to do this. Bottlenecks occur at unexpected places, and this will tell you where you actually have to put in the effort. Examine the time-consuming code for algorithmic suboptimality. This sometimes occurs at the level you are, but often occurs several levels out too. Improving your algorithm will almost always be the biggest chance at a speedup. If you cannot improve your algorithm, test various pieces of code that do the same thing based and see how they perform. Use http://docs.python.org/library/timeit.html to test snippets (this is harder to get right than people realise, so be careful) and re-run your performance tests and profile. It can be tempting to try to do this step upfront, but this would often prove to be unfruitful. You need to know that what you're optimizing makes sense. I hope this provides some insight into how to speedup your code (and when not to bother). I've seen lots of people try replacing random code with rule-of-thumb optimizations, but I haven't seen those people producing great, fast software. Optimization must be done scientifically, using theory (such as the computer science in 6) and experimentation (such as the timing in 7). In this specific case, I would bet money that SilentGhost's code ultimately is slower than yours. I of course don't know for sure, but neither do you unless you time it. (And I don't think you should bother timing it, I think you should go with the clearest approach, your original one.)
Sorting objects in Python
I want to sort objects using by one of their attributes. As of now, I am doing it in the following way USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True) This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort? I tried, keyFunc=operator.attrgetter('utility[chosenCar]') USpeople.sort(key=keyFunc,reverse=True) However, I get an error saying that there is no attribute 'utility[chosenCar]'. The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form: utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500} I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this? Thanks in advance.
[ "No, attrgetter will not be any faster than the lambda - it's really just another way of doing the same thing.\nYou may have been confused by a recommendation to use key instead of cmp, which is indeed significantly faster, but you're already doing that.\n", "to access chosenCar item you'd have to use:\n>>> P.utility={'chosenCar':25000,'anotherCar':24000,'yetAnotherCar':24500}\n>>> operator.itemgetter('chosenCar')(operator.attrgetter('utility')(P))\n25000\n\nfor the key function you'll have to do the following:\n>>> def keyfunc(P):\n util = operator.attrgetter('utility')(P)\n return operator.itemgetter('chosenCar')(util)\n\n>>> USpeople.sort(key=keyfunc,reverse=True)\n\nHowever, your main claim re the better performance of this approach seems poorly researched. I'd suggest to use timeit module to test performance of both approaches for your own data.\n", "\nNever, ever, ever optimize based on something you've read. Going into your code and making random changes from what you have to something you think should be faster is not a working optimization strategy.\nHere is how you optimize if you want to improve your code. \n\nDon't. It's often a waste of time.\nMake a working, testable program. \nDetermine performance metrics—be able to answer \"Is this code fast enough?\"\nRealize that your code is already fast enough.\nIf you weren't able to do step (4), profile your code for realistic input to determine where it spends its time. In Python you can use http://docs.python.org/library/profile.html to do this. Bottlenecks occur at unexpected places, and this will tell you where you actually have to put in the effort.\nExamine the time-consuming code for algorithmic suboptimality. This sometimes occurs at the level you are, but often occurs several levels out too. Improving your algorithm will almost always be the biggest chance at a speedup.\nIf you cannot improve your algorithm, test various pieces of code that do the same thing based and see how they perform. Use http://docs.python.org/library/timeit.html to test snippets (this is harder to get right than people realise, so be careful) and re-run your performance tests and profile.\nIt can be tempting to try to do this step upfront, but this would often prove to be unfruitful. You need to know that what you're optimizing makes sense. \n\nI hope this provides some insight into how to speedup your code (and when not to bother). I've seen lots of people try replacing random code with rule-of-thumb optimizations, but I haven't seen those people producing great, fast software. Optimization must be done scientifically, using theory (such as the computer science in 6) and experimentation (such as the timing in 7).\nIn this specific case, I would bet money that SilentGhost's code ultimately is slower than yours. I of course don't know for sure, but neither do you unless you time it. \n(And I don't think you should bother timing it, I think you should go with the clearest approach, your original one.)\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002743773_python_sorting.txt
Q: How can I tell whether screen is running? I am trying to run a Python program to see if the screen program is running. If it is, then the program should not run the rest of the code. This is what I have and it's not working: #!/usr/bin/python import os var1 = os.system ('screen -r > /root/screenlog/screen.log') fd = open("/root/screenlog/screen.log") content = fd.readline() while content: if content == "There is no screen to be resumed.": os.system ('/etc/init.d/tunnel.sh') print "The tunnel is now active." else: print "The tunnel is running." fd.close() I know there are probably several things here that don't need to be and quite a few that I'm missing. I will be running this program in cron. A: from subprocess import Popen, PIPE def screen_is_running(): out = Popen("screen -list",shell=True,stdout=PIPE).communicate()[0] return not out.startswith("This room is empty")
How can I tell whether screen is running?
I am trying to run a Python program to see if the screen program is running. If it is, then the program should not run the rest of the code. This is what I have and it's not working: #!/usr/bin/python import os var1 = os.system ('screen -r > /root/screenlog/screen.log') fd = open("/root/screenlog/screen.log") content = fd.readline() while content: if content == "There is no screen to be resumed.": os.system ('/etc/init.d/tunnel.sh') print "The tunnel is now active." else: print "The tunnel is running." fd.close() I know there are probably several things here that don't need to be and quite a few that I'm missing. I will be running this program in cron.
[ "from subprocess import Popen, PIPE\n\ndef screen_is_running():\n out = Popen(\"screen -list\",shell=True,stdout=PIPE).communicate()[0]\n return not out.startswith(\"This room is empty\")\n\n" ]
[ 2 ]
[ "Maybe the error message that you redirect on the first os.system call is written on the standard error instead of the standard output. You should try replacing this line with:\nvar1 = os.system ('screen -r 2> /root/screenlog/screen.log')\n\nNote the 2> to redirect standard error to your file.\n" ]
[ -1 ]
[ "gnu_screen", "linux", "python" ]
stackoverflow_0002745711_gnu_screen_linux_python.txt
Q: Python keyword arguments I have several layers of function calls, passing around a common dictionary of key word arguments: def func1(**qwargs): func2(**qwargs) func3(**qwargs) I would like to supply some default arguments in some of the subsequent function calls, something like this: def func1(**qwargs): func2(arg = qwargs.get("arg", default), **qwargs) func3(**qwargs) The problem with this approach is that if arg is inside qwargs, a TypeError is raised with "got multiple values for keyword argument". I don't want to set qwargs["arg"] to default, because then func3 gets this argument without warrant. I could make a copy.copy of the qwargs and set "arg" in the copy, but qwargs could have large data structures in it and I don't want to copy them (maybe copy.copy wouldn't, only copy.deepcopy?). What's the pythonic thing to do here? A: Just build and use another dict for the purpose of calling func2, leaving the original alone for the later call to func3: def func1(**qwargs): d = dict(arg=default) d.update(qwqargs) func2(**d) func3(**qwargs) This is if you want a setting for arg in qwargs to override the default. Otherwise (if you want default to override any possible setting for arg in qwargs): def func1(**qwargs): d = dict(qwargs, arg=default) func2(**d) func3(**qwargs) since the keyword-argument to dict overrides the value in the positional argument, if any. A: To create a new dict with the same keys and values you can use newdict=dict(qwargs) If qwargs doesn't contain really many keys that's cheap. If it's possible you could rewrite the functions to take their args really as dict instead of multiple args.
Python keyword arguments
I have several layers of function calls, passing around a common dictionary of key word arguments: def func1(**qwargs): func2(**qwargs) func3(**qwargs) I would like to supply some default arguments in some of the subsequent function calls, something like this: def func1(**qwargs): func2(arg = qwargs.get("arg", default), **qwargs) func3(**qwargs) The problem with this approach is that if arg is inside qwargs, a TypeError is raised with "got multiple values for keyword argument". I don't want to set qwargs["arg"] to default, because then func3 gets this argument without warrant. I could make a copy.copy of the qwargs and set "arg" in the copy, but qwargs could have large data structures in it and I don't want to copy them (maybe copy.copy wouldn't, only copy.deepcopy?). What's the pythonic thing to do here?
[ "Just build and use another dict for the purpose of calling func2, leaving the original alone for the later call to func3:\ndef func1(**qwargs):\n d = dict(arg=default)\n d.update(qwqargs)\n func2(**d)\n func3(**qwargs)\n\nThis is if you want a setting for arg in qwargs to override the default. Otherwise (if you want default to override any possible setting for arg in qwargs):\ndef func1(**qwargs):\n d = dict(qwargs, arg=default)\n func2(**d)\n func3(**qwargs)\n\nsince the keyword-argument to dict overrides the value in the positional argument, if any.\n", "To create a new dict with the same keys and values you can use \n newdict=dict(qwargs)\n\nIf qwargs doesn't contain really many keys that's cheap.\nIf it's possible you could rewrite the functions to take their args really as dict instead of multiple args.\n" ]
[ 2, 1 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0002745703_keyword_argument_python.txt
Q: Best way to parse XMPP-like XML streams? I am working on a server application which receives data over a TCP socket in an XMPP-like XML format, i.e. every child of the <root> element essentially represents one separate request (stanza). The connection is closed as soon as </root> is received. I do know that I must use a stream parser like SAX, somehow. Though, for convenience, I'd prefer to have a tree-like interface to access each stanza's child elements. (The data sent with every request is not large so I think it makes sense to read each stanza as a whole.) What's the best way to realize that in Python (preferably v3)? This is the code I'd like to build it in. Feel free to point me in a totally different direction to solve this issue. import socketserver import settings class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass class MyRequestHandler(socketserver.StreamRequestHandler): def handle(self): pass if __name__ == '__main__': server = MyServer((settings.host, settings.port), MyRequestHandler) server.serve_forever() A: You'll want to use a push based parser that emits SAX events. Basically you want a parser that you can call pushChunk(data) with a partial bit of data, and have it an event handler for the first-level child end tag event that generates your stanzas. That can then be sent to application processing logic. If you want to see an example of this, here is the expat parser for libstrophe, an XMPP client library I wrote: http://github.com/metajack/libstrophe/blob/master/src/parser_expat.c Building a whole document for each stanza is quite expensive. It is possible to implement this with a single parser instance, as opposed to continually making new document parsers for each stanza. If you need a working Python version, you can probably use or pull out the code from Twisted Words (twisted.words.xish I believe). A: What we did for Skates is that we use a Sax parser to build the stream, but use this parser to build a whole document for each stanza received.
Best way to parse XMPP-like XML streams?
I am working on a server application which receives data over a TCP socket in an XMPP-like XML format, i.e. every child of the <root> element essentially represents one separate request (stanza). The connection is closed as soon as </root> is received. I do know that I must use a stream parser like SAX, somehow. Though, for convenience, I'd prefer to have a tree-like interface to access each stanza's child elements. (The data sent with every request is not large so I think it makes sense to read each stanza as a whole.) What's the best way to realize that in Python (preferably v3)? This is the code I'd like to build it in. Feel free to point me in a totally different direction to solve this issue. import socketserver import settings class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass class MyRequestHandler(socketserver.StreamRequestHandler): def handle(self): pass if __name__ == '__main__': server = MyServer((settings.host, settings.port), MyRequestHandler) server.serve_forever()
[ "You'll want to use a push based parser that emits SAX events. Basically you want a parser that you can call pushChunk(data) with a partial bit of data, and have it an event handler for the first-level child end tag event that generates your stanzas. That can then be sent to application processing logic.\nIf you want to see an example of this, here is the expat parser for libstrophe, an XMPP client library I wrote:\nhttp://github.com/metajack/libstrophe/blob/master/src/parser_expat.c\nBuilding a whole document for each stanza is quite expensive. It is possible to implement this with a single parser instance, as opposed to continually making new document parsers for each stanza.\nIf you need a working Python version, you can probably use or pull out the code from Twisted Words (twisted.words.xish I believe).\n", "What we did for Skates is that we use a Sax parser to build the stream, but use this parser to build a whole document for each stanza received.\n" ]
[ 3, 1 ]
[]
[]
[ "network_protocols", "python", "stream", "xml", "xmpp" ]
stackoverflow_0002741642_network_protocols_python_stream_xml_xmpp.txt
Q: SQLAlchemy - SQLite for testing and Postgresql for development - How to port? I want to use sqlite memory database for all my testing and Postgresql for my development/production server. But the SQL syntax is not same in both dbs. for ex: SQLite has autoincrement, and Postgresql has serial Is it easy to port the SQL script from sqlite to postgresql... what are your solutions? If you want me to use standard SQL, how should I go about generating primary key in both the databases? A: My suggestion would be: don't. The capabilities of Postgresql are far beyond what SQLite can provide, particularly in the areas of date/numeric support, functions and stored procedures, ALTER support, constraints, sequences, other types like UUID, etc., and even using various SQLAlchemy tricks to try to smooth that over will only get you a slight bit further. In particular date and interval arithmetic are totally different beasts on the two platforms, and SQLite has no support for precision decimals (non floating-point) the way PG does. PG is very easy to install on every major OS and life is just easier if you go that route. A: Don't do it. Don't test in one environment and release and develop in another. Your asking for buggy software using this process. A: Although we started with sqllite for our testing environment we are seriously looking to having postgres running for each developer. We have scripts that build the test database that our unittests run against, and we have a 'development' version that the devs use. We investigated running postgres 'in memory' on ramdisk, but this discussion: http://dbaspot.com/forums/postgresql/395602-memory-postgresql-database.html suggests that it isn't necessary. We haven't run into any problems yet, but it is still early in the development process and we haven't had to do anything too fancy yet. zzzeek points out some items that will probably trip us up soon :( Best make the move now....
SQLAlchemy - SQLite for testing and Postgresql for development - How to port?
I want to use sqlite memory database for all my testing and Postgresql for my development/production server. But the SQL syntax is not same in both dbs. for ex: SQLite has autoincrement, and Postgresql has serial Is it easy to port the SQL script from sqlite to postgresql... what are your solutions? If you want me to use standard SQL, how should I go about generating primary key in both the databases?
[ "My suggestion would be: don't. The capabilities of Postgresql are far beyond what SQLite can provide, particularly in the areas of date/numeric support, functions and stored procedures, ALTER support, constraints, sequences, other types like UUID, etc., and even using various SQLAlchemy tricks to try to smooth that over will only get you a slight bit further. In particular date and interval arithmetic are totally different beasts on the two platforms, and SQLite has no support for precision decimals (non floating-point) the way PG does. PG is very easy to install on every major OS and life is just easier if you go that route.\n", "Don't do it. Don't test in one environment and release and develop in another. Your asking for buggy software using this process.\n", "Although we started with sqllite for our testing environment we are seriously looking to having postgres running for each developer. We have scripts that build the test database that our unittests run against, and we have a 'development' version that the devs use.\nWe investigated running postgres 'in memory' on ramdisk, but this discussion: http://dbaspot.com/forums/postgresql/395602-memory-postgresql-database.html suggests that it isn't necessary. \nWe haven't run into any problems yet, but it is still early in the development process and we haven't had to do anything too fancy yet.\nzzzeek points out some items that will probably trip us up soon :(\nBest make the move now....\n" ]
[ 19, 12, 4 ]
[]
[]
[ "postgresql", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0002716847_postgresql_python_sqlalchemy_sqlite.txt
Q: Check if command had some trouble in Python? I have this command h = urllib.urlopen("http://google.com/") How can I check if it retrieves me some error, internet down or something I don't expect? For example, something like if error print 'ERROR' Thank you A: urllib.urlopen is deprecated as it was removed in Python 3.0. Use urllib2.urlopen instead and in the documentation it says: Raises URLError on errors. So do: try: h = urllib2.urlopen("http://google.com/") except urllib2.URLError as e: # do something with the exception e.g. print 'Error:', e.reason or just a (meaningless) error message: try: h = urllib2.urlopen("http://google.com/") except urllib2.URLError: print 'An error occurred.' URLError: exception urllib2.URLError The handlers raise this exception (or derived exceptions) when they run into a problem. It is a subclass of IOError. reason The reason for this error. It can be a message string or another exception instance (socket.error for remote URLs, OSError for local URLs). You might want to read about Errors and Exceptions. A: If that isn't able to do something that makes sense, it will raise an exception, which you can accept with try/except. urllib.urlopen is deprecated in favour of urllib2.urlopen. >>> import urllib2 >>> urllib2.urlopen('not a valid URL') Traceback (most recent call last): File "<stdin>", line 1, in <module> ... ValueError: unknown url type: not a valid URL >>> >>> urllib2.urlopen("http://thiswebsitedoesntexistq.com") Traceback (most recent call last): File "<stdin>", line 1, in <module> ... urllib2.HTTPError: HTTP Error 404: Not Found >>> >>> # URLError is the parent class for the errors raised by urlopen ... # if it can parse the URL ... >>> issubclass(urllib2.HTTPError, urllib2.URLError) True I could catch these like try: urllib2.urlopen(some_url) except ValueError: print "Not a real URL" except urllib2.HTTPError: print "%s does not exist" % (some_url,) or I could let them propagate if I didn't have some sane way to react. (Oftentimes people want to catch an error so they can print the error and close their program. This is usually silly, since that's what Python would do anyway if you didn't catch and fix the error.) A: An exception such as an IOError might occur - you could use exception handling to deal with this. For example: try: h = urllib.urlopen("http://google.com/") except IOError as e: print "Error opening URL" A: I believe an exception is thrown on error. If you catch that and use the error code you can easilly do the appropriate error handling.
Check if command had some trouble in Python?
I have this command h = urllib.urlopen("http://google.com/") How can I check if it retrieves me some error, internet down or something I don't expect? For example, something like if error print 'ERROR' Thank you
[ "urllib.urlopen is deprecated as it was removed in Python 3.0. Use urllib2.urlopen instead and in the documentation it says:\n\nRaises URLError on errors.\n\nSo do:\ntry:\n h = urllib2.urlopen(\"http://google.com/\")\nexcept urllib2.URLError as e:\n # do something with the exception e.g.\n print 'Error:', e.reason\n\nor just a (meaningless) error message:\ntry:\n h = urllib2.urlopen(\"http://google.com/\")\nexcept urllib2.URLError:\n print 'An error occurred.'\n\n\nURLError:\n\nexception urllib2.URLError\nThe handlers raise this exception (or derived exceptions) when they run into a problem. It is a subclass of IOError.\nreason\nThe reason for this error. It can be a message string or another exception instance (socket.error for remote URLs, OSError for local URLs).\n\n\nYou might want to read about Errors and Exceptions.\n", "\nIf that isn't able to do something that makes sense, it will raise an exception, which you can accept with try/except. \nurllib.urlopen is deprecated in favour of urllib2.urlopen.\n>>> import urllib2\n>>> urllib2.urlopen('not a valid URL')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n ...\nValueError: unknown url type: not a valid URL\n>>>\n>>> urllib2.urlopen(\"http://thiswebsitedoesntexistq.com\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n ...\nurllib2.HTTPError: HTTP Error 404: Not Found\n>>>\n>>> # URLError is the parent class for the errors raised by urlopen \n... # if it can parse the URL\n...\n>>> issubclass(urllib2.HTTPError, urllib2.URLError) \nTrue\n\n\nI could catch these like\ntry:\n urllib2.urlopen(some_url)\nexcept ValueError:\n print \"Not a real URL\"\nexcept urllib2.HTTPError:\n print \"%s does not exist\" % (some_url,)\n\nor I could let them propagate if I didn't have some sane way to react. (Oftentimes people want to catch an error so they can print the error and close their program. This is usually silly, since that's what Python would do anyway if you didn't catch and fix the error.)\n", "An exception such as an IOError might occur - you could use exception handling to deal with this. For example:\ntry:\n h = urllib.urlopen(\"http://google.com/\")\nexcept IOError as e: \n print \"Error opening URL\"\n\n", "I believe an exception is thrown on error. If you catch that and use the error code you can easilly do the appropriate error handling.\n" ]
[ 9, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002745968_python.txt
Q: Porting library from Java to Python I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world. I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results. Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another. A: If it were me, I'd consider doing the work by hand. A couple thousand lines of code isn't a lot of code, and by rewriting it yourself (rather than translating it automatically), you'll be in a position to decide how to take advantage of Python idioms appropriately. (FWIW, I worked Java almost exclusively for 9 years, and I'm now working in Python, so I know the kind of translation you'd have to do.) A: Code is always better the second time you write it anyway.... Plus a few thousand lines of Java can probably be translated into a few hundred of Python. A: Have a look at Jython. It can fairly seamlessly integrate Python on top of Java, and provide access to Java libraries but still let you act on them dynamically. A: Automatic translators (f2c, j2py, whatever) normally emit code you wouldn't want to touch by hand. This is fine when all you need to do is use the output (for example, if you have a C compiler and no Fortran compiler, f2c allows you to compile Fortran programs), but terrible when you need to do anything to the code afterwards. If you intend to use this as anything other than a black box, translate it by hand. At that size, it won't be too hard. A: I would write it again by hand. I don't know of any automated tools that would generate non-disgusting looking Python, and having ported Java code to Python myself, I found the result was both higher quality than the original and considerably shorter. You gain quality because Python is more expressive (for example, anonymous inner class MouseAdapters and the like go away in favor of simple first class functions), and you also gain the benefit of writing it a second time. It also is considerably shorter: for example, 99% of getters/setters can just be left out in favor of directly accessing the fields. For the other 1% which actually do something you can use property(). However as David mentioned, if you don't ever need to read or maintain the code, an automatic translator would be fine. A: Jython's not what you're looking for in the final solution, but it will make the porting go much smoother. My approach would be: If there are existing tests (unit or otherwise), rewrite them in Jython (using Python's unittest) Write some characterization tests in Jython (tests that record the current behavior) Start porting class by class: For each class, subclass it in Jython and port the methods one by one, making the method in the superclass abstract After each change, run the tests! You'll now have working Jython code that hopefully has minimal dependencies on Java. Run the tests in CPython and fix whatever's left. Refactor - you'll want to Pythonify the code, probably simplifying it a lot with Python idioms. This is safe and easy because of the tests. I've this in the past with great success. A: I've used Java2Python. It's not too bad, you still need to understand the code as it doesn't do everything correctly, but it does help.
Porting library from Java to Python
I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world. I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results. Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.
[ "If it were me, I'd consider doing the work by hand. A couple thousand lines of code isn't a lot of code, and by rewriting it yourself (rather than translating it automatically), you'll be in a position to decide how to take advantage of Python idioms appropriately. (FWIW, I worked Java almost exclusively for 9 years, and I'm now working in Python, so I know the kind of translation you'd have to do.)\n", "Code is always better the second time you write it anyway....\nPlus a few thousand lines of Java can probably be translated into a few hundred of Python.\n", "Have a look at Jython. It can fairly seamlessly integrate Python on top of Java, and provide access to Java libraries but still let you act on them dynamically.\n", "Automatic translators (f2c, j2py, whatever) normally emit code you wouldn't want to touch by hand. This is fine when all you need to do is use the output (for example, if you have a C compiler and no Fortran compiler, f2c allows you to compile Fortran programs), but terrible when you need to do anything to the code afterwards. If you intend to use this as anything other than a black box, translate it by hand. At that size, it won't be too hard.\n", "I would write it again by hand. I don't know of any automated tools that would generate non-disgusting looking Python, and having ported Java code to Python myself, I found the result was both higher quality than the original and considerably shorter.\nYou gain quality because Python is more expressive (for example, anonymous inner class MouseAdapters and the like go away in favor of simple first class functions), and you also gain the benefit of writing it a second time. \nIt also is considerably shorter: for example, 99% of getters/setters can just be left out in favor of directly accessing the fields. For the other 1% which actually do something you can use property().\nHowever as David mentioned, if you don't ever need to read or maintain the code, an automatic translator would be fine.\n", "Jython's not what you're looking for in the final solution, but it will make the porting go much smoother.\nMy approach would be:\n\nIf there are existing tests (unit or otherwise), rewrite them in Jython (using Python's unittest)\nWrite some characterization tests in Jython (tests that record the current behavior)\nStart porting class by class:\n\n\nFor each class, subclass it in Jython and port the methods one by one, making the method in the superclass abstract\nAfter each change, run the tests!\n\nYou'll now have working Jython code that hopefully has minimal dependencies on Java.\nRun the tests in CPython and fix whatever's left.\nRefactor - you'll want to Pythonify the code, probably simplifying it a lot with Python idioms. This is safe and easy because of the tests.\n\nI've this in the past with great success.\n", "I've used Java2Python. It's not too bad, you still need to understand the code as it doesn't do everything correctly, but it does help.\n" ]
[ 9, 6, 5, 3, 3, 2, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0000448095_java_python.txt
Q: Adding string to end of URL To practise some more bits of python I've been having a go at the challenges on pythonchallenge.com In brief, this challenge as a first step requires one to load an html page from a url with a number at the end. The page contains a single line of text which has in it a number. That number is used to replace the existing one in the url, and so take you to the next page in the sequence. Apparently this continues for some time... (there is more to this challenge, but getting that part working is the first step). My code for doing so is below (limited to running through what should be the first four pages in the sequence, for the time being). For some reason it works the first time - it gets the second page in the sequence, reads the number, goes to the third, and reads the number there. But then it gets stuck on the third. I don't understand why, though think it might be something to do with my attempt to turn the number into a string before putting it on the end of the URL. To answer the obvious question, yes I know that pythonchallenge is working OK - you can do the url-numbers thing manually for as long as you have the patience, to confirm, if you like :p import httplib2 import re counter = 0 new = '12345' #the number for the initial page in the sequence, as a string while True: counter = counter + 1 if counter == 5: break original = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' nextpage = original+new #each page in the sequence is visited by adding #the number after 'nothing=' print(nextpage) h = httplib2.Http('.cache') response, content = h.request(nextpage, "GET") #get the content of the page, #which includes the number for the #*next* page in the sequence p = re.compile(r'\d{4,5}$') #regex to find a 4 to 5 digit number at the end of #the content new = str((p.findall(content))) #make the regex result a string - is this #where the problem lies? print('cached?', response.fromcache) #I was worried my requests were somehow #being cached not actually sent afresh to #pythonchallenge. But it seems they aren't. print(content) print(new) And the output of the above is as follows, below. It seems to work fine for the first run through (adding the 92512 to the url and successfully getting the next page and finding the next value) but after that it just gets stuck, and doesn't seem to load the following page in the sequence. Testing by changing the url manually in a browser confirms that the number is correct and pythonchallenge is working OK. It looks to me like something is going wrong turning my regex search into a string to add onto the end of the URL - but why it should work the first time and not the second I don't know. I was also concerned maybe my requests were only getting as far as a cache (I'm new to httplib2 and not confident about how it does caching) but they seem not to be. I also added a no-cache argument to the request just to be sure (not shown in this code) but it didn't help. http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345 ('cached?', False) and the next nothing is 92512 ['92512'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['92512'] ('cached?', False) and the next nothing is 72758 ['72758'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758'] ('cached?', False) and the next nothing is 72758 ['72758'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758'] ('cached?', False) and the next nothing is 72758 ['72758'] I would be grateful to anyone who can point out where I am going wrong, as well as for any relevant tips Thanks in advance... A: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758'] ^^ ^^ The problem is here I think. findall() return a list: re.findall(pattern, string[, flags]) Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. -- Python doc
Adding string to end of URL
To practise some more bits of python I've been having a go at the challenges on pythonchallenge.com In brief, this challenge as a first step requires one to load an html page from a url with a number at the end. The page contains a single line of text which has in it a number. That number is used to replace the existing one in the url, and so take you to the next page in the sequence. Apparently this continues for some time... (there is more to this challenge, but getting that part working is the first step). My code for doing so is below (limited to running through what should be the first four pages in the sequence, for the time being). For some reason it works the first time - it gets the second page in the sequence, reads the number, goes to the third, and reads the number there. But then it gets stuck on the third. I don't understand why, though think it might be something to do with my attempt to turn the number into a string before putting it on the end of the URL. To answer the obvious question, yes I know that pythonchallenge is working OK - you can do the url-numbers thing manually for as long as you have the patience, to confirm, if you like :p import httplib2 import re counter = 0 new = '12345' #the number for the initial page in the sequence, as a string while True: counter = counter + 1 if counter == 5: break original = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' nextpage = original+new #each page in the sequence is visited by adding #the number after 'nothing=' print(nextpage) h = httplib2.Http('.cache') response, content = h.request(nextpage, "GET") #get the content of the page, #which includes the number for the #*next* page in the sequence p = re.compile(r'\d{4,5}$') #regex to find a 4 to 5 digit number at the end of #the content new = str((p.findall(content))) #make the regex result a string - is this #where the problem lies? print('cached?', response.fromcache) #I was worried my requests were somehow #being cached not actually sent afresh to #pythonchallenge. But it seems they aren't. print(content) print(new) And the output of the above is as follows, below. It seems to work fine for the first run through (adding the 92512 to the url and successfully getting the next page and finding the next value) but after that it just gets stuck, and doesn't seem to load the following page in the sequence. Testing by changing the url manually in a browser confirms that the number is correct and pythonchallenge is working OK. It looks to me like something is going wrong turning my regex search into a string to add onto the end of the URL - but why it should work the first time and not the second I don't know. I was also concerned maybe my requests were only getting as far as a cache (I'm new to httplib2 and not confident about how it does caching) but they seem not to be. I also added a no-cache argument to the request just to be sure (not shown in this code) but it didn't help. http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345 ('cached?', False) and the next nothing is 92512 ['92512'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['92512'] ('cached?', False) and the next nothing is 72758 ['72758'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758'] ('cached?', False) and the next nothing is 72758 ['72758'] http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758'] ('cached?', False) and the next nothing is 72758 ['72758'] I would be grateful to anyone who can point out where I am going wrong, as well as for any relevant tips Thanks in advance...
[ "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=['72758']\n ^^ ^^\n\nThe problem is here I think. findall() return a list:\n\nre.findall(pattern, string[, flags])\nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.\n-- Python doc\n\n" ]
[ 1 ]
[]
[]
[ "httplib2", "python", "string", "url_rewriting" ]
stackoverflow_0002746271_httplib2_python_string_url_rewriting.txt
Q: PyDev and Django: PyDev breaking Django shell? I've set up a new project, and populated it with simple models. (Essentially I'm following the tut.) When I run python manage.py shell on the command line, it works fine: >python manage.py shell Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from mysite.myapp.models import School >>> School.objects.all() [] Works great. Then, I try to do the same thing in Eclipse (using a Django project that is composed of the same files.) Right click on mysite project >> Django >> Shell with Django environment This is the output from the PyDev Console: >>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) C:\Python26\python.exe 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] >>> >>> from django.core import management;import mysite.settings as settings;management.setup_environ(settings) 'path\\to\\mysite' >>> from mysite.myapp.models import School >>> School.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__ self._result_cache.extend(list(self._iter)) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 238, in iterator for row in self.query.results_iter(): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 287, in results_iter for rows in self.execute_sql(MULTI): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 2368, in execute_sql cursor = self.connection.cursor() File "C:\Python26\lib\site-packages\django\db\backends\__init__.py", line 81, in cursor cursor = self._cursor() File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line 170, in _cursor self.connection = Database.connect(**kwargs) OperationalError: unable to open database file What am I doing wrong here? A: The error is about not being open the database file. So I'd guess that the path to the database in your settings.py is a relative path, and PyDev starts the shell with a different current directory than you normally use. If this is the case, change the DATABASE_NAME setting to an absolute path and it should work.
PyDev and Django: PyDev breaking Django shell?
I've set up a new project, and populated it with simple models. (Essentially I'm following the tut.) When I run python manage.py shell on the command line, it works fine: >python manage.py shell Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from mysite.myapp.models import School >>> School.objects.all() [] Works great. Then, I try to do the same thing in Eclipse (using a Django project that is composed of the same files.) Right click on mysite project >> Django >> Shell with Django environment This is the output from the PyDev Console: >>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) C:\Python26\python.exe 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] >>> >>> from django.core import management;import mysite.settings as settings;management.setup_environ(settings) 'path\\to\\mysite' >>> from mysite.myapp.models import School >>> School.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__ self._result_cache.extend(list(self._iter)) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 238, in iterator for row in self.query.results_iter(): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 287, in results_iter for rows in self.execute_sql(MULTI): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 2368, in execute_sql cursor = self.connection.cursor() File "C:\Python26\lib\site-packages\django\db\backends\__init__.py", line 81, in cursor cursor = self._cursor() File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line 170, in _cursor self.connection = Database.connect(**kwargs) OperationalError: unable to open database file What am I doing wrong here?
[ "The error is about not being open the database file. So I'd guess that the path to the database in your settings.py is a relative path, and PyDev starts the shell with a different current directory than you normally use.\nIf this is the case, change the DATABASE_NAME setting to an absolute path and it should work.\n" ]
[ 3 ]
[]
[]
[ "django", "pydev", "python" ]
stackoverflow_0002746342_django_pydev_python.txt
Q: Django custom template tag with 'parser.compile_filter(tokens[2])' doesn't work I tried to implement the solution proposed by T. Stone on my question "how-do-i-pass-a-lot-of-parameters-to-views-in-django" ([link text][1]). I can't manage to get any result. It's difficult to find information about the compile_filter(), but as far as I understand cls(queryset=parser.compile_filter(tokens[2]), template=template) should render the template with the 'variable' tokens[2]. But that doesn't seems to work. Here is the code of my implementation: models.py: class SalesRecord(models.Model): name = models.CharField(max_length=100) month = models.CharField(max_length=10) revenue = models.IntegerField() def __unicode__(self): return self.name + " - " + self.month + " - " + str(self.revenue) views.py: def test(request, *args, **kwargs): name = 'John' monthly_sales_qs = SalesRecord.objects.filter(name=name) print monthly_sales_qs return render_to_response('test.html', locals()) mytags.py: class DataForTag(template.Node): @classmethod def handle_token(cls, parser, token, template): tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0]) if len(tokens) == 3: return cls(queryset=parser.compile_filter(tokens[2]), template=template) else: raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0]) def __init__(self, queryset=None, template=None): self.queryset = queryset self.template = template def render(self, context): return render_to_string(self.template, {'queryset':self.queryset}) @register.tag def render_data_table(parser, token): return DataForTag.handle_token(parser, token, 'testtable.html') test.html: {% load mytags %} {% render_data_table for monthly_sales_qs %} testtable.html: <table class="tabledata"> <tr> {% for m in queryset.month %} <td>queryset.revenue</td> {% endfor %} </tr> </table> The template just returns an empty page. It seems to me that the queryset is empty. Does someone have an idea what I'm doing wrong? (probably some beginners stupidity ;) A: Mark... Couple of things: I was in a rush the other day when I posted that code for you. Within the render method variables need to be resolved as such... def render(self, context): qs = self.queryset.resolve(context) return render_to_string(self.template, { 'queryset': qs } ) Also, in your template, this is wrong: {% for m in queryset.month %} <td>queryset.revenue</td> {% endfor %} First, variables need to be wrapped in {{ }}'s like {{ queryset.revenue }} and second you're not doing anything with the m value so having the for loop is pointless. Lastly, the pattern I showed you in the answer I found in the django.contrib.comments app. If you want to follow some existing/working examples I'd recommend checking out the comments template tags. Lots of great ideas in that app.
Django custom template tag with 'parser.compile_filter(tokens[2])' doesn't work
I tried to implement the solution proposed by T. Stone on my question "how-do-i-pass-a-lot-of-parameters-to-views-in-django" ([link text][1]). I can't manage to get any result. It's difficult to find information about the compile_filter(), but as far as I understand cls(queryset=parser.compile_filter(tokens[2]), template=template) should render the template with the 'variable' tokens[2]. But that doesn't seems to work. Here is the code of my implementation: models.py: class SalesRecord(models.Model): name = models.CharField(max_length=100) month = models.CharField(max_length=10) revenue = models.IntegerField() def __unicode__(self): return self.name + " - " + self.month + " - " + str(self.revenue) views.py: def test(request, *args, **kwargs): name = 'John' monthly_sales_qs = SalesRecord.objects.filter(name=name) print monthly_sales_qs return render_to_response('test.html', locals()) mytags.py: class DataForTag(template.Node): @classmethod def handle_token(cls, parser, token, template): tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0]) if len(tokens) == 3: return cls(queryset=parser.compile_filter(tokens[2]), template=template) else: raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0]) def __init__(self, queryset=None, template=None): self.queryset = queryset self.template = template def render(self, context): return render_to_string(self.template, {'queryset':self.queryset}) @register.tag def render_data_table(parser, token): return DataForTag.handle_token(parser, token, 'testtable.html') test.html: {% load mytags %} {% render_data_table for monthly_sales_qs %} testtable.html: <table class="tabledata"> <tr> {% for m in queryset.month %} <td>queryset.revenue</td> {% endfor %} </tr> </table> The template just returns an empty page. It seems to me that the queryset is empty. Does someone have an idea what I'm doing wrong? (probably some beginners stupidity ;)
[ "Mark...\nCouple of things: I was in a rush the other day when I posted that code for you. Within the render method variables need to be resolved as such...\ndef render(self, context):\n qs = self.queryset.resolve(context)\n return render_to_string(self.template, { 'queryset': qs } )\n\nAlso, in your template, this is wrong:\n{% for m in queryset.month %}\n <td>queryset.revenue</td>\n {% endfor %}\n\nFirst, variables need to be wrapped in {{ }}'s like {{ queryset.revenue }} and second you're not doing anything with the m value so having the for loop is pointless.\nLastly, the pattern I showed you in the answer I found in the django.contrib.comments app. If you want to follow some existing/working examples I'd recommend checking out the comments template tags. Lots of great ideas in that app.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "templatetags" ]
stackoverflow_0002746255_django_python_templatetags.txt
Q: django - How to cross check ModelAdmin and its inlines? I have two models (ModelParent and ModelChild) with same m2m fields on Subject model. ModelChild has a foreign key on ModelParent and ModelChild is defined as inline for ModelParent on admin page. ### models.py ### class Subject(Models.Model): pass class ModelParent(models.Model): subjects_parent = ManyToManyField(Subject) class ModelChild(models.Model): parent = ForeignKey(ModelParent) subjects_child = ManyToManyField(Subject) ### admin.py ### class ModelChildInline(admin.TabularInline): model = ModelChild class ModelParentAdmin(admin.ModelAdmin): inlines = [ModelChildInline] admin.site.register(ModelParent, ModelParentAdmin) I have one important restriction though, ModelChild's subjects_child field must not reference any subject that subject_parent does with its subjects_parent. So, if I select the same Subject (in subject_parent and subject_child) on Admin page for both models, how can I validate this? If only one field changes you validate it against the db, but what if both change (subject_parent and subject_child)? How can I validate both forms together before saving? A: I have inherited a new class named ModelAdminWithInline from admin.ModelAdmin and modified methods add_view(...) and change_view(...) to call function is_cross_valid(self, form, formsets), where you can validate all the forms together. Both functions had: #... if all_valid(formsets) and form_validated: #... changed to: #... formsets_validated = all_valid(formsets) cross_validated = self.is_cross_valid(form, formsets) if formsets_validated and form_validated and cross_validated: #... The new function is_cross_valid(...) is defined like this: def is_cross_valid(self, form, formsets): return True so the new class should work exactly the same as ModelAdmin if you don't change is_cross_valid(...) function. Now my admin.py looks like this: ###admin.py### class ModelAdminWithInline(admin.ModelAdmin): def is_cross_valid(self, form, formsets): return True def add_view(self, request, form_url='', extra_context=None): #modified code def change_view(self, request, object_id, extra_context=None): #modified code class ModelChildInline(admin.TabularInline): model = ModelChild class ModelParentAdmin(ModelAdminWithInline): inlines = [ModelChildInline] def is_cross_valid(self, form, formsets): #Do some cross validation on forms #For example, here is my particular validation: valid = True if hasattr(form, 'cleaned_data'): subjects_parent = form.cleaned_data.get("subjects_parent") #You can access forms from formsets like this: for formset in formsets: for formset_form in formset.forms: if hasattr(formset_form, 'cleaned_data'): subjects_child = formset_form.cleaned_data.get("subjects_child") delete_form = formset_form.cleaned_data.get("DELETE") if subjects_child and (delete_form == False): for subject in subjects_child: if subject in subjects_parent: valid = False #From here you can still report errors like in regular forms: if "subjects_child" in formset_form.cleaned_data.keys(): formset_form._errors["subjects_child"] = ErrorList([u"Subject %s is already selected in parent ModelParent" % subject]) del formset_form.cleaned_data["subjects_child"] else: formset_form._errors["subjects_child"] += ErrorList(u"Subject %s is already selected in parent ModelParent" % subject]) #return True on success or False otherwise. return valid admin.site.register(ModelParent, ModelParentAdmin) The solution is a little bit hackish but it works :). The errors show up the same as with regular ModelForm and ModelAdmin classes. Django 1.2 (which should be released shortly) should have model validation, so I hope that then this problem could be solved more nicely. A: The admin classes do not have the clean() method. Their forms do. Each admin class has a parameter called form. You simply extend the default form (it's the normal ModelAdmin form), implement the clean() method and add the form to the admin class. Example: class SomeForm(ModelForm): #some code def clean(self): #some code class SomeAdminClass(ModelAdmin): #some code form = SomeForm #more code
django - How to cross check ModelAdmin and its inlines?
I have two models (ModelParent and ModelChild) with same m2m fields on Subject model. ModelChild has a foreign key on ModelParent and ModelChild is defined as inline for ModelParent on admin page. ### models.py ### class Subject(Models.Model): pass class ModelParent(models.Model): subjects_parent = ManyToManyField(Subject) class ModelChild(models.Model): parent = ForeignKey(ModelParent) subjects_child = ManyToManyField(Subject) ### admin.py ### class ModelChildInline(admin.TabularInline): model = ModelChild class ModelParentAdmin(admin.ModelAdmin): inlines = [ModelChildInline] admin.site.register(ModelParent, ModelParentAdmin) I have one important restriction though, ModelChild's subjects_child field must not reference any subject that subject_parent does with its subjects_parent. So, if I select the same Subject (in subject_parent and subject_child) on Admin page for both models, how can I validate this? If only one field changes you validate it against the db, but what if both change (subject_parent and subject_child)? How can I validate both forms together before saving?
[ "I have inherited a new class named ModelAdminWithInline from admin.ModelAdmin and modified methods add_view(...) and change_view(...) to call function is_cross_valid(self, form, formsets), where you can validate all the forms together.\nBoth functions had:\n#...\nif all_valid(formsets) and form_validated:\n#...\n\nchanged to:\n#...\nformsets_validated = all_valid(formsets)\ncross_validated = self.is_cross_valid(form, formsets)\nif formsets_validated and form_validated and cross_validated:\n#...\n\nThe new function is_cross_valid(...) is defined like this:\ndef is_cross_valid(self, form, formsets):\n return True\n\nso the new class should work exactly the same as ModelAdmin if you don't change is_cross_valid(...) function.\nNow my admin.py looks like this:\n###admin.py###\nclass ModelAdminWithInline(admin.ModelAdmin):\n def is_cross_valid(self, form, formsets):\n return True\n\n def add_view(self, request, form_url='', extra_context=None):\n #modified code\n\n def change_view(self, request, object_id, extra_context=None):\n #modified code\n\nclass ModelChildInline(admin.TabularInline):\n model = ModelChild\n\nclass ModelParentAdmin(ModelAdminWithInline):\n inlines = [ModelChildInline]\n\n def is_cross_valid(self, form, formsets):\n #Do some cross validation on forms\n #For example, here is my particular validation:\n valid = True\n\n if hasattr(form, 'cleaned_data'): \n\n subjects_parent = form.cleaned_data.get(\"subjects_parent\")\n\n #You can access forms from formsets like this:\n for formset in formsets:\n for formset_form in formset.forms:\n if hasattr(formset_form, 'cleaned_data'):\n\n subjects_child = formset_form.cleaned_data.get(\"subjects_child\")\n delete_form = formset_form.cleaned_data.get(\"DELETE\")\n\n if subjects_child and (delete_form == False):\n for subject in subjects_child:\n if subject in subjects_parent:\n valid = False\n #From here you can still report errors like in regular forms:\n if \"subjects_child\" in formset_form.cleaned_data.keys():\n formset_form._errors[\"subjects_child\"] = ErrorList([u\"Subject %s is already selected in parent ModelParent\" % subject])\n del formset_form.cleaned_data[\"subjects_child\"]\n else:\n formset_form._errors[\"subjects_child\"] += ErrorList(u\"Subject %s is already selected in parent ModelParent\" % subject])\n\n #return True on success or False otherwise.\n return valid\n\nadmin.site.register(ModelParent, ModelParentAdmin)\n\nThe solution is a little bit hackish but it works :). The errors show up the same as with regular ModelForm and ModelAdmin classes. Django 1.2 (which should be released shortly) should have model validation, so I hope that then this problem could be solved more nicely.\n", "The admin classes do not have the clean() method. Their forms do. Each admin class has a parameter called form. You simply extend the default form (it's the normal ModelAdmin form), implement the clean() method and add the form to the admin class.\nExample:\nclass SomeForm(ModelForm):\n #some code\n def clean(self):\n #some code\nclass SomeAdminClass(ModelAdmin):\n #some code\n form = SomeForm\n #more code\n\n" ]
[ 6, 2 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0002720383_django_django_admin_django_forms_python.txt
Q: Django: Change models without clearing all data? I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data? I tried changing the field and running python manage.py syncdb. There was no output from this command. Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db. I am using SQLite. I am able to delete the db file, then re-run python manage.py syncdb, but that is kind of a pain. Is there a better way to do it? A: Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out Django South. See the docs for syndb: Syncdb will not alter existing tables syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. You have to change the column names in your DB manually through whatever administration tools sqlite provides. I've done this with MySQL, for instance, and since MySQL lets you change column names without affecting your data, it's no problem. A: Of course there is. Check out South A: You'll have to manually update the database schema/layout, if you're only talking about adding/removing columns. If you're attempting to rename a column, you'll have to find another way. You can use the python manage.py sql [app name] (http://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname) command to see what the new SQL should look like, to see what columns, of what type/specification Django would have you add, and then manually run corresponding ALTER TABLE commands. There are some apps/projects that enable easier model/DB management, but Django doesn't support this out of the box, on purpose/by design.
Django: Change models without clearing all data?
I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data? I tried changing the field and running python manage.py syncdb. There was no output from this command. Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db. I am using SQLite. I am able to delete the db file, then re-run python manage.py syncdb, but that is kind of a pain. Is there a better way to do it?
[ "Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out Django South. \nSee the docs for syndb:\n\nSyncdb will not alter existing tables\nsyncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.\nIf you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.\n\nYou have to change the column names in your DB manually through whatever administration tools sqlite provides. I've done this with MySQL, for instance, and since MySQL lets you change column names without affecting your data, it's no problem.\n", "Of course there is.\nCheck out South\n", "You'll have to manually update the database schema/layout, if you're only talking about adding/removing columns. \nIf you're attempting to rename a column, you'll have to find another way. \nYou can use the python manage.py sql [app name] (http://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname) command to see what the new SQL should look like, to see what columns, of what type/specification Django would have you add, and then manually run corresponding ALTER TABLE commands. \nThere are some apps/projects that enable easier model/DB management, but Django doesn't support this out of the box, on purpose/by design. \n" ]
[ 20, 8, 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002746818_django_python.txt
Q: How do I overwrite a file currently being read by Python I am not too sure the best way to word this, but what I want to do, is read a pdf file, make various modifications, and save the modified pdf over the original file. As of now, I am able to save the modified pdf to a separate file, but I am looking to replace the original, not create a new file. Here is my current code: from pyPdf import PdfFileWriter, PdfFileReader output = PdfFileWriter() input = PdfFileReader(file('input.pdf', 'rb')) blank = PdfFileReader(file('C:\\BLANK.pdf', 'rb')) # Copy the input pdf to the output. for page in range(int(input.getNumPages())): output.addPage(input.getPage(page)) # Add a blank page if needed. if (input.getNumPages() % 2 != 0): output.addPage(blank.getPage(0)) # Write the output to pdf. outputStream = file('input.pdf', 'wb') output.write(outputStream) outputStream.close() If i change the outputStream to a different file name, it works fine, I just cant save over the input file because it is still being used. I have tried to .close() the stream, but it was giving me errors as well. I have a feeling this has a fairly simple solution, I just haven't had any luck finding it. Thanks! A: You can always rename the temporary output file to the old file: import os f = open('input.pdf', 'rb') # do stuff to temp.pdf f.close() os.rename('temp.pdf', 'input.pdf') A: You said you tried to close() the stream but got errors? You could delete the PdfFileReader objects to ensure nobody still has access to the stream. And then close the stream. from pyPdf import PdfFileWriter, PdfFileReader inputStream = file('input.pdf', 'rb') blankStream = file('C:\\BLANK.pdf', 'rb') output = PdfFileWriter() input = PdfFileReader(inputStream) blank = PdfFileReader(blankStream) ... del input # PdfFileReader won't mess with the stream anymore inputStream.close() del blank blankStream.close() # Write the output to pdf. outputStream = file('input.pdf', 'wb') output.write(outputStream) outputStream.close() A: If the PDFs are small enough (that'll depend on your platform), you could just read the whole thing in, close the file, modify the data, then write the whole thing back over the same file.
How do I overwrite a file currently being read by Python
I am not too sure the best way to word this, but what I want to do, is read a pdf file, make various modifications, and save the modified pdf over the original file. As of now, I am able to save the modified pdf to a separate file, but I am looking to replace the original, not create a new file. Here is my current code: from pyPdf import PdfFileWriter, PdfFileReader output = PdfFileWriter() input = PdfFileReader(file('input.pdf', 'rb')) blank = PdfFileReader(file('C:\\BLANK.pdf', 'rb')) # Copy the input pdf to the output. for page in range(int(input.getNumPages())): output.addPage(input.getPage(page)) # Add a blank page if needed. if (input.getNumPages() % 2 != 0): output.addPage(blank.getPage(0)) # Write the output to pdf. outputStream = file('input.pdf', 'wb') output.write(outputStream) outputStream.close() If i change the outputStream to a different file name, it works fine, I just cant save over the input file because it is still being used. I have tried to .close() the stream, but it was giving me errors as well. I have a feeling this has a fairly simple solution, I just haven't had any luck finding it. Thanks!
[ "You can always rename the temporary output file to the old file:\nimport os\nf = open('input.pdf', 'rb')\n# do stuff to temp.pdf\nf.close()\nos.rename('temp.pdf', 'input.pdf')\n\n", "You said you tried to close() the stream but got errors? You could delete the PdfFileReader objects to ensure nobody still has access to the stream. And then close the stream.\nfrom pyPdf import PdfFileWriter, PdfFileReader\n\ninputStream = file('input.pdf', 'rb')\nblankStream = file('C:\\\\BLANK.pdf', 'rb')\noutput = PdfFileWriter()\ninput = PdfFileReader(inputStream)\nblank = PdfFileReader(blankStream)\n\n...\n\ndel input # PdfFileReader won't mess with the stream anymore\ninputStream.close()\ndel blank\nblankStream.close()\n\n# Write the output to pdf.\noutputStream = file('input.pdf', 'wb')\noutput.write(outputStream)\noutputStream.close()\n\n", "If the PDFs are small enough (that'll depend on your platform), you could just read the whole thing in, close the file, modify the data, then write the whole thing back over the same file.\n" ]
[ 8, 3, 1 ]
[]
[]
[ "input", "overwrite", "pdf", "python" ]
stackoverflow_0002746758_input_overwrite_pdf_python.txt
Q: Django: Difficulty loading data Here are some models I am trying to load data for: class School(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class RequirementSet(models.Model): offeringSchool = models.ForeignKey(School) name = models.CharField(max_length=200) def __unicode__(self): return "%s at %s" % (self.name, self.offeringSchool) Here is the JSON I am trying to use to initialize them: // data.json [ { "pk": "1", "model": "myapp.School", "fields": { "name": "Princeton" } }, { "pk": "1", "model": "myapp.RequirementSet", "fields": { "name": "Computer Science", "offeringSchool": 1 } } ] I run python manage.py loaddata data.json, and I get this error: ... Checking absolute path for fixtures... Trying absolute path for data.json fixture 'data'... Installing json fixture 'data' from absolute path. Problem installing fixture 'data.json': Traceback (most recent call last): File "C:\Python26\lib\site-packages\django\core\management\commands\loaddata.p y", line 150, in handle for obj in objects: File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)): File "C:\Python26\lib\json\__init__.py", line 267, in load parse_constant=parse_constant, **kw) File "C:\Python26\lib\json\__init__.py", line 307, in loads return _default_decoder.decode(s) File "C:\Python26\lib\json\decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python26\lib\json\decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded What am I doing wrong? Interacting with these models through the shell and the admin UI works fine. A: The JSON format is not allowed to have comments. Remove the // data.json line and it should work.
Django: Difficulty loading data
Here are some models I am trying to load data for: class School(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class RequirementSet(models.Model): offeringSchool = models.ForeignKey(School) name = models.CharField(max_length=200) def __unicode__(self): return "%s at %s" % (self.name, self.offeringSchool) Here is the JSON I am trying to use to initialize them: // data.json [ { "pk": "1", "model": "myapp.School", "fields": { "name": "Princeton" } }, { "pk": "1", "model": "myapp.RequirementSet", "fields": { "name": "Computer Science", "offeringSchool": 1 } } ] I run python manage.py loaddata data.json, and I get this error: ... Checking absolute path for fixtures... Trying absolute path for data.json fixture 'data'... Installing json fixture 'data' from absolute path. Problem installing fixture 'data.json': Traceback (most recent call last): File "C:\Python26\lib\site-packages\django\core\management\commands\loaddata.p y", line 150, in handle for obj in objects: File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer for obj in PythonDeserializer(simplejson.load(stream)): File "C:\Python26\lib\json\__init__.py", line 267, in load parse_constant=parse_constant, **kw) File "C:\Python26\lib\json\__init__.py", line 307, in loads return _default_decoder.decode(s) File "C:\Python26\lib\json\decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python26\lib\json\decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded What am I doing wrong? Interacting with these models through the shell and the admin UI works fine.
[ "The JSON format is not allowed to have comments. Remove the // data.json line and it should work.\n" ]
[ 3 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002747094_django_json_python.txt
Q: Twisted connectionLost Event I use the twisted.words.protocols.jabber.client.XMPPClientFactory . Do you know how I can callback a function when the connection gets lost (for example WiFi-connection is down)? thank you for your help! A: You can either add a bootstrap for xmlstream.STREAM_END_EVENT or set a defer to clientConnectionLost. from twisted.words.protocols.jabber import client from twisted.words.protocols.jabber import jid from twisted.words.protocols.jabber import xmlstream j = jid.JID("name@example.org/bla") p = "some pass" factory = client.XMPPClientFactory(j, p) bootstrap method factory.addBootstrap( xmlstream.STREAM_END_EVENT, some_fuction, ) or defer method d = defer.Deferred() factory.clientConnectionLost = d
Twisted connectionLost Event
I use the twisted.words.protocols.jabber.client.XMPPClientFactory . Do you know how I can callback a function when the connection gets lost (for example WiFi-connection is down)? thank you for your help!
[ "You can either add a bootstrap for xmlstream.STREAM_END_EVENT or set a defer to clientConnectionLost.\nfrom twisted.words.protocols.jabber import client\nfrom twisted.words.protocols.jabber import jid\nfrom twisted.words.protocols.jabber import xmlstream\n\nj = jid.JID(\"name@example.org/bla\")\np = \"some pass\"\n\nfactory = client.XMPPClientFactory(j, p)\n\nbootstrap method\nfactory.addBootstrap(\n xmlstream.STREAM_END_EVENT,\n some_fuction,\n)\n\nor\ndefer method\nd = defer.Deferred()\nfactory.clientConnectionLost = d\n\n" ]
[ 1 ]
[]
[]
[ "python", "twisted", "twisted.words", "xmpp" ]
stackoverflow_0002321468_python_twisted_twisted.words_xmpp.txt
Q: Joining different models in Django Let's say I have this data model: class Workflow(models.Model): ... class Command(models.Model): workflow = models.ForeignKey(Workflow) ... class Job(models.Model): command = models.ForeignKey(Command) ... Suppose somewhere I want to loop through all the Workflow objects, and for each workflow I want to loop through its Commands, and for each Command I want to loop through each Job. Is there a way to structure this with a single query? That is, I'd like Workflow.objects.all() to join in its dependent models, so I get a collection that has dependent objects already cached, so workflows[0].command_set.get() doesn't produce an additional query. Is this possible? A: The other way around it's easy since you can do all_jobs = Job.objects.select_related().all() And any job.command or job.command.workflow won't produce additional query. Not sure if it's possible with a Workflow query. A: I think the only way you could do that would be using django.db.connection and write your own query. Since this would be iterating all instances of Job (your ForeignKeys aren't set null) anyway you could select all Job's and then group them outside of the ORM
Joining different models in Django
Let's say I have this data model: class Workflow(models.Model): ... class Command(models.Model): workflow = models.ForeignKey(Workflow) ... class Job(models.Model): command = models.ForeignKey(Command) ... Suppose somewhere I want to loop through all the Workflow objects, and for each workflow I want to loop through its Commands, and for each Command I want to loop through each Job. Is there a way to structure this with a single query? That is, I'd like Workflow.objects.all() to join in its dependent models, so I get a collection that has dependent objects already cached, so workflows[0].command_set.get() doesn't produce an additional query. Is this possible?
[ "The other way around it's easy since you can do\nall_jobs = Job.objects.select_related().all()\n\nAnd any job.command or job.command.workflow won't produce additional query.\nNot sure if it's possible with a Workflow query.\n", "I think the only way you could do that would be using django.db.connection and write your own query.\nSince this would be iterating all instances of Job (your ForeignKeys aren't set null) anyway you could select all Job's and then group them outside of the ORM\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002746580_django_django_models_python.txt
Q: how to exit recursive math formula and still get an answer i wrote this python code, which from wolfram alpha says that its supposed to return the factorial of any positive value (i probably messed up somewhere), integer or not: from math import * def double_factorial(n): if int(n) == n: n = int(n) if [0,1].__contains__(n): return 1 a = (n&1) + 2 b = 1 while a<=n: b*=a a+= 2 return float(b) else: return factorials(n/2) * 2**(n/2) *(pi/2)**(.25 *(-1+cos(n * pi))) def factorials(n): return pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(2*n) the problem is , say i input pi to 6 decimal places. 2*n will not become a float with 0 as its decimals any time soon, so the equation turns out to be pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(loop(loop(loop(...))))) how would i stop the recursion and still get the answer? ive had suggestions to add an index to the definitions or something, but the problem is, if the code stops when it reaches an index, there is still no answer to put back into the previous "nests" or whatever you call them A: You defined f in terms of g and g in terms of f. But you don't just have a circular definition with no base point to start the recursion. You have something worse. The definition of f is actually the definition of g inverted. f is precisely undoing what g did and vice versa. If you're trying to implement gamma yourself (ie. not using the one that's already there in the libraries) then you need to use a formula that expresses gamma in terms of something else that you know how to evaluate. Just using one formula and its inversion like that is a method that will fail for almost any problem you apply it to. A: In your code, you define double_factorial like double_factorial(n) = factorial(n/2) * f(n) ... (1) and in the factorial you define it as factorial(n) = double_factorial(2*n) / f(2*n) ... (2) which is equivalent to equation (1), so you created a circular reference without an exit point. Even math can't help. You have to define either factorial or double_factorial, e.g. def factorials(n): return tgamma(n + 1)
how to exit recursive math formula and still get an answer
i wrote this python code, which from wolfram alpha says that its supposed to return the factorial of any positive value (i probably messed up somewhere), integer or not: from math import * def double_factorial(n): if int(n) == n: n = int(n) if [0,1].__contains__(n): return 1 a = (n&1) + 2 b = 1 while a<=n: b*=a a+= 2 return float(b) else: return factorials(n/2) * 2**(n/2) *(pi/2)**(.25 *(-1+cos(n * pi))) def factorials(n): return pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(2*n) the problem is , say i input pi to 6 decimal places. 2*n will not become a float with 0 as its decimals any time soon, so the equation turns out to be pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(loop(loop(loop(...))))) how would i stop the recursion and still get the answer? ive had suggestions to add an index to the definitions or something, but the problem is, if the code stops when it reaches an index, there is still no answer to put back into the previous "nests" or whatever you call them
[ "You defined f in terms of g and g in terms of f. But you don't just have a circular definition with no base point to start the recursion. You have something worse. The definition of f is actually the definition of g inverted. f is precisely undoing what g did and vice versa. If you're trying to implement gamma yourself (ie. not using the one that's already there in the libraries) then you need to use a formula that expresses gamma in terms of something else that you know how to evaluate. Just using one formula and its inversion like that is a method that will fail for almost any problem you apply it to.\n", "In your code, you define double_factorial like\ndouble_factorial(n) = factorial(n/2) * f(n) ... (1)\n\nand in the factorial you define it as\nfactorial(n) = double_factorial(2*n) / f(2*n) ... (2)\n\nwhich is equivalent to equation (1), so you created a circular reference without an exit point. Even math can't help. You have to define either factorial or double_factorial, e.g.\ndef factorials(n):\n return tgamma(n + 1)\n\n" ]
[ 1, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002747390_math_python.txt
Q: Producing an view of a text's revision history in Python I have two versions of a piece of text and I want to produce an HTML view of its revision similar to what Google Docs or Stack Overflow displays. I need to do this in Python. I don't know what this technique is called but I assume that it has a name and hopefully there is a Python library that can do it. Version 1: William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. Version 2: William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American. The desired output: William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American. Using the diff command doesn't work because it tells me which lines are different but not which columns/words are different. $ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen.' > oldfile $ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > newfile $ diff -u oldfile newfile --- oldfile 2010-04-30 13:32:43.000000000 -0700 +++ newfile 2010-04-30 13:33:09.000000000 -0700 @@ -1 +1 @@ -William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. +William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > oldfile A: Google Diff Merge Patch has a pretty good diff implementation in pure python. A: You can use wdiff. I don't know if there's a Python implementation: $ wdiff oldfile newfile William Henry "Bill" Gates III (born October 28, 1955)[2] is [-an American-] {+a+} business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. {+He is American.+} A: The difflib module might be of assistance with this problem.
Producing an view of a text's revision history in Python
I have two versions of a piece of text and I want to produce an HTML view of its revision similar to what Google Docs or Stack Overflow displays. I need to do this in Python. I don't know what this technique is called but I assume that it has a name and hopefully there is a Python library that can do it. Version 1: William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. Version 2: William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American. The desired output: William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American. Using the diff command doesn't work because it tells me which lines are different but not which columns/words are different. $ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen.' > oldfile $ echo 'William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > newfile $ diff -u oldfile newfile --- oldfile 2010-04-30 13:32:43.000000000 -0700 +++ newfile 2010-04-30 13:33:09.000000000 -0700 @@ -1 +1 @@ -William Henry "Bill" Gates III (born October 28, 1955)[2] is an American business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. +William Henry "Bill" Gates III (born October 28, 1955)[2] is a business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. He is American.' > oldfile
[ "Google Diff Merge Patch has a pretty good diff implementation in pure python.\n", "You can use wdiff. I don't know if there's a Python implementation:\n$ wdiff oldfile newfile\nWilliam Henry \"Bill\" Gates III (born October 28, 1955)[2] is [-an American-] {+a+} business magnate, philanthropist, and chairman[3] of Microsoft, the software company he founded with Paul Allen. {+He is American.+}\n\n", "The difflib module might be of assistance with this problem.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "diff", "history", "python", "revision" ]
stackoverflow_0002747600_diff_history_python_revision.txt
Q: Is it possible to get sqlalchemy to create a composite primary key with an integer part without making it an IDENTITY type? I'm using sqlalchemy 6.0. The SQL Server T-SQL dialect seems to want to make any integer that's part of my primary key into an identity. That may be ok if the integer field were the primary key, but mine is a composite and this isn't going to work for me. Is there a way to suppress this behavior? Here's a demonstration of the problem: from sqlalchemy import * from sqlalchemy.schema import CreateTable from sqlalchemy.types import CHAR import sqlalchemy.dialects.mssql.pyodbc metadata = MetaData() t = Table('TEST', metadata, Column(u'int_part', Integer, primary_key=True, nullable=False), Column(u'char_part', CHAR(length=20), primary_key=True, nullable=False), ) create = CreateTable(t) print "Generic dialect gets it right" print create.compile() print print "MSSql dialect gets it wrong" print create.compile(dialect=sqlalchemy.dialects.mssql.pyodbc.dialect()) Results: Generic dialect gets it right CREATE TABLE "TEST" ( int_part INTEGER NOT NULL, char_part CHAR(20) NOT NULL, PRIMARY KEY (int_part, char_part) ) SQL Server T-SQL dialect gets it wrong CREATE TABLE [TEST] ( int_part INTEGER NOT NULL IDENTITY(1,1), char_part CHAR(20) NOT NULL, PRIMARY KEY (int_part, char_part) ) A: I got bit by the same problem. The solution is to add autoincrement=False to the int primary key column constructor: Column(u'int_part', Integer, primary_key=True, nullable=False, autoincrement=False) Otherwise, sqlalchemy assumes it should make it an identity column.
Is it possible to get sqlalchemy to create a composite primary key with an integer part without making it an IDENTITY type?
I'm using sqlalchemy 6.0. The SQL Server T-SQL dialect seems to want to make any integer that's part of my primary key into an identity. That may be ok if the integer field were the primary key, but mine is a composite and this isn't going to work for me. Is there a way to suppress this behavior? Here's a demonstration of the problem: from sqlalchemy import * from sqlalchemy.schema import CreateTable from sqlalchemy.types import CHAR import sqlalchemy.dialects.mssql.pyodbc metadata = MetaData() t = Table('TEST', metadata, Column(u'int_part', Integer, primary_key=True, nullable=False), Column(u'char_part', CHAR(length=20), primary_key=True, nullable=False), ) create = CreateTable(t) print "Generic dialect gets it right" print create.compile() print print "MSSql dialect gets it wrong" print create.compile(dialect=sqlalchemy.dialects.mssql.pyodbc.dialect()) Results: Generic dialect gets it right CREATE TABLE "TEST" ( int_part INTEGER NOT NULL, char_part CHAR(20) NOT NULL, PRIMARY KEY (int_part, char_part) ) SQL Server T-SQL dialect gets it wrong CREATE TABLE [TEST] ( int_part INTEGER NOT NULL IDENTITY(1,1), char_part CHAR(20) NOT NULL, PRIMARY KEY (int_part, char_part) )
[ "I got bit by the same problem. The solution is to add autoincrement=False to the int primary key column constructor:\nColumn(u'int_part', Integer, primary_key=True, nullable=False,\n autoincrement=False)\n\nOtherwise, sqlalchemy assumes it should make it an identity column.\n" ]
[ 12 ]
[]
[]
[ "python", "sql_server", "sqlalchemy" ]
stackoverflow_0002374243_python_sql_server_sqlalchemy.txt
Q: Why do dicts of defaultdict(int)'s use so much memory? (and other simple python performance questions) I do understand that querying a non-existent key in a defaultdict the way I do will add items to the defaultdict. That is why it is fair to compare my 2nd code snippet to my first one in terms of performance. import numpy as num from collections import defaultdict topKeys = range(16384) keys = range(8192) table = dict((k,defaultdict(int)) for k in topKeys) dat = num.zeros((16384,8192), dtype="int32") print "looping begins" #how much memory should this use? I think it shouldn't use more that a few #times the memory required to hold (16384*8192) int32's (512 mb), but #it uses 11 GB! for k in topKeys: for j in keys: dat[k,j] = table[k][j] print "done" What is going on here? Furthermore, this similar script takes eons to run compared to the first one, and also uses an absurd quantity of memory. topKeys = range(16384) keys = range(8192) table = [(j,0) for k in topKeys for j in keys] I guess python ints might be 64 bit ints, which would account for some of this, but do these relatively natural and simple constructions really produce such a massive overhead? I guess these scripts show that they do, so my question is: what exactly is causing the high memory usage in the first script and the long runtime and high memory usage of the second script and is there any way to avoid these costs? Edit: Python 2.6.4 on 64 bit machine. Edit 2: I can see why, to a first approximation, my table should take up 3 GB 16384*8192*(12+12) bytes and 6GB with a defaultdict load factor that forces it to reserve double the space. Then inefficiencies in memory allocation eat up another factor of 2. So here are my remaining questions: Is there a way for me to tell it to use 32 bit ints somehow? And why does my second code snippet take FOREVER to run compared to the first one? The first one takes about a minute and I killed the second one after 80 minutes. A: Python ints are internally represented as C longs (it's actually a bit more complicated than that), but that's not really the root of your problem. The biggest overhead is your usage of dicts. (defaultdicts and dicts are about the same in this description). dicts are implemented using hash tables, which is nice because it gives quick lookup of pretty general keys. (It's not so necessary when you only need to look up sequential numerical keys, since they can be laid out in an easy way to get to them.) A dict can have many more slots than it has items. Let's say you have a dict with 3x as many slots as items. Each of these slots needs room for a pointer to a key and a pointer serving as the end of a linked list. That's 6x as many points as numbers, plus all the pointers to the items you're interested in. Consider that each of these pointers is 8 bytes on your system and that you have 16384 defaultdicts in this situation. As a rough, handwavey look at this, 16384 occurrences * (8192 items/occurance) * 7 (pointers/item) * 8 (bytes/pointer) = 7 GB. This is before I've gotten to the actual numbers you're storing (each unique number of which is itself a Python dict), the outer dict, that numpy array, or the stuff Python's keeping track of to try to optimize some. Your overhead sounds a little higher than I suspect and I would be interested in knowing whether that 11GB was for a whole process or whether you calculated it for just table. In any event, I do expect the size of this dict-of-defaultdicts data structure to be orders of magnitude bigger than the numpy array representation. As to "is there any way to avoid these costs?" the answer is "use numpy for storing large, fixed-size contiguous numerical arrays, not dicts!" You'll have to be more specific and concrete about why you found such a structure necessary for better advice about what the best solution is. A: Well, look at what your code is actually doing: topKeys = range(16384) table = dict((k,defaultdict(int)) for k in topKeys) This creates a dict holding 16384 defaultdict(int)'s. A dict has a certain amount of overhead: the dict object itself is between 60 and 120 bytes (depending on the size of pointers and ssize_t's in your build.) That's just the object itself; unless the dict is less than a couple of items, the data is a separate block of memory, between 12 and 24 bytes, and it's always between 1/2 and 2/3rds filled. And defaultdicts are 4 to 8 bytes bigger because they have this extra thing to store. And ints are 12 bytes each, and although they're reused where possible, that snippet won't reuse most of them. So, realistically, in a 32-bit build, that snippet will take up 60 + (16384*12) * 1.8 (fill factor) bytes for the table dict, 16384 * 64 bytes for the defaultdicts it stores as values, and 16384 * 12 bytes for the integers. So that's just over a megabyte and a half without storing anything in your defaultdicts. And that's in a 32-bit build; a 64-bit build would be twice that size. Then you create a numpy array, which is actually pretty conservative with memory: dat = num.zeros((16384,8192), dtype="int32") This will have some overhead for the array itself, the usual Python object overhead plus the dimensions and type of the array and such, but it wouldn't be much more than 100 bytes, and only for the one array. It does store 16384*8192 int32's in your 512Mb though. And then you have this rather peculiar way of filling this numpy array: for k in topKeys: for j in keys: dat[k,j] = table[k][j] The two loops themselves don't use much memory, and they re-use it each iteration. However, table[k][j] creates a new Python integer for each value you request, and stores it in the defaultdict. The integer created is always 0, and it so happens that that always gets reused, but storing the reference to it still uses up space in the defaultdict: the aforementioned 12 bytes per entry, times the fill factor (between 1.66 and 2.) That lands you close to 3Gb of actual data right there, and 6Gb in a 64-bit build. On top of that the defaultdicts, because you keep adding data, have to keep growing, which means they have to keep reallocating. Because of Python's malloc frontend (obmalloc) and how it allocates smaller objects in blocks of its own, and how process memory works on most operating systems, this means your process will allocate more and not be able to free it; it won't actually use all of the 11Gb, and Python will re-use the available memory inbetween the large blocks for the defaultdicts, but the total mapped address space will be that 11Gb. A: Mike Graham gives a good explanation of why dictionaries use more memory, but I thought that I'd explain why your table dict of defaultdicts starts to take up so much memory. The way that the defaultdict (DD) is set-up right now, whenever you retrieve an element that isn't in the DD, you get the default value for the DD (0 for your case) but also the DD now stores a key that previously wasn't in the DD with the default value of 0. I personally don't like this, but that's how it goes. However, it means that for every iteration of the inner loop, new memory is being allocated which is why it is taking forever. If you change the lines for k in topKeys: for j in keys: dat[k,j] = table[k][j] to for k in topKeys: for j in keys: if j in table[k]: dat[k,j] = table[k][j] else: dat[k,j] = 0 then default values aren't being assigned to keys in the DDs and so the memory stays around 540 MB for me which is mostly just the memory allocated for dat. DDs are decent for sparse matrices though you probably should just use the sparse matrices in Scipy if that's what you want.
Why do dicts of defaultdict(int)'s use so much memory? (and other simple python performance questions)
I do understand that querying a non-existent key in a defaultdict the way I do will add items to the defaultdict. That is why it is fair to compare my 2nd code snippet to my first one in terms of performance. import numpy as num from collections import defaultdict topKeys = range(16384) keys = range(8192) table = dict((k,defaultdict(int)) for k in topKeys) dat = num.zeros((16384,8192), dtype="int32") print "looping begins" #how much memory should this use? I think it shouldn't use more that a few #times the memory required to hold (16384*8192) int32's (512 mb), but #it uses 11 GB! for k in topKeys: for j in keys: dat[k,j] = table[k][j] print "done" What is going on here? Furthermore, this similar script takes eons to run compared to the first one, and also uses an absurd quantity of memory. topKeys = range(16384) keys = range(8192) table = [(j,0) for k in topKeys for j in keys] I guess python ints might be 64 bit ints, which would account for some of this, but do these relatively natural and simple constructions really produce such a massive overhead? I guess these scripts show that they do, so my question is: what exactly is causing the high memory usage in the first script and the long runtime and high memory usage of the second script and is there any way to avoid these costs? Edit: Python 2.6.4 on 64 bit machine. Edit 2: I can see why, to a first approximation, my table should take up 3 GB 16384*8192*(12+12) bytes and 6GB with a defaultdict load factor that forces it to reserve double the space. Then inefficiencies in memory allocation eat up another factor of 2. So here are my remaining questions: Is there a way for me to tell it to use 32 bit ints somehow? And why does my second code snippet take FOREVER to run compared to the first one? The first one takes about a minute and I killed the second one after 80 minutes.
[ "Python ints are internally represented as C longs (it's actually a bit more complicated than that), but that's not really the root of your problem.\nThe biggest overhead is your usage of dicts. (defaultdicts and dicts are about the same in this description). dicts are implemented using hash tables, which is nice because it gives quick lookup of pretty general keys. (It's not so necessary when you only need to look up sequential numerical keys, since they can be laid out in an easy way to get to them.)\nA dict can have many more slots than it has items. Let's say you have a dict with 3x as many slots as items. Each of these slots needs room for a pointer to a key and a pointer serving as the end of a linked list. That's 6x as many points as numbers, plus all the pointers to the items you're interested in. Consider that each of these pointers is 8 bytes on your system and that you have 16384 defaultdicts in this situation. As a rough, handwavey look at this, 16384 occurrences * (8192 items/occurance) * 7 (pointers/item) * 8 (bytes/pointer) = 7 GB. This is before I've gotten to the actual numbers you're storing (each unique number of which is itself a Python dict), the outer dict, that numpy array, or the stuff Python's keeping track of to try to optimize some. \nYour overhead sounds a little higher than I suspect and I would be interested in knowing whether that 11GB was for a whole process or whether you calculated it for just table. In any event, I do expect the size of this dict-of-defaultdicts data structure to be orders of magnitude bigger than the numpy array representation.\nAs to \"is there any way to avoid these costs?\" the answer is \"use numpy for storing large, fixed-size contiguous numerical arrays, not dicts!\" You'll have to be more specific and concrete about why you found such a structure necessary for better advice about what the best solution is.\n", "Well, look at what your code is actually doing:\ntopKeys = range(16384)\ntable = dict((k,defaultdict(int)) for k in topKeys)\n\nThis creates a dict holding 16384 defaultdict(int)'s. A dict has a certain amount of overhead: the dict object itself is between 60 and 120 bytes (depending on the size of pointers and ssize_t's in your build.) That's just the object itself; unless the dict is less than a couple of items, the data is a separate block of memory, between 12 and 24 bytes, and it's always between 1/2 and 2/3rds filled. And defaultdicts are 4 to 8 bytes bigger because they have this extra thing to store. And ints are 12 bytes each, and although they're reused where possible, that snippet won't reuse most of them. So, realistically, in a 32-bit build, that snippet will take up 60 + (16384*12) * 1.8 (fill factor) bytes for the table dict, 16384 * 64 bytes for the defaultdicts it stores as values, and 16384 * 12 bytes for the integers. So that's just over a megabyte and a half without storing anything in your defaultdicts. And that's in a 32-bit build; a 64-bit build would be twice that size.\nThen you create a numpy array, which is actually pretty conservative with memory:\ndat = num.zeros((16384,8192), dtype=\"int32\")\n\nThis will have some overhead for the array itself, the usual Python object overhead plus the dimensions and type of the array and such, but it wouldn't be much more than 100 bytes, and only for the one array. It does store 16384*8192 int32's in your 512Mb though.\nAnd then you have this rather peculiar way of filling this numpy array:\nfor k in topKeys:\n for j in keys:\n dat[k,j] = table[k][j]\n\nThe two loops themselves don't use much memory, and they re-use it each iteration. However, table[k][j] creates a new Python integer for each value you request, and stores it in the defaultdict. The integer created is always 0, and it so happens that that always gets reused, but storing the reference to it still uses up space in the defaultdict: the aforementioned 12 bytes per entry, times the fill factor (between 1.66 and 2.) That lands you close to 3Gb of actual data right there, and 6Gb in a 64-bit build.\nOn top of that the defaultdicts, because you keep adding data, have to keep growing, which means they have to keep reallocating. Because of Python's malloc frontend (obmalloc) and how it allocates smaller objects in blocks of its own, and how process memory works on most operating systems, this means your process will allocate more and not be able to free it; it won't actually use all of the 11Gb, and Python will re-use the available memory inbetween the large blocks for the defaultdicts, but the total mapped address space will be that 11Gb.\n", "Mike Graham gives a good explanation of why dictionaries use more memory, but I thought that I'd explain why your table dict of defaultdicts starts to take up so much memory.\nThe way that the defaultdict (DD) is set-up right now, whenever you retrieve an element that isn't in the DD, you get the default value for the DD (0 for your case) but also the DD now stores a key that previously wasn't in the DD with the default value of 0. I personally don't like this, but that's how it goes. However, it means that for every iteration of the inner loop, new memory is being allocated which is why it is taking forever. If you change the lines\nfor k in topKeys:\n for j in keys:\n dat[k,j] = table[k][j]\n\nto\nfor k in topKeys:\n for j in keys:\n if j in table[k]:\n dat[k,j] = table[k][j]\n else:\n dat[k,j] = 0\n\nthen default values aren't being assigned to keys in the DDs and so the memory stays around 540 MB for me which is mostly just the memory allocated for dat. DDs are decent for sparse matrices though you probably should just use the sparse matrices in Scipy if that's what you want.\n" ]
[ 9, 2, 1 ]
[]
[]
[ "memory", "performance", "python", "runtime" ]
stackoverflow_0002747511_memory_performance_python_runtime.txt
Q: Forking Multiple Apps Under Python Subprocess I have been looking through Google and SO for something that could help me solve this but I have run into a block. I am a bit new to Python but I am looking for a way to run multiple apps that will continuously run in the background. For example, I need 4 apps to start up with a param -appnum set to a different value. I would like to use python to count up and then start up a new app that will continue to run. I assumed I would use subprocess but I feel a bit overwhelmed by the documentation. I also plan to have the app print out sequences of numbers and would like to redirect this to a file. I noticed some of the SO questions talked about this, but I am a little confused on what to do. A: A simple way to start might be to use os.popen(), like this: import os subprogs = [None] * 4 for i in range(4): subprogs[i] = os.popen("app -appnum " + i, "r") From here, you can read from each subprog[i] just like a file, capturing the output of the app program. Note that although the documentation says this function has been deprecated, it still works perfectly fine for many purposes. You can explore the subprocess module when you're more familiar with the limitations of os.popen().
Forking Multiple Apps Under Python Subprocess
I have been looking through Google and SO for something that could help me solve this but I have run into a block. I am a bit new to Python but I am looking for a way to run multiple apps that will continuously run in the background. For example, I need 4 apps to start up with a param -appnum set to a different value. I would like to use python to count up and then start up a new app that will continue to run. I assumed I would use subprocess but I feel a bit overwhelmed by the documentation. I also plan to have the app print out sequences of numbers and would like to redirect this to a file. I noticed some of the SO questions talked about this, but I am a little confused on what to do.
[ "A simple way to start might be to use os.popen(), like this:\nimport os\n\nsubprogs = [None] * 4\nfor i in range(4):\n subprogs[i] = os.popen(\"app -appnum \" + i, \"r\")\n\nFrom here, you can read from each subprog[i] just like a file, capturing the output of the app program.\nNote that although the documentation says this function has been deprecated, it still works perfectly fine for many purposes. You can explore the subprocess module when you're more familiar with the limitations of os.popen().\n" ]
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002747921_python_subprocess.txt
Q: Confusion on C++ Python extensions. Things like getting C++ values for python values I'm wanted to convert some of my python code to C++ for speed but it's not as easy as simply making a C++ function and making a few function calls. I have no idea how to get a C++ integer from a python integer object. I have an integer which is an attribute of an object that I want to use. I also have integers which are inside a list in the object which I need to use. I wanted to test making a C++ extension with this function: def setup_framebuffer(surface,flip=False): #Create texture if not done already if surface.texture is None: create_texture(surface) #Render child to parent if surface.frame_buffer is None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, c_uint(int(surface.frame_buffer))) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface._scale[0],surface._scale[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix if flip: gluOrtho2D(0,surface._scale[0],surface._scale[1],0) else: gluOrtho2D(0,surface._scale[0],0,surface._scale[1]) That function calls create_texture, so I will have to pass that function to the C++ function which I will do with the third argument. This is what I have so far, while trying to follow information on the python documentation: #include <Python.h> #include <GL/gl.h> static PyMethodDef SpamMethods[] = { ... {"setup_framebuffer", setup_framebuffer, METH_VARARGS,"Loads a texture from a Surface object to the OpenGL framebuffer."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; static PyObject * setup_framebuffer(PyObject *self, PyObject *args){ bool flip; PyObject *create_texture, *arg_list,*pyflip,*frame_buffer_id; if (!PyArg_ParseTuple(args, "OOO", &surface,&pyflip,&create_texture)){ return NULL; } if (PyObject_IsTrue(pyflip) == 1){ flip = true; }else{ flip = false; } Py_XINCREF(create_texture); //Create texture if not done already if(texture == NULL){ arglist = Py_BuildValue("(O)", surface) result = PyEval_CallObject(create_texture, arglist); Py_DECREF(arglist); if (result == NULL){ return NULL; } Py_DECREF(result); } Py_XDECREF(create_texture); //Render child to parent frame_buffer_id = PyObject_GetAttr(surface, Py_BuildValue("s","frame_buffer")) if(surface.frame_buffer == NULL){ glGenFramebuffersEXT(1,frame_buffer_id); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0,0,surface._scale[0],surface._scale[1]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Load the projection matrix if (flip){ gluOrtho2D(0,surface._scale[0],surface._scale[1],0); }else{ gluOrtho2D(0,surface._scale[0],0,surface._scale[1]); } Py_INCREF(Py_None); return Py_None; } PyMODINIT_FUNC initcscalelib(void){ PyObject *module; module = Py_InitModule("cscalelib", Methods); if (m == NULL){ return; } } int main(int argc, char *argv[]){ /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initscalelib(); } A: May I make a sincere suggestion here? Instead of throwing a hundred lines of code at yourself when trying something new like this, first try the simplest test case possible. Try getting a C++ extension to work that does nothing but pass back the value 123. (Picking 0 or 1 might accidentally work, so I chose an easy to recognize value that is not likely to be an accident.) Then get the extension to double a number you pass in, then add two numbers, etc. Sneak up on the problem! :-) A: The way to get a C int from a Python integer is with PyInt_AsLong() and a downcast (although you may want to use a C long instead.) To go the other way, you call PyInt_FromLong(). It's not obvious to me where in the code you want to do this, although I do have a couple of other comments about your code: Conceptually, PyObject_IsTrue() returns a boolean. Don't compare it to 1, just use it as a boolean value. However, you should check if it returned an error, which would be -1. (The usual check is < 0.) If you don't check for error returns you end up swallowing the exception, but leaving the exception object hanging around. This is bad. The Py_XINCREF() of create_texture is not necessary. You have a borrowed reference to the args tuple, which in turn owns a reference to the create_texture object. There is no way for create_texture to go away before your function returns. You only need to incref it if you are going to keep it around longer than this functioncall. If you did have to incref it, you wouldn't need to use Py_XINCREF() because it won't ever be NULL. And if you did have to incref it, you would need to remember to decref it in your error return case, as well. Instead of creating an argument tuple just to call PyEval_CallObject(), just call PyObject_CallFunctionObjectArgs(create_texture, arglist, NULL) or PyObject_CallFunction(create_texture, "O", arglist). Py_BuildValue("s", "frame_buffer") is not really the right way to get a Python string for "frame_buffer". A better way is PyString_FromString(). However, both of those return new references, and PyObject_GetAttr() doesn't eat the reference to the attribute name, so you end up leaking that reference. You should use none of these, and instead use PyObject_GetAttrString(), which takes the attribute name as a const char*. Remember to check the return value of all functions that can return an error value (which is almost all Python API functions.) Besides PyTrue_IsTrue() you're also forgetting this for Py_BuildValue() and PyObject_GetAttr().
Confusion on C++ Python extensions. Things like getting C++ values for python values
I'm wanted to convert some of my python code to C++ for speed but it's not as easy as simply making a C++ function and making a few function calls. I have no idea how to get a C++ integer from a python integer object. I have an integer which is an attribute of an object that I want to use. I also have integers which are inside a list in the object which I need to use. I wanted to test making a C++ extension with this function: def setup_framebuffer(surface,flip=False): #Create texture if not done already if surface.texture is None: create_texture(surface) #Render child to parent if surface.frame_buffer is None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, c_uint(int(surface.frame_buffer))) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface._scale[0],surface._scale[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix if flip: gluOrtho2D(0,surface._scale[0],surface._scale[1],0) else: gluOrtho2D(0,surface._scale[0],0,surface._scale[1]) That function calls create_texture, so I will have to pass that function to the C++ function which I will do with the third argument. This is what I have so far, while trying to follow information on the python documentation: #include <Python.h> #include <GL/gl.h> static PyMethodDef SpamMethods[] = { ... {"setup_framebuffer", setup_framebuffer, METH_VARARGS,"Loads a texture from a Surface object to the OpenGL framebuffer."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; static PyObject * setup_framebuffer(PyObject *self, PyObject *args){ bool flip; PyObject *create_texture, *arg_list,*pyflip,*frame_buffer_id; if (!PyArg_ParseTuple(args, "OOO", &surface,&pyflip,&create_texture)){ return NULL; } if (PyObject_IsTrue(pyflip) == 1){ flip = true; }else{ flip = false; } Py_XINCREF(create_texture); //Create texture if not done already if(texture == NULL){ arglist = Py_BuildValue("(O)", surface) result = PyEval_CallObject(create_texture, arglist); Py_DECREF(arglist); if (result == NULL){ return NULL; } Py_DECREF(result); } Py_XDECREF(create_texture); //Render child to parent frame_buffer_id = PyObject_GetAttr(surface, Py_BuildValue("s","frame_buffer")) if(surface.frame_buffer == NULL){ glGenFramebuffersEXT(1,frame_buffer_id); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0,0,surface._scale[0],surface._scale[1]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Load the projection matrix if (flip){ gluOrtho2D(0,surface._scale[0],surface._scale[1],0); }else{ gluOrtho2D(0,surface._scale[0],0,surface._scale[1]); } Py_INCREF(Py_None); return Py_None; } PyMODINIT_FUNC initcscalelib(void){ PyObject *module; module = Py_InitModule("cscalelib", Methods); if (m == NULL){ return; } } int main(int argc, char *argv[]){ /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initscalelib(); }
[ "May I make a sincere suggestion here? Instead of throwing a hundred lines of code at yourself when trying something new like this, first try the simplest test case possible. Try getting a C++ extension to work that does nothing but pass back the value 123. (Picking 0 or 1 might accidentally work, so I chose an easy to recognize value that is not likely to be an accident.) Then get the extension to double a number you pass in, then add two numbers, etc.\nSneak up on the problem! :-)\n", "The way to get a C int from a Python integer is with PyInt_AsLong() and a downcast (although you may want to use a C long instead.) To go the other way, you call PyInt_FromLong(). It's not obvious to me where in the code you want to do this, although I do have a couple of other comments about your code:\n\nConceptually, PyObject_IsTrue() returns a boolean. Don't compare it to 1, just use it as a boolean value. However, you should check if it returned an error, which would be -1. (The usual check is < 0.) If you don't check for error returns you end up swallowing the exception, but leaving the exception object hanging around. This is bad.\nThe Py_XINCREF() of create_texture is not necessary. You have a borrowed reference to the args tuple, which in turn owns a reference to the create_texture object. There is no way for create_texture to go away before your function returns. You only need to incref it if you are going to keep it around longer than this functioncall. If you did have to incref it, you wouldn't need to use Py_XINCREF() because it won't ever be NULL. And if you did have to incref it, you would need to remember to decref it in your error return case, as well.\nInstead of creating an argument tuple just to call PyEval_CallObject(), just call PyObject_CallFunctionObjectArgs(create_texture, arglist, NULL) or PyObject_CallFunction(create_texture, \"O\", arglist). \nPy_BuildValue(\"s\", \"frame_buffer\") is not really the right way to get a Python string for \"frame_buffer\". A better way is PyString_FromString(). However, both of those return new references, and PyObject_GetAttr() doesn't eat the reference to the attribute name, so you end up leaking that reference. You should use none of these, and instead use PyObject_GetAttrString(), which takes the attribute name as a const char*.\nRemember to check the return value of all functions that can return an error value (which is almost all Python API functions.) Besides PyTrue_IsTrue() you're also forgetting this for Py_BuildValue() and PyObject_GetAttr().\n\n" ]
[ 2, 1 ]
[]
[]
[ "api", "c++", "module", "python" ]
stackoverflow_0002747955_api_c++_module_python.txt
Q: Mako "Missing parentheses in %def" In trying to add a cached section to a Mako template, I get the error listed in the above question. Adding () to the end gets rid of the error, but I see no content on my page. Any help is appreciated! <%def name="test" cached="True" cache_timeout="60" cache_type="file"> Test /%def> A: My problem was that I was not aware that <%def> defines a function. If I use the parenthesis and call the function via ${test()} right after definition, it works as expected.
Mako "Missing parentheses in %def"
In trying to add a cached section to a Mako template, I get the error listed in the above question. Adding () to the end gets rid of the error, but I see no content on my page. Any help is appreciated! <%def name="test" cached="True" cache_timeout="60" cache_type="file"> Test /%def>
[ "My problem was that I was not aware that <%def> defines a function. If I use the parenthesis and call the function via ${test()} right after definition, it works as expected.\n" ]
[ 0 ]
[ "Shouldn't you be using parantheses while defining the def test.\nAlso if the \"cached\" etc. are parameters then I think your \nyour definition should be something like below:\n\n<%def name=\"test(cached='True',cache_timeout='60',cache_type='file')\"> \n Test \n/%def> \n\n\nAlso see the Mako documentation\n" ]
[ -1 ]
[ "mako", "pylons", "python" ]
stackoverflow_0002742600_mako_pylons_python.txt
Q: Pyglet OpenGL drawing anti-aliasing I've been looking around for a way to anti-alias lines in OpenGL, but none of them seem to work... here's some example code: import pyglet from pyglet.gl import * window = pyglet.window.Window(resizable=True) @window.event def on_draw(): window.clear() pyglet.gl.glColor4f(1.0,0,0,1.0) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable (GL_BLEND) glEnable (GL_LINE_SMOOTH); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE) glLineWidth (3) pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (10, 15, 300, 305)) ) pyglet.app.run() Can anyone see what I am doing wrong? A: Allow Pyglet to use an extra sample buffer might help. Change your window line to this: config = pyglet.gl.Config(sample_buffers=1, samples=4) window = pyglet.window.Window(config=config, resizable=True) This works for me. A: It's a bit hard to say for sure. The first thing is probably to change your hint from GL_DONT_CARE to GL_NICEST. It probably won't make much difference with most graphics cards, but it might help a little. Other than that, it's a bit hard to say. Here's a bit of code (in C++; sorry): void draw_line(float y_offset) { glBegin(GL_LINES); glColor3f(1.0f, 1.0f, 1.0f); glVertex3f(-1.0f, 0.0f+y_offset, -1.0f); glVertex3f(1.0f, 0.1f+y_offset, -1.0f); glEnd(); } void draw() { glClearColor(0.0f, 0.0f, 0.2f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.2f, 1.2f, -0.2f, 0.2f, 0.8f, 5.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glLineWidth(3.0f); glDisable(GL_LINE_SMOOTH); draw_line(0.0f); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE); draw_line(-0.1f); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); draw_line(-0.2f); glFlush(); } And here's what I'm getting as output from that: The difference when line-smoothing is turned on seems pretty obvious. The difference between GL_DONT_CARE and GL_NICEST is (at most) a lot less so.
Pyglet OpenGL drawing anti-aliasing
I've been looking around for a way to anti-alias lines in OpenGL, but none of them seem to work... here's some example code: import pyglet from pyglet.gl import * window = pyglet.window.Window(resizable=True) @window.event def on_draw(): window.clear() pyglet.gl.glColor4f(1.0,0,0,1.0) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable (GL_BLEND) glEnable (GL_LINE_SMOOTH); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE) glLineWidth (3) pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (10, 15, 300, 305)) ) pyglet.app.run() Can anyone see what I am doing wrong?
[ "Allow Pyglet to use an extra sample buffer might help. Change your window line to this:\nconfig = pyglet.gl.Config(sample_buffers=1, samples=4)\nwindow = pyglet.window.Window(config=config, resizable=True) \n\nThis works for me.\n", "It's a bit hard to say for sure. The first thing is probably to change your hint from GL_DONT_CARE to GL_NICEST. It probably won't make much difference with most graphics cards, but it might help a little.\nOther than that, it's a bit hard to say. Here's a bit of code (in C++; sorry):\nvoid draw_line(float y_offset) { \n glBegin(GL_LINES);\n glColor3f(1.0f, 1.0f, 1.0f);\n glVertex3f(-1.0f, 0.0f+y_offset, -1.0f);\n glVertex3f(1.0f, 0.1f+y_offset, -1.0f);\n glEnd();\n}\n\nvoid draw() { \n glClearColor(0.0f, 0.0f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n glFrustum(-1.2f, 1.2f, -0.2f, 0.2f, 0.8f, 5.0f);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glLineWidth(3.0f);\n glDisable(GL_LINE_SMOOTH);\n draw_line(0.0f);\n glEnable(GL_LINE_SMOOTH);\n glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);\n draw_line(-0.1f);\n glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);\n draw_line(-0.2f);\n\n glFlush();\n}\n\nAnd here's what I'm getting as output from that:\n\nThe difference when line-smoothing is turned on seems pretty obvious. The difference between GL_DONT_CARE and GL_NICEST is (at most) a lot less so.\n" ]
[ 13, 8 ]
[]
[]
[ "antialiasing", "opengl", "pyglet", "pyopengl", "python" ]
stackoverflow_0002747784_antialiasing_opengl_pyglet_pyopengl_python.txt
Q: What is the best way to translate this recursive python method into Java? In another question I was provided with a great answer involving generating certain sets for the Chinese Postman Problem. The answer provided was: def get_pairs(s): if not s: yield [] else: i = min(s) for j in s - set([i]): for r in get_pairs(s - set([i, j])): yield [(i, j)] + r for x in get_pairs(set([1,2,3,4,5,6])): print x This will output the desire result of: [(1, 2), (3, 4), (5, 6)] [(1, 2), (3, 5), (4, 6)] [(1, 2), (3, 6), (4, 5)] [(1, 3), (2, 4), (5, 6)] [(1, 3), (2, 5), (4, 6)] [(1, 3), (2, 6), (4, 5)] [(1, 4), (2, 3), (5, 6)] [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 6), (3, 5)] [(1, 5), (2, 3), (4, 6)] [(1, 5), (2, 4), (3, 6)] [(1, 5), (2, 6), (3, 4)] [(1, 6), (2, 3), (4, 5)] [(1, 6), (2, 4), (3, 5)] [(1, 6), (2, 5), (3, 4)] This really shows off the expressiveness of Python because this is almost exactly how I would write the pseudo-code for the algorithm. I especially like the usage of yield and and the way that sets are treated as first class citizens. However, there in lies my problem. What would be the best way to: 1.Duplicate the functionality of the yield return construct in Java? Would it instead be best to maintain a list and append my partial results to this list? How would you handle the yield keyword. 2.Handle the dealing with the sets? I know that I could probably use one of the Java collections which implements that implements the Set interface and then using things like removeAll() to give me a set difference. Is this what you would do in that case? Ultimately, I'm looking to reduce this method into as concise and straightforward way as possible in Java. I'm thinking the return type of the java version of this method will likely return a list of int arrays or something similar. How would you handle the situations above when converting this method into Java? A: In order to translate a generator function to Java you have to reimplement it as a Iterable+Iterator. E.g.: def foo(x): for i in xrange(10): yield x * i ... for x in foo(5): print(x) Becomes (warning: code is not tested): import java.util.Iterator; import java.util.Iterable; class Foo implements Iterable<Integer> { public final int x; public Foo(int x) { this.x = x; } public Iterator<Integer> iterate() { return new Iterator<Integer> { int i = 0; public boolean hasNext() { return i < 10; } public Integer next() { return x * (i ++); } }; } } ... for (int x : new Foo(5)) { System.out.println(x); } For the sets I would indeed use java.util.HashSet. A: You probably want to run it on a JVM. Why not use Scala? I think you can translate the python code into almost the same kind of code in scala. Much better then the verbose java stuff. And it's jvm bytecode in the end which will easily blend in/cooperate with your java app. A: This isn't what you asked for, but I wanted to try it out, so here's a solution in C# using LINQ: static IEnumerable<IEnumerable<int>> getPairs(IEnumerable<int> list) { if (!list.Any()) return new [] { new int[0] }; var first = list.First(); return from second in list.Skip(1) from pair in getPairs(list.Skip(1).Where(rest => rest != second)) select Enumerable.Concat(new [] { first, second }, pair); } Doesn't actually return pairs, just ordered lists of integers, but chopping it up by twos after this is easy. Also, nice to see that C# can rival the conciseness of Python. Testing it out: foreach (var p in getPairs(new [] { 1, 2, 3, 4, 5, 6 })) Console.WriteLine("[" + String.Join(",", p.Select(i => i.ToString()).ToArray()) + "]"); And the output: [1,2,3,4,5,6] [1,2,3,5,4,6] [1,2,3,6,4,5] [1,3,2,4,5,6] [1,3,2,5,4,6] [1,3,2,6,4,5] [1,4,2,3,5,6] [1,4,2,5,3,6] [1,4,2,6,3,5] [1,5,2,3,4,6] [1,5,2,4,3,6] [1,5,2,6,3,4] [1,6,2,3,4,5] [1,6,2,4,3,5] [1,6,2,5,3,4] Credit to Noldorin's answer to another LINQ question for some ideas.
What is the best way to translate this recursive python method into Java?
In another question I was provided with a great answer involving generating certain sets for the Chinese Postman Problem. The answer provided was: def get_pairs(s): if not s: yield [] else: i = min(s) for j in s - set([i]): for r in get_pairs(s - set([i, j])): yield [(i, j)] + r for x in get_pairs(set([1,2,3,4,5,6])): print x This will output the desire result of: [(1, 2), (3, 4), (5, 6)] [(1, 2), (3, 5), (4, 6)] [(1, 2), (3, 6), (4, 5)] [(1, 3), (2, 4), (5, 6)] [(1, 3), (2, 5), (4, 6)] [(1, 3), (2, 6), (4, 5)] [(1, 4), (2, 3), (5, 6)] [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 6), (3, 5)] [(1, 5), (2, 3), (4, 6)] [(1, 5), (2, 4), (3, 6)] [(1, 5), (2, 6), (3, 4)] [(1, 6), (2, 3), (4, 5)] [(1, 6), (2, 4), (3, 5)] [(1, 6), (2, 5), (3, 4)] This really shows off the expressiveness of Python because this is almost exactly how I would write the pseudo-code for the algorithm. I especially like the usage of yield and and the way that sets are treated as first class citizens. However, there in lies my problem. What would be the best way to: 1.Duplicate the functionality of the yield return construct in Java? Would it instead be best to maintain a list and append my partial results to this list? How would you handle the yield keyword. 2.Handle the dealing with the sets? I know that I could probably use one of the Java collections which implements that implements the Set interface and then using things like removeAll() to give me a set difference. Is this what you would do in that case? Ultimately, I'm looking to reduce this method into as concise and straightforward way as possible in Java. I'm thinking the return type of the java version of this method will likely return a list of int arrays or something similar. How would you handle the situations above when converting this method into Java?
[ "In order to translate a generator function to Java you have to reimplement it as a Iterable+Iterator. E.g.:\ndef foo(x):\n for i in xrange(10):\n yield x * i\n...\nfor x in foo(5):\n print(x)\n\nBecomes (warning: code is not tested):\nimport java.util.Iterator;\nimport java.util.Iterable;\n\nclass Foo implements Iterable<Integer> {\n public final int x;\n\n public Foo(int x) {\n this.x = x;\n }\n\n public Iterator<Integer> iterate() {\n return new Iterator<Integer> {\n int i = 0;\n\n public boolean hasNext() {\n return i < 10;\n }\n\n public Integer next() {\n return x * (i ++);\n }\n };\n }\n}\n...\nfor (int x : new Foo(5)) {\n System.out.println(x);\n}\n\nFor the sets I would indeed use java.util.HashSet.\n", "You probably want to run it on a JVM. Why not use Scala? \nI think you can translate the python code into almost the same kind of code in scala. Much better then the verbose java stuff. And it's jvm bytecode in the end which will easily blend in/cooperate with your java app.\n", "This isn't what you asked for, but I wanted to try it out, so here's a solution in C# using LINQ:\nstatic IEnumerable<IEnumerable<int>> getPairs(IEnumerable<int> list)\n{\n if (!list.Any())\n return new [] { new int[0] };\n\n var first = list.First();\n return from second in list.Skip(1)\n from pair in getPairs(list.Skip(1).Where(rest => rest != second))\n select Enumerable.Concat(new [] { first, second }, pair);\n}\n\nDoesn't actually return pairs, just ordered lists of integers, but chopping it up by twos after this is easy. Also, nice to see that C# can rival the conciseness of Python.\nTesting it out: \nforeach (var p in getPairs(new [] { 1, 2, 3, 4, 5, 6 }))\n Console.WriteLine(\"[\" + \n String.Join(\",\", p.Select(i => i.ToString()).ToArray()) + \"]\");\n\nAnd the output:\n[1,2,3,4,5,6]\n[1,2,3,5,4,6]\n[1,2,3,6,4,5]\n[1,3,2,4,5,6]\n[1,3,2,5,4,6]\n[1,3,2,6,4,5]\n[1,4,2,3,5,6]\n[1,4,2,5,3,6]\n[1,4,2,6,3,5]\n[1,5,2,3,4,6]\n[1,5,2,4,3,6]\n[1,5,2,6,3,4]\n[1,6,2,3,4,5]\n[1,6,2,4,3,5]\n[1,6,2,5,3,4]\n\nCredit to Noldorin's answer to another LINQ question for some ideas. \n" ]
[ 2, 1, 0 ]
[]
[]
[ "java", "python", "set", "yield" ]
stackoverflow_0002725542_java_python_set_yield.txt
Q: Creating a spam list with a web crawler in python Hey guys, I'm not trying to do anything malicious here, I just need to do some homework. I'm a fairly new programmer, I'm using python 3.0, and I having difficulty using recursion for problem-solving. I've been stuck on this question for quite a while. Here's the Assignment: Write a recursive method spam(url, n) that takes a url of a web page as input and a non-negative integer n, collects all the email address contained in the web page and adds them to a global dictionary variable spam_dict, and then recursively calls itself on every http link contained in the web page. You will use a dictionary so only one copy of every email address is saved; your dictionary will store (key,value) pairs (email, email). The recursive call should use the parameter n-1 instead of n. If n = 0, you should collect the email addresses but no recursive calls should be made. The parameter n is used to limit the recursion to at most depth n. You will need to use the solutions of the two above problems; your method spam() will call the methods links2() and emails() and possibly other functions as well. Notes: running spam() directly will produce no output on the screen; to find your spam_dict, you will need to read the value of spam_dict, and you will also need to reset it to the empty dictionary before every run of spam. Recall how global variables are used. Usage: >>> spam_dict = {} >>> spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',0) >>> spam_dict.keys() dict_keys([]) >>> spam_dict = {} >>> spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',1) >>> spam_dict.keys() dict_keys(['lperkovic@cs.depaul.edu', 'nobody@xyz.com']) So far, I've written a function that traverses web pages and puts all the links in a nice little list, and what I wanted to do was call that functions. And why would I use recursion on a dictionary? And how? I don't understand how n ties into all of this. def links2(url): content = str(urlopen(url).read()) myparser = MyHTMLParser() myparser.feed(content) lst = myparser.get() mergelst = [] for link in lst: mergelst.append(urljoin(lst[0],link)) print(mergelst) Any input (except why spam is bad) would be greatly appreciated. Also, I realize that the above function could probably look better, if you have a way to do it, I'm all ears. However, all I need is the point is for the program to produce the proper output. Added: I wrote a function that collects emails from a page, but I'm not sure how to lump .com and .edu and .org all together. from re import findall def emails(url): links = str(links3(url)) # how do I construct pattern? pattern='[A-Za-z0-9_.]+\@[A-Za-z0-9_.]+.com\.edu\.org lst = findall(pattern,links) print(lst) How do I tell python that? I can't find it in the documentation. A: Think about how recursion works. What you want is for your function to be able to call itself in some cases. In this case, you need to add a parameter for the recursion level to your function, and then you need to figure out what it should do in the various cases? At the most basic level, what should it do with n=0? (hint: you've about got it already) What should it do if n=1? You probably want to call your function again on each element of your existing list with n=0. What about if n is greater than 1? You want to call your function again with n = n-1 on each element you've got so far. A: n would play into it, as the problem states, by limiting the recursion to a maximum "call depth". The idea is that since you're recursively invoking the scanning for emails from an already-running scan, you build up a call stack of what called what that gets deeper and deeper as you continue to recursively call the scanner. You don't want it to go on forever, so as one of the arguments you pass an integer that you decrement each time you make a call. When it reaches 0, you stop doing recursive calls and let the sequence of recursions unwind itself. call 1 (args...., n=3) call 2a (args...., n=2) call 3 (args...., n=1) call 4a (args..., n=0) <-- these calls won't call more scans call 4b (args..., n=0) <-- because n=0, so this is max depth call 2b (args...., n=2)
Creating a spam list with a web crawler in python
Hey guys, I'm not trying to do anything malicious here, I just need to do some homework. I'm a fairly new programmer, I'm using python 3.0, and I having difficulty using recursion for problem-solving. I've been stuck on this question for quite a while. Here's the Assignment: Write a recursive method spam(url, n) that takes a url of a web page as input and a non-negative integer n, collects all the email address contained in the web page and adds them to a global dictionary variable spam_dict, and then recursively calls itself on every http link contained in the web page. You will use a dictionary so only one copy of every email address is saved; your dictionary will store (key,value) pairs (email, email). The recursive call should use the parameter n-1 instead of n. If n = 0, you should collect the email addresses but no recursive calls should be made. The parameter n is used to limit the recursion to at most depth n. You will need to use the solutions of the two above problems; your method spam() will call the methods links2() and emails() and possibly other functions as well. Notes: running spam() directly will produce no output on the screen; to find your spam_dict, you will need to read the value of spam_dict, and you will also need to reset it to the empty dictionary before every run of spam. Recall how global variables are used. Usage: >>> spam_dict = {} >>> spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',0) >>> spam_dict.keys() dict_keys([]) >>> spam_dict = {} >>> spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',1) >>> spam_dict.keys() dict_keys(['lperkovic@cs.depaul.edu', 'nobody@xyz.com']) So far, I've written a function that traverses web pages and puts all the links in a nice little list, and what I wanted to do was call that functions. And why would I use recursion on a dictionary? And how? I don't understand how n ties into all of this. def links2(url): content = str(urlopen(url).read()) myparser = MyHTMLParser() myparser.feed(content) lst = myparser.get() mergelst = [] for link in lst: mergelst.append(urljoin(lst[0],link)) print(mergelst) Any input (except why spam is bad) would be greatly appreciated. Also, I realize that the above function could probably look better, if you have a way to do it, I'm all ears. However, all I need is the point is for the program to produce the proper output. Added: I wrote a function that collects emails from a page, but I'm not sure how to lump .com and .edu and .org all together. from re import findall def emails(url): links = str(links3(url)) # how do I construct pattern? pattern='[A-Za-z0-9_.]+\@[A-Za-z0-9_.]+.com\.edu\.org lst = findall(pattern,links) print(lst) How do I tell python that? I can't find it in the documentation.
[ "Think about how recursion works. What you want is for your function to be able to call itself in some cases. In this case, you need to add a parameter for the recursion level to your function, and then you need to figure out what it should do in the various cases?\nAt the most basic level, what should it do with n=0? (hint: you've about got it already)\nWhat should it do if n=1? You probably want to call your function again on each element of your existing list with n=0.\nWhat about if n is greater than 1? You want to call your function again with n = n-1 on each element you've got so far.\n", "n would play into it, as the problem states, by limiting the recursion to a maximum \"call depth\".\nThe idea is that since you're recursively invoking the scanning for emails from an already-running scan, you build up a call stack of what called what that gets deeper and deeper as you continue to recursively call the scanner.\nYou don't want it to go on forever, so as one of the arguments you pass an integer that you decrement each time you make a call. When it reaches 0, you stop doing recursive calls and let the sequence of recursions unwind itself.\ncall 1 (args...., n=3)\n call 2a (args...., n=2)\n call 3 (args...., n=1)\n call 4a (args..., n=0) <-- these calls won't call more scans\n call 4b (args..., n=0) <-- because n=0, so this is max depth\n call 2b (args...., n=2)\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002748444_python.txt
Q: Is this a good approach to execute a list of operations on a data structure in Python? I have a dictionary of data, the key is the file name and the value is another dictionary of its attribute values. Now I'd like to pass this data structure to various functions, each of which runs some test on the attribute and returns True/False. One approach would be to call each function one by one explicitly from the main code. However I can do something like this: #MYmodule.py class Mymodule: def MYfunc1(self): ... def MYfunc2(self): ... #main.py import Mymodule ... #fill the data structure ... #Now call all the functions in Mymodule one by one for funcs in dir(Mymodule): if funcs[:2]=='MY': result=Mymodule.__dict__.get(funcs)(dataStructure) The advantage of this approach is that implementation of main class needn't change when I add more logic/tests to MYmodule. Is this a good way to solve the problem at hand? Are there better alternatives to this solution? A: I'd say a better and much more Pythonic approach would be to define a decorator to indicate which functions you want to use: class MyFunc(object): funcs = [] def __init__(self, func): self.funcs.append(func) @MyFunc def foo(): return 5 @MyFunc def bar(): return 10 def quux(): # Not decorated, so will not be in MyFunc return 20 for func in MyFunc.funcs: print func() Output: 5 10 Essentially you're performing the same logic: taking only functions who were defined in a particular manner and applying them to a specific set of data. A: Sridhar, the method you proposed is very similar to the one used in the unittest module. For example, this is how unittest.TestLoader finds the names of all the test methods to run (lifted from /usr/lib/python2.6/unittest.py): def getTestCaseNames(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass """ def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__') testFnNames = filter(isTestMethod, dir(testCaseClass)) if self.sortTestMethodsUsing: testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)) return testFnNames Just like your proposal, unittest uses dir to list all the attributes of testCaseClass, and filters the list for those whose name startswith prefix (which is set elsewhere to equal 'test'). I suggest a few minor changes: If you place the functions in MYmodule.py, then (of course) the import statement must be import MYmodule Use getattr instead of .__dict__.get. Not only is it shorter, but it continue to work if you subclass Mymodule. That might not be your intention at this point, but using getattr is probably a good default habit anyway. for funcs in dir(MYmodule.Mymodule): if funcs.startswith('MY'): result=getattr(MYmodule.Mymodule,funcs)(dataStructure)
Is this a good approach to execute a list of operations on a data structure in Python?
I have a dictionary of data, the key is the file name and the value is another dictionary of its attribute values. Now I'd like to pass this data structure to various functions, each of which runs some test on the attribute and returns True/False. One approach would be to call each function one by one explicitly from the main code. However I can do something like this: #MYmodule.py class Mymodule: def MYfunc1(self): ... def MYfunc2(self): ... #main.py import Mymodule ... #fill the data structure ... #Now call all the functions in Mymodule one by one for funcs in dir(Mymodule): if funcs[:2]=='MY': result=Mymodule.__dict__.get(funcs)(dataStructure) The advantage of this approach is that implementation of main class needn't change when I add more logic/tests to MYmodule. Is this a good way to solve the problem at hand? Are there better alternatives to this solution?
[ "I'd say a better and much more Pythonic approach would be to define a decorator to indicate which functions you want to use:\nclass MyFunc(object):\n funcs = []\n def __init__(self, func):\n self.funcs.append(func)\n\n@MyFunc\ndef foo():\n return 5\n\n@MyFunc\ndef bar():\n return 10\n\ndef quux():\n # Not decorated, so will not be in MyFunc\n return 20\n\nfor func in MyFunc.funcs:\n print func()\n\nOutput:\n5\n10\n\nEssentially you're performing the same logic: taking only functions who were defined in a particular manner and applying them to a specific set of data.\n", "Sridhar, the method you proposed is very similar to the one used in the unittest module. \nFor example, this is how unittest.TestLoader finds the names of all the test methods to run (lifted from /usr/lib/python2.6/unittest.py):\ndef getTestCaseNames(self, testCaseClass):\n \"\"\"Return a sorted sequence of method names found within testCaseClass\n \"\"\"\n def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):\n return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')\n testFnNames = filter(isTestMethod, dir(testCaseClass))\n if self.sortTestMethodsUsing:\n testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))\n return testFnNames\n\nJust like your proposal, unittest uses dir to list all the attributes of\ntestCaseClass, and filters the list for those whose name startswith prefix (which is set elsewhere to equal 'test').\nI suggest a few minor changes: \nIf you place the functions in MYmodule.py, then (of course) the import statement must be\nimport MYmodule\n\nUse getattr instead of .__dict__.get. Not only is it shorter, but it continue to work if you subclass Mymodule. That might not be your intention at this point, but using getattr is probably a good default habit anyway.\nfor funcs in dir(MYmodule.Mymodule):\n if funcs.startswith('MY'):\n result=getattr(MYmodule.Mymodule,funcs)(dataStructure)\n\n" ]
[ 6, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0002748280_coding_style_python.txt
Q: Python: Activate F6 Key after certain Interval How to activate the F6 key every x seconds for the active window, x being whatever number I enter, and the program stops with the hit of like ctrl+z or something. What would be a good way to do this? A: Looks like this might do what you need: http://www.rutherfurd.net/python/sendkeys/ I haven't tried to personally and my initial response was going to be that you're most likely going to need to look into Win32 APIs, but a quick google search turned that up.
Python: Activate F6 Key after certain Interval
How to activate the F6 key every x seconds for the active window, x being whatever number I enter, and the program stops with the hit of like ctrl+z or something. What would be a good way to do this?
[ "Looks like this might do what you need: http://www.rutherfurd.net/python/sendkeys/ \nI haven't tried to personally and my initial response was going to be that you're most likely going to need to look into Win32 APIs, but a quick google search turned that up.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002748616_python.txt
Q: What causes the Openid error: Received "invalidate_handle" from server I'm new to openid, and I am getting an "invalidate_handle" and I have no idea what to do to fix it. I'm using django_authopenid [Thu Apr 29 14:13:28 2010] [error] Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required type http://specs.openid.net/auth/2.0/signon not found in ['http://specs.openid.net/auth/2.0/server', 'http://openid.net/srv/ax/1.0', 'http://specs.openid.net/extensions/ui/1.0/mode/popup', 'http://specs.openid.net/extensions/ui/1.0/icon', 'http://specs.openid.net/extensions/pape/1.0'] for endpoint <openid.consumer.discover.OpenIDServiceEndpoint server_url='https://www.google.com/accounts/o8/ud' claimed_id=None local_id=None canonicalID=None used_yadis=True >> [Thu Apr 29 14:13:29 2010] [error] Attempting discovery to verify endpoint [Thu Apr 29 14:13:29 2010] [error] Performing discovery on https://www.google.com/accounts/o8/id?id=AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Received id_res response from https://www.google.com/accounts/o8/ud using association AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Using OpenID check_authentication [Thu Apr 29 14:13:29 2010] [error] op_endpoint [Thu Apr 29 14:13:29 2010] [error] claimed_id [Thu Apr 29 14:13:29 2010] [error] identity [Thu Apr 29 14:13:29 2010] [error] return_to [Thu Apr 29 14:13:29 2010] [error] response_nonce [Thu Apr 29 14:13:29 2010] [error] assoc_handle [Thu Apr 29 14:13:29 2010] [error] Received "invalidate_handle" from server https://www.google.com/accounts/o8/ud A: openid.invalidate_handle is the Provider's way of saying that your RP is sending an association that does not exist or has expired. The RP is supposed to respond by deleting that association handle so it isn't reused in the future. If you're always getting invalidate_handles in the response, then the RP you're using has a bug in it.
What causes the Openid error: Received "invalidate_handle" from server
I'm new to openid, and I am getting an "invalidate_handle" and I have no idea what to do to fix it. I'm using django_authopenid [Thu Apr 29 14:13:28 2010] [error] Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required type http://specs.openid.net/auth/2.0/signon not found in ['http://specs.openid.net/auth/2.0/server', 'http://openid.net/srv/ax/1.0', 'http://specs.openid.net/extensions/ui/1.0/mode/popup', 'http://specs.openid.net/extensions/ui/1.0/icon', 'http://specs.openid.net/extensions/pape/1.0'] for endpoint <openid.consumer.discover.OpenIDServiceEndpoint server_url='https://www.google.com/accounts/o8/ud' claimed_id=None local_id=None canonicalID=None used_yadis=True >> [Thu Apr 29 14:13:29 2010] [error] Attempting discovery to verify endpoint [Thu Apr 29 14:13:29 2010] [error] Performing discovery on https://www.google.com/accounts/o8/id?id=AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Received id_res response from https://www.google.com/accounts/o8/ud using association AOxxxxxxxxOX5-V9oDc3-btHhFxzAcccccccccc2RTHgh [Thu Apr 29 14:13:29 2010] [error] Using OpenID check_authentication [Thu Apr 29 14:13:29 2010] [error] op_endpoint [Thu Apr 29 14:13:29 2010] [error] claimed_id [Thu Apr 29 14:13:29 2010] [error] identity [Thu Apr 29 14:13:29 2010] [error] return_to [Thu Apr 29 14:13:29 2010] [error] response_nonce [Thu Apr 29 14:13:29 2010] [error] assoc_handle [Thu Apr 29 14:13:29 2010] [error] Received "invalidate_handle" from server https://www.google.com/accounts/o8/ud
[ "openid.invalidate_handle is the Provider's way of saying that your RP is sending an association that does not exist or has expired. The RP is supposed to respond by deleting that association handle so it isn't reused in the future. If you're always getting invalidate_handles in the response, then the RP you're using has a bug in it.\n" ]
[ 2 ]
[]
[]
[ "django", "django_authopenid", "openid", "python" ]
stackoverflow_0002739886_django_django_authopenid_openid_python.txt
Q: How can I make a siren noise in Python? I'm trying to make a siren sound in python with beeps, but had no success.. I'm trying something like winsound.Beep(700,500) winsound.Beep(710,500) winsound.Beep(720,500) ... It's a better way to do it? And play it? Without external files... Thx A: Record a high quality siren as a WAV file (Audacity is a nice tool for this task, and might even provide the right mix of sound generators for this) and use PlaySound. winsound.PlaySound('siren.wav', winsound.SND_FILENAME) You could also bundle it into the script as a string to avoid having a separate file: siren = base64.b64decode(''' <base64-encoded data> ''') winsound.PlaySound(siren, winsound.SND_MEMORY) To create the data for siren, run the WAV file through a base64 encoder (e.g., here is a basic command-line tool — the download includes a win32 exe) and paste the output into the siren string. Base64 isn't a requirement, by the way; it's just a convenient way to embed binary data into a Python source file. A: I remember using something similar on QBASIC when I was still a kid: DO FOR n = -180 TO 180 STEP .1 f = 440 + 50 * SIN(n) SOUND f, 1 NEXT LOOP SOUND f, 1 should be the same thing as winsound.Beep, with pitch and duration. It used to work great but since I took the snippet here I'm not sure I did exactly this way. It's just to give you the idea..
How can I make a siren noise in Python?
I'm trying to make a siren sound in python with beeps, but had no success.. I'm trying something like winsound.Beep(700,500) winsound.Beep(710,500) winsound.Beep(720,500) ... It's a better way to do it? And play it? Without external files... Thx
[ "Record a high quality siren as a WAV file (Audacity is a nice tool for this task, and might even provide the right mix of sound generators for this) and use PlaySound.\nwinsound.PlaySound('siren.wav', winsound.SND_FILENAME)\n\nYou could also bundle it into the script as a string to avoid having a separate file:\nsiren = base64.b64decode('''\n <base64-encoded data>\n ''')\nwinsound.PlaySound(siren, winsound.SND_MEMORY)\n\nTo create the data for siren, run the WAV file through a base64 encoder (e.g., here is a basic command-line tool — the download includes a win32 exe) and paste the output into the siren string. Base64 isn't a requirement, by the way; it's just a convenient way to embed binary data into a Python source file.\n", "I remember using something similar on QBASIC when I was still a kid:\nDO\nFOR n = -180 TO 180 STEP .1\nf = 440 + 50 * SIN(n)\nSOUND f, 1\nNEXT\nLOOP\n\nSOUND f, 1 should be the same thing as winsound.Beep, with pitch and duration. It used to work great but since I took the snippet here I'm not sure I did exactly this way.\nIt's just to give you the idea..\n" ]
[ 3, 2 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0002748702_audio_python.txt
Q: In Python, how can I find the index of the first item in a list that is NOT some value? Python's list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x. Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to even just use a function that returns the index of the first item with a value != None. I can think of a 'for' loop implementation with an incrementing counter variable, but I feel like I'm missing something. Is there an existing method, or a one-line Python construction that can handle this? In my program, the situation comes up when I'm handling lists returned from complex regex matches. All but one item in each list have a value of None. If I just needed the matched string, I could use a list comprehension like '[x for x in [my_list] if x is not None]', but I need the index in order to figure out which capture group in my regex actually caused the match. A: Exiting at the first match is really easy: instead of computing a full list comprehension (then tossing away everything except the first item), use next over a genexp. Assuming for example that you want -1 when no item satisfies the condition of being != x, return next((i for i, v in enumerate(L) if v != x), -1) This is Python 2.6 syntax; if you're stuck with 2.5 or earlier, .next() is a method of the genexp (or other iterator) and doesn't accept a default value like the -1 above (so if you don't want to see a StopIteration exception you'll have to use a try/except). But then, there is a reason more releases were made after 2.5 -- continuous improvement of the language and its built-ins!-) A: Using a list comprehension when you only need the first just feels slimy (to me). Use a for-loop and exit early. >>> lst = [None, None, None, "foo", None] >>> for i, item in enumerate(lst): ... if item: break ... else: ... print "not found" ... >>> i 3 A: enumerate() returns an iterator that yields a tuple of the current index of the iterable as well as the item itself. A: [i for i, x in enumerate(my_list) if x != value][0] If you're not sure whether there's a non-matching item, use this instead: match = [i for i, x in enumerate(my_list) if x != value] if match: i = match[0] # i is your number. You can make this even more "functional" with itertools, but you will soon reach the point where a simple for loop is better. Even the above solutions aren't as efficient as a for loop, since they construct a list of all non-matching indices before you pull the one of interest.
In Python, how can I find the index of the first item in a list that is NOT some value?
Python's list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x. Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to even just use a function that returns the index of the first item with a value != None. I can think of a 'for' loop implementation with an incrementing counter variable, but I feel like I'm missing something. Is there an existing method, or a one-line Python construction that can handle this? In my program, the situation comes up when I'm handling lists returned from complex regex matches. All but one item in each list have a value of None. If I just needed the matched string, I could use a list comprehension like '[x for x in [my_list] if x is not None]', but I need the index in order to figure out which capture group in my regex actually caused the match.
[ "Exiting at the first match is really easy: instead of computing a full list comprehension (then tossing away everything except the first item), use next over a genexp. Assuming for example that you want -1 when no item satisfies the condition of being != x,\nreturn next((i for i, v in enumerate(L) if v != x), -1)\n\nThis is Python 2.6 syntax; if you're stuck with 2.5 or earlier, .next() is a method of the genexp (or other iterator) and doesn't accept a default value like the -1 above (so if you don't want to see a StopIteration exception you'll have to use a try/except). But then, there is a reason more releases were made after 2.5 -- continuous improvement of the language and its built-ins!-)\n", "Using a list comprehension when you only need the first just feels slimy (to me). Use a for-loop and exit early.\n>>> lst = [None, None, None, \"foo\", None]\n>>> for i, item in enumerate(lst):\n... if item: break\n... else:\n... print \"not found\"\n... \n>>> i\n3\n\n", "enumerate() returns an iterator that yields a tuple of the current index of the iterable as well as the item itself.\n", "[i for i, x in enumerate(my_list) if x != value][0]\n\nIf you're not sure whether there's a non-matching item, use this instead:\nmatch = [i for i, x in enumerate(my_list) if x != value]\nif match:\n i = match[0]\n # i is your number.\n\nYou can make this even more \"functional\" with itertools, but you will soon reach the point where a simple for loop is better. Even the above solutions aren't as efficient as a for loop, since they construct a list of all non-matching indices before you pull the one of interest.\n" ]
[ 17, 5, 4, 1 ]
[ "A silly itertools-based solution:)\nimport itertools as it, operator as op, functools as ft\n\ndef index_ne(item, sequence):\n sequence= iter(sequence)\n counter= it.count(-1) # start counting at -1\n pairs= it.izip(sequence, counter) # pair them\n get_1st= it.imap(op.itemgetter(0), pairs) # drop the used counter value\n ne_scanner= it.ifilter(ft.partial(op.ne, item), get_1st) # get only not-equals\n try:\n ne_scanner.next() # this should be the first not equal\n except StopIteration:\n return None # or raise some exception, all items equal to item\n else:\n return counter.next() # should be the index of the not-equal item\n\nif __name__ == \"__main__\":\n import random\n\n test_data= [0]*20\n print \"failure\", index_ne(0, test_data)\n\n index= random.randrange(len(test_data))\n test_data[index]= 1\n print \"success:\", index_ne(0, test_data), \"should be\", index\n\nAll this just to take advantage of the itertools.count counting :)\n" ]
[ -1 ]
[ "indexing", "list", "methods", "python" ]
stackoverflow_0002748235_indexing_list_methods_python.txt
Q: Efficient way to build a MySQL update query in Python I have a class variable called attributes which lists the instance variables I want to update in a database: attributes = ['id', 'first_name', 'last_name', 'name', 'name_url', 'email', 'password', 'password_salt', 'picture_id'] Each of the class attributes are updated upon instantiation. I would like to loop through each of the attributes and build a MySQL update query in the form of: UPDATE members SET id = self._id, first_name = self._first name ... Thanks. A: class Ic(object): attributes = ['id', 'first_name', 'last_name', 'name', 'name_url', 'email', 'password', 'password_salt', 'picture_id'] def __init__(self): ... # and other methods that set all the attributes on self def updater(self): sqlbase = 'UPDATE members SET %s WHERE whateveryouwanthere' setpieces = [] values = [] for atr in self.attributes: setpieces.append('%s = ?' % atr) values.append(getattr(self, atr, None)) return sqlbase % ', '.join(setpieces), values The caller needs to build up an object of class Ic appropriately, then do sql, values = theobj.updater() and lastly call mycursor.execute(sql, values) on whatever DB API cursor it has to the database which needs to be updated (I have no idea about the WHERE conditions you want to use to identify the sepcific record to update, which is why I put a whatreveryouwanthere placeholder there;-). A: First question: will all the variables in attributes be used? If so the easiest way is probably to use the DBAPI's execute method. assuming your cursor is instantiated as csr: sql="UPDATE mytable SET phone=? where username=?" variables = ("a phone number","a username") csr.execute(sql,variables) There are additional ways of doing it, such as using dictionaries, positional indicators, etc.. see DBAPI FAQ for more details.
Efficient way to build a MySQL update query in Python
I have a class variable called attributes which lists the instance variables I want to update in a database: attributes = ['id', 'first_name', 'last_name', 'name', 'name_url', 'email', 'password', 'password_salt', 'picture_id'] Each of the class attributes are updated upon instantiation. I would like to loop through each of the attributes and build a MySQL update query in the form of: UPDATE members SET id = self._id, first_name = self._first name ... Thanks.
[ "class Ic(object):\n attributes = ['id', 'first_name', 'last_name', 'name', 'name_url',\n 'email', 'password', 'password_salt', 'picture_id']\n\n def __init__(self): ...\n\n # and other methods that set all the attributes on self\n\n def updater(self):\n sqlbase = 'UPDATE members SET %s WHERE whateveryouwanthere'\n setpieces = []\n values = []\n for atr in self.attributes:\n setpieces.append('%s = ?' % atr)\n values.append(getattr(self, atr, None))\n return sqlbase % ', '.join(setpieces), values\n\nThe caller needs to build up an object of class Ic appropriately, then do\nsql, values = theobj.updater()\n\nand lastly call mycursor.execute(sql, values) on whatever DB API cursor it has to the database which needs to be updated (I have no idea about the WHERE conditions you want to use to identify the sepcific record to update, which is why I put a whatreveryouwanthere placeholder there;-).\n", "First question: will all the variables in attributes be used? If so the easiest way is probably to use the DBAPI's execute method.\nassuming your cursor is instantiated as csr:\nsql=\"UPDATE mytable SET phone=? where username=?\"\nvariables = (\"a phone number\",\"a username\")\ncsr.execute(sql,variables)\n\nThere are additional ways of doing it, such as using dictionaries, positional indicators, etc.. see DBAPI FAQ for more details.\n" ]
[ 3, 0 ]
[]
[]
[ "mysql", "pylons", "python" ]
stackoverflow_0002746232_mysql_pylons_python.txt
Q: Modern, Non-trivial, Pygame Tutorials? What are some 'good', non-trivial Pygame tutorials? I realize good is relative. As an example, a good one (to me) is the one that describes how to use pygame.camera. It's recent uses a modern PyGame (1.9) non-trivial, in that it shows how to use it the module for a real application. I'd like to find others. A lot of the ones on the Pygame site are from 1.3 era or earlier! Info on related projects, like Gloss is welcome as well. (If your answer is "read the source of some pygame games", please link to the source of particular ones and note what is good about them) A: (Shameless plug) - a 4-part tutorial that starts here. It builds a non-trivial 2D game-like simulation complete with quite a few features, using a modern version of Pygame. (source: thegreenplace.net) (editor comment: In particular, this tutorial covers: the 'centering trick' for smoothing rotation simple animation AI pathfinding (using the A* algorithm) storing a 'grid map' to have obstacles on the game field ) A: Object oriented approach to PyGame The aim is to create 2D game engine, with classes that wraps PyGame.
Modern, Non-trivial, Pygame Tutorials?
What are some 'good', non-trivial Pygame tutorials? I realize good is relative. As an example, a good one (to me) is the one that describes how to use pygame.camera. It's recent uses a modern PyGame (1.9) non-trivial, in that it shows how to use it the module for a real application. I'd like to find others. A lot of the ones on the Pygame site are from 1.3 era or earlier! Info on related projects, like Gloss is welcome as well. (If your answer is "read the source of some pygame games", please link to the source of particular ones and note what is good about them)
[ "(Shameless plug) - a 4-part tutorial that starts here. It builds a non-trivial 2D game-like simulation complete with quite a few features, using a modern version of Pygame.\n\n(source: thegreenplace.net) \n(editor comment: In particular, this tutorial covers:\n\nthe 'centering trick' for smoothing rotation\nsimple animation\nAI pathfinding (using the A* algorithm)\nstoring a 'grid map' to have obstacles on the game field\n)\n\n", "Object oriented approach to PyGame\nThe aim is to create 2D game engine, with classes that wraps PyGame.\n" ]
[ 7, 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0001617038_pygame_python.txt
Q: Alternative pygame resources I have been trying to access the pygame website for a few weeks now, and I can't get to it. I doubt it's down, so I have to conclude that it's blocked because I am in China. I have no idea why. Anyways, I want the pygame documentation, but all the download links I fond lead back to pygame.org (which I does not even begin loading, it's such a politically subversive website you know!). Can anyone tell me where I can get documentation and other pygame resources without going through pygame.org? I would really appreciate it, thanks. PS> I am on windows XP, if it matters. A: I'll upload the pygame source here http://www.cse.unsw.edu.au/~cma/pygame-1.9.1release.zip Unzip it and there's a folder called 'docs' all the documentation is in there. A: Here is Seul mirror maybe it will work :), if not you can always install any Linux on VM, and than download PyGame from repos.
Alternative pygame resources
I have been trying to access the pygame website for a few weeks now, and I can't get to it. I doubt it's down, so I have to conclude that it's blocked because I am in China. I have no idea why. Anyways, I want the pygame documentation, but all the download links I fond lead back to pygame.org (which I does not even begin loading, it's such a politically subversive website you know!). Can anyone tell me where I can get documentation and other pygame resources without going through pygame.org? I would really appreciate it, thanks. PS> I am on windows XP, if it matters.
[ "I'll upload the pygame source here http://www.cse.unsw.edu.au/~cma/pygame-1.9.1release.zip\nUnzip it and there's a folder called 'docs' all the documentation is in there. \n", "Here is Seul mirror maybe it will work :), if not you can always install any Linux on VM, and than download PyGame from repos.\n" ]
[ 16, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0001997679_pygame_python.txt
Q: Is TDD broken in Python? Assume we have a class UserService with attribute current_user. Suppose it is used in AppService class. We have AppService covered with tests. In test setup we stub out current_user with some mock value: UserService.current_user = 'TestUser' Assume we decide to rename current_user to active_user. We rename it in UserService but forget to make change to its usage in AppService. We run tests and they pass! Test setup adds attribute current_user which is still (wrongly but successfully) used in AppService. Now our tests are useless. They pass but application will fail in production. We can't rely on our test suite ==> TDD is not possible. Is TDD broken in Python? A: The problem really is not in TDD, nor Python. First of all, TDD does not give you a proof that when all your tests pass, your application is good. Imagine e.g. multiplyBy2() function, which can be tested with input 1,2,3 and output 2,4,8 and now imagine, you implemented multiplyBy2 as squaring. All your tests pass, you have 100% code coverage and your implementation is wrong. You have to understand, that TDD can only give you assurance, that once your test fails, something is wrong with your app, nothing more, nothing less. So as suggested in other answer, the problem is in that you do not have test that fails. If you had used some statically typed language, compiler would do that test for you and complain about using non-existent method. This does not mean you should use statically typed language, it just means you need to write more tests in dynamically typed language. If you are interested in enforcing correctness of the code, you should look at design by contract for ensuring correctness at least during runtime and formal specifications to have proofs for at least some algorithms, but this is I guess quite far from standard coding. A: OK, I have found the solution. Python library Mock does what I want. Below is the code I end up with. Model and service definitions: class User(object): def __init__(self): self.roles = [] class UserService(object): def get_current_user(self): return None # get from environment, database, etc. current_user = property(get_current_user) class AppService(object): def __init__(self, userService): self.userService = userService def can_write(self): return 'admin' in self.userService.current_user.roles Here's how to test can_write method of AppService with different users: class AppServiceTests(unittest.TestCase): def test_can_write(self): user = User() @patch_object(UserService, 'current_user', user) def can_write(): appService = AppService(UserService()) return appService.can_write() user.roles = ['admin'] self.assertTrue(can_write()) user.roles = ['user'] self.assertFalse(can_write()) If you rename property current_user only in class UserService, you'll get error when trying to patch the object. This is the behavior I was looking for. A: Before the change, something should be different about the object's behavior, depending on the value of current_user. Let's call that something predicate(). And pardon my python; consider this pseudocode: UserService.current_user = 'X' assertFalse(obj.predicate()) UserService.current_user = 'Y' assertTrue(obj.predicate()) OK? So, that's your test. Get it to pass. Now change the class under test so that current_user is renamed to active_user. Now the test will fail, either at the first assertion, or at the second. Because you're no longer changing the value of the field formerly known as current_user, so predicate will be false or true in both cases. Now you have a very focused test that will alert you when the class changes in such a way as to invalidate the other test's setup.
Is TDD broken in Python?
Assume we have a class UserService with attribute current_user. Suppose it is used in AppService class. We have AppService covered with tests. In test setup we stub out current_user with some mock value: UserService.current_user = 'TestUser' Assume we decide to rename current_user to active_user. We rename it in UserService but forget to make change to its usage in AppService. We run tests and they pass! Test setup adds attribute current_user which is still (wrongly but successfully) used in AppService. Now our tests are useless. They pass but application will fail in production. We can't rely on our test suite ==> TDD is not possible. Is TDD broken in Python?
[ "The problem really is not in TDD, nor Python. First of all, TDD does not give you a proof that when all your tests pass, your application is good. Imagine e.g. multiplyBy2() function, which can be tested with input 1,2,3 and output 2,4,8 and now imagine, you implemented multiplyBy2 as squaring. All your tests pass, you have 100% code coverage and your implementation is wrong. You have to understand, that TDD can only give you assurance, that once your test fails, something is wrong with your app, nothing more, nothing less. So as suggested in other answer, the problem is in that you do not have test that fails. If you had used some statically typed language, compiler would do that test for you and complain about using non-existent method. This does not mean you should use statically typed language, it just means you need to write more tests in dynamically typed language.\nIf you are interested in enforcing correctness of the code, you should look at design by contract for ensuring correctness at least during runtime and formal specifications to have proofs for at least some algorithms, but this is I guess quite far from standard coding.\n", "OK, I have found the solution. Python library Mock does what I want.\nBelow is the code I end up with.\nModel and service definitions:\nclass User(object):\n def __init__(self):\n self.roles = []\n\n\nclass UserService(object):\n def get_current_user(self):\n return None # get from environment, database, etc.\n\n current_user = property(get_current_user)\n\n\nclass AppService(object):\n def __init__(self, userService):\n self.userService = userService\n\n def can_write(self):\n return 'admin' in self.userService.current_user.roles\n\nHere's how to test can_write method of AppService with different users:\nclass AppServiceTests(unittest.TestCase):\n def test_can_write(self):\n user = User()\n\n @patch_object(UserService, 'current_user', user)\n def can_write():\n appService = AppService(UserService())\n return appService.can_write()\n\n user.roles = ['admin']\n self.assertTrue(can_write())\n\n user.roles = ['user']\n self.assertFalse(can_write())\n\nIf you rename property current_user only in class UserService, you'll get error when trying to patch the object. This is the behavior I was looking for.\n", "Before the change, something should be different about the object's behavior, depending on the value of current_user. Let's call that something predicate(). And pardon my python; consider this pseudocode:\nUserService.current_user = 'X'\nassertFalse(obj.predicate())\nUserService.current_user = 'Y'\nassertTrue(obj.predicate())\n\nOK? So, that's your test. Get it to pass. Now change the class under test so that current_user is renamed to active_user. Now the test will fail, either at the first assertion, or at the second. Because you're no longer changing the value of the field formerly known as current_user, so predicate will be false or true in both cases. Now you have a very focused test that will alert you when the class changes in such a way as to invalidate the other test's setup.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "mocking", "python", "refactoring", "tdd", "unit_testing" ]
stackoverflow_0002741593_mocking_python_refactoring_tdd_unit_testing.txt
Q: Best deployment strategy for Python google app engine I wonder if there are any best practices/patterns for deploying python apps on Google app engine specifically Django. The best practice should be combination of existing best practices viz. Fabric, Paver, Buildout etc. Also please share best practice patterns for developing (I could not get virtualenv running with Django and Django App engine helper) A: For many projects, you shouldn't need any deployment process at all. If you're using App Engine Patch or Django-Nonrel, they should take care of everything for you. For other needs, check out this article on buildout and this set of buildout recipes.
Best deployment strategy for Python google app engine
I wonder if there are any best practices/patterns for deploying python apps on Google app engine specifically Django. The best practice should be combination of existing best practices viz. Fabric, Paver, Buildout etc. Also please share best practice patterns for developing (I could not get virtualenv running with Django and Django App engine helper)
[ "For many projects, you shouldn't need any deployment process at all. If you're using App Engine Patch or Django-Nonrel, they should take care of everything for you.\nFor other needs, check out this article on buildout and this set of buildout recipes.\n" ]
[ 2 ]
[]
[]
[ "deployment", "google_app_engine", "python" ]
stackoverflow_0002743806_deployment_google_app_engine_python.txt
Q: xml to Python data structure using lxml How can I convert xml to Python data structure using lxml? I have searched high and low but can't find anything. Input example <ApplicationPack> <name>Mozilla Firefox</name> <shortname>firefox</shortname> <description>Leading Open Source internet browser.</description> <version>3.6.3-1</version> <license name="Firefox EULA">http://www.mozilla.com/en-US/legal/eula/firefox-en.html</license> <ms-license>False</ms-license> <vendor>Mozilla Foundation</vendor> <homepage>http://www.mozilla.org/firefox</homepage> <icon>resources/firefox.png</icon> <download>http://download.mozilla.org/?product=firefox-3.6.3&amp;os=win&amp;lang=en-GB</download> <crack required="0"/> <install>scripts/install.sh</install> <postinstall name="Clean Up"></postinstall> <run>C:\\Program Files\\Mozilla Firefox\\firefox.exe</run> <uninstall>c:\\Program Files\\Mozilla Firefox\\uninstall\\helper.exe /S</uninstall> <requires name="autohotkey" /> </ApplicationPack> A: >>> from lxml import etree >>> treetop = etree.fromstring(anxmlstring) converts the xml in the string to a Python data structure, and so does >>> othertree = etree.parse(somexmlurl) where somexmlurl is the path to a local XML file or the URL of an XML file on the web. The Python data structure these functions provide (known as an "element tree", whence the etree module name) is well documented here -- all the classes, functions, methods, etc, that the Python data structure in question supports. It closely matches one supported in the Python standard library, by the way. If you want some different Python data structure, you'll have to walk through the Python data structure which lxml returns, as above mentioned, and build your different data structure yourself based on the information thus collected; lxml can't specifically help you, except by offering several helpers for finding information in the parsed structure it returns, so that collecting said info is a flexible, easy task (again, see the documentation URL above). A: It's not entirely clear what kind of data structure you're looking for, but here's a link to a code sample to convert XML to python dictionary of lists via lxml.etree.
xml to Python data structure using lxml
How can I convert xml to Python data structure using lxml? I have searched high and low but can't find anything. Input example <ApplicationPack> <name>Mozilla Firefox</name> <shortname>firefox</shortname> <description>Leading Open Source internet browser.</description> <version>3.6.3-1</version> <license name="Firefox EULA">http://www.mozilla.com/en-US/legal/eula/firefox-en.html</license> <ms-license>False</ms-license> <vendor>Mozilla Foundation</vendor> <homepage>http://www.mozilla.org/firefox</homepage> <icon>resources/firefox.png</icon> <download>http://download.mozilla.org/?product=firefox-3.6.3&amp;os=win&amp;lang=en-GB</download> <crack required="0"/> <install>scripts/install.sh</install> <postinstall name="Clean Up"></postinstall> <run>C:\\Program Files\\Mozilla Firefox\\firefox.exe</run> <uninstall>c:\\Program Files\\Mozilla Firefox\\uninstall\\helper.exe /S</uninstall> <requires name="autohotkey" /> </ApplicationPack>
[ ">>> from lxml import etree\n>>> treetop = etree.fromstring(anxmlstring)\n\nconverts the xml in the string to a Python data structure, and so does\n>>> othertree = etree.parse(somexmlurl)\n\nwhere somexmlurl is the path to a local XML file or the URL of an XML file on the web.\nThe Python data structure these functions provide (known as an \"element tree\", whence the etree module name) is well documented here -- all the classes, functions, methods, etc, that the Python data structure in question supports. It closely matches one supported in the Python standard library, by the way.\nIf you want some different Python data structure, you'll have to walk through the Python data structure which lxml returns, as above mentioned, and build your different data structure yourself based on the information thus collected; lxml can't specifically help you, except by offering several helpers for finding information in the parsed structure it returns, so that collecting said info is a flexible, easy task (again, see the documentation URL above).\n", "It's not entirely clear what kind of data structure you're looking for, but here's a link to a code sample to convert XML to python dictionary of lists via lxml.etree.\n" ]
[ 5, 0 ]
[]
[]
[ "data_structures", "lxml", "python", "xml" ]
stackoverflow_0002747712_data_structures_lxml_python_xml.txt
Q: Solution for distributing MANY simple network tasks? I would like to create some sort of a distributed setup for running a ton of small/simple REST web queries in a production environment. For each 5-10 related queries which are executed from a node, I will generate a very small amount of derived data, which will need to be stored in a standard relational database (such as PostgreSQL). What platforms are built for this type of problem set? The nature, data sizes, and quantities seem to contradict the mindset of Hadoop. There are also more grid based architectures such as Condor and Sun Grid Engine, which I have seen mentioned. I'm not sure if these platforms have any recovery from errors though (checking if a job succeeds). What I would really like is a FIFO type queue that I could add jobs to, with the end result of my database getting updated. Any suggestions on the best tool for the job? A: Have you looked at Celery?
Solution for distributing MANY simple network tasks?
I would like to create some sort of a distributed setup for running a ton of small/simple REST web queries in a production environment. For each 5-10 related queries which are executed from a node, I will generate a very small amount of derived data, which will need to be stored in a standard relational database (such as PostgreSQL). What platforms are built for this type of problem set? The nature, data sizes, and quantities seem to contradict the mindset of Hadoop. There are also more grid based architectures such as Condor and Sun Grid Engine, which I have seen mentioned. I'm not sure if these platforms have any recovery from errors though (checking if a job succeeds). What I would really like is a FIFO type queue that I could add jobs to, with the end result of my database getting updated. Any suggestions on the best tool for the job?
[ "Have you looked at Celery?\n" ]
[ 1 ]
[]
[]
[ "cluster_analysis", "grid", "open_source", "python" ]
stackoverflow_0002749078_cluster_analysis_grid_open_source_python.txt
Q: Equivalent of PHP "echo something; exit();" with Python/Django? Sometimes the best way to debug something is to print some stuff to the page, and exit(), how can I do this in a Python/Django site? e.g. in PHP: echo $var; exit(); Thanks A: Put this in your view function: from django.http import HttpResponse return HttpResponse(str(var)) A: I just wanted to give an alternative answer: Simply use print statements and serve your django site with python manage.py runserver In this case the print statements show up in your shell, and your site continues functioning as it would normally. A: If you are using mod_wsgi you can say: print var raise SystemExit The SystemExit exception will not actually cause the whole process to exit as it would normally, but only cause that request to exit, presuming that no higher code catches it and ignores. Ensure you are using mod_wsgi 3.X. If using older mod_wsgi, you would need to instead say: import sys print >> sys.stderr raise SystemExit Other WSGI servers may also treat SystemExit in a request the same way, say you would need to experiment as to what happens if using other hosting solution. For other information about debugging WSGI applications read: http://code.google.com/p/modwsgi/wiki/DebuggingTechniques
Equivalent of PHP "echo something; exit();" with Python/Django?
Sometimes the best way to debug something is to print some stuff to the page, and exit(), how can I do this in a Python/Django site? e.g. in PHP: echo $var; exit(); Thanks
[ "Put this in your view function:\nfrom django.http import HttpResponse\nreturn HttpResponse(str(var))\n\n", "I just wanted to give an alternative answer: Simply use print statements and serve your django site with python manage.py runserver\nIn this case the print statements show up in your shell, and your site continues functioning as it would normally.\n", "If you are using mod_wsgi you can say:\nprint var\nraise SystemExit\n\nThe SystemExit exception will not actually cause the whole process to exit as it would normally, but only cause that request to exit, presuming that no higher code catches it and ignores.\nEnsure you are using mod_wsgi 3.X. If using older mod_wsgi, you would need to instead say:\nimport sys\nprint >> sys.stderr\nraise SystemExit\n\nOther WSGI servers may also treat SystemExit in a request the same way, say you would need to experiment as to what happens if using other hosting solution.\nFor other information about debugging WSGI applications read:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques\n" ]
[ 17, 14, 3 ]
[ "If you don't want to crash mod_wsgi on print's do this in your wsgi file\nsys.stdout = sys.stderr\n\nprints will then be sent to the error_log\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0002747554_django_python.txt
Q: How can I reorder an mbox file chronologically? I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such? The emails currently exist in the format: From x@blah.com Fri Aug 12 09:34:09 2005 Message-ID: <42FBEE81.9090701@blah.com> Date: Fri, 12 Aug 2005 09:34:09 +0900 From: me <x@blah.com> User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716) X-Accept-Language: en-us, en MIME-Version: 1.0 To: someone <someone@hotmail.com> Subject: Re: (no subject) References: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl> In-Reply-To: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Status: RO X-Status: X-Keywords: X-UID: 371 X-Evolution-Source: imap://x+blah.com@blah.com/ X-Evolution: 00000002-0010 Hey the actual content of the email someone wrote: > lines of quotedtext I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such. A: This is how you could do it in python: #!/usr/bin/python2.5 from email.utils import parsedate import mailbox def extract_date(email): date = email.get('Date') return parsedate(date) the_mailbox = mailbox.mbox('/path/to/mbox') sorted_mails = sorted(the_mailbox, key=extract_date) the_mailbox.update(enumerate(sorted_mails)) the_mailbox.flush() A: Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon. There are a bug: messages shall prefix with 'from' line in format: From - Tue Apr 27 19:42:22 2010 but ImportExportTools prefix with such 'from' line: From - Sat May 01 2010 15:07:31 GMT+0400 (Russian Daylight Time) So there are two errors: sequence 'time year' broken into 'year time' extra trash with GMT info along with time zone name Since Python's mailbox.py/UnixMailbox has hardcoded regexp for 'from' line matching, some of messages can't parsed. I wrote the error message to the author, but there are many mistakenly imported messages :(.
How can I reorder an mbox file chronologically?
I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such? The emails currently exist in the format: From x@blah.com Fri Aug 12 09:34:09 2005 Message-ID: <42FBEE81.9090701@blah.com> Date: Fri, 12 Aug 2005 09:34:09 +0900 From: me <x@blah.com> User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716) X-Accept-Language: en-us, en MIME-Version: 1.0 To: someone <someone@hotmail.com> Subject: Re: (no subject) References: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl> In-Reply-To: <BAY101-F9353854000A4758A7E2CCA9BD0@phx.gbl> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Status: RO X-Status: X-Keywords: X-UID: 371 X-Evolution-Source: imap://x+blah.com@blah.com/ X-Evolution: 00000002-0010 Hey the actual content of the email someone wrote: > lines of quotedtext I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such.
[ "This is how you could do it in python:\n#!/usr/bin/python2.5\nfrom email.utils import parsedate\nimport mailbox\n\ndef extract_date(email):\n date = email.get('Date')\n return parsedate(date)\n\nthe_mailbox = mailbox.mbox('/path/to/mbox')\nsorted_mails = sorted(the_mailbox, key=extract_date)\nthe_mailbox.update(enumerate(sorted_mails))\nthe_mailbox.flush()\n\n", "Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon.\nThere are a bug: messages shall prefix with 'from' line in format:\nFrom - Tue Apr 27 19:42:22 2010\n\nbut ImportExportTools prefix with such 'from' line:\nFrom - Sat May 01 2010 15:07:31 GMT+0400 (Russian Daylight Time)\n\nSo there are two errors:\n\nsequence 'time year' broken into\n'year time' \nextra trash with GMT\ninfo along with time zone name\n\nSince Python's mailbox.py/UnixMailbox has hardcoded regexp for 'from' line matching, some of messages can't parsed.\nI wrote the error message to the author, but there are many mistakenly imported messages :(.\n" ]
[ 14, 2 ]
[ "What's the point in rewriting the mbox whereas you can reorder the mails in memory when loading up the mailbox? Which time is the one you want to order on? Receive date? Sent date? Anyway, all the Ruby/Python/Perl modules for playing with mboxes can do that.\n" ]
[ -5 ]
[ "email", "mbox", "python", "sorting" ]
stackoverflow_0000368003_email_mbox_python_sorting.txt
Q: Why are closures broken within exec? In Python 2.6, >>> exec "print (lambda: a)()" in dict(a=2), {} 2 >>> exec "print (lambda: a)()" in globals(), {'a': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <lambda> NameError: global name 'a' is not defined >>> exec "print (lambda: a).__closure__" in globals(), {'a': 2} None I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on? A: When you pass a string to exec or eval, it compiles that string to a code object before considering globals or locals. So when you say: eval('lambda: a', ...) it means: eval(compile('lambda: a', '<stdin>', 'eval'), ...) There's no way for compile to know that a is a freevar, so it compiles it to a global reference: >>> c= compile('lambda: a', '<stdin>', 'eval') >>> c.co_consts[0] <code object <lambda> at 0x7f36577330a8, file "<stdin>", line 1> >>> dis.dis(c.co_consts[0]) 1 0 LOAD_GLOBAL 0 (a) 3 RETURN_VALUE Therefore to make it work you have to put a in the globals and not the locals. Yeah, it's a bit dodgy. But then that's exec and eval for you I suppose... they're not supposed to be nice.
Why are closures broken within exec?
In Python 2.6, >>> exec "print (lambda: a)()" in dict(a=2), {} 2 >>> exec "print (lambda: a)()" in globals(), {'a': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <lambda> NameError: global name 'a' is not defined >>> exec "print (lambda: a).__closure__" in globals(), {'a': 2} None I expected it to print 2 twice, and then print a tuple with a single cell. It is the same situation in 3.1. What's going on?
[ "When you pass a string to exec or eval, it compiles that string to a code object before considering globals or locals. So when you say:\neval('lambda: a', ...)\n\nit means:\neval(compile('lambda: a', '<stdin>', 'eval'), ...)\n\nThere's no way for compile to know that a is a freevar, so it compiles it to a global reference:\n>>> c= compile('lambda: a', '<stdin>', 'eval')\n>>> c.co_consts[0]\n<code object <lambda> at 0x7f36577330a8, file \"<stdin>\", line 1>\n>>> dis.dis(c.co_consts[0])\n 1 0 LOAD_GLOBAL 0 (a)\n 3 RETURN_VALUE \n\nTherefore to make it work you have to put a in the globals and not the locals.\nYeah, it's a bit dodgy. But then that's exec and eval for you I suppose... they're not supposed to be nice.\n" ]
[ 26 ]
[]
[]
[ "closures", "exec", "python" ]
stackoverflow_0002749655_closures_exec_python.txt
Q: cannot output a json encoded dict containing accents (noob inside) here is a fairly simple example wich is driving me nuts since a couple of days. Considering the following script: # -*- coding: utf-8 -* from json import dumps as json_dumps machaine = u"une personne émérite" print(machaine) output = {} output[1] = machaine jsonoutput = json_dumps(output) print(jsonoutput) The result of this from cli: une personne émérite {"1": "une personne \u00e9m\u00e9rite"} I don't understand why their such a difference between the two strings. i have been trying all sorts of encode, decode etc but i can't seem to be able to find the right way to do it. Does anybody has an idea ? Thanks in advance. Matthieu A: The encoding is correct. Load it back in and print it, and you'll see the correct output: >>> import json >>> jsoninput = json.loads(jsonoutput) >>> print jsoninput {u'1': u'une personne \xe9m\xe9rite'} >>> print jsoninput['1'] une personne émérite A: To clarify Marcelo Cantos's answer: json.dumps() returns a JSON-encoding, which is an ASCII string, starting with the character '{', and containing backslashes, quotes, etc. You have to decode it (e.g. with json.loads() to get back the actual dict with data. # -*- coding: utf-8 -* import json output = {1: u"une personne émérite"} print output[1] json_encoded = json.dumps(output) print "Encoded: %s" % repr(json_encoded) input = json.loads(json_encoded) print input['1'] outputs: une personne émérite Encoded: '{"1": "une personne \\u00e9m\\u00e9rite"}' une personne émérite
cannot output a json encoded dict containing accents (noob inside)
here is a fairly simple example wich is driving me nuts since a couple of days. Considering the following script: # -*- coding: utf-8 -* from json import dumps as json_dumps machaine = u"une personne émérite" print(machaine) output = {} output[1] = machaine jsonoutput = json_dumps(output) print(jsonoutput) The result of this from cli: une personne émérite {"1": "une personne \u00e9m\u00e9rite"} I don't understand why their such a difference between the two strings. i have been trying all sorts of encode, decode etc but i can't seem to be able to find the right way to do it. Does anybody has an idea ? Thanks in advance. Matthieu
[ "The encoding is correct. Load it back in and print it, and you'll see the correct output:\n>>> import json\n>>> jsoninput = json.loads(jsonoutput)\n>>> print jsoninput\n{u'1': u'une personne \\xe9m\\xe9rite'}\n>>> print jsoninput['1']\nune personne émérite\n\n", "To clarify Marcelo Cantos's answer: json.dumps() returns a JSON-encoding, which is an ASCII string, starting with the character '{', and containing backslashes, quotes, etc. You have to decode it (e.g. with json.loads() to get back the actual dict with data.\n# -*- coding: utf-8 -*\nimport json\n\noutput = {1: u\"une personne émérite\"}\nprint output[1]\n\njson_encoded = json.dumps(output)\nprint \"Encoded: %s\" % repr(json_encoded)\n\ninput = json.loads(json_encoded)\nprint input['1']\n\noutputs:\nune personne émérite\nEncoded: '{\"1\": \"une personne \\\\u00e9m\\\\u00e9rite\"}'\nune personne émérite\n\n" ]
[ 3, 2 ]
[]
[]
[ "json", "python", "utf_8" ]
stackoverflow_0002750156_json_python_utf_8.txt
Q: pythonpath issue? "python2.5: can't open file 'dev_appserver.py': [Errno 2] No such file or directory" I added this line to my .bashrc (Ubuntu 9.10): export PYTHONPATH=/opt/google_appengine/ And then I ran the dev_appserver through python2.5 on Ubuntu like this: $ python2.5 dev_appserver.py guestbook/ python2.5: can't open file 'dev_appserver.py': [Errno 2] No such file or directory As you can see, it can't find dev_appserver.py even though it's in my /opt/google_appengine/ directory. Just to make sure it's not a permissions issue I did this: sudo chmod a+rwx dev_appserver.py To check whether it's been added to the system path for python2.5 I did this: $ python2.5 Python 2.5.5 (r255:77872, Apr 29 2010, 23:59:20) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for line in sys.path: print line ... /usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg /opt/google_appengine/demos /opt/google_appengine /usr/local/lib/python25.zip ... The directory shows up in this list so I don't understand why it can't be found when I type: $ python2.5 dev_appserver.py guestbook/ I'm new to Python so I would appreciate any help. Thanks. A: Python doesn't observe PYTHONPATH when looking for a script you name on the command line. You either need to supply the complete path to dev_appserver.py, or modify the first line of dev_appserver.py (and other tools) to start with "#!/usr/bin/env python2.5". A: When doing $ python2.5 dev_appserver.py guestbook/ what you are passing to the executable python2.5 is CURRENT_PATH/dev_appserver.py. You have to execute using $ python /opt/google_appengine/dev_appserver.py guestbook/ or $ dev_appserver.py guestbook/ if dev_appserver.py has a shebang for Python, that is, as Nick Johnson points out, #!/usr/bin/env python2.5 or #!/usr/bin/env python. Unless you have a very good reason, don't over specify the python version, use the generic python command, that is a symlink to the latest version.
pythonpath issue? "python2.5: can't open file 'dev_appserver.py': [Errno 2] No such file or directory"
I added this line to my .bashrc (Ubuntu 9.10): export PYTHONPATH=/opt/google_appengine/ And then I ran the dev_appserver through python2.5 on Ubuntu like this: $ python2.5 dev_appserver.py guestbook/ python2.5: can't open file 'dev_appserver.py': [Errno 2] No such file or directory As you can see, it can't find dev_appserver.py even though it's in my /opt/google_appengine/ directory. Just to make sure it's not a permissions issue I did this: sudo chmod a+rwx dev_appserver.py To check whether it's been added to the system path for python2.5 I did this: $ python2.5 Python 2.5.5 (r255:77872, Apr 29 2010, 23:59:20) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for line in sys.path: print line ... /usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg /opt/google_appengine/demos /opt/google_appengine /usr/local/lib/python25.zip ... The directory shows up in this list so I don't understand why it can't be found when I type: $ python2.5 dev_appserver.py guestbook/ I'm new to Python so I would appreciate any help. Thanks.
[ "Python doesn't observe PYTHONPATH when looking for a script you name on the command line. You either need to supply the complete path to dev_appserver.py, or modify the first line of dev_appserver.py (and other tools) to start with \"#!/usr/bin/env python2.5\".\n", "When doing\n$ python2.5 dev_appserver.py guestbook/\n\nwhat you are passing to the executable python2.5 is CURRENT_PATH/dev_appserver.py.\nYou have to execute using\n$ python /opt/google_appengine/dev_appserver.py guestbook/\n\nor \n$ dev_appserver.py guestbook/\n\nif dev_appserver.py has a shebang for Python, that is, as Nick Johnson points out, #!/usr/bin/env python2.5 or #!/usr/bin/env python.\nUnless you have a very good reason, don't over specify the python version, use the generic python command, that is a symlink to the latest version.\n" ]
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python", "pythonpath", "ubuntu_9.10" ]
stackoverflow_0002750496_google_app_engine_python_pythonpath_ubuntu_9.10.txt
Q: Representing geographical points/polygons in Python/Django I'm building a website in Django, and I want one of my datatypes to be a geographical polygon. I want to mark points on a map (say, in Google Maps) and then store the resulting polygon in the database. Is there any way to do it that will save me the work of typing all the longitudes and latitudes manually? I guess I'm looking both for a geographical library for Python, and for a special website that will let me mark points on the map and save them in a standard format. Thanks! A: You're lucky, Django has maybe the best GIS support of all web frameworks: GeoDjango
Representing geographical points/polygons in Python/Django
I'm building a website in Django, and I want one of my datatypes to be a geographical polygon. I want to mark points on a map (say, in Google Maps) and then store the resulting polygon in the database. Is there any way to do it that will save me the work of typing all the longitudes and latitudes manually? I guess I'm looking both for a geographical library for Python, and for a special website that will let me mark points on the map and save them in a standard format. Thanks!
[ "You're lucky, Django has maybe the best GIS support of all web frameworks:\nGeoDjango\n" ]
[ 4 ]
[]
[]
[ "django", "gis", "google_maps", "mapping", "python" ]
stackoverflow_0002751189_django_gis_google_maps_mapping_python.txt
Q: DSA module in Python Does anyone know of a pure DSA module in Python for signing messages? A: Python Cryptography Toolkit has this module Chilkat (this may be a pure module check with chilkat - commercially licensed ) A: If OpenSSL has the functionality you are looking for, try pyOpenSSL. A: Unfortunately, you might have to use a wrapper to some non-Python implementation, like pyOpenSSL. I'm not aware of any pure Python crypto library that is secure. In particular, pycrypto is a piece of crap. E.g., if you use DSA as proposed here by the author then the attack described in the paper "The Insecurity of the Digital Signature Algorithm with partially known nonces" by Nguyen and Shparlinski can be used to find the secret key very very fast. Note, that this paper has been presented in 2002, but pycrypto is still susceptible to it. Python is a really nice an friendly language for prototyping, but when it comes to defending against adversaries, it is a little too friendly.
DSA module in Python
Does anyone know of a pure DSA module in Python for signing messages?
[ "Python Cryptography Toolkit has this module\nChilkat (this may be a pure module check with chilkat - commercially licensed )\n", "If OpenSSL has the functionality you are looking for, try pyOpenSSL.\n", "Unfortunately, you might have to use a wrapper to some non-Python implementation, like pyOpenSSL. I'm not aware of any pure Python crypto library that is secure.\nIn particular, pycrypto is a piece of crap. E.g., if you use DSA as proposed\nhere by the author then the attack described in the paper \"The Insecurity of the Digital Signature Algorithm with partially known nonces\" by Nguyen and Shparlinski can be used to find the secret key very very fast.\nNote, that this paper has been presented in 2002, but pycrypto is still susceptible to it.\nPython is a really nice an friendly language for prototyping, but when it comes to defending against adversaries, it is a little too friendly.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "cryptography", "python" ]
stackoverflow_0002729468_cryptography_python.txt
Q: How do I check for Existence of a Record in GAE I am trying to create a simple view in Django & GAE, which will check if the user has a profile entity and prints a different message for each case. I have the program below, but somehow GAE always seem to return a object. My program is below import datetime from django.http import HttpResponse, HttpResponseRedirect from google.appengine.api import users from google.appengine.ext import db from models import Profile import logging #from accounts.views import profile # Create your views here. def login_view(request): user = users.get_current_user() profile = db.GqlQuery("SELECT * FROM Profile WHERE account = :1", users.get_current_user()) logging.info(profile) logging.info(user) if profile: return HttpResponse("Congratulations Your profile is already created.") else: return HttpResponse("Sorry Your profile is NOT created.") My model object is Profile defined as follows: class Profile(db.Model): first_name = db.StringProperty() last_name = db.StringProperty() gender = db.StringProperty(choices=set(["Male", "Female"])) account = db.UserProperty(required = True) friends = db.ListProperty(item_type=users.User) last_login = db.DateTimeProperty(required=True) Thanks for the help. A: I am afraid you forgot to execute the query. Try the get() method. It returns the first result, or None if the query returned no results. profile = db.GqlQuery("SELECT * FROM Profile WHERE account = :1", users.get_current_user()).get()
How do I check for Existence of a Record in GAE
I am trying to create a simple view in Django & GAE, which will check if the user has a profile entity and prints a different message for each case. I have the program below, but somehow GAE always seem to return a object. My program is below import datetime from django.http import HttpResponse, HttpResponseRedirect from google.appengine.api import users from google.appengine.ext import db from models import Profile import logging #from accounts.views import profile # Create your views here. def login_view(request): user = users.get_current_user() profile = db.GqlQuery("SELECT * FROM Profile WHERE account = :1", users.get_current_user()) logging.info(profile) logging.info(user) if profile: return HttpResponse("Congratulations Your profile is already created.") else: return HttpResponse("Sorry Your profile is NOT created.") My model object is Profile defined as follows: class Profile(db.Model): first_name = db.StringProperty() last_name = db.StringProperty() gender = db.StringProperty(choices=set(["Male", "Female"])) account = db.UserProperty(required = True) friends = db.ListProperty(item_type=users.User) last_login = db.DateTimeProperty(required=True) Thanks for the help.
[ "I am afraid you forgot to execute the query. Try the get() method. It returns the first result, or None if the query returned no results.\nprofile = db.GqlQuery(\"SELECT * FROM Profile WHERE account = :1\",\n users.get_current_user()).get()\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "google_app_engine", "python" ]
stackoverflow_0002751345_django_django_models_google_app_engine_python.txt
Q: Is www.example.com/post/21/edit a RESTful URI? I think I know the answer, but have another question I'm almost afraid to post this question, there has to be an obvious answer I've overlooked, but here I go: Context: I am creating a blog for educational purposes (want to learn python and web.py). I've decided that my blog have posts, so I've created a Post class. I've also decided that posts can be created, read, updated, or deleted (so CRUD). So in my Post class, I've created methods that respond to POST, GET, PUT, and DELETE HTTP methods). So far so good. The current problem I'm having is a conceptual one, I know that sending a PUT HTTP message (with an edited Post) to, e.g., /post/52 should update post with id 52 with the body contents of the HTTP message. What I do not know is how to conceptually correctly serve the (HTML) edit page. Will doing it like this: /post/52/edit violate the idea of URI, as 'edit' is not a resource, but an action? On the other side though, could it be considered a resource since all that URI will respond to is a GET method, that will only return an HTML page? So my ultimate question is this: How do I serve an HTML page intended for user editing in a RESTful manner? A: Another RESTful approach is to use the query string for modifiers: /post/52?edit=1 Also, don't get too hung up on the purity of the REST model. If your app doesn't fit neatly into the model, break the rules. A: There is no such thing as a RESTful URI. It is false concept as URIs should be completely opaque to the client. If it helps you to properly implement the HTTP uniform interface by avoiding verbs in your URIs then that's great, but don't feel constrained by what your URI looks like. It is very limiting to think of resource modeling as type of data modelling. A RESTful system usually needs to do way more than just CRUD operations, so you need to be creative about what resources you make available in your system. If you create a URL and dereferencing it returns a 200 status code, then that URL refers to a resource. If you create another URL and it also returns a 200, then that is a difference resource. That means: http://example.org/customer/10.xml http://example.org/customer/10.json http://example.org/customer/10?format=xml http://example.org/customer/10?format=json are 4 different resources, and http://example.org/customers http://example.org/customers?closed=true http://example.org/customers?page=2&pagelength=20 are also different resources. Therefore to answer your question, if you do GET /post/52/edit and it returns a 200 status code and a representation, then it must be a resource. A: Instead of calling it /post/52/edit, what if you called it /post/52/editor? Now it is a resource. Dilemma averted. A: I don't think /object/id/action is part of the REST specification. Is your editor going to be a generic thing for all objects ? Then maybe your URL should look like /editor/object/id The action is an HTTP Verb ( GET,PUT,DELETE,POST ) and is supposed to be a part of the HTTP request and not part of the URL. For a better summary, check out this Wikipedia article on RESTful_web_services.
Is www.example.com/post/21/edit a RESTful URI? I think I know the answer, but have another question
I'm almost afraid to post this question, there has to be an obvious answer I've overlooked, but here I go: Context: I am creating a blog for educational purposes (want to learn python and web.py). I've decided that my blog have posts, so I've created a Post class. I've also decided that posts can be created, read, updated, or deleted (so CRUD). So in my Post class, I've created methods that respond to POST, GET, PUT, and DELETE HTTP methods). So far so good. The current problem I'm having is a conceptual one, I know that sending a PUT HTTP message (with an edited Post) to, e.g., /post/52 should update post with id 52 with the body contents of the HTTP message. What I do not know is how to conceptually correctly serve the (HTML) edit page. Will doing it like this: /post/52/edit violate the idea of URI, as 'edit' is not a resource, but an action? On the other side though, could it be considered a resource since all that URI will respond to is a GET method, that will only return an HTML page? So my ultimate question is this: How do I serve an HTML page intended for user editing in a RESTful manner?
[ "Another RESTful approach is to use the query string for modifiers: /post/52?edit=1\nAlso, don't get too hung up on the purity of the REST model. If your app doesn't fit neatly into the model, break the rules. \n", "There is no such thing as a RESTful URI. It is false concept as URIs should be completely opaque to the client. \nIf it helps you to properly implement the HTTP uniform interface by avoiding verbs in your URIs then that's great, but don't feel constrained by what your URI looks like. It is very limiting to think of resource modeling as type of data modelling. A RESTful system usually needs to do way more than just CRUD operations, so you need to be creative about what resources you make available in your system.\nIf you create a URL and dereferencing it returns a 200 status code, then that URL refers to a resource. If you create another URL and it also returns a 200, then that is a difference resource.\nThat means:\nhttp://example.org/customer/10.xml\nhttp://example.org/customer/10.json\nhttp://example.org/customer/10?format=xml\nhttp://example.org/customer/10?format=json\n\nare 4 different resources, and\nhttp://example.org/customers\nhttp://example.org/customers?closed=true\nhttp://example.org/customers?page=2&pagelength=20\n\nare also different resources.\nTherefore to answer your question, if you do\nGET /post/52/edit \n\nand it returns a 200 status code and a representation, then it must be a resource.\n", "Instead of calling it /post/52/edit, what if you called it /post/52/editor?\nNow it is a resource. Dilemma averted.\n", "I don't think /object/id/action is part of the REST specification.\nIs your editor going to be a generic thing for all objects ? Then maybe your URL should look like \n/editor/object/id\n\nThe action is an HTTP Verb ( GET,PUT,DELETE,POST ) and is supposed to be a part of the HTTP request and not part of the URL. For a better summary, check out this Wikipedia article on RESTful_web_services.\n" ]
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "rest", "web.py" ]
stackoverflow_0002750341_python_rest_web.py.txt
Q: Sending Data as Instances using Python Sockets I'm working on the networking part of a 2 player game (similar to tetris), and I'm trying to pass the game grid from client to server and vice versa. However, when I tried using send(grid) I get a TypeError: send() argument 1 must be string or read-only buffer, not instance. Is there anyway to circumvent this, or do I have to convert my grid instance into a string and then interpret it from the other side? Thanks in advance! A: Unless you're in total control over both the client and server software, you should hesitate to use pickle to transmit data back and forth. Pickle is great if you're sure the data you're unpickling is trustworthy, but if it might have been tampered with, it is insecure. See Why Python Pickle is Insecure, or the security cautionary suggestions in the pickle module documentation. JSON is a good choice for formatting of data to send back and forth; XML is okay, YAML is pretty good. A simple messaging format might be to send the size of the message data, a delimiter (CRLF or \r\n is common) and then the message data. If you use JSON, you'll have to either stick with the objects the json module knows how to encode/decode, or write JSONEncoder and JSONDecoder subclasses to deal with the types you're interested in. Below is a little JSON proof of concept you can run (not sure if it would work on Windows or not). Just run it in each of two terminals, type in one and it should show up in the other. import socket import select import sys import json CRLF = '\r\n' class MalformedMessage(Exception): pass class ConnectionClosed(Exception): pass def read_exactly(sock, buflen): data = '' while len(data) != buflen: data += sock.recv(buflen - len(data)) return data def peek(sock, buflen): data = sock.recv(buflen, socket.MSG_PEEK) return data def socket_send(sock, obj): data = json.dumps(obj) size = len(data) sock.sendall('%i%s%s' % (size, CRLF, data)) def socket_recv(sock): peekdata = peek(sock, 1024) if peekdata == '': raise ConnectionClosed sizepos = peekdata.find(CRLF) if sizepos == -1: raise MalformedMessage('Did not find CRLF in message %r' % peekdata) sizedata = read_exactly(sock, sizepos) read_exactly(sock, len(CRLF)) try: size = int(sizedata) except ValueError: raise MalformedMessage( 'size data %r could not be converted to an int' % sizedata) data = read_exactly(sock, size) return json.loads(data) if __name__ == '__main__': netloc = ('', 7777) try: servsock = socket.socket() servsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) servsock.bind(netloc) servsock.listen(5) sock, _ = servsock.accept() except socket.error: sock = socket.socket() sock.connect(netloc) try: while True: r_ok, _, _ = select.select([sys.stdin, sock], [], []) for fd in r_ok: if fd == sys.stdin: obj = eval(fd.readline().strip()) socket_send(sock, obj) elif fd == sock: obj = socket_recv(sock) print repr(obj) except (KeyboardInterrupt, ConnectionClosed): pass finally: print '\nexiting...' A: Look into data serialisation: pickle. It would do data serialisation (read convers into a string) on the sender side, and then de-serialisation (ie, converts back into the data structure) on the receiver side.
Sending Data as Instances using Python Sockets
I'm working on the networking part of a 2 player game (similar to tetris), and I'm trying to pass the game grid from client to server and vice versa. However, when I tried using send(grid) I get a TypeError: send() argument 1 must be string or read-only buffer, not instance. Is there anyway to circumvent this, or do I have to convert my grid instance into a string and then interpret it from the other side? Thanks in advance!
[ "Unless you're in total control over both the client and server software, you should hesitate to use pickle to transmit data back and forth. Pickle is great if you're sure the data you're unpickling is trustworthy, but if it might have been tampered with, it is insecure. See Why Python Pickle is Insecure, or the security cautionary suggestions in the pickle module documentation.\nJSON is a good choice for formatting of data to send back and forth; XML is okay, YAML is pretty good. A simple messaging format might be to send the size of the message data, a delimiter (CRLF or \\r\\n is common) and then the message data.\nIf you use JSON, you'll have to either stick with the objects the json module knows how to encode/decode, or write JSONEncoder and JSONDecoder subclasses to deal with the types you're interested in.\nBelow is a little JSON proof of concept you can run (not sure if it would work on Windows or not). Just run it in each of two terminals, type in one and it should show up in the other.\nimport socket\nimport select\nimport sys\nimport json\n\nCRLF = '\\r\\n'\nclass MalformedMessage(Exception): pass\nclass ConnectionClosed(Exception): pass\n\ndef read_exactly(sock, buflen):\n data = ''\n while len(data) != buflen:\n data += sock.recv(buflen - len(data))\n return data\n\ndef peek(sock, buflen):\n data = sock.recv(buflen, socket.MSG_PEEK)\n return data\n\ndef socket_send(sock, obj):\n data = json.dumps(obj)\n size = len(data)\n sock.sendall('%i%s%s' % (size, CRLF, data))\n\ndef socket_recv(sock):\n peekdata = peek(sock, 1024)\n if peekdata == '':\n raise ConnectionClosed\n sizepos = peekdata.find(CRLF)\n if sizepos == -1:\n raise MalformedMessage('Did not find CRLF in message %r' % peekdata)\n sizedata = read_exactly(sock, sizepos)\n read_exactly(sock, len(CRLF))\n try:\n size = int(sizedata)\n except ValueError:\n raise MalformedMessage(\n 'size data %r could not be converted to an int' % sizedata)\n data = read_exactly(sock, size)\n return json.loads(data)\n\nif __name__ == '__main__':\n netloc = ('', 7777)\n try:\n servsock = socket.socket()\n servsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n servsock.bind(netloc)\n servsock.listen(5)\n sock, _ = servsock.accept()\n except socket.error:\n sock = socket.socket()\n sock.connect(netloc)\n\n try:\n while True:\n r_ok, _, _ = select.select([sys.stdin, sock], [], [])\n for fd in r_ok:\n if fd == sys.stdin:\n obj = eval(fd.readline().strip())\n socket_send(sock, obj)\n elif fd == sock:\n obj = socket_recv(sock)\n print repr(obj)\n except (KeyboardInterrupt, ConnectionClosed):\n pass\n finally:\n print '\\nexiting...'\n\n", "Look into data serialisation: pickle. It would do data serialisation (read convers into a string) on the sender side, and then de-serialisation (ie, converts back into the data structure) on the receiver side.\n" ]
[ 6, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002751098_python_sockets.txt
Q: Figure out if element is present in multi-dimensional array in python I am parsing a log containing nicknames and hostnames. I want to end up with an array that contains the hostname and the latest used nickname. I have the following code, which only creates a list over the hostnames: hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames: # Hostname is already present. pass else: # Hostname is not present hostnames.append(host) print hostnames # ['foo@google.com', 'bar@hotmail.com', 'hi@to.you'] I thought it would be nice to end up with something along the lines of the following: # [['foo@google.com', 'John'], ['bar@hotmail.com', 'Mary'], ['hi@to.you', 'Joe']] My problem is finding out if the hostname is present in such a list hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames[0]: # This doesn't work. # Hostname is already present. # Somehow check if the nick stored together # with the hostname is the latest one else: # Hostname is not present hostnames.append([host, nick]) Are there any easy fix to this, or should I try a different approach? I could always have an array with objects or structs (if there is such a thing in python), but I would prefer a solution to my array problem. A: Use a dictionary instead of a list. Use the hostname as the key and the username as the value. A: Just use a dictionary instead. names = {} while(parsing): nick = nick_on_current_line host = host_on_current_line names[host] = nick A: if host in zip(*hostnames)[0]: or if host in (x[0] for x in hostnames):
Figure out if element is present in multi-dimensional array in python
I am parsing a log containing nicknames and hostnames. I want to end up with an array that contains the hostname and the latest used nickname. I have the following code, which only creates a list over the hostnames: hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames: # Hostname is already present. pass else: # Hostname is not present hostnames.append(host) print hostnames # ['foo@google.com', 'bar@hotmail.com', 'hi@to.you'] I thought it would be nice to end up with something along the lines of the following: # [['foo@google.com', 'John'], ['bar@hotmail.com', 'Mary'], ['hi@to.you', 'Joe']] My problem is finding out if the hostname is present in such a list hostnames = [] # while(parsing): # nick = nick_on_current_line # host = host_on_current_line if host in hostnames[0]: # This doesn't work. # Hostname is already present. # Somehow check if the nick stored together # with the hostname is the latest one else: # Hostname is not present hostnames.append([host, nick]) Are there any easy fix to this, or should I try a different approach? I could always have an array with objects or structs (if there is such a thing in python), but I would prefer a solution to my array problem.
[ "Use a dictionary instead of a list. Use the hostname as the key and the username as the value.\n", "Just use a dictionary instead.\nnames = {}\n\nwhile(parsing):\n nick = nick_on_current_line\n host = host_on_current_line \n\n names[host] = nick\n\n", "if host in zip(*hostnames)[0]:\n\nor\nif host in (x[0] for x in hostnames):\n\n" ]
[ 4, 3, 2 ]
[]
[]
[ "arrays", "multidimensional_array", "python" ]
stackoverflow_0002751471_arrays_multidimensional_array_python.txt
Q: In Python, is there an easy way to edit xml in place? Suppose I want to edit a node in xml and edit one of its attributes. I want to be able to do a simple file diff to just see one row changed. Dumping the xml using prettyprint changes the whole xml structure. A: Well then don't use prettyprint. In xml.dom.minidom for example, if you do doc = xml.dom.minidom.parse(inputfile) do_something_with(doc) outputfile.write(doc.toxml("utf-8").decode("utf-8")) all the structure/whitespace etc. will remain unchanged. A: Consider NOT using "a simple file diff". See this SO question.
In Python, is there an easy way to edit xml in place?
Suppose I want to edit a node in xml and edit one of its attributes. I want to be able to do a simple file diff to just see one row changed. Dumping the xml using prettyprint changes the whole xml structure.
[ "Well then don't use prettyprint.\nIn xml.dom.minidom for example, if you do\ndoc = xml.dom.minidom.parse(inputfile)\ndo_something_with(doc)\noutputfile.write(doc.toxml(\"utf-8\").decode(\"utf-8\"))\n\nall the structure/whitespace etc. will remain unchanged.\n", "Consider NOT using \"a simple file diff\". See this SO question.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002751451_python_xml.txt
Q: Make qwidget in new window in PyQt4 I'm trying to make a class that extends qwidget, that pops up a new window, I must be missing something fundamental, class NewQuery(QtGui.QWidget): def __init__(self, parent): QtGui.QMainWindow.__init__(self,parent) self.setWindowTitle('Add New Query') grid = QtGui.QGridLayout() label = QtGui.QLabel('blah') grid.addWidget(label,0,0) self.setLayout(grid) self.resize(300,200) when a new instance of this is made in main window's class, and show() called, the content is overlaid on the main window, how can I make it display in a new window? A: follow the advice that @ChristopheD gave you and try this instead from PyQt4 import QtGui class NewQuery(QtGui.QWidget): def __init__(self, parent=None): super(NewQuery, self).__init__(parent) self.setWindowTitle('Add New Query') grid = QtGui.QGridLayout() label = QtGui.QLabel('blah') grid.addWidget(label,0,0) self.setLayout(grid) self.resize(300,200) app = QtGui.QApplication([]) mainform = NewQuery() mainform.show() newchildform = NewQuery() newchildform.show() app.exec_() A: Your superclass initialiser is wrong, you probably meant: class NewQuery(QtGui.QWidget): def __init__(self, parent): QtGui.QWidget.__init__(self, parent) (a reason to use super): class NewQuery(QtGui.QWidget): def __init__(self, parent): super(NewQuery, self).__init__(parent) But maybe you want inherit from QtGui.QDialog instead (that could be appropriate - hard to tell with the current context). Also note that the indentation in your code example is wrong (a single space will work but 4 spaces or a single tab are considered nicer).
Make qwidget in new window in PyQt4
I'm trying to make a class that extends qwidget, that pops up a new window, I must be missing something fundamental, class NewQuery(QtGui.QWidget): def __init__(self, parent): QtGui.QMainWindow.__init__(self,parent) self.setWindowTitle('Add New Query') grid = QtGui.QGridLayout() label = QtGui.QLabel('blah') grid.addWidget(label,0,0) self.setLayout(grid) self.resize(300,200) when a new instance of this is made in main window's class, and show() called, the content is overlaid on the main window, how can I make it display in a new window?
[ "follow the advice that @ChristopheD gave you and try this instead\nfrom PyQt4 import QtGui\n\nclass NewQuery(QtGui.QWidget):\n def __init__(self, parent=None):\n super(NewQuery, self).__init__(parent)\n self.setWindowTitle('Add New Query')\n grid = QtGui.QGridLayout()\n label = QtGui.QLabel('blah')\n grid.addWidget(label,0,0)\n self.setLayout(grid)\n self.resize(300,200)\n\napp = QtGui.QApplication([])\nmainform = NewQuery()\nmainform.show()\nnewchildform = NewQuery()\nnewchildform.show()\napp.exec_()\n\n", "Your superclass initialiser is wrong, you probably meant:\nclass NewQuery(QtGui.QWidget):\n def __init__(self, parent):\n QtGui.QWidget.__init__(self, parent)\n\n(a reason to use super):\nclass NewQuery(QtGui.QWidget):\n def __init__(self, parent):\n super(NewQuery, self).__init__(parent)\n\nBut maybe you want inherit from QtGui.QDialog instead (that could be appropriate - hard to tell with the current context).\nAlso note that the indentation in your code example is wrong (a single space will work but 4 spaces or a single tab are considered nicer).\n" ]
[ 2, 1 ]
[]
[]
[ "pyqt4", "python", "qwidget" ]
stackoverflow_0002751691_pyqt4_python_qwidget.txt
Q: chatbot using twisted and wokkel I am writing a chatbot using Twisted and wokkel and everything seems to be working except that bot periodically logs off. To temporarily fix that I set presence to available on every connection initialized. Does anyone know how to prevent going offline? (I assume if i keep sending available presence every minute or so bot wont go offline but that just seems too wasteful.) Suggestions anyone? Here is the presence code: class BotPresenceClientProtocol(PresenceClientProtocol): def connectionInitialized(self): PresenceClientProtocol.connectionInitialized(self) self.available(statuses={None: 'Here'}) def subscribeReceived(self, entity): self.subscribed(entity) self.available(statuses={None: 'Here'}) def unsubscribeReceived(self, entity): self.unsubscribed(entity) Thanks in advance. A: If you're using XMPP, as I assume is the case given your mention of wokkel, then, per RFC 3921, the applicable standard, you do need periodic exchanges of presence information (indeed, that's a substantial overhead of XMPP, and solutions to it are being researched, but that's the state of the art as of now). Essentially, given the high likelihood that total silence from a client may be due to that client just going away, periodic "reassurance" of the kind "I'm still here" appears to be a must (I'm not sure what direction those research efforts are taking to ameliorate this situation -- maybe the client could commit to "being there for at least the next 15 minutes", but given that most clients are about a fickle human user who can't be stopped from changing their mind at any time and going away, I'm not sure that would be solid enough to be useful).
chatbot using twisted and wokkel
I am writing a chatbot using Twisted and wokkel and everything seems to be working except that bot periodically logs off. To temporarily fix that I set presence to available on every connection initialized. Does anyone know how to prevent going offline? (I assume if i keep sending available presence every minute or so bot wont go offline but that just seems too wasteful.) Suggestions anyone? Here is the presence code: class BotPresenceClientProtocol(PresenceClientProtocol): def connectionInitialized(self): PresenceClientProtocol.connectionInitialized(self) self.available(statuses={None: 'Here'}) def subscribeReceived(self, entity): self.subscribed(entity) self.available(statuses={None: 'Here'}) def unsubscribeReceived(self, entity): self.unsubscribed(entity) Thanks in advance.
[ "If you're using XMPP, as I assume is the case given your mention of wokkel, then, per RFC 3921, the applicable standard, you do need periodic exchanges of presence information (indeed, that's a substantial overhead of XMPP, and solutions to it are being researched, but that's the state of the art as of now). Essentially, given the high likelihood that total silence from a client may be due to that client just going away, periodic \"reassurance\" of the kind \"I'm still here\" appears to be a must (I'm not sure what direction those research efforts are taking to ameliorate this situation -- maybe the client could commit to \"being there for at least the next 15 minutes\", but given that most clients are about a fickle human user who can't be stopped from changing their mind at any time and going away, I'm not sure that would be solid enough to be useful).\n" ]
[ 3 ]
[]
[]
[ "chatbot", "python", "twisted", "xmpp" ]
stackoverflow_0002751918_chatbot_python_twisted_xmpp.txt
Q: Python grab class in class definition I don't even know how to explain this, so here is the code I'm trying. from couchdb.schema import Document, TextField class Base(Document): type = TextField(default=self.__name__) #self doesn't work, how do I get a reference to Base? class User(Base): pass #User.type be defined as TextField(default="Test2") The reason I'm even trying this is I'm working on creating a base class for an orm I'm using. I want to avoid defining the table name for every model I have. Also knowing what the limits of python is will help me avoid wasting time trying impossible things. A: The class object does not (yet) exist while the class body is executing, so there is no way for code in the class body to get a reference to it (just as, more generally, there is no way for any code to get a reference to any object that does not exist). Test2.__name__, however, already does what you're specifically looking for, so I don't think you need any workaround (such as metaclasses or class decorators) for your specific use case. Edit: for the edited question, where you don't just need the name as a string, a class decorator is the simplest way to work around the problem (in Python 2.6 or later): def maketype(cls): cls.type = TextField(default=cls.__name__) return cls and put @maketype in front of each class you want to decorate that way. In Python 2.5 or earlier, you need instead to say maketype(Base) after each relevant class statement. If you want this functionality to get inherited, then you have to define a custom metaclass that performs the same functionality in its __init__ or __new__ methods. Personally, I would recommend against defining custom metaclasses unless they're really indispensable -- instead, I'd stick with the simpler decorator approach. A: You may want to check out the other question python super class relection In your case, Test2.__base__ will return the base class Test. If it doesn't work, you may use the new style: class Test(object)
Python grab class in class definition
I don't even know how to explain this, so here is the code I'm trying. from couchdb.schema import Document, TextField class Base(Document): type = TextField(default=self.__name__) #self doesn't work, how do I get a reference to Base? class User(Base): pass #User.type be defined as TextField(default="Test2") The reason I'm even trying this is I'm working on creating a base class for an orm I'm using. I want to avoid defining the table name for every model I have. Also knowing what the limits of python is will help me avoid wasting time trying impossible things.
[ "The class object does not (yet) exist while the class body is executing, so there is no way for code in the class body to get a reference to it (just as, more generally, there is no way for any code to get a reference to any object that does not exist). Test2.__name__, however, already does what you're specifically looking for, so I don't think you need any workaround (such as metaclasses or class decorators) for your specific use case.\nEdit: for the edited question, where you don't just need the name as a string, a class decorator is the simplest way to work around the problem (in Python 2.6 or later):\ndef maketype(cls):\n cls.type = TextField(default=cls.__name__)\n return cls \n\nand put @maketype in front of each class you want to decorate that way. In Python 2.5 or earlier, you need instead to say maketype(Base) after each relevant class statement.\nIf you want this functionality to get inherited, then you have to define a custom metaclass that performs the same functionality in its __init__ or __new__ methods. Personally, I would recommend against defining custom metaclasses unless they're really indispensable -- instead, I'd stick with the simpler decorator approach.\n", "You may want to check out the other question python super class relection\nIn your case, Test2.__base__ will return the base class Test. If it doesn't work, you may use the new style: class Test(object)\n" ]
[ 3, 0 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0002752184_python_reflection.txt
Q: Emacs shell output buffer height i have the following in my .emacs file(thanks to SOer nikwin), which evaluates the current buffer content and displays the output in another buffer. (defun shell-compile () (interactive) (save-buffer) (shell-command (concat "python " (buffer-file-name)))) (add-hook 'python-mode-hook (lambda () (local-set-key (kbd "\C-c\C-c") 'shell-compile))) The problem is that the output window takes half the emacs screen. Is there any way to set the output windows's height to something smaller. I googled for 30mins or so and could not find anything that worked. Thanks in advance. A: This expands the source code buffer by 20 lines whenever its height is less than or equal to half the frame's height. Pretty crude, but it may serve your purpose. (defun shell-compile () (interactive) (save-buffer) (shell-command (concat "python " (buffer-file-name))) (if (<= (* 2 (window-height)) (frame-height)) (enlarge-window 20) nil)) A: I asked very similar question before: emacs programmatically change window size this is what I used to have (before using ecb) (defun collapse-compilation-window (buffer) "Shrink the window if the process finished successfully." (let ((compilation-window-height 5)) (compilation-set-window-height (get-buffer-window buffer 0)))) (add-hook 'compilation-finish-functions (lambda (buf str) (if (string-match "exited abnormally" str) ; (next-error) ;;no errors, make the compilation window go away in a few seconds ;(run-at-time "2 sec" nil 'delete-windows-on (get-buffer-create "*compilation*")) (collapse-compilation-window buf) (message "No Compilation Errors!") ) )) ;(add-hook 'compilation-finish-functions 'my-compilation-finish-function)
Emacs shell output buffer height
i have the following in my .emacs file(thanks to SOer nikwin), which evaluates the current buffer content and displays the output in another buffer. (defun shell-compile () (interactive) (save-buffer) (shell-command (concat "python " (buffer-file-name)))) (add-hook 'python-mode-hook (lambda () (local-set-key (kbd "\C-c\C-c") 'shell-compile))) The problem is that the output window takes half the emacs screen. Is there any way to set the output windows's height to something smaller. I googled for 30mins or so and could not find anything that worked. Thanks in advance.
[ "This expands the source code buffer by 20 lines whenever its height is less than or equal to half the frame's height. Pretty crude, but it may serve your purpose.\n(defun shell-compile ()\n (interactive)\n (save-buffer)\n (shell-command (concat \"python \" (buffer-file-name)))\n (if (<= (* 2 (window-height)) (frame-height))\n (enlarge-window 20)\n nil))\n\n", "I asked very similar question before: emacs programmatically change window size\nthis is what I used to have (before using ecb)\n(defun collapse-compilation-window (buffer)\n \"Shrink the window if the process finished successfully.\"\n (let ((compilation-window-height 5))\n (compilation-set-window-height (get-buffer-window buffer 0))))\n\n(add-hook 'compilation-finish-functions\n (lambda (buf str)\n (if (string-match \"exited abnormally\" str)\n; (next-error)\n ;;no errors, make the compilation window go away in a few seconds\n ;(run-at-time \"2 sec\" nil 'delete-windows-on (get-buffer-create \"*compilation*\"))\n (collapse-compilation-window buf)\n (message \"No Compilation Errors!\")\n )\n ))\n\n;(add-hook 'compilation-finish-functions 'my-compilation-finish-function)\n\n" ]
[ 1, 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0002748880_emacs_python.txt
Q: Python's JSON module doesn't use __get__? When I serialize a list of objects with a custom __get__ method, __get__ is not called and the raw (unprocessed by custom __get__) value from __set__ is used. How does Python's json module iterate over an item? Note: if I iterate over the list before serializing, the correct value returned by __get__ is used. A: It checks whether the object is certain values, or isinstances of list, tuple, or dicts... It provides a method for what to do if all this fails, and documents how to do this: import simplejson class IterEncoder(simplejson.JSONEncoder): def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return simplejson.JSONEncoder.default(self, o) simplejson.dumps(YourObject,cls=IterEncoder) A: From the Python 3.1.2 documentation (re-formatted for viewing here but otherwise unedited): json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, **kw) default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. So your __get__ function should be passed as default=yourcustomjsonencoder.__get__ or something like that? Just a thought. I could be way off (and probably am), but it's an idea at least.
Python's JSON module doesn't use __get__?
When I serialize a list of objects with a custom __get__ method, __get__ is not called and the raw (unprocessed by custom __get__) value from __set__ is used. How does Python's json module iterate over an item? Note: if I iterate over the list before serializing, the correct value returned by __get__ is used.
[ "It checks whether the object is certain values, or isinstances of list, tuple, or dicts...\nIt provides a method for what to do if all this fails, and documents how to do this:\n\nimport simplejson\nclass IterEncoder(simplejson.JSONEncoder):\n def default(self, o):\n try:\n iterable = iter(o)\n except TypeError:\n pass\n else:\n return list(iterable)\n return simplejson.JSONEncoder.default(self, o)\n\nsimplejson.dumps(YourObject,cls=IterEncoder)\n\n", "From the Python 3.1.2 documentation (re-formatted for viewing here but otherwise unedited):\njson.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,\n allow_nan=True, cls=None, indent=None, separators=None,\n default=None, **kw)\n\n\ndefault(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.\n\nSo your __get__ function should be passed as default=yourcustomjsonencoder.__get__ or something like that? Just a thought. I could be way off (and probably am), but it's an idea at least.\n" ]
[ 1, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002238847_json_python.txt
Q: Python line file iteration and strange characters I have a huge gzipped text file which I need to read, line by line. I go with the following: for i, line in enumerate(codecs.getreader('utf-8')(gzip.open('file.gz'))): print i, line At some point late in the file, the python output diverges from the file. This is because lines are getting broken due to weird special characters that python thinks are newlines. When I open the file in 'vim', they are correct, but the suspect characters are formatted weirdly. Is there something I can do to fix this? I've tried other codecs including utf-16, latin-1. I've also tried with no codec. I looked at the file using 'od'. Sure enough, there are \n characters where they shouldn't be. But, the "wrong" ones are prepended by a weird character. I think there's some encoding here with some characters being 2-bytes, but the trailing byte being a \n if not viewed properly. According to 'od -h file' the offending character is '1d1c'. If I replace: gzip.open('file.gz') With: os.popen('zcat file.gz') It works fine (and actually, quite faster). But, I'd like to know where I'm going wrong. A: Try again with no codec. The following reproduces your problem when using codec, and the absence of the problem without it: import gzip import os import codecs data = gzip.open("file.gz", "wb") data.write('foo\x1d\x1cbar\nbaz') data.close() print list(codecs.getreader('utf-8')(gzip.open('file.gz'))) print list(os.popen('zcat file.gz')) print list(gzip.open('file.gz')) Outputs: [u'foo\x1d', u'\x1c', u'bar\n', u'baz'] ['foo\x1d\x1cbar\n', 'baz'] ['foo\x1d\x1cbar\n', 'baz'] A: I asked (in a comment) """Show us the output from print repr(weird_special_characters). When you open the file in vim, WHAT are correct? Please be more precise than "formatted weirdly".""" But nothing :-( What file are you looking at with od? file.gz?? If you can see anything recognisable in there, it's not a gzip file! You're not seeing newlines, you're seeing binary bytes that contain 0x0A. If the original file was utf-8 encoded, what was the point of trying it with other codecs? Does "works OK with zcat" mean that you got recognisable data without a utf8 decode step?? I suggest that you simplify your code, and do it a step at a time ... see for example the accepted answer to this question. Try it again and please show the exact code that you ran, and use repr() when describing the results. Update It looks like DS has guessed what you were trying to explain about the \x1c and \x1d. Here are some notes on WHY it happens like that: In ASCII, only \r and \n are considered when line-breaking: >>> import pprint >>> text = ''.join('A' + chr(i) for i in range(32)) + 'BBB' >>> print repr(text) 'A\x00A\x01A\x02A\x03A\x04A\x05A\x06A\x07A\x08A\tA\nA\x0bA\x0cA\rA\x0eA\x0fA\x10 A\x11A\x12A\x13A\x14A\x15A\x16A\x17A\x18A\x19A\x1aA\x1bA\x1cA\x1dA\x1eA\x1fBBB' >>> pprint.pprint(text.splitlines(True)) ['A\x00A\x01A\x02A\x03A\x04A\x05A\x06A\x07A\x08A\tA\n', # line break 'A\x0bA\x0cA\r', # line break 'A\x0eA\x0fA\x10A\x11A\x12A\x13A\x14A\x15A\x16A\x17A\x18A\x19A\x1aA\x1bA\x1cA\x 1dA\x1eA\x1fBBB'] >>> However in Unicode, the characters \x1D (FILE SEPARATOR), \x1E (GROUP SEPARATOR), and \x1E (RECORD SEPARATOR) also qualify as line-endings: >>> text = u''.join('A' + unichr(i) for i in range(32)) + u'BBB' >>> print repr(text) u'A\x00A\x01A\x02A\x03A\x04A\x05A\x06A\x07A\x08A\tA\nA\x0bA\x0cA\rA\x0eA\x0fA\x10A\x11A\x12A\x13A\x14A\x15A\x16A\x17A\x18A\x19A\x1aA\x1bA\x1cA\x1dA\x1eA\x1fBBB' >>> pprint.pprint(text.splitlines(True)) [u'A\x00A\x01A\x02A\x03A\x04A\x05A\x06A\x07A\x08A\tA\n', # line break u'A\x0bA\x0cA\r', # line break u'A\x0eA\x0fA\x10A\x11A\x12A\x13A\x14A\x15A\x16A\x17A\x18A\x19A\x1aA\x1bA\x1c', # line break u'A\x1d', # line break u'A\x1e', # line break u'A\x1fBBB'] >>> This will happen whatever codec you use. You still need to work out what (if any) codec you need to use. You also need to work out whether the original file was really a text file and not a binary file. If it's a text file, you need to consider the meaning of the \x1c and \x1d in the file.
Python line file iteration and strange characters
I have a huge gzipped text file which I need to read, line by line. I go with the following: for i, line in enumerate(codecs.getreader('utf-8')(gzip.open('file.gz'))): print i, line At some point late in the file, the python output diverges from the file. This is because lines are getting broken due to weird special characters that python thinks are newlines. When I open the file in 'vim', they are correct, but the suspect characters are formatted weirdly. Is there something I can do to fix this? I've tried other codecs including utf-16, latin-1. I've also tried with no codec. I looked at the file using 'od'. Sure enough, there are \n characters where they shouldn't be. But, the "wrong" ones are prepended by a weird character. I think there's some encoding here with some characters being 2-bytes, but the trailing byte being a \n if not viewed properly. According to 'od -h file' the offending character is '1d1c'. If I replace: gzip.open('file.gz') With: os.popen('zcat file.gz') It works fine (and actually, quite faster). But, I'd like to know where I'm going wrong.
[ "Try again with no codec. The following reproduces your problem when using codec, and the absence of the problem without it:\nimport gzip \nimport os \nimport codecs \n\ndata = gzip.open(\"file.gz\", \"wb\") \ndata.write('foo\\x1d\\x1cbar\\nbaz') \ndata.close() \n\nprint list(codecs.getreader('utf-8')(gzip.open('file.gz'))) \nprint list(os.popen('zcat file.gz')) \nprint list(gzip.open('file.gz')) \n\nOutputs:\n[u'foo\\x1d', u'\\x1c', u'bar\\n', u'baz']\n['foo\\x1d\\x1cbar\\n', 'baz']\n['foo\\x1d\\x1cbar\\n', 'baz']\n\n", "I asked (in a comment) \"\"\"Show us the output from print repr(weird_special_characters). When you open the file in vim, WHAT are correct? Please be more precise than \"formatted weirdly\".\"\"\" But nothing :-(\nWhat file are you looking at with od? file.gz?? If you can see anything recognisable in there, it's not a gzip file! You're not seeing newlines, you're seeing binary bytes that contain 0x0A.\nIf the original file was utf-8 encoded, what was the point of trying it with other codecs?\nDoes \"works OK with zcat\" mean that you got recognisable data without a utf8 decode step??\nI suggest that you simplify your code, and do it a step at a time ... see for example the accepted answer to this question. Try it again and please show the exact code that you ran, and use repr() when describing the results.\nUpdate It looks like DS has guessed what you were trying to explain about the \\x1c and \\x1d.\nHere are some notes on WHY it happens like that:\nIn ASCII, only \\r and \\n are considered when line-breaking:\n>>> import pprint\n>>> text = ''.join('A' + chr(i) for i in range(32)) + 'BBB'\n>>> print repr(text)\n'A\\x00A\\x01A\\x02A\\x03A\\x04A\\x05A\\x06A\\x07A\\x08A\\tA\\nA\\x0bA\\x0cA\\rA\\x0eA\\x0fA\\x10\nA\\x11A\\x12A\\x13A\\x14A\\x15A\\x16A\\x17A\\x18A\\x19A\\x1aA\\x1bA\\x1cA\\x1dA\\x1eA\\x1fBBB'\n>>> pprint.pprint(text.splitlines(True))\n['A\\x00A\\x01A\\x02A\\x03A\\x04A\\x05A\\x06A\\x07A\\x08A\\tA\\n', # line break\n 'A\\x0bA\\x0cA\\r', # line break\n 'A\\x0eA\\x0fA\\x10A\\x11A\\x12A\\x13A\\x14A\\x15A\\x16A\\x17A\\x18A\\x19A\\x1aA\\x1bA\\x1cA\\x\n1dA\\x1eA\\x1fBBB']\n>>>\n\nHowever in Unicode, the characters \\x1D (FILE SEPARATOR), \\x1E (GROUP SEPARATOR), and \\x1E (RECORD SEPARATOR) also qualify as line-endings:\n>>> text = u''.join('A' + unichr(i) for i in range(32)) + u'BBB'\n>>> print repr(text)\nu'A\\x00A\\x01A\\x02A\\x03A\\x04A\\x05A\\x06A\\x07A\\x08A\\tA\\nA\\x0bA\\x0cA\\rA\\x0eA\\x0fA\\x10A\\x11A\\x12A\\x13A\\x14A\\x15A\\x16A\\x17A\\x18A\\x19A\\x1aA\\x1bA\\x1cA\\x1dA\\x1eA\\x1fBBB'\n>>> pprint.pprint(text.splitlines(True))\n[u'A\\x00A\\x01A\\x02A\\x03A\\x04A\\x05A\\x06A\\x07A\\x08A\\tA\\n', # line break\n u'A\\x0bA\\x0cA\\r', # line break\n u'A\\x0eA\\x0fA\\x10A\\x11A\\x12A\\x13A\\x14A\\x15A\\x16A\\x17A\\x18A\\x19A\\x1aA\\x1bA\\x1c', # line break\n u'A\\x1d', # line break\n u'A\\x1e', # line break\n u'A\\x1fBBB']\n>>>\n\nThis will happen whatever codec you use. You still need to work out what (if any) codec you need to use. You also need to work out whether the original file was really a text file and not a binary file. If it's a text file, you need to consider the meaning of the \\x1c and \\x1d in the file.\n" ]
[ 5, 1 ]
[]
[]
[ "codec", "gzip", "line_breaks", "python" ]
stackoverflow_0002737894_codec_gzip_line_breaks_python.txt
Q: Appengine (python) returns empty for valid queries EDIT: Figured it out. For whatever reason the field in the index was called strWord instead of wordStr. I didn't notice because of the similarities. The file was auto generated, so I must have called the field that in a previous development version. I've got an app with around half a million 'records', each of which only stores three fields. I'd like to look up records by a string field with a query, but I'm running into problems. If I visit the console page, manually view a record and save it (without making changes) it shows up in a query: SELECT * FROM wordEntry WHERE wordStr = 'SomeString' If I don't do this, I get 'no results'. Does appengine need time to update? If so, how much? (I was also having trouble batch deleting and modifying data, but I was able to break the problem up into smaller chunks.) A: When this has happened to me it's because I've been using a TextField, which cannot be queried (but confusingly just gets ignored). Try switching to StringField.
Appengine (python) returns empty for valid queries
EDIT: Figured it out. For whatever reason the field in the index was called strWord instead of wordStr. I didn't notice because of the similarities. The file was auto generated, so I must have called the field that in a previous development version. I've got an app with around half a million 'records', each of which only stores three fields. I'd like to look up records by a string field with a query, but I'm running into problems. If I visit the console page, manually view a record and save it (without making changes) it shows up in a query: SELECT * FROM wordEntry WHERE wordStr = 'SomeString' If I don't do this, I get 'no results'. Does appengine need time to update? If so, how much? (I was also having trouble batch deleting and modifying data, but I was able to break the problem up into smaller chunks.)
[ "When this has happened to me it's because I've been using a TextField, which cannot be queried (but confusingly just gets ignored). Try switching to StringField.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002752008_google_app_engine_python.txt
Q: Which version of Python should be used? I'm starting a new Python web project. With most frameworks, everyone rushes to the latest version, however, it seems that this is not as true for Python 3.x. Which version of Python should brand new projects use? A: A lot of 3rd party Python modules still require Python 2.x (numpy, scipy for example). If you will use any of those, or if you don't yet know what modules you need and want to keep your options open then stick with Python 2.x for now. If you know that all the modules you need work with Python 3.x then go with that. A: for a web project, chose the python version that is supported by your hosting provider. if you are lucky to have a dedicated server, then chose whatever version is best supported by the framework you chose. python 3 is still not supported by the major web framework, so python 2.6 seems the best choice. if your project is hosted on a shared host, you will have to stick with the python version installed on the host (personally, i am stuck with python 2.4.4, hoping my hosting provider will upgrade to 2.5 or 2.6, which will not come anytime soon) A: I'd recommend Python 2.6 because it has some features of Python 3.x, but it still retains the same functionality found in Python 2.5. While some might argue that Python 3.x is better (quite possibly because of the immense amount of reorganisation and the fact that all strings are Unicode by default), most Python code in use right now is still for Python 2.x. I'd say stick with Python 2.6 until you need Python 3.x. :) A: Python 3 is a great place to start for those "with no baggage" (meaning no existing Python code or apps, no libraries/dependencies that haven't been ported to Python 3 yet, etc.). However on the other hand, although Python 3 is here, most of the industrial world still runs on Python 2, so if you do need to create an app to run today using the libraries and packages available to you, that's where you should start. If you do, use any release 2.6 or newer as they have features backported from 3.x to help you start thinking in a 3.x kind of way. :-) If you learn one, it's easy to adapt to the other (and vice versa). Although Python 3.x is backwards-incompatible with 2.x, Python syntax isn't going to be unrecognizable... pretty much everything is very similar to 2.x, but it's easy to break code when print changes from a statement to a function. So don't worry about Python 3 for now. Also, just because of the numbering, do NOT be fooled in thinking that Python 2 is obsolete in any way nor can you follow the timeline serially. In other words, Python 2.7 will be newer than both Python 3.0 and 3.1. (3.2 won't be released until the end of this year.) Again, Python 2 has NOT been EOL'd -- both 2.x and 3.x are being developed actively. So, like the others, I would suggest you start with any Python 2.x. On a related note, I had the publishers add two new appendices (C & D) to the latest printing (5th!!) of my book, Core Python Programming, one on Python 3.x and the other on the importance of 2.6 and the role it plays in helping users to transition to Python 3. Finally, I've been giving talks on Python 3 and covering the main differences from Python 2. Here's one that I gave a PyCon a few months ago which includes the slide preso. A: I use 2.5 for Google App Engine projects and 2.6 for my Django projects.
Which version of Python should be used?
I'm starting a new Python web project. With most frameworks, everyone rushes to the latest version, however, it seems that this is not as true for Python 3.x. Which version of Python should brand new projects use?
[ "A lot of 3rd party Python modules still require Python 2.x (numpy, scipy for example). If you will use any of those, or if you don't yet know what modules you need and want to keep your options open then stick with Python 2.x for now.\nIf you know that all the modules you need work with Python 3.x then go with that.\n", "for a web project, chose the python version that is supported by your hosting provider. \nif you are lucky to have a dedicated server, then chose whatever version is best supported by the framework you chose. python 3 is still not supported by the major web framework, so python 2.6 seems the best choice.\nif your project is hosted on a shared host, you will have to stick with the python version installed on the host (personally, i am stuck with python 2.4.4, hoping my hosting provider will upgrade to 2.5 or 2.6, which will not come anytime soon)\n", "I'd recommend Python 2.6 because it has some features of Python 3.x, but it still retains the same functionality found in Python 2.5. While some might argue that Python 3.x is better (quite possibly because of the immense amount of reorganisation and the fact that all strings are Unicode by default), most Python code in use right now is still for Python 2.x. I'd say stick with Python 2.6 until you need Python 3.x. :)\n", "Python 3 is a great place to start for those \"with no baggage\" (meaning no existing Python code or apps, no libraries/dependencies that haven't been ported to Python 3 yet, etc.).\nHowever on the other hand, although Python 3 is here, most of the industrial world still runs on Python 2, so if you do need to create an app to run today using the libraries and packages available to you, that's where you should start. If you do, use any release 2.6 or newer as they have features backported from 3.x to help you start thinking in a 3.x kind of way. :-) If you learn one, it's easy to adapt to the other (and vice versa).\nAlthough Python 3.x is backwards-incompatible with 2.x, Python syntax isn't going to be unrecognizable... pretty much everything is very similar to 2.x, but it's easy to break code when print changes from a statement to a function. So don't worry about Python 3 for now.\nAlso, just because of the numbering, do NOT be fooled in thinking that Python 2 is obsolete in any way nor can you follow the timeline serially. In other words, Python 2.7 will be newer than both Python 3.0 and 3.1. (3.2 won't be released until the end of this year.) Again, Python 2 has NOT been EOL'd -- both 2.x and 3.x are being developed actively. So, like the others, I would suggest you start with any Python 2.x.\nOn a related note, I had the publishers add two new appendices (C & D) to the latest printing (5th!!) of my book, Core Python Programming, one on Python 3.x and the other on the importance of 2.6 and the role it plays in helping users to transition to Python 3.\nFinally, I've been giving talks on Python 3 and covering the main differences from Python 2. Here's one that I gave a PyCon a few months ago which includes the slide preso.\n", "I use 2.5 for Google App Engine projects and 2.6 for my Django projects.\n" ]
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002751250_python.txt
Q: Python GUI Scraper hanging issues I wrote a scraper using python a while back, and it worked fine in the command line. I have made a GUI for the application now, but I am having trouble with one issue. When I attempt to update text inside the gui (e.g. 'fetching URL 12/50'), I am unable seeing as the function within the scraper is grabbing 100+ links. Also when going from one scraping function, to a function that should update the gui, to another function, the gui update function seems to be skipped over while the next scrape function is run. An example would be: scrapeLinksA() #takes 20 seconds updateInfo("LinksA done") scrapeLinksB() #takes another 20 seconds in the above example, updateInfo is never executed, unless I end the program with a KeyboardInterrupt. I'm thinking my solution is threading, but I'm not sure. What can I do to fix this? I am using: PyQt4 urllib2 BeautifulSoup A: I'd suggest to use QNetworkAccessManager for a non-blocking way of downloading the websites. It's a different approach, so you will probably rewrite the handling part of your application. Instead of waiting until the page is downloaded so that you can parse it, you have multiple smaller functions, connected via signals and they are executed when some events happen (e.g. "the page is downloaded"). A: Lukáš Lalinský 's answer is very good. Another possibility would be to use the PyQt threads. If the problem is merely the 'updating' part (and not the need for asynchronous processing), try putting this call: QCoreApplication.processEvents() between scrapeLinksA and scrapeLinksB to see if that helps (it temporarily interrupts the main event loop to see if there are other (paint requests e.g.) pending). If that doesn't, please provide us with the source of updateInfo.
Python GUI Scraper hanging issues
I wrote a scraper using python a while back, and it worked fine in the command line. I have made a GUI for the application now, but I am having trouble with one issue. When I attempt to update text inside the gui (e.g. 'fetching URL 12/50'), I am unable seeing as the function within the scraper is grabbing 100+ links. Also when going from one scraping function, to a function that should update the gui, to another function, the gui update function seems to be skipped over while the next scrape function is run. An example would be: scrapeLinksA() #takes 20 seconds updateInfo("LinksA done") scrapeLinksB() #takes another 20 seconds in the above example, updateInfo is never executed, unless I end the program with a KeyboardInterrupt. I'm thinking my solution is threading, but I'm not sure. What can I do to fix this? I am using: PyQt4 urllib2 BeautifulSoup
[ "I'd suggest to use QNetworkAccessManager for a non-blocking way of downloading the websites. It's a different approach, so you will probably rewrite the handling part of your application. Instead of waiting until the page is downloaded so that you can parse it, you have multiple smaller functions, connected via signals and they are executed when some events happen (e.g. \"the page is downloaded\").\n", "Lukáš Lalinský 's answer is very good.\nAnother possibility would be to use the PyQt threads.\nIf the problem is merely the 'updating' part (and not the need for asynchronous processing), try putting this call: \nQCoreApplication.processEvents()\n\nbetween scrapeLinksA and scrapeLinksB to see if that helps (it temporarily interrupts the main event loop to see if there are other (paint requests e.g.) pending).\nIf that doesn't, please provide us with the source of updateInfo.\n" ]
[ 2, 2 ]
[]
[]
[ "beautifulsoup", "pyqt4", "python", "screen_scraping", "urllib2" ]
stackoverflow_0002752518_beautifulsoup_pyqt4_python_screen_scraping_urllib2.txt
Q: Why would one build supervisord inside of a buildout? I've seen buildout recipes that build supervisor into the buildout, I suppose to control the daemons inside. However, it seems to me that one would still need something in /etc/init.d ( for example ) to run said supervisor instance on boot. So, why build supervisor inside the buildout? Why not install it system wide and just make a config file for the daemons involved inside? A: When we create a buildout for a customer, we want that buildout to run on arbitrary hosting environments with minimal dependencies, all satisfiable with system packages. By including supervisord in the buildout, we eliminate the need for it to be installed system-wide and can tweak it's parameters finely, without having to ask a system admin to change settings for us. It's easy to get supervisor to run at boot time from a buildout, using the usercrontab recipe: [supervisor-cron] recipe = z3c.recipe.usercrontab times = @reboot command = ${buildout:bin-directory}/supervisord -c ${buildout:directory}/etc/supervisord.conf The above part will add an entry to the crontab that causes supervisor to run at boot time.
Why would one build supervisord inside of a buildout?
I've seen buildout recipes that build supervisor into the buildout, I suppose to control the daemons inside. However, it seems to me that one would still need something in /etc/init.d ( for example ) to run said supervisor instance on boot. So, why build supervisor inside the buildout? Why not install it system wide and just make a config file for the daemons involved inside?
[ "When we create a buildout for a customer, we want that buildout to run on arbitrary hosting environments with minimal dependencies, all satisfiable with system packages. By including supervisord in the buildout, we eliminate the need for it to be installed system-wide and can tweak it's parameters finely, without having to ask a system admin to change settings for us.\nIt's easy to get supervisor to run at boot time from a buildout, using the usercrontab recipe:\n[supervisor-cron]\nrecipe = z3c.recipe.usercrontab\ntimes = @reboot\ncommand = ${buildout:bin-directory}/supervisord -c ${buildout:directory}/etc/supervisord.conf\n\nThe above part will add an entry to the crontab that causes supervisor to run at boot time.\n" ]
[ 9 ]
[]
[]
[ "buildout", "python", "supervisord" ]
stackoverflow_0002752433_buildout_python_supervisord.txt
Q: Why does Python Array Module Process Strings and Lists Differently? I'm having trouble understanding the result of the following statements: >>> from array import array >>> array('L',[0xff,0xff,0xff,0xff]) array('L', [255L, 255L, 255L, 255L]) >>> from array import array >>> array('L','\xff\xff\xff\xff') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: string length not a multiple of item size A: You are running this on a 64-bit build of Python, on which array treats type code 'L' as a 64-bit unsigned integer. >>> array('L','\xff\xff\xff\xff\xff\xff\xff\xff') array('L', [18446744073709551615L]) The documentation isn't very clear. All it says is that 'L' is at least four bytes. A: In the first case you are initializing the array from a list with 4 elements. That will give you an array with 4 elements: one for each value in the list. In the second case you are initializing the array from a byte string: the bytes in the string will be copied directly into the array. The 'L' specifier creates an array of unsigned longs which have a minimum size of 4 bytes. On my machine (Windows 64 bit Python 2.6) initializing from a 4 byte string works fine: >>> a = array('L','\xff\xff\xff\xff') >>> a.tostring() '\xff\xff\xff\xff' I guess whichever version of Python you are using has unsigned longs that are 8 bytes rather than 4. Try converting the array you created from a list back to a string and see how many bytes that contains: >>> a = array('L',[0xff,0xff,0xff,0xff]) >>> a.tostring() '\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00' P.S. I'm assuming that you are using Python 2.x, on Python 3.x you would have got a TypeError instead.
Why does Python Array Module Process Strings and Lists Differently?
I'm having trouble understanding the result of the following statements: >>> from array import array >>> array('L',[0xff,0xff,0xff,0xff]) array('L', [255L, 255L, 255L, 255L]) >>> from array import array >>> array('L','\xff\xff\xff\xff') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: string length not a multiple of item size
[ "You are running this on a 64-bit build of Python, on which array treats type code 'L' as a 64-bit unsigned integer.\n>>> array('L','\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff')\narray('L', [18446744073709551615L])\n\nThe documentation isn't very clear. All it says is that 'L' is at least four bytes.\n", "In the first case you are initializing the array from a list with 4 elements. That will give you an array with 4 elements: one for each value in the list.\nIn the second case you are initializing the array from a byte string: the bytes in the string will be copied directly into the array. The 'L' specifier creates an array of unsigned longs which have a minimum size of 4 bytes.\nOn my machine (Windows 64 bit Python 2.6) initializing from a 4 byte string works fine:\n>>> a = array('L','\\xff\\xff\\xff\\xff')\n\n>>> a.tostring()\n'\\xff\\xff\\xff\\xff'\n\nI guess whichever version of Python you are using has unsigned longs that are 8 bytes rather than 4. Try converting the array you created from a list back to a string and see how many bytes that contains:\n>>> a = array('L',[0xff,0xff,0xff,0xff])\n>>> a.tostring()\n'\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00'\n\nP.S. I'm assuming that you are using Python 2.x, on Python 3.x you would have got a TypeError instead.\n" ]
[ 3, 1 ]
[]
[]
[ "arrays", "python", "python_module", "type_conversion" ]
stackoverflow_0002752913_arrays_python_python_module_type_conversion.txt
Q: What is a good SOAP client library for python on App Engine? I have read that SUDS doesn't work on App Engine. http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html Can anyone confirm or refute this? Can you suggest an alternative for calling SOAP services from App Engine's python runtime? A: Have you tried ElementSoap? It seems like a good option. A: http://code.google.com/p/google-api-adwords-python-lib/ This is a soap library from Google. I have not had time to test it,
What is a good SOAP client library for python on App Engine?
I have read that SUDS doesn't work on App Engine. http://osdir.com/ml/fedora-suds-list/2010-03/msg00004.html Can anyone confirm or refute this? Can you suggest an alternative for calling SOAP services from App Engine's python runtime?
[ "Have you tried ElementSoap? It seems like a good option.\n", "http://code.google.com/p/google-api-adwords-python-lib/\nThis is a soap library from Google. I have not had time to test it,\n" ]
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python", "soap" ]
stackoverflow_0002557461_google_app_engine_python_soap.txt
Q: Need to constantly monitor serial data in Python Right now I am using an Arduino to send data from an analog sensor to COM4. I am trying to make a python script that continuously monitors that data and looks for a certain parameter. I tried something like this but it isn't alerting me correctly import serial from Tkinter import * import tkMessageBox port = "COM4" ser = serial.Serial(port,9600) value = 0 while 1: value = ser.read() if value > 400: tkMessageBox.showwarning( "Open file",) time.sleep(1) A: If the serial package you are using is pySerial, take note of the definition of the Serial.read() method: read(size=1) Parameter: size – Number of bytes to read. Returns: Bytes read from the port. Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read. Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise. Although you are trying to process byte objects, you may (depending on Python version) be handling str or bytes (array) objects. These objects do not necessarily correspond to integer values. Even when receiving byte objects from read(), the largest unsigned integer will be 255. Comparing value with 400 doesn't make sense. Try to find the type of the returned objects with a simple debugging output. print type(value) If you need to handle an str object, check the use of ord() for convertion. (The flush suggestion refers to the original question, which used print, not tkinter). See how-to-flush-output-of-python-print, and try the command line shell, not the IDE which may affect output buffering. A: Instead of having the Arduino code relay all the analog values to COM4, have it relay a flag only when you meet the conditional. So arduino code could be: void loop() { sensorValue = analogRead(sensorPin); if (sensorValue >= 400){ Serial.print("1"); // 1 will be the flag that will be sent to COM4 } Then your Python code can just look for the flag like this: import serial from Tkinter import * import tkMessageBox port = "COM4" ser = serial.Serial(port,9600) value = 0 while 1: value = ser.read(); print value if value == "1": tkMessageBox.showwarning("BLAH", "BLAH\n") exit() else: continue A: Assuming that you are using pySerial, serial.read() only reads one byte, which means a maximum value of 255. If your Arduino is sending string values back it's probably best to separate them with newline characters and use serial.readline(). Unless you have specific performance requirements sending strings back from the Arduino will make debugging significanly easier anyway. Also if you are receiving strings back from the Arduino, your test should be if int(value) > 400:
Need to constantly monitor serial data in Python
Right now I am using an Arduino to send data from an analog sensor to COM4. I am trying to make a python script that continuously monitors that data and looks for a certain parameter. I tried something like this but it isn't alerting me correctly import serial from Tkinter import * import tkMessageBox port = "COM4" ser = serial.Serial(port,9600) value = 0 while 1: value = ser.read() if value > 400: tkMessageBox.showwarning( "Open file",) time.sleep(1)
[ "If the serial package you are using is pySerial, take note of the definition of the Serial.read() method:\n\nread(size=1)\nParameter: size – Number of bytes to read.\nReturns: Bytes read from the port.\nRead size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.\nChanged in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.\n\nAlthough you are trying to process byte objects, you may (depending on Python version) be handling str or bytes (array) objects. These objects do not necessarily correspond to integer values.\nEven when receiving byte objects from read(), the largest unsigned integer will be 255.\nComparing value with 400 doesn't make sense. Try to find the type of the returned objects with a simple debugging output.\nprint type(value)\n\nIf you need to handle an str object, check the use of ord() for convertion.\n(The flush suggestion refers to the original question, which used print, not tkinter).\nSee how-to-flush-output-of-python-print, and try the command line shell, not the IDE which may affect output buffering.\n", "Instead of having the Arduino code relay all the analog values to COM4, have it relay a flag only when you meet the conditional. \nSo arduino code could be:\nvoid loop() {\n sensorValue = analogRead(sensorPin);\n if (sensorValue >= 400){\n Serial.print(\"1\"); // 1 will be the flag that will be sent to COM4\n }\n\nThen your Python code can just look for the flag like this:\nimport serial\nfrom Tkinter import *\nimport tkMessageBox\n\nport = \"COM4\"\nser = serial.Serial(port,9600)\nvalue = 0\n\n\nwhile 1:\n value = ser.read();\n print value\n if value == \"1\":\n tkMessageBox.showwarning(\"BLAH\", \"BLAH\\n\")\n exit()\n else:\n continue\n\n", "Assuming that you are using pySerial, serial.read() only reads one byte, which means a maximum value of 255. If your Arduino is sending string values back it's probably best to separate them with newline characters and use serial.readline(). \nUnless you have specific performance requirements sending strings back from the Arduino will make debugging significanly easier anyway.\nAlso if you are receiving strings back from the Arduino, your test should be if int(value) > 400:\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python", "serial_port" ]
stackoverflow_0002752809_python_serial_port.txt
Q: plotting stem with a continuous line I need to plot a stem plot of my signal using python and matplotlib. I saw the example and the code but the line connecting the black big dot and the x-axis is not a continous line. Do you know whether is possible and how to get a straight line instead? #!/usr/bin/env python from pylab import * x = linspace(0.1, 2*pi, 10) markerline, stemlines, baseline = stem(x, cos(x), '-.') setp(markerline, 'markerfacecolor', 'b') setp(baseline, 'color','r', 'linewidth', 2) show() A: Change '-.' to '-': markerline, stemlines, baseline = stem(x, cos(x), '-') The final argument indicates the line style.
plotting stem with a continuous line
I need to plot a stem plot of my signal using python and matplotlib. I saw the example and the code but the line connecting the black big dot and the x-axis is not a continous line. Do you know whether is possible and how to get a straight line instead? #!/usr/bin/env python from pylab import * x = linspace(0.1, 2*pi, 10) markerline, stemlines, baseline = stem(x, cos(x), '-.') setp(markerline, 'markerfacecolor', 'b') setp(baseline, 'color','r', 'linewidth', 2) show()
[ "Change '-.' to '-':\nmarkerline, stemlines, baseline = stem(x, cos(x), '-')\n\nThe final argument indicates the line style.\n" ]
[ 4 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002753107_matplotlib_python.txt
Q: Python - Finding unicode/ascii problems I am csv.reader to pull in info from a very long sheet. I am doing work on that data set and then I am using the xlwt package to give me a workable excel file. However, I get this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 34: ordinal not in range(128) My question to you all is, how can I find exactly where that error is in my data set? Also, is there some code that I can write which will look through my data set and find out where the issues lie (because some data sets run without the above error and others have problems)? A: The answer is quite simple actually : As soon as you read your data from your file, convert it to unicode using the encoding of your file, and handle the UnicodeDecodeError exception : try: # decode using utf-8 (use ascii if you want) unicode_data = str_data.decode("utf-8") except UnicodeDecodeError, e: print "The error is there !" this will save you from many troubles; you won't have to worry about multibyte character encoding, and external libraries (including xlwt) will just do The Right Thing if they need to write it. Python 3.0 will make it mandatory to specify the encoding of a string, so it's a good idea to do it now. A: The csv module doesn't support unicode and null characters. You might be able to replace them by doing something like this though (Replace 'utf-8' with the encoding which your CSV data is encoded in): import codecs import csv class AsciiFile: def __init__(self, path): self.f = codecs.open(path, 'rb', 'utf-8') def close(self): self.f.close() def __iter__(self): for line in self.f: # 'replace' for unicode characters -> ?, 'ignore' to ignore them y = line.encode('ascii', 'replace') y = y.replace('\0', '?') # Can't handle null characters! yield y f = AsciiFile(PATH) r = csv.reader(f) ... f.close() If you want to find the positions of the characters which you can't be handled by the CSV module, you could do e.g: import codecs lineno = 0 f = codecs.open(PATH, 'rb', 'utf-8') for line in f: for x, c in enumerate(line): if not c.encode('ascii', 'ignore') or c == '\0': print "Character ordinal %s line %s character %s is unicode or null!" % (ord(c), lineno, x) lineno += 1 f.close() Alternatively again, you could use this CSV opener which I wrote which can handle Unicode characters: import codecs def OpenCSV(Path, Encoding, Delims, StartAtRow, Qualifier, Errors): infile = codecs.open(Path, "rb", Encoding, errors=Errors) for Line in infile: Line = Line.strip('\r\n') if (StartAtRow - 1) and StartAtRow > 0: StartAtRow -= 1 elif Qualifier != '(None)': # Take a note of the chars 'before' just # in case of excel-style """ quoting. cB41 = ''; cB42 = '' L = [''] qMode = False for c in Line: if c==Qualifier and c==cB41==cB42 and qMode: # Triple qualifiers, so allow it with one L[-1] = L[-1][:-2] L[-1] += c elif c==Qualifier: # A qualifier, so reverse qual mode qMode = not qMode elif c in Delims and not qMode: # Not in qual mode and delim L.append('') else: # Nothing to see here, move along L[-1] += c cB42 = cB41 cB41 = c yield L else: # There aren't any qualifiers. cB41 = ''; cB42 = '' L = [''] for c in Line: cB42 = cB41; cB41 = c if c in Delims: # Delim L.append('') else: # Nothing to see here, move along L[-1] += c yield L for listItem in openCSV(PATH, Encoding='utf-8', Delims=[','], StartAtRow=0, Qualifier='"', Errors='replace') ... A: You can refer to code snippets in the question below to get a csv reader with unicode encoding support: General Unicode/UTF-8 support for csv files in Python 2.6 A: PLEASE give the full traceback that you got along with the error message. When we know where you are getting the error (reading CSV file, "doing work on that data set", or in writing an XLS file using xlwt), then we can give a focused answer. It is very possible that your input data is not all plain old ASCII. What produces it, and in what encoding? To find where the problems (not necessarily errors) are, try a little script like this (untested): import sys, glob for pattern in sys.argv[1:]: for filepath in glob.glob(pattern): for linex, line in enumerate(open(filepath, 'r')): if any(c >= '\x80' for c in line): print "Non-ASCII in line %d of file %r" % (linex+1, filepath) print repr(line) It would be useful if you showed some samples of the "bad" lines that you find, so that we can judge what the encoding might be. I'm curious about using "csv.reader to pull in info from a very long sheet" -- what kind of "sheet"? Do you mean that you are saving an XLS file as CSV, then reading the CSV file? If so, you could use xlrd to read directly from the input XLS file, getting unicode text which you can give straight to xlwt, avoiding any encode/decode problems. Have you worked through the tutorial from the python-excel.org site?
Python - Finding unicode/ascii problems
I am csv.reader to pull in info from a very long sheet. I am doing work on that data set and then I am using the xlwt package to give me a workable excel file. However, I get this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 34: ordinal not in range(128) My question to you all is, how can I find exactly where that error is in my data set? Also, is there some code that I can write which will look through my data set and find out where the issues lie (because some data sets run without the above error and others have problems)?
[ "The answer is quite simple actually : As soon as you read your data from your file, convert it to unicode using the encoding of your file, and handle the UnicodeDecodeError exception :\ntry:\n # decode using utf-8 (use ascii if you want)\n unicode_data = str_data.decode(\"utf-8\")\nexcept UnicodeDecodeError, e:\n print \"The error is there !\"\n\nthis will save you from many troubles; you won't have to worry about multibyte character encoding, and external libraries (including xlwt) will just do The Right Thing if they need to write it.\nPython 3.0 will make it mandatory to specify the encoding of a string, so it's a good idea to do it now.\n", "The csv module doesn't support unicode and null characters. You might be able to replace them by doing something like this though (Replace 'utf-8' with the encoding which your CSV data is encoded in):\nimport codecs\nimport csv\n\nclass AsciiFile:\n def __init__(self, path):\n self.f = codecs.open(path, 'rb', 'utf-8')\n\n def close(self):\n self.f.close()\n\n def __iter__(self):\n for line in self.f:\n # 'replace' for unicode characters -> ?, 'ignore' to ignore them\n y = line.encode('ascii', 'replace')\n y = y.replace('\\0', '?') # Can't handle null characters!\n yield y\n\nf = AsciiFile(PATH)\nr = csv.reader(f)\n...\nf.close()\n\nIf you want to find the positions of the characters which you can't be handled by the CSV module, you could do e.g:\nimport codecs\n\nlineno = 0\nf = codecs.open(PATH, 'rb', 'utf-8')\nfor line in f:\n for x, c in enumerate(line):\n if not c.encode('ascii', 'ignore') or c == '\\0':\n print \"Character ordinal %s line %s character %s is unicode or null!\" % (ord(c), lineno, x)\n lineno += 1\nf.close()\n\nAlternatively again, you could use this CSV opener which I wrote which can handle Unicode characters:\nimport codecs\n\ndef OpenCSV(Path, Encoding, Delims, StartAtRow, Qualifier, Errors):\n infile = codecs.open(Path, \"rb\", Encoding, errors=Errors)\n for Line in infile:\n Line = Line.strip('\\r\\n')\n if (StartAtRow - 1) and StartAtRow > 0: StartAtRow -= 1\n elif Qualifier != '(None)':\n # Take a note of the chars 'before' just \n # in case of excel-style \"\"\" quoting.\n cB41 = ''; cB42 = ''\n L = ['']\n qMode = False\n for c in Line: \n if c==Qualifier and c==cB41==cB42 and qMode:\n # Triple qualifiers, so allow it with one\n L[-1] = L[-1][:-2]\n L[-1] += c\n elif c==Qualifier: \n # A qualifier, so reverse qual mode\n qMode = not qMode\n elif c in Delims and not qMode: \n # Not in qual mode and delim\n L.append('')\n else: \n # Nothing to see here, move along\n L[-1] += c\n cB42 = cB41\n cB41 = c\n yield L\n else:\n # There aren't any qualifiers.\n cB41 = ''; cB42 = ''\n L = ['']\n for c in Line: \n cB42 = cB41; cB41 = c\n if c in Delims: \n # Delim\n L.append('')\n else: \n # Nothing to see here, move along\n L[-1] += c\n yield L\n\nfor listItem in openCSV(PATH, Encoding='utf-8', Delims=[','], StartAtRow=0, Qualifier='\"', Errors='replace')\n ...\n\n", "You can refer to code snippets in the question below to get a csv reader with unicode encoding support:\n\nGeneral Unicode/UTF-8 support for csv files in Python 2.6\n\n", "PLEASE give the full traceback that you got along with the error message. When we know where you are getting the error (reading CSV file, \"doing work on that data set\", or in writing an XLS file using xlwt), then we can give a focused answer.\nIt is very possible that your input data is not all plain old ASCII. What produces it, and in what encoding?\nTo find where the problems (not necessarily errors) are, try a little script like this (untested):\nimport sys, glob\nfor pattern in sys.argv[1:]:\n for filepath in glob.glob(pattern):\n for linex, line in enumerate(open(filepath, 'r')):\n if any(c >= '\\x80' for c in line):\n print \"Non-ASCII in line %d of file %r\" % (linex+1, filepath)\n print repr(line)\n\nIt would be useful if you showed some samples of the \"bad\" lines that you find, so that we can judge what the encoding might be.\nI'm curious about using \"csv.reader to pull in info from a very long sheet\" -- what kind of \"sheet\"? Do you mean that you are saving an XLS file as CSV, then reading the CSV file? If so, you could use xlrd to read directly from the input XLS file, getting unicode text which you can give straight to xlwt, avoiding any encode/decode problems.\nHave you worked through the tutorial from the python-excel.org site?\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002753022_python.txt
Q: Which template technology should I use with CherryPy? I'm in the process of building a web application using cherrypy. What template technology do you recommend I use? A: If you mean a templating engine, I've had some success using mako with cherrypy. They just seem to play nicely together. Mako is extremely easy to get started with and customize, which is, I assume, also two of your major reasons for choosing cherrypy. The cherrypy official tutorial also uses mako, and you can see a simple sample application there. A: Do you mean View in MVC? I recommend you very nice template engine Jinja2. A: I like Cheetah. A: I like Genshi. One reason that I like it is simply that the XML syntax looks much cleaner to me when mixed with HTML versus the text-level syntax of the other popular templating engines. For example, it's nice to be able to stick a py:for attribute on to output a table versus nesting messy #if or whatever lines. Another reason is that because it's based on XML and treats your HTML as XML, it guarantees that your markup is syntactically correct -- i.e. that tags are closed and properly nested, special characters are properly escaped, etc.. Other templating engines will simply treat your HTML as text and output whatever you give it without the extra santity checks. The main disadvantage of Genshi is that it is much slower than the faster text-based engines. However, its performance should be good enough for most sites. Unless you have a site that has a special need to render text/HTML at a super fast rate, the readability and syntax checking that Genshi provides probably outweigh the performance hit. A: A Zen master would probably answer: "Yes". If you are building a web interface I would choose an engine that provides readable markup templates such as Genshi does. If you are building a rest server and need to return other types of data I would go with one of the more text oriented engines such as Cheetah or Mako. For building HTML pages I prefer Genshi over Cheetah or Mako even if it's quite a bit slower. When returning JSON I rather prefer the faster text-based engines. And because Cherrypy is engine agnostic you can use both if you need it. A: There is also Genshi Their tutorial is based on using cherrypy
Which template technology should I use with CherryPy?
I'm in the process of building a web application using cherrypy. What template technology do you recommend I use?
[ "If you mean a templating engine, I've had some success using mako with cherrypy. They just seem to play nicely together.\nMako is extremely easy to get started with and customize, which is, I assume, also two of your major reasons for choosing cherrypy. The cherrypy official tutorial also uses mako, and you can see a simple sample application there.\n", "Do you mean View in MVC? I recommend you very nice template engine Jinja2.\n", "I like Cheetah.\n", "I like Genshi. \nOne reason that I like it is simply that the XML syntax looks much cleaner to me when mixed with HTML versus the text-level syntax of the other popular templating engines. For example, it's nice to be able to stick a py:for attribute on to output a table versus nesting messy #if or whatever lines. \nAnother reason is that because it's based on XML and treats your HTML as XML, it guarantees that your markup is syntactically correct -- i.e. that tags are closed and properly nested, special characters are properly escaped, etc.. Other templating engines will simply treat your HTML as text and output whatever you give it without the extra santity checks. \nThe main disadvantage of Genshi is that it is much slower than the faster text-based engines. However, its performance should be good enough for most sites. Unless you have a site that has a special need to render text/HTML at a super fast rate, the readability and syntax checking that Genshi provides probably outweigh the performance hit.\n", "A Zen master would probably answer: \"Yes\".\nIf you are building a web interface I would choose an engine that provides readable markup templates such as Genshi does.\nIf you are building a rest server and need to return other types of data I would go with one of the more text oriented engines such as Cheetah or Mako.\nFor building HTML pages I prefer Genshi over Cheetah or Mako even if it's quite a bit slower. When returning JSON I rather prefer the faster text-based engines.\nAnd because Cherrypy is engine agnostic you can use both if you need it.\n", "There is also Genshi\nTheir tutorial is based on using cherrypy\n" ]
[ 5, 5, 4, 3, 2, 0 ]
[]
[]
[ "cherrypy", "python", "template_engine", "templates" ]
stackoverflow_0000993029_cherrypy_python_template_engine_templates.txt
Q: How to make shell output redirect (>) write while script is still running? I wrote a short script that never terminates. This script continuously generates output that I have to check on every now and then. I'm running it on a lab computer through SSH, and redirecting the output to a file in my public_html folder on that machine. python script.py > ~/public_html/results.txt However, the results don't show up immediately when I refresh the address. The results show up when I terminate the program, but as I said, it doesn't halt by itself. Is that redirect (>) being lazy with with writing? Is there a way to continuously (or with an interval) update the results in the file? Or is it the webserver that doesn't update the file while it is still being written? A: You need to flush the output sys.stdout.flush() (or smth) if you want to see it immediately. See this A: stdout is buffered, if not connected to terminal. You can change this policy to line-buffering via stdbuf stdbuf -oL python script.py > ~/public_html/results.txt So you don't have to flush in your Python script and keep it IO efficient, if line-buffering is not required. A: I suspect the file is being continuously written, but that the web server is reporting the modified date of the file as the time it was opened, and thus is reporting that no change to the file has occurred and the result is being cached (either at the web server or at the client). I would first try a forced reload (Ctrl+F5 or Ctrl+Shift+R or Shift+<reload_button>) and see if that helps. If it doesn't, then you can try something else. In a separate shell on the server, do tail -f ~/public_html/results.txt Tail prints out the last n lines of the file (where n defaults to 10), but the -f parameter monitors the file and continues to report output as the file grows. This will at least give you confidence that the file is being written to incrementally. I hope that helps.
How to make shell output redirect (>) write while script is still running?
I wrote a short script that never terminates. This script continuously generates output that I have to check on every now and then. I'm running it on a lab computer through SSH, and redirecting the output to a file in my public_html folder on that machine. python script.py > ~/public_html/results.txt However, the results don't show up immediately when I refresh the address. The results show up when I terminate the program, but as I said, it doesn't halt by itself. Is that redirect (>) being lazy with with writing? Is there a way to continuously (or with an interval) update the results in the file? Or is it the webserver that doesn't update the file while it is still being written?
[ "You need to flush the output sys.stdout.flush() (or smth) if you want to see it immediately. See this\n", "stdout is buffered, if not connected to terminal. \nYou can change this policy to line-buffering via stdbuf\nstdbuf -oL python script.py > ~/public_html/results.txt\n\nSo you don't have to flush in your Python script and keep it IO efficient, if line-buffering is not required.\n", "I suspect the file is being continuously written, but that the web server is reporting the modified date of the file as the time it was opened, and thus is reporting that no change to the file has occurred and the result is being cached (either at the web server or at the client).\nI would first try a forced reload (Ctrl+F5 or Ctrl+Shift+R or Shift+<reload_button>) and see if that helps. If it doesn't, then you can try something else.\nIn a separate shell on the server, do\ntail -f ~/public_html/results.txt\n\nTail prints out the last n lines of the file (where n defaults to 10), but the -f parameter monitors the file and continues to report output as the file grows. This will at least give you confidence that the file is being written to incrementally.\nI hope that helps.\n" ]
[ 16, 7, 1 ]
[]
[]
[ "bash", "command_line", "linux", "python", "shell" ]
stackoverflow_0002753350_bash_command_line_linux_python_shell.txt
Q: Has Twisted changed its dependencies? I'm currently working on a Python/Twisted project which is to be distributed and tested on Planetlab. For some reason my code was working on friday and now that I wanted to test a minor change it refuses to work at all: Traceback (most recent call last): File "acn_a4/src/node.py", line 6, in <module> from twisted.internet.protocol import DatagramProtocol File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/__init__.py", line 18, in <module> from twisted.python import compat File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/compat.py", line 146, in <module> import operator File "/home/cdecker/dev/acn/acn_a4/src/operator.py", line 7, in <module> File "/home/cdecker/acn_a4/src/node.py", line 6, in <module> from twisted.internet.protocol import DatagramProtocol File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/internet/protocol.py", line 20, in <module> from twisted.python import log, failure, components File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/log.py", line 19, in <module> from twisted.python import util, context, reflect File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/util.py", line 5, in <module> import os, sys, hmac, errno, new, inspect, warnings File "/usr/lib/python2.5/inspect.py", line 32, in <module> from operator import attrgetter ImportError: cannot import name attrgetter And since I'm pretty new to python I have no idea what could have caused this problem. All suggestions are welcome :-) A: One of your own files, /home/cdecker/dev/acn/acn_a4/src/operator.py shadows Python's builtin operator module. You should rename your own operator.py to something else. You can see the problem here: File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/compat.py", line 146, in <module> import operator File "/home/cdecker/dev/acn/acn_a4/src/operator.py", line 7, in <module> Twisted tries to import operator but Python loads one of your own modules. To prevent stuff like that in the future you should probably not add your src folder to the PYTHONPATH like that. Create a package instead, so that your own files appear as myproject.mymodule and can't shadow builtins. A: ImportError is raised on import statement when a name cannot be imported, because module or package or name doesn't exists. In your case attrgetter doesn't exists in operator module. The first idea is that you define a module called operator in the project's main directory. Modules, or packages, are searched following sys.path order, if you define a module with the same name in your main directory, you are hiding all others module with the same name in the search path.
Has Twisted changed its dependencies?
I'm currently working on a Python/Twisted project which is to be distributed and tested on Planetlab. For some reason my code was working on friday and now that I wanted to test a minor change it refuses to work at all: Traceback (most recent call last): File "acn_a4/src/node.py", line 6, in <module> from twisted.internet.protocol import DatagramProtocol File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/__init__.py", line 18, in <module> from twisted.python import compat File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/compat.py", line 146, in <module> import operator File "/home/cdecker/dev/acn/acn_a4/src/operator.py", line 7, in <module> File "/home/cdecker/acn_a4/src/node.py", line 6, in <module> from twisted.internet.protocol import DatagramProtocol File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/internet/protocol.py", line 20, in <module> from twisted.python import log, failure, components File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/log.py", line 19, in <module> from twisted.python import util, context, reflect File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/util.py", line 5, in <module> import os, sys, hmac, errno, new, inspect, warnings File "/usr/lib/python2.5/inspect.py", line 32, in <module> from operator import attrgetter ImportError: cannot import name attrgetter And since I'm pretty new to python I have no idea what could have caused this problem. All suggestions are welcome :-)
[ "One of your own files, /home/cdecker/dev/acn/acn_a4/src/operator.py shadows Python's builtin operator module. You should rename your own operator.py to something else. \nYou can see the problem here:\nFile \"/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/compat.py\", line 146, in <module>\nimport operator\nFile \"/home/cdecker/dev/acn/acn_a4/src/operator.py\", line 7, in <module>\n\nTwisted tries to import operator but Python loads one of your own modules. \nTo prevent stuff like that in the future you should probably not add your src folder to the PYTHONPATH like that. Create a package instead, so that your own files appear as myproject.mymodule and can't shadow builtins.\n", "ImportError is raised on import statement when a name cannot be imported, because module or package or name doesn't exists. In your case attrgetter doesn't exists in operator module.\nThe first idea is that you define a module called operator in the project's main directory. Modules, or packages, are searched following sys.path order, if you define a module with the same name in your main directory, you are hiding all others module with the same name in the search path.\n" ]
[ 10, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002753552_python_twisted.txt
Q: symlink files newer than X age, then later remove symlink once file ages? i have a large number of files/folders coming in each day that are being sorted automatically to a wide variety of folders. I'm looking for a way to automatically find these files/folders and create symlinks to them all within an "incoming" folder. Searching for file age should be sufficient for finding the files, however searching for age and owner would be ideal. Then once the files/folders being linked to reach a certain age, say 5 days, remove the symlinks to them automatically from the "incoming" folder. Is this possible to do with a simple shell or python script that can be run with cron? Thanks! A: Use incron to create the symlink, then find -L in cron to break it. A: Not quite sure what you want the symlinks to but here's a first shot: find /incoming -mtime -5 -user nr -exec ln -s '{}' /usr/local/symlinks ';' Finds anything in /incoming owned by nr less than 5 days old and links it into /usr/local/symlinks. Unfortunately ln doesn't have a nice option to ignore something that already exists. You are better off writing a script that links things in, and at the same time you can make things much more efficient: find /incoming -mtime -5 -user nr -print0 | xargs -0 mylink Where mylink has #!/bin/bash for i do link=/usr/local/symlinks/"$(basename "$i")" [[ -L "$link" ]] || ln -s "$i" /usr/local/symlinks done If you want to be even more efficient you can accumulate the list of files to be linked in an array and than link them all with one ln command, but that's a lot of notation and I probably wouldn't bother. To remove the symlinks that point to files older than 5 days: find -L /usr/local/symlinks -mtime +5 -user nr -exec rm '{}' ';' or again you can use xargs: find -L /usr/local/symlinks -mtime +5 -user nr -print0 | xargs -0 rm -f
symlink files newer than X age, then later remove symlink once file ages?
i have a large number of files/folders coming in each day that are being sorted automatically to a wide variety of folders. I'm looking for a way to automatically find these files/folders and create symlinks to them all within an "incoming" folder. Searching for file age should be sufficient for finding the files, however searching for age and owner would be ideal. Then once the files/folders being linked to reach a certain age, say 5 days, remove the symlinks to them automatically from the "incoming" folder. Is this possible to do with a simple shell or python script that can be run with cron? Thanks!
[ "Use incron to create the symlink, then find -L in cron to break it.\n", "Not quite sure what you want the symlinks to but here's a first shot:\nfind /incoming -mtime -5 -user nr -exec ln -s '{}' /usr/local/symlinks ';'\n\nFinds anything in /incoming owned by nr less than 5 days old and links it into /usr/local/symlinks. Unfortunately ln doesn't have a nice option to ignore something that already exists. You are better off writing a script that links things in, and at the same time you can make things much more efficient:\nfind /incoming -mtime -5 -user nr -print0 | xargs -0 mylink\n\nWhere mylink has\n#!/bin/bash\nfor i\ndo\n link=/usr/local/symlinks/\"$(basename \"$i\")\"\n [[ -L \"$link\" ]] || ln -s \"$i\" /usr/local/symlinks\ndone\n\nIf you want to be even more efficient you can accumulate the list of files to be linked\nin an array and than link them all with one ln command, but that's a lot of notation and I probably wouldn't bother.\nTo remove the symlinks that point to files older than 5 days:\nfind -L /usr/local/symlinks -mtime +5 -user nr -exec rm '{}' ';'\n\nor again you can use xargs:\nfind -L /usr/local/symlinks -mtime +5 -user nr -print0 | xargs -0 rm -f\n\n" ]
[ 2, 1 ]
[]
[]
[ "bash", "linux", "python", "scripting", "unix" ]
stackoverflow_0002752915_bash_linux_python_scripting_unix.txt
Q: App Engine Django Form Uniqueness Validation? Is there a simpler way to use uniqueness validation with Django Forms in AppEngine? I understand that performance would be problem if we keep an uniqueness constraint but since the amount of data being added is very small performance is not a big concern, rather development time is a concern here. Any help is appreciated. A: You can use keys for uniqueness: The complete key of an entity, including the path, the kind and the name or numeric ID, is unique and specific to that entity. The complete key is assigned when the entity is created in the datastore, and none of its parts can change... Every entity has an identifier. An application can assign its own identifier for use in the key by giving the instance constructor a key_name argument (a str value): s = Story(key_name="xzy123") ...Once the entity has been created, its ID or name cannot be changed. EDIT As jbochi noted, this could be dangerous and you could loss data. Another way to achieve the same is using an hash function with shard counters. A good example is showed in "Paging through large datasets" article.
App Engine Django Form Uniqueness Validation?
Is there a simpler way to use uniqueness validation with Django Forms in AppEngine? I understand that performance would be problem if we keep an uniqueness constraint but since the amount of data being added is very small performance is not a big concern, rather development time is a concern here. Any help is appreciated.
[ "You can use keys for uniqueness:\n\nThe complete key of an entity,\nincluding the path, the kind and the\nname or numeric ID, is unique and\nspecific to that entity. The complete\nkey is assigned when the entity is\ncreated in the datastore, and none of\nits parts can change...\nEvery entity has an identifier. An\napplication can assign its own\nidentifier for use in the key by\ngiving the instance constructor a\nkey_name argument (a str value):\n\ns = Story(key_name=\"xzy123\")\n\n\n...Once the entity has been created, its\nID or name cannot be changed.\n\nEDIT\nAs jbochi noted, this could be dangerous and you could loss data. Another way to achieve the same is using an hash function with shard counters. A good example is showed in \"Paging through large datasets\" article.\n" ]
[ 1 ]
[]
[]
[ "django_forms", "google_app_engine", "python" ]
stackoverflow_0002753623_django_forms_google_app_engine_python.txt
Q: Python 2.4 inline if statements I am setting up an existing django project on a dreamhost web server, so far I have got everything to work correctly. However I developed under python 2.5 and dreamhost by default uses python 2.4. The following line seems gives a syntax error because of the if keyword: 'parent': c.parent.pk if c.parent is not None else None ^ Is it the case that this form of if statement was introduced in Python 2.5, if so is there an easy change that would make it compatible with Python 2.4? Or, should I just change to Python 2.5. I have already installed python 2.5 to a directory under my home directory, and have succeeded in running the python interpreter under 2.5. If I wish to use Python 2.5 for everything, where can I set this? A: Yes, this kind of inline if was added with 2.5, released almost 4 years ago. You can update your Dreamhost version like this A: http://www.diveintopython.net/power_of_introspection/and_or.html (1 and [a] or [b])[0] 'parent': (c.parent is not None and [c.parent.pk] else [None])[0]
Python 2.4 inline if statements
I am setting up an existing django project on a dreamhost web server, so far I have got everything to work correctly. However I developed under python 2.5 and dreamhost by default uses python 2.4. The following line seems gives a syntax error because of the if keyword: 'parent': c.parent.pk if c.parent is not None else None ^ Is it the case that this form of if statement was introduced in Python 2.5, if so is there an easy change that would make it compatible with Python 2.4? Or, should I just change to Python 2.5. I have already installed python 2.5 to a directory under my home directory, and have succeeded in running the python interpreter under 2.5. If I wish to use Python 2.5 for everything, where can I set this?
[ "Yes, this kind of inline if was added with 2.5, released almost 4 years ago. You can update your Dreamhost version like this\n", "http://www.diveintopython.net/power_of_introspection/and_or.html\n(1 and [a] or [b])[0]\n'parent': (c.parent is not None and [c.parent.pk] else [None])[0]\n\n" ]
[ 4, 2 ]
[]
[]
[ "django", "dreamhost", "python", "python_2.4", "python_2.5" ]
stackoverflow_0002753664_django_dreamhost_python_python_2.4_python_2.5.txt
Q: Programatically importing a file and creating an instance of a class in Python I have a (python) list of strings which refer to python source files and subsequently classes within those files which I want to import and then create an instance of the classes within the files (everything follows a strict naming convention, making this theoretically possible), in Ruby I would do something like: require "lib/sources/#{source}.rb" s = source.constantize.new How would I do something similar in Python? Thanks, Ben A: Please see Dynamic Module Loading in Python: If you have a need to import a module in python and, for whatever reason, you will not know the name of the module until run-time, python provides the built-in __import__ function.
Programatically importing a file and creating an instance of a class in Python
I have a (python) list of strings which refer to python source files and subsequently classes within those files which I want to import and then create an instance of the classes within the files (everything follows a strict naming convention, making this theoretically possible), in Ruby I would do something like: require "lib/sources/#{source}.rb" s = source.constantize.new How would I do something similar in Python? Thanks, Ben
[ "Please see Dynamic Module Loading in Python:\n\nIf you have a need to import a module\n in python and, for whatever reason,\n you will not know the name of the\n module until run-time, python provides\n the built-in __import__ function.\n\n" ]
[ 3 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0002753916_metaprogramming_python.txt
Q: Complex form widgets in Django I am looking for good helper libraries to generate a rather complex form in Django. Dynamic field dependencies: Say if option a is selected certain fields are shown/hidden and subset of these are mandatory depending on option selection. Add more: On clicking "Add more" button that clones some widget. This is something which ToscaWidgets is capable of handle. http://toscawidgets.org/documentation/tw.dynforms/tutorial.html#growing Some working ToscaWidgets Demos Currently I am managing this with some jquery code however not completely satisfied. And sadly cant use ToscaWidgets for some reason. TIA A: I've used a heavily customized Formset to make a rather complicated form with complicated user permission dependencies. This involved subclassing django.forms.formsets.BaseFormSet, overriding __init__, add_fields, is_valid, and save, and of course using a customized Form. The end-product was a bit hairy, but I'm still able to understand and modify it after 6 months or so. I didn't make use of the Formset ability to work with adding and subtracting subforms, but this should meet your needs. Documentation at: http://docs.djangoproject.com/en/1.1/topics/forms/formsets/ A: After searching a little more I found one solution. django-dynamic-formset based on django formsets solves the purpose. Impressive work PS: Will try to add some screenshots later.
Complex form widgets in Django
I am looking for good helper libraries to generate a rather complex form in Django. Dynamic field dependencies: Say if option a is selected certain fields are shown/hidden and subset of these are mandatory depending on option selection. Add more: On clicking "Add more" button that clones some widget. This is something which ToscaWidgets is capable of handle. http://toscawidgets.org/documentation/tw.dynforms/tutorial.html#growing Some working ToscaWidgets Demos Currently I am managing this with some jquery code however not completely satisfied. And sadly cant use ToscaWidgets for some reason. TIA
[ "I've used a heavily customized Formset to make a rather complicated form with complicated user permission dependencies. This involved subclassing django.forms.formsets.BaseFormSet, overriding __init__, add_fields, is_valid, and save, and of course using a customized Form. The end-product was a bit hairy, but I'm still able to understand and modify it after 6 months or so.\nI didn't make use of the Formset ability to work with adding and subtracting subforms, but this should meet your needs.\nDocumentation at: http://docs.djangoproject.com/en/1.1/topics/forms/formsets/\n", "After searching a little more I found one solution. django-dynamic-formset based on django formsets solves the purpose. Impressive work\nPS: Will try to add some screenshots later.\n" ]
[ 3, 2 ]
[]
[]
[ "django", "forms", "jquery", "python" ]
stackoverflow_0002689739_django_forms_jquery_python.txt
Q: Using JRuby/Jython for Ruby/Python interoperability? Quite-probably a silly question, as I don't know much about Java/Jython/JRuby/bytecode, but.. I stumbled across _why's unholy again today.. It allows you to output Python bytecode from Ruby code.. Basically allowing them to produce the same bytecode.. Jython outputs Java bytecode, as does JRuby.. Since these both compile to the same bytecode, does this mean you could potentially use any Python library from Ruby, and Ruby libraries from Python? A: No, that won't work. At least not the way you think it would. Interoperability between Jython and JRuby works the same way as between CPython and YARV: they both run on the same platform, so they can communicate with each other using that platform. In the case of CPython and YARV, that platform is C/POSIX, so they can communicate with each other using C structs, ints, char*s and C function calls. In the case of Jython and JRuby, that platform is the JVM, so they can communicate with each other using JVM objects, JVM classes, JVM interfaces, JVM types and JVM methods. In both cases, those platform primitives look nothing like Python or Ruby objects. To JRuby, Jython is just yet another Java program. To Jython, JRuby is just another Java program. For example: in Ruby, you can add, remove and redefine methods dynamically at any moment. On the JVM, the smallest unit of code that can be dynamically added and removed is a class. So, a Ruby method is actually not represented as a Java method. It is represented as a Java class. And logically, a Ruby object with a couple of methods is represented as a Java object with no methods, just a Dictionary<String, RubyMethod> field. IOW: it's totally unusable from Java, and, since from JRuby's point of view Jython is just Java, it's also unusable from Jython. Now, there are ways to make this a little bit better. You could use actual Java types to communicate between the two – both implementations have great interoperability with Java. So, instead of passing a Ruby hash to Python or a Python dictionary to Ruby, you would use a Java Map from both Ruby and Python. But note that this requires that both your Ruby and Python code are specifically written to work on the JVM. IOW: you cannot just use any Python or Ruby library you find on the web, which is what you are asking about. Another possibility is the one mentioned by @duncan in his answer: embed Jython or JRuby as a scripting engine into your Ruby or Python application. But again, this doesn't really answer your question about using arbitrary Python libraries from Ruby or vice versa. So, what is the problem here? The problem is that in order for the two runtimes to communicate, they need to speak the same "language". And in this particular case, the only language that the two runtimes have in common, is Java, or rather a severely crippled subset of Java. So, we need to find a common language. One way to define such a language would be for both runtimes to understand each other's Meta-Object Protocol (MOP). A MOP is basically an object model for the language's object model. Um, that's confusing because we use the word "object model" to mean two different things. Let me rephrase that: A MOP is basically a domain model for the language's object system. Just like a domain model for a banking system contains objects that represent real-world customers, accounts, balances, ledgers and so on, and methods that represent real-world actions like money transfers, withdrawals and so on, a MOP contains objects that represent language classes, methods, variables, objects and methods that represent language actions like looking up a variable, calling a method, inheriting from a class, constructing an instance of a class. Normally, every runtime keeps its MOP private, and every runtime has its own MOP. If JRuby and Jython exposed their MOPs to each other and understood each other's MOPs (or, even better yet: they exposed their MOPs to the JVM and both used the same MOP), then you could pass one of those crazy JRuby method bags to Jython, and it would know how to find the methods that belong to that object and how to call them, because it can just ask JRuby's MOP how to do it. There is actually a project to create just such a MOP for the JVM: the dynalang MOP is a project for a shared, standardized MOP for dynamic languages running on the JVM. It was created by Attila Szegedi, the maintainer of the Mozilla Rhino ECMAScript engine. At the moment, none of the big language implementations uses it, but there is collaboration going on between at least Rhino, JRuby, Jython and Groovy to make sure that dynalang is generic enough that it can support all of the different language's object models. If you want a sneak peek at what a world with such a shared MOP would look like, you can take a look at Microsoft's Dynamic Language Runtime (DLR). The DLR contains just such a MOP and all runtimes which support the DLR (which, in addition to the usual suspects such as IronRuby, IronPython, IronJS and IronScheme now also includes C# 4 and Visual Basic.NET 10) can almost seamlessly interoperate with each other. Another similar platform is the Parrot Virtual Machine, which was specifically designed to allow multiple dynamic languages to interoperate on the same runtime platform. There are implementations of Python (Pynie) and Ruby (Cardinal) available, but especially Cardinal is still very far from being even a remotely complete Ruby implementation. A: There are two ways to do it. Both offer the ability to statically compile code and produce a real Java class from the script. Jython AFAIK in this case generates Java source code and then calls javac, via an jythonc script. But this requires compilation. For both interpreters, you can call Java code from scripts, and you can embed the interpreter in a Java application. For example, to call Java from Python: >>> from java.util import Random >>> r = Random() >>> r.nextInt() 501203849 To embed JRuby interpreter in Java, you can do (note, there is a JSR223 based way too, this is the core one): package vanilla; import org.jruby.embed.ScriptingContainer; public class HelloWorld { private HelloWorld() { ScriptingContainer container = new ScriptingContainer(); container.runScriptlet("puts Hello world"); } public static void main(String[] args) { new HelloWorld(); } You could do the same from Jyton (I guess you would need to give the jruby paths correctly): import org.jruby.embed.ScriptingContainer container = ScriptingContainer() container.runScriptlet("puts Hello world") The same can be done the other way around. You won't get the whole ruby stdlib exported to the python interpreter by doing an import. You would need to precompile ruby's stdlib to bytecode in advance. However with the technique described above, and adding a couple of helper scripts and defined interfaces, you can bridge specific functionality from one language to the other.
Using JRuby/Jython for Ruby/Python interoperability?
Quite-probably a silly question, as I don't know much about Java/Jython/JRuby/bytecode, but.. I stumbled across _why's unholy again today.. It allows you to output Python bytecode from Ruby code.. Basically allowing them to produce the same bytecode.. Jython outputs Java bytecode, as does JRuby.. Since these both compile to the same bytecode, does this mean you could potentially use any Python library from Ruby, and Ruby libraries from Python?
[ "No, that won't work. At least not the way you think it would.\nInteroperability between Jython and JRuby works the same way as between CPython and YARV: they both run on the same platform, so they can communicate with each other using that platform.\nIn the case of CPython and YARV, that platform is C/POSIX, so they can communicate with each other using C structs, ints, char*s and C function calls. In the case of Jython and JRuby, that platform is the JVM, so they can communicate with each other using JVM objects, JVM classes, JVM interfaces, JVM types and JVM methods.\nIn both cases, those platform primitives look nothing like Python or Ruby objects.\nTo JRuby, Jython is just yet another Java program. To Jython, JRuby is just another Java program.\nFor example: in Ruby, you can add, remove and redefine methods dynamically at any moment. On the JVM, the smallest unit of code that can be dynamically added and removed is a class. So, a Ruby method is actually not represented as a Java method. It is represented as a Java class. And logically, a Ruby object with a couple of methods is represented as a Java object with no methods, just a Dictionary<String, RubyMethod> field. IOW: it's totally unusable from Java, and, since from JRuby's point of view Jython is just Java, it's also unusable from Jython.\nNow, there are ways to make this a little bit better. You could use actual Java types to communicate between the two – both implementations have great interoperability with Java. So, instead of passing a Ruby hash to Python or a Python dictionary to Ruby, you would use a Java Map from both Ruby and Python. But note that this requires that both your Ruby and Python code are specifically written to work on the JVM. IOW: you cannot just use any Python or Ruby library you find on the web, which is what you are asking about.\nAnother possibility is the one mentioned by @duncan in his answer: embed Jython or JRuby as a scripting engine into your Ruby or Python application. But again, this doesn't really answer your question about using arbitrary Python libraries from Ruby or vice versa.\nSo, what is the problem here?\nThe problem is that in order for the two runtimes to communicate, they need to speak the same \"language\". And in this particular case, the only language that the two runtimes have in common, is Java, or rather a severely crippled subset of Java.\nSo, we need to find a common language. One way to define such a language would be for both runtimes to understand each other's Meta-Object Protocol (MOP).\nA MOP is basically an object model for the language's object model. Um, that's confusing because we use the word \"object model\" to mean two different things. Let me rephrase that:\nA MOP is basically a domain model for the language's object system. Just like a domain model for a banking system contains objects that represent real-world customers, accounts, balances, ledgers and so on, and methods that represent real-world actions like money transfers, withdrawals and so on, a MOP contains objects that represent language classes, methods, variables, objects and methods that represent language actions like looking up a variable, calling a method, inheriting from a class, constructing an instance of a class.\nNormally, every runtime keeps its MOP private, and every runtime has its own MOP.\nIf JRuby and Jython exposed their MOPs to each other and understood each other's MOPs (or, even better yet: they exposed their MOPs to the JVM and both used the same MOP), then you could pass one of those crazy JRuby method bags to Jython, and it would know how to find the methods that belong to that object and how to call them, because it can just ask JRuby's MOP how to do it.\nThere is actually a project to create just such a MOP for the JVM: the dynalang MOP is a project for a shared, standardized MOP for dynamic languages running on the JVM. It was created by Attila Szegedi, the maintainer of the Mozilla Rhino ECMAScript engine. At the moment, none of the big language implementations uses it, but there is collaboration going on between at least Rhino, JRuby, Jython and Groovy to make sure that dynalang is generic enough that it can support all of the different language's object models.\nIf you want a sneak peek at what a world with such a shared MOP would look like, you can take a look at Microsoft's Dynamic Language Runtime (DLR). The DLR contains just such a MOP and all runtimes which support the DLR (which, in addition to the usual suspects such as IronRuby, IronPython, IronJS and IronScheme now also includes C# 4 and Visual Basic.NET 10) can almost seamlessly interoperate with each other.\nAnother similar platform is the Parrot Virtual Machine, which was specifically designed to allow multiple dynamic languages to interoperate on the same runtime platform. There are implementations of Python (Pynie) and Ruby (Cardinal) available, but especially Cardinal is still very far from being even a remotely complete Ruby implementation.\n", "There are two ways to do it. Both offer the ability to statically compile code and produce a real Java class from the script. Jython AFAIK in this case generates Java source code and then calls javac, via an jythonc script. But this requires compilation.\nFor both interpreters, you can call Java code from scripts, and you can embed the interpreter in a Java application.\nFor example, to call Java from Python:\n>>> from java.util import Random\n>>> r = Random()\n>>> r.nextInt()\n501203849\n\nTo embed JRuby interpreter in Java, you can do (note, there is a JSR223 based way too, this is the core one):\npackage vanilla;\n\nimport org.jruby.embed.ScriptingContainer;\n\npublic class HelloWorld {\n\n private HelloWorld() {\n ScriptingContainer container = new ScriptingContainer();\n container.runScriptlet(\"puts Hello world\");\n }\n\n public static void main(String[] args) {\n new HelloWorld();\n }\n\nYou could do the same from Jyton (I guess you would need to give the jruby paths correctly):\nimport org.jruby.embed.ScriptingContainer\ncontainer = ScriptingContainer()\ncontainer.runScriptlet(\"puts Hello world\")\n\nThe same can be done the other way around.\nYou won't get the whole ruby stdlib exported to the python interpreter by doing an import. You would need to precompile ruby's stdlib to bytecode in advance.\nHowever with the technique described above, and adding a couple of helper scripts and defined interfaces, you can bridge specific functionality from one language to the other.\n" ]
[ 7, 5 ]
[]
[]
[ "bytecode", "jruby", "jython", "python", "ruby" ]
stackoverflow_0002752979_bytecode_jruby_jython_python_ruby.txt
Q: Have I checked every consecutive subset of this list? I'm trying to solve problem 50 on Project Euler. Don't give me the answer or solve it for me, just try to answer this specific question. The goal is to find the longest sum of consecutive primes that adds to a prime below one million. I wrote a sieve to find all the primes below n, and I have confirmed that it is correct. Next, I am going to check the sum of each subset of consecutive primes using the following method: I have a empty list sums. For each prime number, I add it to each element in sums and check the new sum, then I append the prime to sums. Here it is in python primes = allPrimesBelow(1000000) sums = [] for p in primes: for i in range(len(sums)): sums[i] += p check(sums[i]) sums.append(p) I want to know if I have called check() for every sum of two or more consecutive primes below one million The problem says that there is a prime, 953, that can be written as the sum of 21 consecutive primes, but I am not finding it. A: Your code is correct. I ran it and it does generate the number 953, so the problem is probably with your prime generating function. There should be 78498 primes below a million - you may want to check if you get that result. That said, your code will take a long time to run, since it will call check() 3,080,928,753 times. You may want to find a method that checks less sums. I won't expand on this since you asked for no spoilers, but let me know if you're interested in general hints. A: I don't have a straight answer off the top of my head, but have you tried making sums into a nested array and then appending primes p to the sub-arrays instead of adding them to a summation counter? That would let you visually check which primes were being added to each sub-array, and by extension would tell you which primes the original code was summing up.
Have I checked every consecutive subset of this list?
I'm trying to solve problem 50 on Project Euler. Don't give me the answer or solve it for me, just try to answer this specific question. The goal is to find the longest sum of consecutive primes that adds to a prime below one million. I wrote a sieve to find all the primes below n, and I have confirmed that it is correct. Next, I am going to check the sum of each subset of consecutive primes using the following method: I have a empty list sums. For each prime number, I add it to each element in sums and check the new sum, then I append the prime to sums. Here it is in python primes = allPrimesBelow(1000000) sums = [] for p in primes: for i in range(len(sums)): sums[i] += p check(sums[i]) sums.append(p) I want to know if I have called check() for every sum of two or more consecutive primes below one million The problem says that there is a prime, 953, that can be written as the sum of 21 consecutive primes, but I am not finding it.
[ "Your code is correct. I ran it and it does generate the number 953, so the problem is probably with your prime generating function. There should be 78498 primes below a million - you may want to check if you get that result.\nThat said, your code will take a long time to run, since it will call check() 3,080,928,753 times. You may want to find a method that checks less sums. I won't expand on this since you asked for no spoilers, but let me know if you're interested in general hints.\n", "I don't have a straight answer off the top of my head, but have you tried making sums into a nested array and then appending primes p to the sub-arrays instead of adding them to a summation counter? That would let you visually check which primes were being added to each sub-array, and by extension would tell you which primes the original code was summing up.\n" ]
[ 5, 0 ]
[]
[]
[ "list", "primes", "proof", "python" ]
stackoverflow_0002754003_list_primes_proof_python.txt
Q: Node.js as a custom (streaming) upload handler for Django I want to build an upload-centric app using Django. One way to do this is with nginx's upload module (nonblocking) but it has its problems. Node.js is supposed to be a good candidate for this type of application. But how can I make node.js act as an upload_handler() for Django? I'm not sure where to look for examples? A: Okay I'm not like an expert on the subject or anything, but the way I think I understand it, nginx is a proxy that runs in front of the webserver that serves your django app, right? You could build a simple node.js server that does the same - listen on port 80, wait until the request is completely sent to the server, and then forward it to the webserver that serves the Django app. If your problem is that the webservers threads are being used up by long running uploads, then I think this would solve that problem. Here's some code - just off the top of my head var http = require('http'); var server = http.createServer(function (req, res) { var headers = req.headers; var url = req.url; var method = req.method; var body = ''; req.addListener('data', function(chunk) { body += chunk; }); req.addListener('end', function() { // at this point the request is completely uploaded (including files) // so it can be forwarded to the django webserver var dj_client = http.createClient(8000, 'localhost'); var dj_req = dj_client.request(method, url, headers); dj_req.addListener('response', function (dj_res) { // here the response have been received from the django server // so we can return that to the waiting client res.writeHead(dj_res.status, dj_res.headers); dj_res.addListener('data', res.write); dj_res.addListener('end', res.close); }); // send the request to the django webserver dj_req.write(body); dj_req.close(); }); }); server.listen(80); A: Make node.js write the file to disk and proxy the upload POST to Django along with a '_node_file' value so your Django view knows where to get the file.
Node.js as a custom (streaming) upload handler for Django
I want to build an upload-centric app using Django. One way to do this is with nginx's upload module (nonblocking) but it has its problems. Node.js is supposed to be a good candidate for this type of application. But how can I make node.js act as an upload_handler() for Django? I'm not sure where to look for examples?
[ "Okay I'm not like an expert on the subject or anything, but the way I think I understand it, nginx is a proxy that runs in front of the webserver that serves your django app, right?\nYou could build a simple node.js server that does the same - listen on port 80, wait until the request is completely sent to the server, and then forward it to the webserver that serves the Django app. If your problem is that the webservers threads are being used up by long running uploads, then I think this would solve that problem.\nHere's some code - just off the top of my head\nvar http = require('http');\n\nvar server = http.createServer(function (req, res) {\n var headers = req.headers;\n var url = req.url;\n var method = req.method;\n var body = '';\n req.addListener('data', function(chunk) {\n body += chunk;\n });\n req.addListener('end', function() {\n // at this point the request is completely uploaded (including files)\n // so it can be forwarded to the django webserver\n\n var dj_client = http.createClient(8000, 'localhost');\n var dj_req = dj_client.request(method, url, headers);\n dj_req.addListener('response', function (dj_res) {\n // here the response have been received from the django server\n // so we can return that to the waiting client\n res.writeHead(dj_res.status, dj_res.headers);\n\n dj_res.addListener('data', res.write);\n dj_res.addListener('end', res.close);\n });\n\n // send the request to the django webserver\n dj_req.write(body);\n dj_req.close();\n });\n});\n\nserver.listen(80);\n\n", "Make node.js write the file to disk and proxy the upload POST to Django along with a '_node_file' value so your Django view knows where to get the file.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "javascript", "node.js", "python", "uploading" ]
stackoverflow_0002403280_django_javascript_node.js_python_uploading.txt
Q: Do i have to store mails in db? Are received mails stored somewhere in google app engine app or have i to store it with separated db class? A: No, you don't need to store mails in the datastore. Incoming emails generate http requests and you just need to associate script handlers to email addresses. See the documentation.
Do i have to store mails in db?
Are received mails stored somewhere in google app engine app or have i to store it with separated db class?
[ "No, you don't need to store mails in the datastore. Incoming emails generate http requests and you just need to associate script handlers to email addresses. See the documentation.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002754427_google_app_engine_python.txt
Q: how to make site show different language(chinese and english) on google-app-engine if you using django ,you can use the "LC_MESSAGES -->django.po" but has any way to do this on gae ? and how to .. thanks and if i only want to use django's this features, how can i import it? A: Try this snippet: urls.py: from django.conf import settings try: settings.configure() except: pass settings.LANGUAGE_CODE = 'zh-tw' settings.USE_I18N = True appdir = os.path.abspath( os.path.dirname( __file__ ) ) settings.LOCALE_PATHS = ( os.path.join( appdir, 'locale' ), ) from django.utils.translation import * for each request: class Page(webapp.RequestHandler): def getLanguage(self): try: language = self.request.cookies['django_language'] self.locate = language logging.info( "Get Language as %s" % self.locate ) except: from django.conf import settings self.locate = settings.LANGUAGE_CODE logging.info( "Set Language as %s" % self.locate ) translation.activate( self.locate ) def get(self): self.getLanguage() #... A: I had the same question, and it was answered here. That way I managed to internationalize my GAE app by using standard gettext tools. If your app is open source, you can even enjoy translations on Launchpad!
how to make site show different language(chinese and english) on google-app-engine
if you using django ,you can use the "LC_MESSAGES -->django.po" but has any way to do this on gae ? and how to .. thanks and if i only want to use django's this features, how can i import it?
[ "Try this snippet:\nurls.py:\nfrom django.conf import settings\ntry:\n settings.configure()\nexcept:\n pass\nsettings.LANGUAGE_CODE = 'zh-tw'\nsettings.USE_I18N = True\nappdir = os.path.abspath( os.path.dirname( __file__ ) )\nsettings.LOCALE_PATHS = ( \n os.path.join( appdir, 'locale' ),\n )\nfrom django.utils.translation import *\n\nfor each request:\nclass Page(webapp.RequestHandler):\n def getLanguage(self):\n try:\n language = self.request.cookies['django_language']\n self.locate = language\n logging.info( \"Get Language as %s\" % self.locate )\n except:\n from django.conf import settings\n self.locate = settings.LANGUAGE_CODE\n logging.info( \"Set Language as %s\" % self.locate ) \n translation.activate( self.locate )\n def get(self):\n self.getLanguage()\n #...\n\n", "I had the same question, and it was answered here.\nThat way I managed to internationalize my GAE app by using standard gettext tools. If your app is open source, you can even enjoy translations on Launchpad!\n" ]
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002752333_django_google_app_engine_python.txt
Q: How do I configure multiple Ubuntu Python installations to avoid App Engine's SSL error? I have Karmic Koala which has Python 2.6 installed by default. However I can't run any Python App Engine projects because they require Python 2.5 and python ssl. To install ssl I installed python2.5-dev first while following some instructions I found elsewhere. sudo apt-get install libssl-dev sudo apt-get install python-setuptools sudo apt-get install python2.5-dev sudo easy_install-2.5 pyopenssl However, I am afraid this is not good for my Ubuntu installation since Ubuntu expects to see version 2.6 of Python when you type 'python' on the command line. Instead, it says '2.5.5'. But App Engine still doesn't work after all this. I continue to get an SSL-related error whenever I try to run my Python app: AttributeError: 'module' object has no attribute 'HTTPSHandler' UPDATE1: Just checked whether SSL actually installed as a result of those commands by typing this: $ python2.5 Python 2.5.5 (r255:77872, Apr 29 2010, 23:59:20) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import ssl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named ssl >>> As you can see, SSL is still not installed, which explains the continuing App Engine error. UPDATE2: I tried to revert to the original default version of Python by doing this: sudo ln -s /usr/bin/python2.6 python in my /usr/bin/local folder. Now I get Python 2.6.4 when I type 'python' on the command line. But this doesn't solve my App Engine SSL issue. If anyone knows how I can dig myself out of this hole, I would appreciate it. A: You should be able to simply install Ubuntu's standard copy of Python 2.5. The SSL module isn't a requirement - as the warning message says, it's necessary if you want to do certificate validation, but that's all. The error you're getting with a missing 'HTTPSHandler' is probably due to installing a version of Python that was compiled without SSL support (this is independent of the ssl module, which is what does certificate validation) - again, try installing the standard version. As far as version selection goes, installing Python 2.5 shouldn't intefere with the default system version - there's a selector tool for choosing which version is the default - so you can simply run the dev_appserver etc with 'python2.5 dev_appserver.py'. A: On Ubuntu 9.10, a simple sudo aptitude install python2.5 should do the trick, then just call the scripts by prepending python2.5, like this: python2.5 google_appengine/dev_appserver.py ... On Ubuntu 10.04 however, this is a whole lot different since Python 2.5 is not in the repositories anymore... This means installing from source, and from having had to do it, I can tell you it's not funny. It just makes you wish Google would move on issue 757. Installing the SSL support for Python 2.5 is the same, whether installed from the repos or compiled from source. Just download the SSL lib for 2.5, un-package it, and run sudo python2.5 setup.py install Edit: Comment 51 of previously cited issue explains in detail how to install Python 2.5 on Ubuntu 10.04. As you can see, this is really cumbersome!
How do I configure multiple Ubuntu Python installations to avoid App Engine's SSL error?
I have Karmic Koala which has Python 2.6 installed by default. However I can't run any Python App Engine projects because they require Python 2.5 and python ssl. To install ssl I installed python2.5-dev first while following some instructions I found elsewhere. sudo apt-get install libssl-dev sudo apt-get install python-setuptools sudo apt-get install python2.5-dev sudo easy_install-2.5 pyopenssl However, I am afraid this is not good for my Ubuntu installation since Ubuntu expects to see version 2.6 of Python when you type 'python' on the command line. Instead, it says '2.5.5'. But App Engine still doesn't work after all this. I continue to get an SSL-related error whenever I try to run my Python app: AttributeError: 'module' object has no attribute 'HTTPSHandler' UPDATE1: Just checked whether SSL actually installed as a result of those commands by typing this: $ python2.5 Python 2.5.5 (r255:77872, Apr 29 2010, 23:59:20) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import ssl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named ssl >>> As you can see, SSL is still not installed, which explains the continuing App Engine error. UPDATE2: I tried to revert to the original default version of Python by doing this: sudo ln -s /usr/bin/python2.6 python in my /usr/bin/local folder. Now I get Python 2.6.4 when I type 'python' on the command line. But this doesn't solve my App Engine SSL issue. If anyone knows how I can dig myself out of this hole, I would appreciate it.
[ "You should be able to simply install Ubuntu's standard copy of Python 2.5. The SSL module isn't a requirement - as the warning message says, it's necessary if you want to do certificate validation, but that's all.\nThe error you're getting with a missing 'HTTPSHandler' is probably due to installing a version of Python that was compiled without SSL support (this is independent of the ssl module, which is what does certificate validation) - again, try installing the standard version.\nAs far as version selection goes, installing Python 2.5 shouldn't intefere with the default system version - there's a selector tool for choosing which version is the default - so you can simply run the dev_appserver etc with 'python2.5 dev_appserver.py'.\n", "On Ubuntu 9.10, a simple sudo aptitude install python2.5 should do the trick, then just call the scripts by prepending python2.5, like this:\npython2.5 google_appengine/dev_appserver.py ...\n\nOn Ubuntu 10.04 however, this is a whole lot different since Python 2.5 is not in the repositories anymore... This means installing from source, and from having had to do it, I can tell you it's not funny. It just makes you wish Google would move on issue 757.\nInstalling the SSL support for Python 2.5 is the same, whether installed from the repos or compiled from source. Just download the SSL lib for 2.5, un-package it, and run\nsudo python2.5 setup.py install\n\nEdit: Comment 51 of previously cited issue explains in detail how to install Python 2.5 on Ubuntu 10.04. As you can see, this is really cumbersome!\n" ]
[ 2, 2 ]
[]
[]
[ "google_app_engine", "python", "ssl", "ubuntu_9.10" ]
stackoverflow_0002748963_google_app_engine_python_ssl_ubuntu_9.10.txt