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: Red hat enterprise 5 Linux with Python 2.5 I have to deploy a Django project on Red hat enterprise linux 5, the project has been developed on Python 2.5 but the server environment has Python 2.4 which is causing some issues. I googled a lot over internet to get the Python 2.5 built rpm for the server but there are only src rpm available for the mentioned Linux version. I have not been allowed to compile and use the src rpm due to some system administration issues. Is there any Linux version which is easily available and has python 2.5 as default? or any link to the python 2.5 built rpm. Please suggest. thanks in advance. A: I would recommend ActivePython, it's pretty brain dead easy to install and it works pretty well with redhat in my experience. A: Install the python package from http://iuscommunity.org/ A: This would help you with finding a linux distro with specifications DistroWatch Specifically Ubuntu 8.10 "intrepid" would fit if another distro absolutely has to be the solution. This is a site that specificly talks about the issues you are having and a given work around updating python on rhelc entos This site keeps a list of updates for rhel iuscommunity
Red hat enterprise 5 Linux with Python 2.5
I have to deploy a Django project on Red hat enterprise linux 5, the project has been developed on Python 2.5 but the server environment has Python 2.4 which is causing some issues. I googled a lot over internet to get the Python 2.5 built rpm for the server but there are only src rpm available for the mentioned Linux version. I have not been allowed to compile and use the src rpm due to some system administration issues. Is there any Linux version which is easily available and has python 2.5 as default? or any link to the python 2.5 built rpm. Please suggest. thanks in advance.
[ "I would recommend ActivePython, it's pretty brain dead easy to install and it works pretty well with redhat in my experience.\n", "Install the python package from http://iuscommunity.org/\n", "This would help you with finding a linux distro with specifications DistroWatch\nSpecifically Ubuntu 8.10 \"intrepid\" would fit if another distro absolutely has to be the solution.\n\n\nThis is a site that specificly talks about the issues you are having and a given work around\nupdating python on rhelc entos\n\n\nThis site keeps a list of updates for rhel\niuscommunity\n\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "linux", "python" ]
stackoverflow_0003069842_django_linux_python.txt
Q: How to substitute module.Class() to locally defined Class() when loading with Python's Pickle? I have a pickle dump which has an array of foo.Bar() objects. I am trying to unpickle it, but the Bar() class definition is in the same file that's trying to unpickle, and not in the foo module. So, pickle complains that it couldn't find module foo. I tried to inject foo module doing something similar to: import imp, sys class Bar: pass foo_module = imp.new_module('foo') foo_module.Bar = Bar sys.modules['foo'] = foo_module import foo print foo.Bar() Which works, but when I try to add, after that: import pickle p = pickle.load(open("my-pickle.pkl")) I receive the friendly error: Traceback (most recent call last): File "pyppd.py", line 69, in ppds = loads(ppds_decompressed) File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) File "/tmp/test.py", line 69, in p = pickle.load(open("my-pickle.pkl")) File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named foo Any ideas? A: class Bar: pass class MyUnpickler(pickle.Unpickler): def find_class(self, module, name): if module == "foo" and name == "Bar": return Bar else: return pickle.Unpickler.find_class(self, module, name) bars = MyUnpickler(open("objects.pkl")).load() CAVEAT CAVEAT CAVEAT: If you are calling this snippet of code from another module, let's say baz, then the unpickled objects will be of type baz.Bar, not foo.Bar. Assuming the class definitions of foo.Bar and baz.Bar are the same, you will have no trouble unpickling. But be careful with downstream use of isinstance, type, etc. In general, trying to do this sort of thing for anything but a one-off is probably not smart, because your codebase now contains two instances of Bar. If at all possible you should just put foo in your PATH.
How to substitute module.Class() to locally defined Class() when loading with Python's Pickle?
I have a pickle dump which has an array of foo.Bar() objects. I am trying to unpickle it, but the Bar() class definition is in the same file that's trying to unpickle, and not in the foo module. So, pickle complains that it couldn't find module foo. I tried to inject foo module doing something similar to: import imp, sys class Bar: pass foo_module = imp.new_module('foo') foo_module.Bar = Bar sys.modules['foo'] = foo_module import foo print foo.Bar() Which works, but when I try to add, after that: import pickle p = pickle.load(open("my-pickle.pkl")) I receive the friendly error: Traceback (most recent call last): File "pyppd.py", line 69, in ppds = loads(ppds_decompressed) File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) File "/tmp/test.py", line 69, in p = pickle.load(open("my-pickle.pkl")) File "/usr/lib/python2.6/pickle.py", line 1374, in loads return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named foo Any ideas?
[ "class Bar:\n pass\n\nclass MyUnpickler(pickle.Unpickler):\n def find_class(self, module, name):\n if module == \"foo\" and name == \"Bar\":\n return Bar\n else:\n return pickle.Unpickler.find_class(self, module, name)\n\nbars = MyUnpickler(open(\"objects.pkl\")).load()\n\nCAVEAT CAVEAT CAVEAT:\nIf you are calling this snippet of code from another module, let's say baz, then the unpickled objects will be of type baz.Bar, not foo.Bar. Assuming the class definitions of foo.Bar and baz.Bar are the same, you will have no trouble unpickling. But be careful with downstream use of isinstance, type, etc. In general, trying to do this sort of thing for anything but a one-off is probably not smart, because your codebase now contains two instances of Bar. If at all possible you should just put foo in your PATH.\n" ]
[ 4 ]
[]
[]
[ "import", "pickle", "python" ]
stackoverflow_0003073211_import_pickle_python.txt
Q: Query crashes MS Access THE TASK: I am in the process of migrating a DB from MS Access to Maximizer. In order to do this I must take 64 tables in MS ACCESS and merge them into one. The output must be in the form of a TAB or CSV file. Which will then be imported into Maximizer. THE PROBLEM: Access is unable to perform a query that is so complex it seems, as it crashes any time I run the query. ALTERNATIVES: I have thought about a few alternatives, and would like to do the least time-consuming one, out of these, while also taking advantage of any opportunities to learn something new. Export each table into CSVs and import into SQLight and then make a query with it to do the same as what ACCESS fails to do (merge 64 tables). Export each table into CSVs and write a script to access each one and merge the CSVs into a single CSV. Somehow connect to the MS ACCESS DB (API), and write a script to pull data from each table and merge them into a CSV file. QUESTION: What do you recommend? CLARIFICATIONS: I am merging tables, not concatenating. Each table has a different structure and different data. It is a normalized CRM database. Companies->contacts->details = ~ 60 tables of details. As the Access db will be scuttled after the db is migrated, I want to spend as little time in Access as possible. A: I agree with FrustratedWithFormsDesigner. #2 seems the simplest method. Here is some tested code if you decide to go that route (requires pyodbc): import csv import pyodbc MDB = 'c:/path/to/my.mdb' DRV = '{Microsoft Access Driver (*.mdb)}' PWD = 'mypassword' conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD)) curs = conn.cursor() SQL = 'SELECT * FROM mytable;' # insert your query here curs.execute(SQL) rows = curs.fetchall() curs.close() conn.close() # you could change the 'w' to 'a' for subsequent queries csv_writer = csv.writer(open('mytable.csv', 'w'), lineterminator='\n') for row in rows: csv_writer.writerow(row) A: Since you want to merge 64 tables, may we assume those tables all have the same structure? If so, create a new empty table with matching structure, then append the rows from each of those 64 tables into the new merge master table. Then export the merge master table as a single CSV file. The merge operation should not have to be a single complex query. INSERT INTO tblMergeMaster( some_field, another_field, yet_another) SELECT some_field, another_field, yet_another FROM tbl_1_of_64; You can build the INSERT statement 64 times with VBA code, with a different FROM table each time. And execute each statement with CurrentDb.Execute A: I would recommend #2 if the merge is fairly simple and straightforward, and doesn't need the power of an RDBMS. I'd go with #1 if the merge is more complex and you will need to write some actual queries to get the data merged properly. A: I'm not even clear on what you're trying to do. I assume your problem is that Jet/ACE can't handle a UNION with that many SELECT statements. If you have 64 identically-structured tables and you want them in a single CSV, I'd create a temp table in Access, append each table in turn, then export from the temp table to CSV. This is a simple solution and shouldn't be slow, either. The only possible issue might be if there are dupes, but if there are, you can export from a SELECT DISTINCT saved QueryDef. Tangentially, I'm surprised Maximizer still exists. I had a client who used to use it, and the db structure was terribly unnormalized, just like all the other sales software like ACT.
Query crashes MS Access
THE TASK: I am in the process of migrating a DB from MS Access to Maximizer. In order to do this I must take 64 tables in MS ACCESS and merge them into one. The output must be in the form of a TAB or CSV file. Which will then be imported into Maximizer. THE PROBLEM: Access is unable to perform a query that is so complex it seems, as it crashes any time I run the query. ALTERNATIVES: I have thought about a few alternatives, and would like to do the least time-consuming one, out of these, while also taking advantage of any opportunities to learn something new. Export each table into CSVs and import into SQLight and then make a query with it to do the same as what ACCESS fails to do (merge 64 tables). Export each table into CSVs and write a script to access each one and merge the CSVs into a single CSV. Somehow connect to the MS ACCESS DB (API), and write a script to pull data from each table and merge them into a CSV file. QUESTION: What do you recommend? CLARIFICATIONS: I am merging tables, not concatenating. Each table has a different structure and different data. It is a normalized CRM database. Companies->contacts->details = ~ 60 tables of details. As the Access db will be scuttled after the db is migrated, I want to spend as little time in Access as possible.
[ "I agree with FrustratedWithFormsDesigner. #2 seems the simplest method. \nHere is some tested code if you decide to go that route (requires pyodbc):\nimport csv\nimport pyodbc\n\nMDB = 'c:/path/to/my.mdb'\nDRV = '{Microsoft Access Driver (*.mdb)}'\nPWD = 'mypassword'\n\nconn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))\ncurs = conn.cursor()\n\nSQL = 'SELECT * FROM mytable;' # insert your query here\ncurs.execute(SQL)\n\nrows = curs.fetchall()\n\ncurs.close()\nconn.close()\n\n# you could change the 'w' to 'a' for subsequent queries\ncsv_writer = csv.writer(open('mytable.csv', 'w'), lineterminator='\\n')\n\nfor row in rows:\n csv_writer.writerow(row)\n\n", "Since you want to merge 64 tables, may we assume those tables all have the same structure?\nIf so, create a new empty table with matching structure, then append the rows from each of those 64 tables into the new merge master table. Then export the merge master table as a single CSV file. \nThe merge operation should not have to be a single complex query. \nINSERT INTO tblMergeMaster(\n some_field,\n another_field,\n yet_another)\nSELECT\n some_field,\n another_field,\n yet_another\nFROM\n tbl_1_of_64;\n\nYou can build the INSERT statement 64 times with VBA code, with a different FROM table each time. And execute each statement with CurrentDb.Execute\n", "I would recommend #2 if the merge is fairly simple and straightforward, and doesn't need the power of an RDBMS. I'd go with #1 if the merge is more complex and you will need to write some actual queries to get the data merged properly.\n", "I'm not even clear on what you're trying to do. I assume your problem is that Jet/ACE can't handle a UNION with that many SELECT statements. \nIf you have 64 identically-structured tables and you want them in a single CSV, I'd create a temp table in Access, append each table in turn, then export from the temp table to CSV. This is a simple solution and shouldn't be slow, either. The only possible issue might be if there are dupes, but if there are, you can export from a SELECT DISTINCT saved QueryDef.\nTangentially, I'm surprised Maximizer still exists. I had a client who used to use it, and the db structure was terribly unnormalized, just like all the other sales software like ACT.\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "crm", "ms_access", "python", "sql" ]
stackoverflow_0003064830_crm_ms_access_python_sql.txt
Q: Can I use the google chat image on google app engine? I am writing an app using python on GAE. I figure since I'm using google logins as the authentication for my users, why can't I use each users google chat picture as their user portrait? However I haven't found a way to access that info. Maybe I've been using facebook api's for too long, but is there any way to access that information? Chris A: There is a separate API for retrieving a user's profile information, which unfortunately does not currently support profile pictures.
Can I use the google chat image on google app engine?
I am writing an app using python on GAE. I figure since I'm using google logins as the authentication for my users, why can't I use each users google chat picture as their user portrait? However I haven't found a way to access that info. Maybe I've been using facebook api's for too long, but is there any way to access that information? Chris
[ "There is a separate API for retrieving a user's profile information, which unfortunately does not currently support profile pictures.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_talk", "python" ]
stackoverflow_0003073267_google_app_engine_google_talk_python.txt
Q: Need a way to determine if a file is done being written to The situation I'm in is this - there's a process that's writing to a file, sometimes the file is rather large say 400 - 500MB. I need to know when it's done writing. How can I determine this? If I look in the directory I'll see it there but it might not be done being written. Plus this needs to be done remotely - as in on the same internal LAN but not on the same computer and typically the process that wants to know when the file writing is done is running on a Linux box with a the process that's writing the file and the file itself on a windows box. No samba isn't an option. xmlrpc communication to a service on that windows box is an option as well as using snmp to check if that's viable. Ideally Works on either Linux or Windows - meaning the solution is OS independent. Works for any type of file. Good enough: Works just on windows but can be done through some library or whatever that can be accessed with Python. Works only for PDF files. Current best idea is to periodically open the file in question from some process on the windows box and look at the last bytes checking for the PDF end tag and accounting for the eol differences because the file may have been created on Linux or Windows. A: There are probably many approaches you can take. I would try to open the file with write access. If that succeeds then no-one else is writing to that file. Build a web service around this concept if you don't have direct access to the file between machines. A: I ended up resolving it for our situation. As it turns out the process that was writing the files out had them opened exclusively so all we had to do was try opening them for read access - when denied they were in use.
Need a way to determine if a file is done being written to
The situation I'm in is this - there's a process that's writing to a file, sometimes the file is rather large say 400 - 500MB. I need to know when it's done writing. How can I determine this? If I look in the directory I'll see it there but it might not be done being written. Plus this needs to be done remotely - as in on the same internal LAN but not on the same computer and typically the process that wants to know when the file writing is done is running on a Linux box with a the process that's writing the file and the file itself on a windows box. No samba isn't an option. xmlrpc communication to a service on that windows box is an option as well as using snmp to check if that's viable. Ideally Works on either Linux or Windows - meaning the solution is OS independent. Works for any type of file. Good enough: Works just on windows but can be done through some library or whatever that can be accessed with Python. Works only for PDF files. Current best idea is to periodically open the file in question from some process on the windows box and look at the last bytes checking for the PDF end tag and accounting for the eol differences because the file may have been created on Linux or Windows.
[ "There are probably many approaches you can take. I would try to open the file with write access. If that succeeds then no-one else is writing to that file.\nBuild a web service around this concept if you don't have direct access to the file between machines.\n", "I ended up resolving it for our situation. As it turns out the process that was writing the files out had them opened exclusively so all we had to do was try opening them for read access - when denied they were in use.\n" ]
[ 8, 1 ]
[]
[]
[ "file_io", "linux", "pdf", "python", "windows" ]
stackoverflow_0003070210_file_io_linux_pdf_python_windows.txt
Q: How to download data to b.csv that like a.csv format from gae localhost server My a.csv is: 001,哈哈大学 002,拉拉大学 003,啊啊啊大学 004,文网文大学 005,卡卡卡大学 006,请求权大学 007,凤飞飞大学 And my str_loader.py is: class College(db.Model): cid = db.StringProperty(required=True) name = db.StringProperty(required=True) class CollegeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) loaders = [CollegeLoader] And I use this code to update data to localhost server: appcfg.py upload_data --application=zjm1126 --config_file=upload/str_loader.py --filename=upload/a.csv --kind=College --url=http://localhost:8100/remote_api I want to test download data to b.csv that like a.csv format, So do this: appcfg.py download_data --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv How to download data to b.csv that like a.csv format. I have added this to str_loader.py: class CollegeExporter2(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) exporters = [CollegeExporter2] I use this code to run: appcfg.py download_data --config_file=upload/str_loader.py --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv But, it show error: D:\zjm_demo\app>appcfg.py download_data --config_file=upload/str_loader.py --app lication=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filena me=b.csv Downloading data records. [INFO ] Logging to bulkloader-log-20100619.120030 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INFO ] Batch Size: 10 Traceback (most recent call last): File "d:\Program Files\Google\google_appengine\appcfg.py", line 68, in <module > run_file(__file__, globals()) File "d:\Program Files\Google\google_appengine\appcfg.py", line 64, in run_fil e execfile(script_path, globals_) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2757, in <module> main(sys.argv) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2748, in main result = AppCfgApp(argv).Run() File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 1763, in Run self.action(self) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2619, in __call__ return method() File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2451, in PerformDownload run_fn(args) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2368, in RunBulkloader sys.exit(bulkloader.Run(arg_dict)) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 4014, in Run return _PerformBulkload(arg_dict) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 3837, in _PerformBulkload LoadConfig(config_file) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 3553, in LoadConfig Exporter.RegisterExporter(cls()) File "upload/str_loader.py", line 57, in __init__ ('name', lambda x: unicode(x, 'utf8')), File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 2786, in __init__ for name, fn, default in properties: ValueError: need more than 2 values to unpack And when I run: print repr(open('b.csv', 'rb').read())' I am getting: 'SQLite format 3\x00\x04\x00\x01\x01\x00@ \x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\r\x03\xfc\x00\x03\x02\xd5\x00\x03f\x03\xcf\x02\xd5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x81\x0e\x03\x07\x17GG\x01\x81\x1btablebulkloader_database_signaturebulkloader_database_signature\x04CREATE TABLE bulkloader_database_signature (\n value TEXT not null)g\x01\x07\x17\x19\x19\x01\x81)tableresultresult\x02CREATE TABLE result (\nid BLOB primary key,\nvalue BLOB not null,\nsort_key BLOB)+\x02\x06\x17?\x19\x01\x00indexsqlite_autoindex_result_1result\x03\x00\x00\x00\x04\r\x00\x00\x00\x07\x00\x94\x00\x03\x85\x03\n\x02\x8c\x02\x0e\x01\x90\x01\x12\x00\x94\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|\x07\x05H\x81>\r:College\x00\x0000000000000000000742j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe6\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03007r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x87\xa4\xe9\xa3\x9e\xe9\xa3\x9e\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe6\x05\x0c|\x06\x05H\x81>\r:College\x00\x0000000000000000000741j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe5\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03006r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe8\xaf\xb7\xe6\xb1\x82\xe6\x9d\x83\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe5\x05\x0c|\x05\x05H\x81>\r:College\x00\x0000000000000000000740j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe4\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03005r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x8d\xa1\xe5\x8d\xa1\xe5\x8d\xa1\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe4\x05\x0c|\x04\x05H\x81>\r:College\x00\x0000000000000000000739j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe3\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03004r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe6\x96\x87\xe7\xbd\x91\xe6\x96\x87\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe3\x05\x0c|\x03\x05H\x81>\r:College\x00\x0000000000000000000738j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe2\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03003r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x95\x8a\xe5\x95\x8a\xe5\x95\x8a\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe2\x05\x0cy\x02\x05H\x818\r:College\x00\x0000000000000000000737j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe1\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03002r\x18\x1a\x04name \x00*\x0e\x1a\x0c\xe6\x8b\x89\xe6\x8b\x89\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe1\x05\x0cy\x01\x05H\x818\r:College\x00\x0000000000000000000736j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe0\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03001r\x18\x1a\x04name \x00*\x0e\x1a\x0c\xe5\x93\x88\xe5\x93\x88\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe0\x05\x0c\n\x00\x00\x00\x07\x03\x0b\x00\x03\xdd\x03\xba\x03\x97\x03t\x03Q\x03.\x03\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"\x03H\x01:College\x00\x0000000000000000000742\x07"\x03H\x01:College\x00\x0000000000000000000741\x06"\x03H\x01:College\x00\x0000000000000000000740\x05"\x03H\x01:College\x00\x0000000000000000000739\x04"\x03H\x01:College\x00\x0000000000000000000738\x03"\x03H\x01:College\x00\x0000000000000000000737\x02"\x03H\x01:College\x00\x0000000000000000000736\x01\r\x00\x00\x00\x01\x03!\x00\x03!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x81\\\x01\x03\x83?\n app_id: zjm1126\n url: http://localhost:8100/remote_api\n kind: College\n download: False\n map: False\n dump: True\n restore: False\n progress_db: bulkloader-progress-20100619.121020.sql3\n has_header: False\n \n ' class CollegeExporter2(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'College', [ ('cid', str,None), ('name', lambda x:x.encode('utf8'),None), ],) exporters = [CollegeExporter2] A: As per http://appengine-cookbook.appspot.com/recipe/using-the-python-bulk-exporter-tool-with-a-java-application/ , first add the following to your str_loader.py: class CollegeExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'College', [ ('cid', str, None), ('name', lambda x: unicode(x, 'utf8'), None), ]) exporters = [CollegeExporter] Next, run: appcfg.py update zjm1126 appcfg.py download_data --config_file=upload/str_loader.py --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv Of course you probably ultimately want to create a separate file for download vs. upload, but you get the idea. A: I strongly suggest that you dump the contents of b.csv by issuing the following command at your shell prompt python -c"print repr(open('b.csv', 'rb').read())" That way we can see what is actually in the file. HOWEVER It looks very much like an SQLite3 database -- perhaps you need to explore what options the appcfg.py script has for choosing an output file format.
How to download data to b.csv that like a.csv format from gae localhost server
My a.csv is: 001,哈哈大学 002,拉拉大学 003,啊啊啊大学 004,文网文大学 005,卡卡卡大学 006,请求权大学 007,凤飞飞大学 And my str_loader.py is: class College(db.Model): cid = db.StringProperty(required=True) name = db.StringProperty(required=True) class CollegeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) loaders = [CollegeLoader] And I use this code to update data to localhost server: appcfg.py upload_data --application=zjm1126 --config_file=upload/str_loader.py --filename=upload/a.csv --kind=College --url=http://localhost:8100/remote_api I want to test download data to b.csv that like a.csv format, So do this: appcfg.py download_data --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv How to download data to b.csv that like a.csv format. I have added this to str_loader.py: class CollegeExporter2(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) exporters = [CollegeExporter2] I use this code to run: appcfg.py download_data --config_file=upload/str_loader.py --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv But, it show error: D:\zjm_demo\app>appcfg.py download_data --config_file=upload/str_loader.py --app lication=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filena me=b.csv Downloading data records. [INFO ] Logging to bulkloader-log-20100619.120030 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HTTP connections: 8/second [INFO ] Entities inserted/fetched/modified: 20/second [INFO ] Batch Size: 10 Traceback (most recent call last): File "d:\Program Files\Google\google_appengine\appcfg.py", line 68, in <module > run_file(__file__, globals()) File "d:\Program Files\Google\google_appengine\appcfg.py", line 64, in run_fil e execfile(script_path, globals_) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2757, in <module> main(sys.argv) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2748, in main result = AppCfgApp(argv).Run() File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 1763, in Run self.action(self) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2619, in __call__ return method() File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2451, in PerformDownload run_fn(args) File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p y", line 2368, in RunBulkloader sys.exit(bulkloader.Run(arg_dict)) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 4014, in Run return _PerformBulkload(arg_dict) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 3837, in _PerformBulkload LoadConfig(config_file) File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 3553, in LoadConfig Exporter.RegisterExporter(cls()) File "upload/str_loader.py", line 57, in __init__ ('name', lambda x: unicode(x, 'utf8')), File "d:\Program Files\Google\google_appengine\google\appengine\tools\bulkload er.py", line 2786, in __init__ for name, fn, default in properties: ValueError: need more than 2 values to unpack And when I run: print repr(open('b.csv', 'rb').read())' I am getting: 'SQLite format 3\x00\x04\x00\x01\x01\x00@ \x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\r\x03\xfc\x00\x03\x02\xd5\x00\x03f\x03\xcf\x02\xd5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x81\x0e\x03\x07\x17GG\x01\x81\x1btablebulkloader_database_signaturebulkloader_database_signature\x04CREATE TABLE bulkloader_database_signature (\n value TEXT not null)g\x01\x07\x17\x19\x19\x01\x81)tableresultresult\x02CREATE TABLE result (\nid BLOB primary key,\nvalue BLOB not null,\nsort_key BLOB)+\x02\x06\x17?\x19\x01\x00indexsqlite_autoindex_result_1result\x03\x00\x00\x00\x04\r\x00\x00\x00\x07\x00\x94\x00\x03\x85\x03\n\x02\x8c\x02\x0e\x01\x90\x01\x12\x00\x94\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|\x07\x05H\x81>\r:College\x00\x0000000000000000000742j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe6\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03007r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x87\xa4\xe9\xa3\x9e\xe9\xa3\x9e\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe6\x05\x0c|\x06\x05H\x81>\r:College\x00\x0000000000000000000741j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe5\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03006r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe8\xaf\xb7\xe6\xb1\x82\xe6\x9d\x83\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe5\x05\x0c|\x05\x05H\x81>\r:College\x00\x0000000000000000000740j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe4\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03005r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x8d\xa1\xe5\x8d\xa1\xe5\x8d\xa1\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe4\x05\x0c|\x04\x05H\x81>\r:College\x00\x0000000000000000000739j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe3\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03004r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe6\x96\x87\xe7\xbd\x91\xe6\x96\x87\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe3\x05\x0c|\x03\x05H\x81>\r:College\x00\x0000000000000000000738j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe2\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03003r\x1b\x1a\x04name \x00*\x11\x1a\x0f\xe5\x95\x8a\xe5\x95\x8a\xe5\x95\x8a\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe2\x05\x0cy\x02\x05H\x818\r:College\x00\x0000000000000000000737j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe1\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03002r\x18\x1a\x04name \x00*\x0e\x1a\x0c\xe6\x8b\x89\xe6\x8b\x89\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe1\x05\x0cy\x01\x05H\x818\r:College\x00\x0000000000000000000736j\x19j\x07zjm1126r\x0e\x0b\x12\x07College\x18\xe0\x05\x0cr\x0e\x1a\x03cid \x00*\x05\x1a\x03001r\x18\x1a\x04name \x00*\x0e\x1a\x0c\xe5\x93\x88\xe5\x93\x88\xe5\xa4\xa7\xe5\xad\xa6\x82\x01\x0e\x0b\x12\x07College\x18\xe0\x05\x0c\n\x00\x00\x00\x07\x03\x0b\x00\x03\xdd\x03\xba\x03\x97\x03t\x03Q\x03.\x03\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"\x03H\x01:College\x00\x0000000000000000000742\x07"\x03H\x01:College\x00\x0000000000000000000741\x06"\x03H\x01:College\x00\x0000000000000000000740\x05"\x03H\x01:College\x00\x0000000000000000000739\x04"\x03H\x01:College\x00\x0000000000000000000738\x03"\x03H\x01:College\x00\x0000000000000000000737\x02"\x03H\x01:College\x00\x0000000000000000000736\x01\r\x00\x00\x00\x01\x03!\x00\x03!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x81\\\x01\x03\x83?\n app_id: zjm1126\n url: http://localhost:8100/remote_api\n kind: College\n download: False\n map: False\n dump: True\n restore: False\n progress_db: bulkloader-progress-20100619.121020.sql3\n has_header: False\n \n ' class CollegeExporter2(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'College', [ ('cid', str,None), ('name', lambda x:x.encode('utf8'),None), ],) exporters = [CollegeExporter2]
[ "As per http://appengine-cookbook.appspot.com/recipe/using-the-python-bulk-exporter-tool-with-a-java-application/ , first add the following to your str_loader.py:\nclass CollegeExporter(bulkloader.Exporter):\n def __init__(self):\n bulkloader.Exporter.__init__(self, 'College',\n [\n ('cid', str, None),\n ('name', lambda x: unicode(x, 'utf8'), None),\n ])\nexporters = [CollegeExporter]\n\nNext, run:\nappcfg.py update zjm1126\nappcfg.py download_data --config_file=upload/str_loader.py --application=zjm1126 --kind=College --url=http://localhost:8100/remote_api --filename=b.csv\n\nOf course you probably ultimately want to create a separate file for download vs. upload, but you get the idea.\n", "I strongly suggest that you dump the contents of b.csv by issuing the following command at your shell prompt \npython -c\"print repr(open('b.csv', 'rb').read())\"\n\nThat way we can see what is actually in the file.\nHOWEVER It looks very much like an SQLite3 database -- perhaps you need to explore what options the appcfg.py script has for choosing an output file format.\n" ]
[ 1, 0 ]
[ "by loading the data into an sqlite db and then dumping that via the python csv module.\n" ]
[ -2 ]
[ "format", "google_app_engine", "python" ]
stackoverflow_0003074172_format_google_app_engine_python.txt
Q: How to override equals() in google app engine data model type? I'm using the Python libraries for Google App Engine. How can I override the equals() method on a class so that it judges equality on the user_id field of the following class: class UserAccount(db.Model): # compare all equality tests on user_id user = db.UserProperty(required=True) user_id = db.StringProperty(required=True) first_name = db.StringProperty() last_name = db.StringProperty() notifications = db.ListProperty(db.Key) Right now, I'm doing equalty by getting a UserAccount object and doing user1.user_id == user2.user_id. Is there a way I can override it so that 'user1 == user2' will look at only the 'user_id' fields? Thanks in advance A: Override operators __eq__ (==) and __ne__ (!=) e.g. class UserAccount(db.Model): def __eq__(self, other): if isinstance(other, UserAccount): return self.user_id == other.user_id return NotImplemented def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result return not result
How to override equals() in google app engine data model type?
I'm using the Python libraries for Google App Engine. How can I override the equals() method on a class so that it judges equality on the user_id field of the following class: class UserAccount(db.Model): # compare all equality tests on user_id user = db.UserProperty(required=True) user_id = db.StringProperty(required=True) first_name = db.StringProperty() last_name = db.StringProperty() notifications = db.ListProperty(db.Key) Right now, I'm doing equalty by getting a UserAccount object and doing user1.user_id == user2.user_id. Is there a way I can override it so that 'user1 == user2' will look at only the 'user_id' fields? Thanks in advance
[ "Override operators __eq__ (==) and __ne__ (!=)\ne.g.\nclass UserAccount(db.Model):\n\n def __eq__(self, other):\n if isinstance(other, UserAccount):\n return self.user_id == other.user_id\n return NotImplemented\n\n def __ne__(self, other):\n result = self.__eq__(other)\n if result is NotImplemented:\n return result\n return not result\n\n" ]
[ 14 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003074275_google_app_engine_python_web_applications.txt
Q: How can I iterate over only the first variable of a tuple In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then: for x,y,z in points: pass # do something with x y or z What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python? A: Is something preventing you from not touching variables that you're not interested in? There is a conventional use of underscore in Python to indicate variable that you're not interested. E.g.: for x, _,_ in points: print(x) You need to understand that this is just a convention and has no bearing on performance. A: Yes, the underscore: >>> a=(1,2,3,4) >>> b,_,_,c = a >>> b,c (1, 4) This is not exactly 'skipping', just a convention. Underscore variable still gets the value assigned: >>> _ 3 A: A common way to do this is to use underscores for the unused variables: for x, _, z in points: # use x and z This doesn't actually do anything different from what you wrote. The underscore is a normal variable like any other. But this shows people reading your code that you don't intend to use the variable. It is not advisable to do this in the interactive prompt as _ has a special meaning there: the value of the last run statement/expression. A: While this is not as slick as you're asking for, perhaps this is most legible for your intentions of giving meaningful names only to the tuple indices you care about: for each in points: x = each[0] # do something with x A: In Python 3.1 you can use an asterisk in front of an identifier on the left side of a tuple assignment and it will suck up whatever is left over. This construct will handle a variable number of tuple items. Like this: >>> tpl = 1,2,3,4,5 >>> a, *b = tpl >>> a 1 >>> b >>> (2, 3, 4, 5) Or in various orders and combinations: >>> a, *b, c = tpl >>> a 1 >>> b (2, 3, 4) >>> c 5 So, for the case you asked about, where you're only interested in the first item, use *_ to suck up and discard the remaining items you don't care about: >>> a, *_ = tpl >>> a 1
How can I iterate over only the first variable of a tuple
In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then: for x,y,z in points: pass # do something with x y or z What if you only want to use the first variable, or the first and the third. Is there any skipping symbol in python?
[ "Is something preventing you from not touching variables that you're not interested in? There is a conventional use of underscore in Python to indicate variable that you're not interested. E.g.:\nfor x, _,_ in points:\n print(x)\n\nYou need to understand that this is just a convention and has no bearing on performance.\n", "Yes, the underscore:\n>>> a=(1,2,3,4)\n>>> b,_,_,c = a\n>>> b,c\n(1, 4)\n\nThis is not exactly 'skipping', just a convention. Underscore variable still gets the value assigned:\n>>> _\n3\n\n", "A common way to do this is to use underscores for the unused variables:\nfor x, _, z in points:\n # use x and z\n\nThis doesn't actually do anything different from what you wrote. The underscore is a normal variable like any other. But this shows people reading your code that you don't intend to use the variable.\nIt is not advisable to do this in the interactive prompt as _ has a special meaning there: the value of the last run statement/expression.\n", "While this is not as slick as you're asking for, perhaps this is most legible for your intentions of giving meaningful names only to the tuple indices you care about:\nfor each in points:\n x = each[0]\n # do something with x\n\n", "In Python 3.1 you can use an asterisk in front of an identifier on the left side of a tuple assignment and it will suck up whatever is left over. This construct will handle a variable number of tuple items. Like this:\n>>> tpl = 1,2,3,4,5\n>>> a, *b = tpl\n>>> a\n1\n>>> b\n>>> (2, 3, 4, 5)\n\nOr in various orders and combinations:\n>>> a, *b, c = tpl\n>>> a\n1\n>>> b\n(2, 3, 4)\n>>> c\n5\n\nSo, for the case you asked about, where you're only interested in the first item, use *_ to suck up and discard the remaining items you don't care about:\n>>> a, *_ = tpl\n>>> a\n1\n\n" ]
[ 8, 7, 5, 4, 2 ]
[]
[]
[ "loops", "python", "tuples" ]
stackoverflow_0003061336_loops_python_tuples.txt
Q: is a decorator in python exactly the same as calling a function on a function? I thought that doing @f def g(): print 'hello' is exactly the same as def g(): print 'hello' g=f(g) But, I had this code, that uses contextlib.contextmanager: @contextlib.contextmanager def f(): print 1 yield print 2 with f: print 3 which works and yields 1 3 2 And when I tried to change it into def f(): print 1 yield print 2 f=contextlib.contextmanager(f) with f: print 3 I get AttributeError: 'function' object has no attribute '__exit__' What am I missing? is there some black magic specifically in contextlib.contextmanager, or do i misunderstand how decorators work in general? A: Yes, decorator is exactly same as calling a function and assigning to returned value In this case error comes because you are not calling function, so correct code would be def f(): print 1 yield print 2 f=contextlib.contextmanager(f) with f(): print 3 also I am not sure if you tested code, because decorator code you have given will fail due to same reason @contextlib.contextmanager def f(): print 1 yield print 2 with f: print 3 Error: with f: AttributeError: 'function' object has no attribute '__exit__'
is a decorator in python exactly the same as calling a function on a function?
I thought that doing @f def g(): print 'hello' is exactly the same as def g(): print 'hello' g=f(g) But, I had this code, that uses contextlib.contextmanager: @contextlib.contextmanager def f(): print 1 yield print 2 with f: print 3 which works and yields 1 3 2 And when I tried to change it into def f(): print 1 yield print 2 f=contextlib.contextmanager(f) with f: print 3 I get AttributeError: 'function' object has no attribute '__exit__' What am I missing? is there some black magic specifically in contextlib.contextmanager, or do i misunderstand how decorators work in general?
[ "Yes, decorator is exactly same as calling a function and assigning to returned value\nIn this case error comes because you are not calling function, so correct code would be\ndef f():\n print 1\n yield\n print 2\n\nf=contextlib.contextmanager(f)\nwith f():\n print 3\n\nalso I am not sure if you tested code, because decorator code you have given will fail due to same reason\n@contextlib.contextmanager\ndef f():\n print 1\n yield\n print 2\nwith f:\n print 3\n\nError:\n with f:\nAttributeError: 'function' object has no attribute '__exit__'\n\n" ]
[ 5 ]
[]
[]
[ "contextmanager", "decorator", "python" ]
stackoverflow_0003074672_contextmanager_decorator_python.txt
Q: Python IRC Client import socket, sys, string if len(sys.argv) !=4 : print "Usage: ./supabot.py <host> <port> <channel>" sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) chan = sys.argv[3] sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN ' + " " + chan + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print data elif data.find('!info') != -1: sck.send('PRIVMSG ' + chan + ' :' + ' supaBOT v1 by sourD ' + '\r\n') print data elif data.find('!commands') != -1: nick = data.split('!')[ 0 ].replace(':',' ') if nick == "s0urd": sck.send('PRIVMSG ' + chan + ' :' + ' no commands have been set ' + '\r\n') else: sck.send('PRIVMSG ' + chan + ' :' + ' youre not my master ' + '\r\n') print data elif data.find('PRIVMSG') != -1: message = ':'.join(data.split (':')[2:]) if message.lower().find('darkunderground') == -1: nick = data.split('!')[ 0 ].replace(':',' ') destination = ''.join (data.split(':')[:2]).split (' ')[-2] function = message.split( )[0] print nick + ' : ' + function arg = data.split( ) print sck.recv(1024) my nick in IRC is s0urd but when I type !commands I get "youre not my master" but my nick is s0urd. Maybe I did the whole nick thing wrong, I don't know, but any help would be appreciated, thanks. line 26 A: nick = data.split('!')[ 0 ].replace(':',' ') That's going to replace the : with a space (), and thus the resulting string will be "s0urd ", not "s0urd". You probably meant this instead: nick = data.split('!')[ 0 ].replace(':','') Note the lack of space between the '' being passed as the replacement string.
Python IRC Client
import socket, sys, string if len(sys.argv) !=4 : print "Usage: ./supabot.py <host> <port> <channel>" sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) chan = sys.argv[3] sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN ' + " " + chan + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print data elif data.find('!info') != -1: sck.send('PRIVMSG ' + chan + ' :' + ' supaBOT v1 by sourD ' + '\r\n') print data elif data.find('!commands') != -1: nick = data.split('!')[ 0 ].replace(':',' ') if nick == "s0urd": sck.send('PRIVMSG ' + chan + ' :' + ' no commands have been set ' + '\r\n') else: sck.send('PRIVMSG ' + chan + ' :' + ' youre not my master ' + '\r\n') print data elif data.find('PRIVMSG') != -1: message = ':'.join(data.split (':')[2:]) if message.lower().find('darkunderground') == -1: nick = data.split('!')[ 0 ].replace(':',' ') destination = ''.join (data.split(':')[:2]).split (' ')[-2] function = message.split( )[0] print nick + ' : ' + function arg = data.split( ) print sck.recv(1024) my nick in IRC is s0urd but when I type !commands I get "youre not my master" but my nick is s0urd. Maybe I did the whole nick thing wrong, I don't know, but any help would be appreciated, thanks. line 26
[ "nick = data.split('!')[ 0 ].replace(':',' ') \n\nThat's going to replace the : with a space (), and thus the resulting string will be \"s0urd \", not \"s0urd\". You probably meant this instead:\nnick = data.split('!')[ 0 ].replace(':','')\n\nNote the lack of space between the '' being passed as the replacement string.\n" ]
[ 1 ]
[]
[]
[ "irc", "python", "sockets" ]
stackoverflow_0003074734_irc_python_sockets.txt
Q: Python | How to create complex dictionary I want to create a data structure that will be parse as a JSON object. The out put must look like this and this should be a dynamic data structure. {"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876}, {"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126}, {"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876}, {"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]} I'm struggling in the middle of implementing this data structure so expecting some good ideas. Thanks A: As response to the comment on Mathiasdm answer: You mean how to create dictionary with a list of dictionaries? That can be done like this: dict = {} dict["data"] = [] dict["data"].append({'type': 'poi', 'lat': 123}) dict["data"].append({'type': 'locale', 'lat': 321}) And so on. But if this was really the problem, i would suggest to read the reference for lists and dictionaries again: http://docs.python.org/tutorial/datastructures.html A: Your question is unclear, but do you want probably something like this: >>> r = DataResult() >>> r.add_poi(-34.96615974838191, 149.89967626953126) >>> r.add_locale(-34.72271328279892, 150.46547216796876) >>>r.add_poi(-34.67303411621243, 149.96559423828126) >>> print r {"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876}, {"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126}, {"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876}, {"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]} You can create this by creating a DataResult class and overriding the __str__ or __unicode__ methods. Your add_poi can be something like: def add_poi(self, lat, lon): self.append(PoiData(lat, lon)) where PoiData is another class representing a data entry of type "poi" etc. A: What exactly do you mean? If you create a data structure composed of dicts and lists (like the one you have given), you can always parse it to a JSON object using the json package.
Python | How to create complex dictionary
I want to create a data structure that will be parse as a JSON object. The out put must look like this and this should be a dynamic data structure. {"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876}, {"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126}, {"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876}, {"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]} I'm struggling in the middle of implementing this data structure so expecting some good ideas. Thanks
[ "As response to the comment on Mathiasdm answer:\nYou mean how to create dictionary with a list of dictionaries?\nThat can be done like this:\ndict = {}\ndict[\"data\"] = []\ndict[\"data\"].append({'type': 'poi', 'lat': 123})\ndict[\"data\"].append({'type': 'locale', 'lat': 321})\n\nAnd so on.\nBut if this was really the problem, i would suggest to read the reference for lists and dictionaries again:\nhttp://docs.python.org/tutorial/datastructures.html\n", "Your question is unclear, but do you want probably something like this:\n>>> r = DataResult()\n>>> r.add_poi(-34.96615974838191, 149.89967626953126)\n>>> r.add_locale(-34.72271328279892, 150.46547216796876)\n>>>r.add_poi(-34.67303411621243, 149.96559423828126)\n\n>>> print r\n{\"data\": [{\"type\": \"locale\", \"lat\": -34.43778387240597, \"lon\": 150.04799169921876},\n{\"type\": \"poi\", \"lat\": -34.96615974838191, \"lon\": 149.89967626953126},\n{\"type\": \"locale\", \"lat\": -34.72271328279892, \"lon\": 150.46547216796876},\n{\"type\": \"poi\", \"lat\": -34.67303411621243, \"lon\": 149.96559423828126}]}\n\nYou can create this by creating a DataResult class and overriding the __str__ or __unicode__ methods.\nYour add_poi can be something like:\ndef add_poi(self, lat, lon):\n self.append(PoiData(lat, lon))\n\nwhere PoiData is another class representing a data entry of type \"poi\" etc.\n", "What exactly do you mean? If you create a data structure composed of dicts and lists (like the one you have given), you can always parse it to a JSON object using the json package.\n" ]
[ 6, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003075021_python.txt
Q: Timeout with Ajaxterm I have a similar question to this: PHP session timeout callback? Basically, I want to run some code once a user has been inactive for a certain amount of time. However my case is a little more tricky than the above question. This is because I am using Ajaxterm: http://antony.lesuisse.org/software/ajaxterm/ My php script will handle authentication, and if logged in, will start an ajaxterm daemon. Ajaxterm starts its own little web server, which my php script will "proxy" its output to the user. What I wish to do is if the user has not pressed a key for a certain amount of time in ajaxterm, to kill the process. Has anyone got any ideas on how I could do this? BTW: I could scrap php if there is a better language to do the above in Thanks A: The question you've posted is not only similar to what you want, it's pretty much the same. I guess you're asking how to do the cleanup task, which consists of killing ajaxterm. There way I describe here works for Linux, but is portable with a little effort. To identify and kill a process you need to know the process id. You could get it by starting ajaxterm within a bash script, echo the pid and read it out with php. Or even easier use the ajaxterm -PPIDFILE, --pidfile=PIDFILE command line option to set each users ajaxterm instance to a different pidfile. You then just need to read out this file with your language of choice and execute a kill command.
Timeout with Ajaxterm
I have a similar question to this: PHP session timeout callback? Basically, I want to run some code once a user has been inactive for a certain amount of time. However my case is a little more tricky than the above question. This is because I am using Ajaxterm: http://antony.lesuisse.org/software/ajaxterm/ My php script will handle authentication, and if logged in, will start an ajaxterm daemon. Ajaxterm starts its own little web server, which my php script will "proxy" its output to the user. What I wish to do is if the user has not pressed a key for a certain amount of time in ajaxterm, to kill the process. Has anyone got any ideas on how I could do this? BTW: I could scrap php if there is a better language to do the above in Thanks
[ "The question you've posted is not only similar to what you want, it's pretty much the same. I guess you're asking how to do the cleanup task, which consists of killing ajaxterm.\nThere way I describe here works for Linux, but is portable with a little effort. To identify and kill a process you need to know the process id. You could get it by starting ajaxterm within a bash script, echo the pid and read it out with php. Or even easier use the ajaxterm -PPIDFILE, --pidfile=PIDFILE command line option to set each users ajaxterm instance to a different pidfile. You then just need to read out this file with your language of choice and execute a kill command.\n" ]
[ 0 ]
[]
[]
[ "apache", "php", "python" ]
stackoverflow_0003075037_apache_php_python.txt
Q: python - Which is the better way to enable/disable logging? Which is better way to enable/disable logging? 1) Changing log levels, logging.disable(logging.CRITICAL) 2) log = None And logging messages this way, if log: log.info("log message") So that we can avoid unnecessary string constructions in case of logging disabled... A: 1 is best, ideally via a configuration file or command line argument (--quiet) 2 will just clutter up your code If you want to avoid expensive string construction (this is probably worthwhile about 0.001% of the time in my experience), use: if logger.isEnabledFor(logging.DEBUG): logger.debug("Message with %s, %s", expensive_func1(), expensive_func2()) http://docs.python.org/library/logging.html#optimization
python - Which is the better way to enable/disable logging?
Which is better way to enable/disable logging? 1) Changing log levels, logging.disable(logging.CRITICAL) 2) log = None And logging messages this way, if log: log.info("log message") So that we can avoid unnecessary string constructions in case of logging disabled...
[ "1 is best, ideally via a configuration file or command line argument (--quiet)\n2 will just clutter up your code\nIf you want to avoid expensive string construction (this is probably worthwhile about 0.001% of the time in my experience), use:\nif logger.isEnabledFor(logging.DEBUG):\n logger.debug(\"Message with %s, %s\", expensive_func1(),\n expensive_func2())\n\nhttp://docs.python.org/library/logging.html#optimization\n" ]
[ 15 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003075202_logging_python.txt
Q: From the web to games I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make? A: Python's Pygame is certainly a good choice as others have said. If you want to get in to deep video game programming though.. move on to something like C++ or another lower level language.. from experience, most higher level languages tend to put artificial hurdles up in regards to decent video games. Though for a simple 2d game you cant go wrong with python. another decent environment to use is Ogre3d, but you would need C++ or the PyOgre bindings (which are not up to date, but I hear they do work okay). Going from web to game design really is a decent step, as long as you have a good sense of design. the physics and game logic can be learned, but ive yet to see anyone who could properly learn how to write a decent GUI.. as is seen in most cases these days, the final GUI lay out tends to be a process of elimination or beta with trial and error. Only suggestion i have left is keep your game logic as far away as possible from your graphics. Be Modular. -edit- oh and a note.. stay away from Tkinter in python for anything more than a simple tool.. I have found it most frustrating to use. there is wxPython, GTK, pygame, and PyQT.. and all of them (in my opinion) are far better graphic frameworks. A: You should figure out why you want to learn. If you're interested in making money, developing small standalone games is probably not a good idea. If you're just interested in learning fundamentals, there are plenty of good libraries out there. Some examples: PyGame - http://www.pygame.org/news.html SDK - http://www.libsdl.org/ Allegro - http://alleg.sourceforge.net/ Reference http://code.reddit.com/wiki/help/faqs/programming#WhatprogramminglanguageshouldIuseformynewgame A: A good starting point might be trying a turn-based game or two, if PHP is currently your main strength. Those work well over HTTP, bouncing requests and responses back & forth, while an action platformer is a very different beast - you might make an HTTP request to log high score or level-clear info, but actual gameplay would have to be run client-side to maintain any sense of action - either Javascript & canvas or Flash, if it's web-based. There are some (mostly dead but) open source turn-based PHP games worth a look, to get a feel for some general concepts - the wittily-named phpMud and phpMMORPG come to mind, and a few board & card games. It's just a baby step towards what you want to do and might not sound as fun, but game programming of any kind involves a lot of learning and hard work. Designing maps & system mechanics, animation & visual effects, physics, hitboxes, tons of math everywhere, and the hardest part, getting it all to actually run smoothly - it's a struggle to get something working, and an all-out war to get it "right." That said, if you just want to get up to your elbows in a platformer to see what it's like and your Javascript is fairly solid, this set of articles is a great starting point. Brent Silby made a few neat shmups & platformers that pre-date canvas too, also worth a look. A: Looking at your tags, web games are mostly client side, and since you aren't going to use flash, i would say JavaScript would work for 2D. With all the libraries and plug-ins out there, JavaScript can actually handle it. A: Taking a look at OpenGL may not be a terrible idea. You can use the library in many languages, and is supported with in HTML5 (WebGL). There are several excellent tutorials out there. A: If you want to learn more Python while doing so, you may want to take PyGame or an equivalent program. PHP, Ruby and JavaScript aren't going to help you in the video game section, though. They're all related to the internet. If you want to start of real easy, try out Genesis3D. you can make awesome 3D FPS games, and its quite easy to get the hang of too. Took me only 5 days :D Unity made me sick to my stomach, and so did Blender3D's game engine, so I personally say not to use those. It intimidated me.
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make?
[ "Python's Pygame is certainly a good choice as others have said. If you want to get in to deep video game programming though.. move on to something like C++ or another lower level language.. from experience, most higher level languages tend to put artificial hurdles up in regards to decent video games. Though for a simple 2d game you cant go wrong with python.\nanother decent environment to use is Ogre3d, but you would need C++ or the PyOgre bindings (which are not up to date, but I hear they do work okay).\nGoing from web to game design really is a decent step, as long as you have a good sense of design. the physics and game logic can be learned, but ive yet to see anyone who could properly learn how to write a decent GUI.. as is seen in most cases these days, the final GUI lay out tends to be a process of elimination or beta with trial and error.\nOnly suggestion i have left is keep your game logic as far away as possible from your graphics. Be Modular.\n-edit-\noh and a note.. stay away from Tkinter in python for anything more than a simple tool.. I have found it most frustrating to use. there is wxPython, GTK, pygame, and PyQT.. and all of them (in my opinion) are far better graphic frameworks.\n", "You should figure out why you want to learn. If you're interested in making money, developing small standalone games is probably not a good idea. If you're just interested in learning fundamentals, there are plenty of good libraries out there.\nSome examples:\n\nPyGame - http://www.pygame.org/news.html\nSDK - http://www.libsdl.org/\nAllegro - http://alleg.sourceforge.net/\n\nReference\nhttp://code.reddit.com/wiki/help/faqs/programming#WhatprogramminglanguageshouldIuseformynewgame\n", "A good starting point might be trying a turn-based game or two, if PHP is currently your main strength. Those work well over HTTP, bouncing requests and responses back & forth, while an action platformer is a very different beast - you might make an HTTP request to log high score or level-clear info, but actual gameplay would have to be run client-side to maintain any sense of action - either Javascript & canvas or Flash, if it's web-based.\nThere are some (mostly dead but) open source turn-based PHP games worth a look, to get a feel for some general concepts - the wittily-named phpMud and phpMMORPG come to mind, and a few board & card games.\nIt's just a baby step towards what you want to do and might not sound as fun, but game programming of any kind involves a lot of learning and hard work. Designing maps & system mechanics, animation & visual effects, physics, hitboxes, tons of math everywhere, and the hardest part, getting it all to actually run smoothly - it's a struggle to get something working, and an all-out war to get it \"right.\"\n\nThat said, if you just want to get up to your elbows in a platformer to see what it's like and your Javascript is fairly solid, this set of articles is a great starting point. Brent Silby made a few neat shmups & platformers that pre-date canvas too, also worth a look.\n", "Looking at your tags, web games are mostly client side, and since you aren't going to use flash, i would say JavaScript would work for 2D. With all the libraries and plug-ins out there, JavaScript can actually handle it.\n", "Taking a look at OpenGL may not be a terrible idea. You can use the library in many languages, and is supported with in HTML5 (WebGL). There are several excellent tutorials out there.\n", "If you want to learn more Python while doing so, you may want to take PyGame or an equivalent program. PHP, Ruby and JavaScript aren't going to help you in the video game section, though. They're all related to the internet. \nIf you want to start of real easy, try out Genesis3D. you can make awesome 3D FPS games, and its quite easy to get the hang of too. Took me only 5 days :D\nUnity made me sick to my stomach, and so did Blender3D's game engine, so I personally say not to use those. It intimidated me.\n" ]
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "javascript", "php", "python" ]
stackoverflow_0003074103_javascript_php_python.txt
Q: unusual django admin behavior when storing string values Using django trunk r13359 and django piston, I created a small restful service that stores string values. This is the model I am using to store strings: class DataStore(models.Model): data = models.CharField(max_length=200) url = models.URLField(default = '', verify_exists=False, blank = True) I used curl to post following data: curl -d "data=somedata" http://localhost:8000/api/datastorage/ This is the code that handles storage as part of the django-piston handler store = DataStore() store.url = request.POST.get('url',""), store.data = request.POST['data'], store.save() return {'data':store} When I post the data with curl I get the following response body, which is expected: { "result": { "url": [ "" ], "data": [ "somedata" ], "id": 1 } } Whats not expected however is when I look at the stored instance from django admin, the value stored in the data field looks something like this: (u'somedata',) and the following is stored in the url: ('',) Whats even more interesting is when I query the service with curl to see what is stored, I get the following: { "result": { "url": [ "('',)" ], "data": [ "(u'somedata',)" ], "id": 1 } } I'm stumped .. any ideas what could be going on? A: Actually your response is also not what should be expected, note the [] around your strings, those shouldn't be there. Your error is adding the comma after these two lines: store.url = request.POST.get('url',""), store.data = request.POST['data'], Python will interprete you want to store a tuple in url and data, and django will convert those tuples to strings implicitly, resulting in the behaviour you see. Just remove the two commas and you'll be fine.
unusual django admin behavior when storing string values
Using django trunk r13359 and django piston, I created a small restful service that stores string values. This is the model I am using to store strings: class DataStore(models.Model): data = models.CharField(max_length=200) url = models.URLField(default = '', verify_exists=False, blank = True) I used curl to post following data: curl -d "data=somedata" http://localhost:8000/api/datastorage/ This is the code that handles storage as part of the django-piston handler store = DataStore() store.url = request.POST.get('url',""), store.data = request.POST['data'], store.save() return {'data':store} When I post the data with curl I get the following response body, which is expected: { "result": { "url": [ "" ], "data": [ "somedata" ], "id": 1 } } Whats not expected however is when I look at the stored instance from django admin, the value stored in the data field looks something like this: (u'somedata',) and the following is stored in the url: ('',) Whats even more interesting is when I query the service with curl to see what is stored, I get the following: { "result": { "url": [ "('',)" ], "data": [ "(u'somedata',)" ], "id": 1 } } I'm stumped .. any ideas what could be going on?
[ "Actually your response is also not what should be expected, note the [] around your strings, those shouldn't be there.\nYour error is adding the comma after these two lines: \nstore.url = request.POST.get('url',\"\"),\nstore.data = request.POST['data'],\n\nPython will interprete you want to store a tuple in url and data, and django will convert those tuples to strings implicitly, resulting in the behaviour you see. Just remove the two commas and you'll be fine.\n" ]
[ 1 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0003075326_django_django_piston_python.txt
Q: In a pylons web app, should a cookie be set from a model class or a controller? Trying to figure out the best way to do this: Should I do something like: def index(self): if request.POST: u = User(id) u.setCookie() #All session logic in def setCookie() Or set the cookie in the controller like: def index(self): if request.POST: u = User(id) response.set_cookie('session_key', u.session_key, max_age=3600) Why do it one way or the other? Thank you. A: I think traditionally you would want the model to be concerned with data persistence and validation but not http related stuff like cookies. Which leaves the controller to be the more appropriate place in my opinion. A reason(not the only one) I can think of for this is that it might be required someday that you need to run applications against your model logic that have nothing to do with web stuff. given your implementation above I suspect the user object would have to get access to the response from the stacked proxy/globals stuff in pylons(could be wrong). So, if you ever needed to use the same model classes in a program that consumes messages from a message queue for example, the pylons machinery that makes the response available would not be available. This could be a problem that is easily avoided. A: I share also Tom's opinion, you should try to avoid to much dependencies in different classes. So the controller should to all the http (request, response) related stuff. Also for testing it is much easier.
In a pylons web app, should a cookie be set from a model class or a controller?
Trying to figure out the best way to do this: Should I do something like: def index(self): if request.POST: u = User(id) u.setCookie() #All session logic in def setCookie() Or set the cookie in the controller like: def index(self): if request.POST: u = User(id) response.set_cookie('session_key', u.session_key, max_age=3600) Why do it one way or the other? Thank you.
[ "I think traditionally you would want the model to be concerned with data persistence and validation but not http related stuff like cookies. Which leaves the controller to be the more appropriate place in my opinion. \nA reason(not the only one) I can think of for this is that it might be required someday that you need to run applications against your model logic that have nothing to do with web stuff. \ngiven your implementation above I suspect the user object would have to get access to the response from the stacked proxy/globals stuff in pylons(could be wrong). So, if you ever needed to use the same model classes in a program that consumes messages from a message queue for example, the pylons machinery that makes the response available would not be available. This could be a problem that is easily avoided. \n", "I share also Tom's opinion, you should try to avoid to much dependencies in different classes. So the controller should to all the http (request, response) related stuff. Also for testing it is much easier.\n" ]
[ 2, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002396804_pylons_python.txt
Q: (python) recursively remove capitalisation from directory structure? uppercase letters - what's the point of them? all they give you is rsi. i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python? it should recursively parse a specified directory, identify the file/folder names with capital letters and rename them in lowercase. A: os.walk is great for doing recursive stuff with the filesystem. import os def lowercase_rename( dir ): # renames all subforders of dir, not including dir itself def rename_all( root, items): for name in items: try: os.rename( os.path.join(root, name), os.path.join(root, name.lower())) except OSError: pass # can't rename it, so what # starts from the bottom so paths further up remain valid after renaming for root, dirs, files in os.walk( dir, topdown=False ): rename_all( root, dirs ) rename_all( root, files) The point of walking the tree upwards is that when you have a directory structure like '/A/B' you will have path '/A' during the recursion too. Now, if you start from the top, you'd rename /A to /a first, thus invalidating the /A/B path. On the other hand, when you start from the bottom and rename /A/B to /A/b first, it doesn't affect any other paths. Actually you could use os.walk for top-down too, but that's (slightly) more complicated. A: try the following script: #!/usr/bin/python ''' renames files or folders, changing all uppercase characters to lowercase. directories will be parsed recursively. usage: ./changecase.py file|directory ''' import sys, os def rename_recursive(srcpath): srcpath = os.path.normpath(srcpath) if os.path.isdir(srcpath): # lower the case of this directory newpath = name_to_lowercase(srcpath) # recurse to the contents for entry in os.listdir(newpath): #FIXME newpath nextpath = os.path.join(newpath, entry) rename_recursive(nextpath) elif os.path.isfile(srcpath): # base case name_to_lowercase(srcpath) else: # error print "bad arg: " + srcpath sys.exit() def name_to_lowercase(srcpath): srcdir, srcname = os.path.split(srcpath) newname = srcname.lower() if newname == srcname: return srcpath newpath = os.path.join(srcdir, newname) print "rename " + srcpath + " to " + newpath os.rename(srcpath, newpath) return newpath arg = sys.argv[1] arg = os.path.expanduser(arg) rename_recursive(arg)
(python) recursively remove capitalisation from directory structure?
uppercase letters - what's the point of them? all they give you is rsi. i'd like to remove as much capitalisation as possible from my directory structure. how would i write a script to do this in python? it should recursively parse a specified directory, identify the file/folder names with capital letters and rename them in lowercase.
[ "os.walk is great for doing recursive stuff with the filesystem.\nimport os\n\ndef lowercase_rename( dir ):\n # renames all subforders of dir, not including dir itself\n def rename_all( root, items):\n for name in items:\n try:\n os.rename( os.path.join(root, name), \n os.path.join(root, name.lower()))\n except OSError:\n pass # can't rename it, so what\n\n # starts from the bottom so paths further up remain valid after renaming\n for root, dirs, files in os.walk( dir, topdown=False ):\n rename_all( root, dirs )\n rename_all( root, files)\n\nThe point of walking the tree upwards is that when you have a directory structure like '/A/B' you will have path '/A' during the recursion too. Now, if you start from the top, you'd rename /A to /a first, thus invalidating the /A/B path. On the other hand, when you start from the bottom and rename /A/B to /A/b first, it doesn't affect any other paths. \nActually you could use os.walk for top-down too, but that's (slightly) more complicated.\n", "try the following script:\n#!/usr/bin/python\n\n'''\nrenames files or folders, changing all uppercase characters to lowercase.\ndirectories will be parsed recursively.\n\nusage: ./changecase.py file|directory\n'''\n\nimport sys, os\n\ndef rename_recursive(srcpath):\n srcpath = os.path.normpath(srcpath)\n if os.path.isdir(srcpath):\n # lower the case of this directory\n newpath = name_to_lowercase(srcpath)\n # recurse to the contents\n for entry in os.listdir(newpath): #FIXME newpath\n nextpath = os.path.join(newpath, entry)\n rename_recursive(nextpath)\n elif os.path.isfile(srcpath): # base case\n name_to_lowercase(srcpath)\n else: # error\n print \"bad arg: \" + srcpath\n sys.exit()\n\ndef name_to_lowercase(srcpath):\n srcdir, srcname = os.path.split(srcpath)\n newname = srcname.lower()\n if newname == srcname:\n return srcpath\n newpath = os.path.join(srcdir, newname)\n print \"rename \" + srcpath + \" to \" + newpath\n os.rename(srcpath, newpath)\n return newpath\n\narg = sys.argv[1]\narg = os.path.expanduser(arg)\nrename_recursive(arg)\n\n" ]
[ 16, 2 ]
[]
[]
[ "python", "uppercase" ]
stackoverflow_0003075443_python_uppercase.txt
Q: How do I override a Python import? I'm working on pypreprocessor which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports. The problem is: The preprocessor runs through the file, processes it, outputs to a temporary file, and exec() the temporary file. Libraries that are imported need to be handled a little different, because they aren't executed, but rather they are loaded and made accessible to the caller module. What I need to be able to do is: Interrupt the import (since the preprocessor is being run in the middle of the import), load the postprocessed code as a tempModule, and replace the original import with the tempModule to trick the calling script with the import into believing that the tempModule is the original module. I have searched everywhere and so far and have no solution. This Stack Overflow question is the closest I've seen so far to providing an answer: Override namespace in Python Here's what I have. # Remove the bytecode file created by the first import os.remove(moduleName + '.pyc') # Remove the first import del sys.modules[moduleName] # Import the postprocessed module tmpModule = __import__(tmpModuleName) # Set first module's reference to point to the preprocessed module sys.modules[moduleName] = tmpModule moduleName is the name of the original module, and tmpModuleName is the name of the postprocessed code file. The strange part is this solution still runs completely normal as if the first module completed loaded normally; unless you remove the last line, then you get a module not found error. Hopefully someone on Stack Overflow know a lot more about imports than I do, because this one has me stumped. Note: I will only award a solution, or, if this is not possible in Python; the best, most detailed explanation of why this is not impossible. Update: For anybody who is interested, here is the working code. if imp.lock_held() is True: del sys.modules[moduleName] sys.modules[tmpModuleName] = __import__(tmpModuleName) sys.modules[moduleName] = __import__(tmpModuleName) The 'imp.lock_held' part detects whether the module is being loaded as a library. The following lines do the rest. A: Does this answer your question? The second import does the trick. Mod_1.py def test_function(): print "Test Function -- Mod 1" Mod_2.py def test_function(): print "Test Function -- Mod 2" Test.py #!/usr/bin/python import sys import Mod_1 Mod_1.test_function() del sys.modules['Mod_1'] sys.modules['Mod_1'] = __import__('Mod_2') import Mod_1 Mod_1.test_function() A: To define a different import behavior or to totally subvert the import process you will need to write import hooks. See PEP 302. For example, import sys class MyImporter(object): def find_module(self, module_name, package_path): # Return a loader return self def load_module(self, module_name): # Return a module return self sys.meta_path.append(MyImporter()) import now_you_can_import_any_name print now_you_can_import_any_name It outputs: <__main__.MyImporter object at 0x009F85F0> So basically it returns a new module (which can be any object), in this case itself. You may use it to alter the import behavior by returning processe_xxx on import of xxx. IMO: Python doesn't need a preprocessor. Whatever you are accomplishing can be accomplished in Python itself due to it very dynamic nature, for example, taking the case of the debug example, what is wrong with having at top of file debug = 1 and later if debug: print "wow" ? A: In Python 2 there is the imputil module that seems to provide the functionality you are looking for, but has been removed in python 3. It's not very well documented but contains an example section that shows how you can replace the standard import functions. For Python 3 there is the importlib module (introduced in Python 3.1) that contains functions and classes to modify the import functionality in all kinds of ways. It should be suitable to hook your preprocessor into the import system.
How do I override a Python import?
I'm working on pypreprocessor which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports. The problem is: The preprocessor runs through the file, processes it, outputs to a temporary file, and exec() the temporary file. Libraries that are imported need to be handled a little different, because they aren't executed, but rather they are loaded and made accessible to the caller module. What I need to be able to do is: Interrupt the import (since the preprocessor is being run in the middle of the import), load the postprocessed code as a tempModule, and replace the original import with the tempModule to trick the calling script with the import into believing that the tempModule is the original module. I have searched everywhere and so far and have no solution. This Stack Overflow question is the closest I've seen so far to providing an answer: Override namespace in Python Here's what I have. # Remove the bytecode file created by the first import os.remove(moduleName + '.pyc') # Remove the first import del sys.modules[moduleName] # Import the postprocessed module tmpModule = __import__(tmpModuleName) # Set first module's reference to point to the preprocessed module sys.modules[moduleName] = tmpModule moduleName is the name of the original module, and tmpModuleName is the name of the postprocessed code file. The strange part is this solution still runs completely normal as if the first module completed loaded normally; unless you remove the last line, then you get a module not found error. Hopefully someone on Stack Overflow know a lot more about imports than I do, because this one has me stumped. Note: I will only award a solution, or, if this is not possible in Python; the best, most detailed explanation of why this is not impossible. Update: For anybody who is interested, here is the working code. if imp.lock_held() is True: del sys.modules[moduleName] sys.modules[tmpModuleName] = __import__(tmpModuleName) sys.modules[moduleName] = __import__(tmpModuleName) The 'imp.lock_held' part detects whether the module is being loaded as a library. The following lines do the rest.
[ "Does this answer your question? The second import does the trick.\nMod_1.py\ndef test_function():\n print \"Test Function -- Mod 1\"\n\nMod_2.py\ndef test_function():\n print \"Test Function -- Mod 2\"\n\nTest.py\n#!/usr/bin/python\n\nimport sys\n\nimport Mod_1\n\nMod_1.test_function()\n\ndel sys.modules['Mod_1']\n\nsys.modules['Mod_1'] = __import__('Mod_2')\n\nimport Mod_1\n\nMod_1.test_function()\n\n", "To define a different import behavior or to totally subvert the import process you will need to write import hooks. See PEP 302.\nFor example,\nimport sys\n\nclass MyImporter(object):\n\n def find_module(self, module_name, package_path):\n # Return a loader\n return self\n\n def load_module(self, module_name):\n # Return a module\n return self\n\nsys.meta_path.append(MyImporter())\n\nimport now_you_can_import_any_name\nprint now_you_can_import_any_name\n\nIt outputs:\n<__main__.MyImporter object at 0x009F85F0>\n\nSo basically it returns a new module (which can be any object), in this case itself. You may use it to alter the import behavior by returning processe_xxx on import of xxx.\nIMO: Python doesn't need a preprocessor. Whatever you are accomplishing can be accomplished in Python itself due to it very dynamic nature, for example, taking the case of the debug example, what is wrong with having at top of file\ndebug = 1\n\nand later\nif debug:\n print \"wow\"\n\n?\n", "In Python 2 there is the imputil module that seems to provide the functionality you are looking for, but has been removed in python 3. It's not very well documented but contains an example section that shows how you can replace the standard import functions.\nFor Python 3 there is the importlib module (introduced in Python 3.1) that contains functions and classes to modify the import functionality in all kinds of ways. It should be suitable to hook your preprocessor into the import system.\n" ]
[ 44, 14, 0 ]
[]
[]
[ "import", "overriding", "preprocessor", "python" ]
stackoverflow_0003012473_import_overriding_preprocessor_python.txt
Q: Python multiprocessing/threading with shared variables that only will be read Considering the code below. I would like to run 3 experiments at a time. The experiments are independent, the only thing they share is the Model object which they only read. As there are seemingly no hard things in threading this out, how can I best do this in Python? I would like to use a pool or so to make sure that only three experiments run at a time. Shall I use multi-processing? If yes, how is the shortest and most concise? #!/usr/bin/env python2.6 import time class Model: name = "" def __init__(self,name): self.name = name class Experiment: id = 0 model = None done = False def __init__(self,id,model): self.id = id self.model = model def run(self): for _ in range(0,60): print "Hey %s from experiment %d" % (self.model.name, id) time.sleep(1) self.done = True if __name__ == "__main__": experiments = [] model = Model("statictistical model") for i in range(0,5): experiments.append(Experiment(i, model)) #How to run 3 experiments at the same time A: Check the docs, specifically: http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool There really are a lot of examples there that should get you on your way. For instance, I could come up with: #!/usr/bin/env python2.6 import time import multiprocessing class Model: name = "" def __init__(self,name): self.name = name def run_experiment(id, model): print "Experiment %d is starting" % id for _ in range(0,60): print "Hey %s from experiment %d" % (model.name, id) time.sleep(1) print "Experiment %d is done" % id return "Result for %d" % id if __name__ == "__main__": model = Model("statictistical model") experiments = ((i, model) for i in range(0, 5)) pool = multiprocessing.Pool(3) results = [pool.apply_async(run_experiment, experiment) for experiment in experiments] for result in results: r = result.get() # do something with r # or nothing, i suppose... Do also pay attention to what the docs say about using the multiprocessing module: Functionality within this package requires that the __main__ method be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter A: You must always keep in mind that threads do not really run parallel, if that is what you actually want. I do not unterstand what the actual problem is...? If you only want 3 threads running the same time, why not just start only 3 threads?
Python multiprocessing/threading with shared variables that only will be read
Considering the code below. I would like to run 3 experiments at a time. The experiments are independent, the only thing they share is the Model object which they only read. As there are seemingly no hard things in threading this out, how can I best do this in Python? I would like to use a pool or so to make sure that only three experiments run at a time. Shall I use multi-processing? If yes, how is the shortest and most concise? #!/usr/bin/env python2.6 import time class Model: name = "" def __init__(self,name): self.name = name class Experiment: id = 0 model = None done = False def __init__(self,id,model): self.id = id self.model = model def run(self): for _ in range(0,60): print "Hey %s from experiment %d" % (self.model.name, id) time.sleep(1) self.done = True if __name__ == "__main__": experiments = [] model = Model("statictistical model") for i in range(0,5): experiments.append(Experiment(i, model)) #How to run 3 experiments at the same time
[ "Check the docs, specifically:\nhttp://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool\nThere really are a lot of examples there that should get you on your way. For instance, I could come up with:\n#!/usr/bin/env python2.6\nimport time\nimport multiprocessing\n\nclass Model:\n name = \"\"\n def __init__(self,name):\n self.name = name\n\ndef run_experiment(id, model):\n print \"Experiment %d is starting\" % id\n for _ in range(0,60):\n print \"Hey %s from experiment %d\" % (model.name, id)\n time.sleep(1)\n print \"Experiment %d is done\" % id\n return \"Result for %d\" % id\n\n\nif __name__ == \"__main__\":\n model = Model(\"statictistical model\")\n experiments = ((i, model) for i in range(0, 5))\n pool = multiprocessing.Pool(3)\n\n results = [pool.apply_async(run_experiment, experiment) for experiment in experiments]\n for result in results:\n r = result.get()\n # do something with r\n # or nothing, i suppose...\n\nDo also pay attention to what the docs say about using the multiprocessing module:\n\nFunctionality within this package\n requires that the __main__ method be\n importable by the children. This is\n covered in Programming guidelines\n however it is worth pointing out here.\n This means that some examples, such as\n the multiprocessing.Pool examples\n will not work in the interactive\n interpreter\n\n", "You must always keep in mind that threads do not really run parallel, if that is what you actually want.\nI do not unterstand what the actual problem is...? If you only want 3 threads running the same time, why not just start only 3 threads?\n" ]
[ 3, 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0003071602_multiprocessing_multithreading_python.txt
Q: Reboot windows machines at a certain time of day and automatically login with Python I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and go home, or shutdown their computers, whatever, python or some combination of python + windows could restart their machines (for cleanliness) and automatically login, running a process for the night, then in the morning, stop said process and restart the machine so the user could easily login like normal. I've looked around, haven't had too terribly much luck, though it looks like one could do it with a changing of the registry. That sounds like a rough idea though, modifying the registry on a per-day basis. Is there an easier way? A: You probably want to consider running whatever program you're considering as a Windows service, unless you absolute need a desktop. There are a couple of questions concerning that, e.g. here and here, as well as recipes on Active State. That involves no real need to start up or login to the computer. There's also always the option of scheduled tasks and what not. That can actually be done programmatically through Python, e.g., as in this blog post. As for powering on powered off computers, while I've never done anything with it, I know Windows supports Wake-on-LAN functionality, and there seem to be some good resources, including, again, a recipe on ActiveState. If you need a desktop to run your program, I don't think you have any choice but to mess with the registry to permit autologins, as I don't believe the Window's GINA is scriptable in any way shape or form. A: I can't think of any way to do strictly what you want off the top of my head other than the registry, at least not without even more drastic measures. But doing this registry modification isn't a big deal; just change the autologon username/password and reboot the computer. To have the computer reboot when the user logs off, give them a "logoff" option that actually reboots rather than logging off; I've seen other places do that. (edit)FYI: for registry edits, Windows has a REG command that will be useful if you decide to go with that route.(/edit) Also, what kind of process are you trying to run? If it's not a GUI app that needs your interaction, you don't have to go through any great pains; just run the app remotely. At my work, we use psexec to do it very simply, and I've also created C++ programs that run code remotely. It's not that difficult, the way I do it is to have C++ call the WinAPI function to remotely register a service on the remote PC and start it, the service then does whatever I want (itself, or as a staging point to launch other things), then unregisters itself. I have only used Python for simple webpage stuff, so I'm not sure what kind of support it has for accessing the DLLs required, but if it can do that, you can still use Python here. Or even better yet, if you don't need to do this remotely but just want it done every night, you can just use the Windows scheduler to run whatever application you want run during the night. You can even do this programmatically as there are a couple Windows commands for that: one is the "at" command, and I don't recall right now what the other is but just a little Googling should find it for you. A: Thanks for the responses. To be more clear on what I'm doing, I have a program that automatically starts on bootup, so getting logged in would be preferred. I'm coding a manager for a render-farm for work which will take all the machines that our guys use during the day and turn them into render servers at night (or whenever they log off for a period of time, for example). I'm not sure if I necessarily require a GUI app, but the computer would need to boot and login to launch a server application that does the rendering, and I'm not certain if that can be done without logging in. What i'm needing to run is Autodesk's Backburner Server.exe Maybe that can be run without needing to be logged in specifically, but I'm unfamiliar with doing things of that nature.
Reboot windows machines at a certain time of day and automatically login with Python
I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and go home, or shutdown their computers, whatever, python or some combination of python + windows could restart their machines (for cleanliness) and automatically login, running a process for the night, then in the morning, stop said process and restart the machine so the user could easily login like normal. I've looked around, haven't had too terribly much luck, though it looks like one could do it with a changing of the registry. That sounds like a rough idea though, modifying the registry on a per-day basis. Is there an easier way?
[ "You probably want to consider running whatever program you're considering as a Windows service, unless you absolute need a desktop. There are a couple of questions concerning that, e.g. here and here, as well as recipes on Active State. That involves no real need to start up or login to the computer.\nThere's also always the option of scheduled tasks and what not. That can actually be done programmatically through Python, e.g., as in this blog post.\nAs for powering on powered off computers, while I've never done anything with it, I know Windows supports Wake-on-LAN functionality, and there seem to be some good resources, including, again, a recipe on ActiveState.\nIf you need a desktop to run your program, I don't think you have any choice but to mess with the registry to permit autologins, as I don't believe the Window's GINA is scriptable in any way shape or form. \n", "I can't think of any way to do strictly what you want off the top of my head other than the registry, at least not without even more drastic measures. But doing this registry modification isn't a big deal; just change the autologon username/password and reboot the computer. To have the computer reboot when the user logs off, give them a \"logoff\" option that actually reboots rather than logging off; I've seen other places do that.\n(edit)FYI: for registry edits, Windows has a REG command that will be useful if you decide to go with that route.(/edit)\nAlso, what kind of process are you trying to run? If it's not a GUI app that needs your interaction, you don't have to go through any great pains; just run the app remotely. At my work, we use psexec to do it very simply, and I've also created C++ programs that run code remotely. It's not that difficult, the way I do it is to have C++ call the WinAPI function to remotely register a service on the remote PC and start it, the service then does whatever I want (itself, or as a staging point to launch other things), then unregisters itself. I have only used Python for simple webpage stuff, so I'm not sure what kind of support it has for accessing the DLLs required, but if it can do that, you can still use Python here.\nOr even better yet, if you don't need to do this remotely but just want it done every night, you can just use the Windows scheduler to run whatever application you want run during the night. You can even do this programmatically as there are a couple Windows commands for that: one is the \"at\" command, and I don't recall right now what the other is but just a little Googling should find it for you.\n", "Thanks for the responses. To be more clear on what I'm doing, I have a program that automatically starts on bootup, so getting logged in would be preferred. I'm coding a manager for a render-farm for work which will take all the machines that our guys use during the day and turn them into render servers at night (or whenever they log off for a period of time, for example).\nI'm not sure if I necessarily require a GUI app, but the computer would need to boot and login to launch a server application that does the rendering, and I'm not certain if that can be done without logging in. What i'm needing to run is Autodesk's Backburner Server.exe\nMaybe that can be run without needing to be logged in specifically, but I'm unfamiliar with doing things of that nature.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "authentication", "boot", "python", "restart" ]
stackoverflow_0003066438_authentication_boot_python_restart.txt
Q: HTTP Banner Grabbing with Python I am interested in making an HTTP Banner Grabber, but when i connect to a server on port 80 and i send something (e.g. "HEAD / HTTP/1.1") recv doesn't return anything to me like when i do it in let's say netcat.. How would i go about this? Thanks! A: Are you sending a "\r\n\r\n" to indicate the end of the request? If you're not, the server's still waiting for the rest of the request. A: Try using the urllib2 module. >>> data = urllib2.urlopen('http://www.example.com').read() >>> print data <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE>Example Web Page</TITLE> </HEAD> <body> <p>You have reached this web page by typing &quot;example.com&quot;, &quot;example.net&quot;, or &quot;example.org&quot; into your web browser.</p> <p>These domain names are reserved for use in documentation and are not available for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </BODY> </HTML> >>> Asking for examples, you may miss finer points. To see the content-type header: >>> stream = urllib2.urlopen('http://www.example.com') >>> stream.headers['content-type'] 'text/html; charset=UTF-8' >>> data = stream.read() >>> print data[:100] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META http-equiv= >>>
HTTP Banner Grabbing with Python
I am interested in making an HTTP Banner Grabber, but when i connect to a server on port 80 and i send something (e.g. "HEAD / HTTP/1.1") recv doesn't return anything to me like when i do it in let's say netcat.. How would i go about this? Thanks!
[ "Are you sending a \"\\r\\n\\r\\n\" to indicate the end of the request? If you're not, the server's still waiting for the rest of the request.\n", "Try using the urllib2 module.\n>>> data = urllib2.urlopen('http://www.example.com').read()\n>>> print data\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<HTML>\n<HEAD>\n <META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <TITLE>Example Web Page</TITLE>\n</HEAD> \n<body> \n<p>You have reached this web page by typing &quot;example.com&quot;,\n&quot;example.net&quot;,\n or &quot;example.org&quot; into your web browser.</p>\n<p>These domain names are reserved for use in documentation and are not available \n for registration. See <a href=\"http://www.rfc-editor.org/rfc/rfc2606.txt\">RFC \n 2606</a>, Section 3.</p>\n</BODY>\n</HTML>\n\n>>>\n\nAsking for examples, you may miss finer points. To see the content-type header:\n>>> stream = urllib2.urlopen('http://www.example.com')\n>>> stream.headers['content-type']\n'text/html; charset=UTF-8'\n>>> data = stream.read()\n>>> print data[:100]\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<HTML>\n<HEAD>\n <META http-equiv=\n>>>\n\n" ]
[ 2, 2 ]
[]
[]
[ "netcat", "python" ]
stackoverflow_0003076263_netcat_python.txt
Q: Pylons: Proper Way to Establish Per-Thread/Per-Request Resource? I have a connection to an external resource that I need to make for my Pylons app (think along the lines of a database connection.) There is a modest amount of overhead involved in establishing the connection. I could setup a piece of middleware that opens and closes the connection with every request but that seems wasteful. I'd like to establish a connection for each new thread that starts up and save myself the overhead. How do I hook into thread startup in Pylons? A: Do the connections have to belong to a single thread for their lifetime? If not, you could consider implementing your own connection pool for this resource. The pool would be responsible for initializing connections and each thread would acquire and release the connections as they are needed. If you want to limit the number of available connections, you just block during the acquire phase until a connection is released or some timeout is reached. The code to implement such a pool is going to be very dependent on the resource you are talking about, so it would be difficult to give you anything other than a suggested API.
Pylons: Proper Way to Establish Per-Thread/Per-Request Resource?
I have a connection to an external resource that I need to make for my Pylons app (think along the lines of a database connection.) There is a modest amount of overhead involved in establishing the connection. I could setup a piece of middleware that opens and closes the connection with every request but that seems wasteful. I'd like to establish a connection for each new thread that starts up and save myself the overhead. How do I hook into thread startup in Pylons?
[ "Do the connections have to belong to a single thread for their lifetime? \nIf not, you could consider implementing your own connection pool for this resource. The pool would be responsible for initializing connections and each thread would acquire and release the connections as they are needed. \nIf you want to limit the number of available connections, you just block during the acquire phase until a connection is released or some timeout is reached.\nThe code to implement such a pool is going to be very dependent on the resource you are talking about, so it would be difficult to give you anything other than a suggested API. \n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003076348_pylons_python.txt
Q: How to update data to gae localhost server from MySQL? I follow this article to update data to gae localhost server from MySQL. This is my str_loader.py is: class College(db.Model): cid = db.StringProperty(required=True) name = db.StringProperty(required=True) class MySQLLoader(bulkloader.Loader): def generate_records(self, filename): """Generates records from a MySQL database.""" conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8") cursor = conn.cursor() sql ="select * from haha" cursor.execute(sql) #alldata = cursor.fetchall() return iter(cursor.fetchone, None) class Mysql_update(bulkloader.Loader): def __init__(self): MySQLLoader.__init__(self,'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) ]) loaders = [Mysql_update] And I use this code to run: appcfg.py upload_data --application=zjm1126 --config_file=upload/str_loader.py --filename=b.csv --kind=College --url=http://localhost:8100/remote_api However, it shows an error. So I change str_loader.py: class Mysql_update(bulkloader.Loader): def __init__(self): MySQLLoader('College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) But it still shows an error. What should I do? A: Your Mysql_update class needs to subclass MySQLLoader, not bulkloader.Loader.
How to update data to gae localhost server from MySQL?
I follow this article to update data to gae localhost server from MySQL. This is my str_loader.py is: class College(db.Model): cid = db.StringProperty(required=True) name = db.StringProperty(required=True) class MySQLLoader(bulkloader.Loader): def generate_records(self, filename): """Generates records from a MySQL database.""" conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8") cursor = conn.cursor() sql ="select * from haha" cursor.execute(sql) #alldata = cursor.fetchall() return iter(cursor.fetchone, None) class Mysql_update(bulkloader.Loader): def __init__(self): MySQLLoader.__init__(self,'College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) ]) loaders = [Mysql_update] And I use this code to run: appcfg.py upload_data --application=zjm1126 --config_file=upload/str_loader.py --filename=b.csv --kind=College --url=http://localhost:8100/remote_api However, it shows an error. So I change str_loader.py: class Mysql_update(bulkloader.Loader): def __init__(self): MySQLLoader('College', [ ('cid', str), ('name', lambda x: unicode(x, 'utf8')), ]) But it still shows an error. What should I do?
[ "Your Mysql_update class needs to subclass MySQLLoader, not bulkloader.Loader.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "mysql", "python" ]
stackoverflow_0003074918_google_app_engine_mysql_python.txt
Q: Virtual classes: doing it right? I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the parameters it is given and hand that back the calling function. For now I have a summary way of rerouting calls to the virtual class down to the underlying class. The idea is the following: class Shape: def __init__(self, description): if description == "It's flat": self.underlying_class = Line(description) elif description == "It's spiky": self.underlying_class = Triangle(description) elif description == "It's big": self.underlying_class = Rectangle(description) def number_of_edges(self, parameters): return self.underlying_class(parameters) class Line: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 1 class Triangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 3 class Rectangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 4 shape_dont_know_what_it_is = Shape("It's big") shape_dont_know_what_it_is.number_of_edges(parameters) My rerouting is far from optimal, as only calls to the number_of_edges() function get passed on. Adding something like this to Shape doesn't seam to do the trick either: def __getattr__(self, *args): return underlying_class.__getattr__(*args) What I am doing wrong ? Is the whole idea badly implemented ? Any help greatly appreciated. A: I agree with TooAngel, but I'd use the __new__ method. class Shape(object): def __new__(cls, *args, **kwargs): if cls is Shape: # <-- required because Line's description, args = args[0], args[1:] #  __new__ method is the if description == "It's flat": # same as Shape's new_cls = Line else: raise ValueError("Invalid description: {}.".format(description)) else: new_cls = cls return super(Shape, cls).__new__(new_cls, *args, **kwargs) def number_of_edges(self): return "A shape can have many edges…" class Line(Shape): def number_of_edges(self): return 1 class SomeShape(Shape): pass >>> l1 = Shape("It's flat") >>> l1.number_of_edges() 1 >>> l2 = Line() >>> l2.number_of_edges() 1 >>> u = SomeShape() >>> u.number_of_edges() 'A shape can have many edges…' >>> s = Shape("Hexagon") ValueError: Invalid description: Hexagon. A: I would prefer doing it with a factory: def factory(description): if description == "It's flat": return Line(description) elif description == "It's spiky": return Triangle(description) elif description == "It's big": return Rectangle(description) or: def factory(description): classDict = {"It's flat":Line("It's flat"), "It's spiky":Triangle("It's spiky"), "It's big":Rectangle("It's big")} return classDict[description] and inherit the classes from Shape class Line(Shape): def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 1 A: Python doesn't have virtual classes out of the box. You will have to implement them yourself (it should be possible, Python's reflection capabilities should be powerful enough to let you do this). However, if you need virtual classes, then why don't you just use a programming language which does have virtual classes like Beta, gBeta or Newspeak? (BTW: are there any others?) In this particular case, though, I don't really see how virtual classes would simplify your solution, at least not in the example you have given. Maybe you could elaborate why you think you need virtual classes? Don't get me wrong: I like virtual classes, but the fact that only three languages have ever implemented them, only one of those three is still alive and exactly 0 of those three are actually used by anybody is somewhat telling … A: You can change the class with object.__class__, but it's much better to just make a function that returns an instance of an arbitrary class. On another note, all class should inherit from object unless you use using Python 3, like this, otherwise you end up with an old-style class: class A(object): pass
Virtual classes: doing it right?
I have been reading documentation describing class inheritance, abstract base classes and even python interfaces. But nothing seams to be exactly what I want. Namely, a simple way of building virtual classes. When the virtual class gets called, I would like it to instantiate some more specific class based on what the parameters it is given and hand that back the calling function. For now I have a summary way of rerouting calls to the virtual class down to the underlying class. The idea is the following: class Shape: def __init__(self, description): if description == "It's flat": self.underlying_class = Line(description) elif description == "It's spiky": self.underlying_class = Triangle(description) elif description == "It's big": self.underlying_class = Rectangle(description) def number_of_edges(self, parameters): return self.underlying_class(parameters) class Line: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 1 class Triangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 3 class Rectangle: def __init__(self, description): self.desc = description def number_of_edges(self, parameters): return 4 shape_dont_know_what_it_is = Shape("It's big") shape_dont_know_what_it_is.number_of_edges(parameters) My rerouting is far from optimal, as only calls to the number_of_edges() function get passed on. Adding something like this to Shape doesn't seam to do the trick either: def __getattr__(self, *args): return underlying_class.__getattr__(*args) What I am doing wrong ? Is the whole idea badly implemented ? Any help greatly appreciated.
[ "I agree with TooAngel, but I'd use the __new__ method.\nclass Shape(object):\n def __new__(cls, *args, **kwargs):\n if cls is Shape: # <-- required because Line's\n description, args = args[0], args[1:] #  __new__ method is the\n if description == \"It's flat\": # same as Shape's\n new_cls = Line\n else:\n raise ValueError(\"Invalid description: {}.\".format(description))\n else:\n new_cls = cls\n return super(Shape, cls).__new__(new_cls, *args, **kwargs)\n\n def number_of_edges(self):\n return \"A shape can have many edges…\"\n\nclass Line(Shape):\n def number_of_edges(self):\n return 1\n\nclass SomeShape(Shape):\n pass\n\n\n>>> l1 = Shape(\"It's flat\")\n>>> l1.number_of_edges()\n1\n>>> l2 = Line()\n>>> l2.number_of_edges()\n1\n>>> u = SomeShape()\n>>> u.number_of_edges()\n'A shape can have many edges…'\n>>> s = Shape(\"Hexagon\")\nValueError: Invalid description: Hexagon.\n\n", "I would prefer doing it with a factory:\ndef factory(description):\n if description == \"It's flat\": return Line(description)\n elif description == \"It's spiky\": return Triangle(description)\n elif description == \"It's big\": return Rectangle(description)\n\nor:\ndef factory(description):\n classDict = {\"It's flat\":Line(\"It's flat\"), \"It's spiky\":Triangle(\"It's spiky\"), \"It's big\":Rectangle(\"It's big\")}\n return classDict[description]\n\nand inherit the classes from Shape\nclass Line(Shape):\n def __init__(self, description):\n self.desc = description\n def number_of_edges(self, parameters):\n return 1\n\n", "Python doesn't have virtual classes out of the box. You will have to implement them yourself (it should be possible, Python's reflection capabilities should be powerful enough to let you do this).\nHowever, if you need virtual classes, then why don't you just use a programming language which does have virtual classes like Beta, gBeta or Newspeak? (BTW: are there any others?)\nIn this particular case, though, I don't really see how virtual classes would simplify your solution, at least not in the example you have given. Maybe you could elaborate why you think you need virtual classes?\nDon't get me wrong: I like virtual classes, but the fact that only three languages have ever implemented them, only one of those three is still alive and exactly 0 of those three are actually used by anybody is somewhat telling …\n", "You can change the class with object.__class__, but it's much better to just make a function that returns an instance of an arbitrary class.\nOn another note, all class should inherit from object unless you use using Python 3, like this, otherwise you end up with an old-style class:\nclass A(object):\n pass\n\n" ]
[ 18, 15, 1, 0 ]
[]
[]
[ "abstract", "class", "inheritance", "python", "virtual" ]
stackoverflow_0003076537_abstract_class_inheritance_python_virtual.txt
Q: how to introspect a couchdb document for its set of fields via couchdb-python How can I get the fields for a couchdb document? I'm thinking of how to use couchdb-python, and often will not know the complete set of fields for a document. I haven't seen anything about how to introspect a document in the docs. What's the best way? If the document was a python object I would query object.__dict__ for its attributes. A: .keys() returns a list of field names. db = server['test'] for doc in db: print doc for key in db[doc].keys(): print key You should get the doc id, followed by the fields.
how to introspect a couchdb document for its set of fields via couchdb-python
How can I get the fields for a couchdb document? I'm thinking of how to use couchdb-python, and often will not know the complete set of fields for a document. I haven't seen anything about how to introspect a document in the docs. What's the best way? If the document was a python object I would query object.__dict__ for its attributes.
[ ".keys() returns a list of field names.\ndb = server['test']\nfor doc in db:\n print doc\n for key in db[doc].keys():\n print key\n\nYou should get the doc id, followed by the fields.\n" ]
[ 0 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0003076438_couchdb_python.txt
Q: Optimizing operations on lists I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python. The main ways I've come up with are using: - List comprehensions - generator expressions - functional style operations (map,filter etc.) I know generally list comprehensions are probably the most "Pythonic" method, but what is best in terms of performance? A: Inspired by this answer: Python List Comprehension Vs. Map , I've tweaked the questions to allow generator expressions to be compared: For built-ins: $ python -mtimeit -s 'import math;xs=range(10)' 'sum(map(math.sqrt, xs))' 100000 loops, best of 3: 2.96 usec per loop $ python -mtimeit -s 'import math;xs=range(10)' 'sum([math.sqrt(x) for x in xs)]' 100000 loops, best of 3: 3.75 usec per loop $ python -mtimeit -s 'import math;xs=range(10)' 'sum(math.sqrt(x) for x in xs)' 100000 loops, best of 3: 3.71 usec per loop For lambdas: $ python -mtimeit -s'xs=range(10)' 'sum(map(lambda x: x+2, xs))' 100000 loops, best of 3: 2.98 usec per loop $ python -mtimeit -s'xs=range(10)' 'sum([x+2 for x in xs])' 100000 loops, best of 3: 1.66 usec per loop $ python -mtimeit -s'xs=range(10)' 'sum(x+2 for x in xs)' 100000 loops, best of 3: 1.48 usec per loop Making a list: $ python -mtimeit -s'xs=range(10)' 'list(map(lambda x: x+2, xs))' 100000 loops, best of 3: 3.19 usec per loop $ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]' 100000 loops, best of 3: 1.21 usec per loop $ python -mtimeit -s'xs=range(10)' 'list(x+2 for x in xs)' 100000 loops, best of 3: 3.36 usec per loop It appears that map is best when paired with built-in functions, otherwise, generator expressions beat out list comprehensions. Along with slightly cleaner syntax, generator expressions also save much memory over list comprehensions because they are lazily evaluated. So in the absence of specific tests for your application, you should use map with builtins, a list comprehension when you require a list result, otherwise a generator. If you're really concerned with performance, you might take a look at whether you actually require lists at all points in your program.
Optimizing operations on lists
I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python. The main ways I've come up with are using: - List comprehensions - generator expressions - functional style operations (map,filter etc.) I know generally list comprehensions are probably the most "Pythonic" method, but what is best in terms of performance?
[ "Inspired by this answer: Python List Comprehension Vs. Map , I've tweaked the questions to allow generator expressions to be compared:\nFor built-ins:\n$ python -mtimeit -s 'import math;xs=range(10)' 'sum(map(math.sqrt, xs))'\n100000 loops, best of 3: 2.96 usec per loop\n$ python -mtimeit -s 'import math;xs=range(10)' 'sum([math.sqrt(x) for x in xs)]'\n100000 loops, best of 3: 3.75 usec per loop\n$ python -mtimeit -s 'import math;xs=range(10)' 'sum(math.sqrt(x) for x in xs)'\n100000 loops, best of 3: 3.71 usec per loop\n\nFor lambdas:\n$ python -mtimeit -s'xs=range(10)' 'sum(map(lambda x: x+2, xs))'\n100000 loops, best of 3: 2.98 usec per loop\n$ python -mtimeit -s'xs=range(10)' 'sum([x+2 for x in xs])'\n100000 loops, best of 3: 1.66 usec per loop\n$ python -mtimeit -s'xs=range(10)' 'sum(x+2 for x in xs)'\n100000 loops, best of 3: 1.48 usec per loop\n\nMaking a list:\n$ python -mtimeit -s'xs=range(10)' 'list(map(lambda x: x+2, xs))'\n100000 loops, best of 3: 3.19 usec per loop\n$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'\n100000 loops, best of 3: 1.21 usec per loop\n$ python -mtimeit -s'xs=range(10)' 'list(x+2 for x in xs)'\n100000 loops, best of 3: 3.36 usec per loop\n\nIt appears that map is best when paired with built-in functions, otherwise, generator expressions beat out list comprehensions. Along with slightly cleaner syntax, generator expressions also save much memory over list comprehensions because they are lazily evaluated. So in the absence of specific tests for your application, you should use map with builtins, a list comprehension when you require a list result, otherwise a generator. If you're really concerned with performance, you might take a look at whether you actually require lists at all points in your program.\n" ]
[ 1 ]
[]
[]
[ "list", "performance", "python" ]
stackoverflow_0003075375_list_performance_python.txt
Q: Python ctypes - how to handle arrays of strings I'm trying to call an external library function that returns a NULL-terminated array of NULL-terminated strings. kernel32 = ctypes.windll.kernel32 buf = ctypes.create_unicode_buffer(1024) length = ctypes.c_int32() if kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume), buf, ctypes.sizeof(buf), ctypes.pointer(length)): ## ??? In other words: buf = ctypes.create_unicode_buffer(u'Hello\0StackOverflow\0World!\0') How do I access all contents of buf as a Python list? buf.value only reaches up to the first NULL. In C it would be something like this: while (*sz) {; doStuff(sz); sz += lstrlen(sz) + 1; } A: After discovering ctypes.wstring_at() and ctypes.addressof(), I got this: def wszarray_to_list(array): offset = 0 while offset < ctypes.sizeof(array): sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2) if sz: yield sz offset += len(sz)+1 else: break A: It would be easier if you posted runnable code: getting a suitable volume name for this call is a bit of a pain. buf is an array containing length characters. The last two characters are nulls, so ignore them, convert the array to a string using ''.join() and split on the null characters. import ctypes kernel32 = ctypes.windll.kernel32 def volumes(): buf = ctypes.create_unicode_buffer(1024) length = ctypes.c_int32() handle = kernel32.FindFirstVolumeW(buf, ctypes.sizeof(buf)) if handle: yield buf.value while kernel32.FindNextVolumeW(handle, buf, ctypes.sizeof(buf)): yield buf.value kernel32.FindVolumeClose(handle) def VolumePathNames(volume): buf = ctypes.create_unicode_buffer(1024) length = ctypes.c_int32() kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume), buf, ctypes.sizeof(buf), ctypes.pointer(length)) return ''.join(buf[:length.value-2]).split('\0') for volume in volumes(): print volume print VolumePathNames(volume) When I run this all the lists just contain a single name, but if you double check against length that's all they contained in returned buffer.
Python ctypes - how to handle arrays of strings
I'm trying to call an external library function that returns a NULL-terminated array of NULL-terminated strings. kernel32 = ctypes.windll.kernel32 buf = ctypes.create_unicode_buffer(1024) length = ctypes.c_int32() if kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume), buf, ctypes.sizeof(buf), ctypes.pointer(length)): ## ??? In other words: buf = ctypes.create_unicode_buffer(u'Hello\0StackOverflow\0World!\0') How do I access all contents of buf as a Python list? buf.value only reaches up to the first NULL. In C it would be something like this: while (*sz) {; doStuff(sz); sz += lstrlen(sz) + 1; }
[ "After discovering ctypes.wstring_at() and ctypes.addressof(), I got this:\ndef wszarray_to_list(array):\n offset = 0\n while offset < ctypes.sizeof(array):\n sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)\n if sz:\n yield sz\n offset += len(sz)+1\n else:\n break\n\n", "It would be easier if you posted runnable code: getting a suitable volume name for this call is a bit of a pain. buf is an array containing length characters. The last two characters are nulls, so ignore them, convert the array to a string using ''.join() and split on the null characters.\nimport ctypes\nkernel32 = ctypes.windll.kernel32\n\ndef volumes():\n buf = ctypes.create_unicode_buffer(1024)\n length = ctypes.c_int32()\n handle = kernel32.FindFirstVolumeW(buf, ctypes.sizeof(buf))\n if handle:\n yield buf.value\n while kernel32.FindNextVolumeW(handle, buf, ctypes.sizeof(buf)):\n yield buf.value\n kernel32.FindVolumeClose(handle)\n\ndef VolumePathNames(volume):\n buf = ctypes.create_unicode_buffer(1024)\n length = ctypes.c_int32()\n kernel32.GetVolumePathNamesForVolumeNameW(ctypes.c_wchar_p(volume),\n buf, ctypes.sizeof(buf), ctypes.pointer(length))\n return ''.join(buf[:length.value-2]).split('\\0')\n\nfor volume in volumes():\n print volume\n print VolumePathNames(volume)\n\nWhen I run this all the lists just contain a single name, but if you double check against length that's all they contained in returned buffer.\n" ]
[ 6, 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003073478_ctypes_python.txt
Q: Start nano as a subprocess from python, capture input I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the subprocess module before, nor pipes, so I don't know what to try next. So far I have this code: a = subprocess.Popen('nano', stdout=subprocess.PIPE, shell=True) Where a should capture the output. This code, however, doesn't bring up nano, and instead makes the python terminal behave strangely. Up and down keys (history) stop working and the backspace key becomes dysfunctional. Can someone point me in the right direction to solve this issue? I realize that I may need to read up on pipes in Python, but the only info I can find is the pipes module and it doesn't help much. A: Control-O in Nano writes to the file being edited, i.e., not to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac: >>> import tempfile >>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False) >>> n = f.name >>> f.close() >>> import subprocess >>> subprocess.call(['nano', n]) Here, I write "Hello world!" then hit control-O Return control-X , and: 0 >>> with open(n) as f: print f.read() ... Hello world! >>> A: I'm not sure you can capture what the user has entered into nano. After all, that's nano's job. What you can (and I think should do) to get user input from an editor is to spawn it off with a temporary file. Then when the user has entered what he wants, he saves and quits. Your program reads the content from the file and then deletes it. Just spawn the editor using os.system. Your terminal is behaving funny because nano is a full screen program and will use terminal escape sequences (probably via. curses) the manipulate the screen and cursor. If you spawn it unattached to a terminal, it will misbehave. Also, you should consider opening $EDITOR if it's defined rather than nano. That's what people would expect.
Start nano as a subprocess from python, capture input
I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the subprocess module before, nor pipes, so I don't know what to try next. So far I have this code: a = subprocess.Popen('nano', stdout=subprocess.PIPE, shell=True) Where a should capture the output. This code, however, doesn't bring up nano, and instead makes the python terminal behave strangely. Up and down keys (history) stop working and the backspace key becomes dysfunctional. Can someone point me in the right direction to solve this issue? I realize that I may need to read up on pipes in Python, but the only info I can find is the pipes module and it doesn't help much.
[ "Control-O in Nano writes to the file being edited, i.e., not to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac:\n>>> import tempfile\n>>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)\n>>> n = f.name\n>>> f.close()\n>>> import subprocess\n>>> subprocess.call(['nano', n])\n\nHere, I write \"Hello world!\" then hit control-O Return control-X , and:\n0\n>>> with open(n) as f: print f.read()\n... \nHello world!\n\n\n>>> \n\n", "I'm not sure you can capture what the user has entered into nano. After all, that's nano's job. \nWhat you can (and I think should do) to get user input from an editor is to spawn it off with a temporary file. Then when the user has entered what he wants, he saves and quits. Your program reads the content from the file and then deletes it. \nJust spawn the editor using os.system. Your terminal is behaving funny because nano is a full screen program and will use terminal escape sequences (probably via. curses) the manipulate the screen and cursor. If you spawn it unattached to a terminal, it will misbehave. \nAlso, you should consider opening $EDITOR if it's defined rather than nano. That's what people would expect.\n" ]
[ 10, 4 ]
[]
[]
[ "pipe", "popen", "python", "subprocess" ]
stackoverflow_0003076798_pipe_popen_python_subprocess.txt
Q: Google App Engine Unittest: Difficulty with AssertEquals I have a unit test for my GAE app: def test_getNeighborhoodKeys_twoCourses(self): cs1110, cs2110 = testutils.setUpSimpleCourses() foo = getFooResult() bar = getBarResult() self.assertEquals(foo, bar) # fails This is the failure: AssertionError: set([CS 1110: Untitled, CS 2110: Untitled]) != set([CS 2110: Untitled, CS 1110: Untitled]) It looks to me like the test should pass. What's going wrong? A: Looks like the items belonging to sets foo and bar are of some extremely funky type which overrides __repr__ -- otherwise, with normal types, there would be quotes to clarify exactly what's inside those brackets. Thus, that type must also override __eq__ to determine equality conditions (otherwise, by default, two instances are equal only if they're the same instance). You could alternatively override __cmp__, but that's a pretty old and dusty approach -- specific comparisons such as __eq__ are vastly preferred nowadays! If you do override __eq__ (or __cmp__ for that matter) be sure to also override __hash__ because it's crucial that two instances that compare equal have exactly the same hash too, otherwise use of such instances as members of sets, or keys in dictionaries, misbehaves in very hard to predict ways.
Google App Engine Unittest: Difficulty with AssertEquals
I have a unit test for my GAE app: def test_getNeighborhoodKeys_twoCourses(self): cs1110, cs2110 = testutils.setUpSimpleCourses() foo = getFooResult() bar = getBarResult() self.assertEquals(foo, bar) # fails This is the failure: AssertionError: set([CS 1110: Untitled, CS 2110: Untitled]) != set([CS 2110: Untitled, CS 1110: Untitled]) It looks to me like the test should pass. What's going wrong?
[ "Looks like the items belonging to sets foo and bar are of some extremely funky type which overrides __repr__ -- otherwise, with normal types, there would be quotes to clarify exactly what's inside those brackets. Thus, that type must also override __eq__ to determine equality conditions (otherwise, by default, two instances are equal only if they're the same instance). You could alternatively override __cmp__, but that's a pretty old and dusty approach -- specific comparisons such as __eq__ are vastly preferred nowadays!\nIf you do override __eq__ (or __cmp__ for that matter) be sure to also override __hash__ because it's crucial that two instances that compare equal have exactly the same hash too, otherwise use of such instances as members of sets, or keys in dictionaries, misbehaves in very hard to predict ways.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0003076856_google_app_engine_python_unit_testing.txt
Q: What is the difference between these two solutions - lambda or loop - Python I want to calculate the sum of even numbers within a domain. I have two solutions, but I'm not sure of the advantages/disadvantages of each. Which is the optimal solution? import sys domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Cal1 = sum(filter(lambda n : n % 2 == 0, domain)) Cal2 = sum([n for n in domain if n % 2 == 0]) sys.stdout.write("Cal1 = {0}\n".format(Cal1)) sys.stdout.write("Cal2 = {0}\n".format(Cal2)) A: The second really should be just a generator, not a list comprehension (since you don't actually need to create a list to be able to sum the output of a generator): Cal2 = sum(n for n in domain if n % 2 == 0) It's the now-preferred ("pythonic") way for accomplishing this task. Using a list comprehension (the one including the [], your original Cal2) is disadvantageous because it actually constructs a list object to return, which has overhead. Using filter (your Cal1) is equivalent to a generator (the no-[] version), but requires a bit more typing and doesn't read quite as well as just using a generator expression (the code I posted above). A: Here are the speeds of the various versions on an old-ish Mac laptop: $ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(filter(lambda n : n % 2 == 0, domain))' 100000 loops, best of 3: 4.41 usec per loop $ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum([n for n in domain if n % 2 == 0])' 100000 loops, best of 3: 2.69 usec per loop $ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(n for n in domain if n % 2 == 0)' 100000 loops, best of 3: 2.86 usec per loop Note that, while the genexp version is no doubt more cool, the listcomp is marginally faster (probably not by enough to worry about unless this code is in a tight inner loop you're striving to optimize the snot out of;-). As usual, the lambda-based version is substantially slower, as others have mentioned -- lambda is kind of a "poor relation" in Python:-(. ((Not that a defined function would perform noticeably better here, either)) A: Your second way of doing it is what is called a list comprehension. List comprehensions can be used to achieve the things you would previously use filter and map for prior to their introduction to the language. See this previous question for a discussion on list comprehensions vs map which is similar to what you are asking. As Amber writes, the recommended Pythonic way to do it is to use a generator. With the list comprehsions your entire filtered list is built and then summed. With the generator it is summed as it goes along without ever having the full list in memory. This makes more of a difference when you are working with more than 10 items. A: +1 to the other great answers. Bonus: the generator expression is faster... $ python -m timeit -s 'L = xrange(10)' 'sum(filter(lambda n: n % 2 == 0, L))' 100000 loops, best of 3: 3.59 usec per loop $ python -m timeit -s 'L = xrange(10)' 'sum(n for n in L if n % 2 == 0)' 100000 loops, best of 3: 2.82 usec per loop Docs re timeit.
What is the difference between these two solutions - lambda or loop - Python
I want to calculate the sum of even numbers within a domain. I have two solutions, but I'm not sure of the advantages/disadvantages of each. Which is the optimal solution? import sys domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Cal1 = sum(filter(lambda n : n % 2 == 0, domain)) Cal2 = sum([n for n in domain if n % 2 == 0]) sys.stdout.write("Cal1 = {0}\n".format(Cal1)) sys.stdout.write("Cal2 = {0}\n".format(Cal2))
[ "The second really should be just a generator, not a list comprehension (since you don't actually need to create a list to be able to sum the output of a generator):\nCal2 = sum(n for n in domain if n % 2 == 0)\n\nIt's the now-preferred (\"pythonic\") way for accomplishing this task.\n\nUsing a list comprehension (the one including the [], your original Cal2) is disadvantageous because it actually constructs a list object to return, which has overhead.\nUsing filter (your Cal1) is equivalent to a generator (the no-[] version), but requires a bit more typing and doesn't read quite as well as just using a generator expression (the code I posted above).\n\n", "Here are the speeds of the various versions on an old-ish Mac laptop:\n$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(filter(lambda n : n % 2 == 0, domain))'\n100000 loops, best of 3: 4.41 usec per loop\n$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum([n for n in domain if n % 2 == 0])'\n100000 loops, best of 3: 2.69 usec per loop\n$ py26 -mtimeit -s'domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 'sum(n for n in domain if n % 2 == 0)'\n100000 loops, best of 3: 2.86 usec per loop\n\nNote that, while the genexp version is no doubt more cool, the listcomp is marginally faster (probably not by enough to worry about unless this code is in a tight inner loop you're striving to optimize the snot out of;-). As usual, the lambda-based version is substantially slower, as others have mentioned -- lambda is kind of a \"poor relation\" in Python:-(. ((Not that a defined function would perform noticeably better here, either))\n", "Your second way of doing it is what is called a list comprehension. List comprehensions can be used to achieve the things you would previously use filter and map for prior to their introduction to the language. See this previous question for a discussion on list comprehensions vs map which is similar to what you are asking.\nAs Amber writes, the recommended Pythonic way to do it is to use a generator. With the list comprehsions your entire filtered list is built and then summed. With the generator it is summed as it goes along without ever having the full list in memory. This makes more of a difference when you are working with more than 10 items.\n", "+1 to the other great answers.\nBonus: the generator expression is faster...\n$ python -m timeit -s 'L = xrange(10)' 'sum(filter(lambda n: n % 2 == 0, L))'\n100000 loops, best of 3: 3.59 usec per loop\n\n$ python -m timeit -s 'L = xrange(10)' 'sum(n for n in L if n % 2 == 0)'\n100000 loops, best of 3: 2.82 usec per loop\n\nDocs re timeit.\n" ]
[ 13, 7, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003076692_python.txt
Q: Python: Is this an ok way of overriding __eq__ and __hash__? I'm new to Python, and I wanted to make sure that I overrode __eq__ and __hash__ correctly, so as not to cause painful errors later: (I'm using Google App Engine.) class Course(db.Model): dept_code = db.StringProperty() number = db.IntegerProperty() title = db.StringProperty() raw_pre_reqs = db.StringProperty(multiline=True) original_description = db.StringProperty() def getPreReqs(self): return pickle.loads(str(self.raw_pre_reqs)) def __repr__(self): title_msg = self.title if self.title else "Untitled" return "%s %s: %s" % (self.dept_code, self.number, title_msg) def __attrs(self): return (self.dept_code, self.number, self.title, self.raw_pre_reqs, self.original_description) def __eq__(self, other): return isinstance(other, Course) and self.__attrs() == other.__attrs() def __hash__(self): return hash(self.__attrs()) A slightly more complicated type: class DependencyArcTail(db.Model): ''' A list of courses that is a pre-req for something else ''' courses = db.ListProperty(db.Key) ''' a list of heads that reference this one ''' forwardLinks = db.ListProperty(db.Key) def __repr__(self): return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks)) def __eq__(self, other): if not isinstance(other, DependencyArcTail): return False for this_course in self.courses: if not (this_course in other.courses): return False for other_course in other.courses: if not (other_course in self.courses): return False return True def __hash__(self): return hash((tuple(self.courses), tuple(self.forwardLinks))) Everything look good? Updated to reflect @Alex's comments class DependencyArcTail(db.Model): ''' A list of courses that is a pre-req for something else ''' courses = db.ListProperty(db.Key) ''' a list of heads that reference this one ''' forwardLinks = db.ListProperty(db.Key) def __repr__(self): return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks)) def __eq__(self, other): return isinstance(other, DependencyArcTail) and set(self.courses) == set(other.courses) and set(self.forwardLinks) == set(other.forwardLinks) def __hash__(self): return hash((tuple(self.courses), tuple(self.forwardLinks))) A: The first one is fine. The second one is problematic for two reasons: there might be duplicates in .courses two entities with identical .courses but different .forwardLinks would compare equal but have different hashes I would fix the second one by making equality depend on both courses and forward links, but both changes to sets (hence no duplicates), and the same for hashing. I.e.: def __eq__(self, other): if not isinstance(other, DependencyArcTail): return False return (set(self.courses) == set(other.courses) and set(self.forwardLinks) == set(other.forwardLinks)) def __hash__(self): return hash((frozenset(self.courses), frozenset(self.forwardLinks))) This of course is assuming that the forward links are crucial to an object's "real value", otherwise they should be omitted from both __eq__ and __hash__. Edit: removed from __hash__ calls to tuple which were at best redundant (and possibly damaging, as suggested by a comment by @Mark [[tx!!!]]); changed set to frozenset in the hashing, as suggested by a comment by @Phillips [[tx!!!]].
Python: Is this an ok way of overriding __eq__ and __hash__?
I'm new to Python, and I wanted to make sure that I overrode __eq__ and __hash__ correctly, so as not to cause painful errors later: (I'm using Google App Engine.) class Course(db.Model): dept_code = db.StringProperty() number = db.IntegerProperty() title = db.StringProperty() raw_pre_reqs = db.StringProperty(multiline=True) original_description = db.StringProperty() def getPreReqs(self): return pickle.loads(str(self.raw_pre_reqs)) def __repr__(self): title_msg = self.title if self.title else "Untitled" return "%s %s: %s" % (self.dept_code, self.number, title_msg) def __attrs(self): return (self.dept_code, self.number, self.title, self.raw_pre_reqs, self.original_description) def __eq__(self, other): return isinstance(other, Course) and self.__attrs() == other.__attrs() def __hash__(self): return hash(self.__attrs()) A slightly more complicated type: class DependencyArcTail(db.Model): ''' A list of courses that is a pre-req for something else ''' courses = db.ListProperty(db.Key) ''' a list of heads that reference this one ''' forwardLinks = db.ListProperty(db.Key) def __repr__(self): return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks)) def __eq__(self, other): if not isinstance(other, DependencyArcTail): return False for this_course in self.courses: if not (this_course in other.courses): return False for other_course in other.courses: if not (other_course in self.courses): return False return True def __hash__(self): return hash((tuple(self.courses), tuple(self.forwardLinks))) Everything look good? Updated to reflect @Alex's comments class DependencyArcTail(db.Model): ''' A list of courses that is a pre-req for something else ''' courses = db.ListProperty(db.Key) ''' a list of heads that reference this one ''' forwardLinks = db.ListProperty(db.Key) def __repr__(self): return "DepArcTail %d: courses='%s' forwardLinks='%s'" % (id(self), getReprOfKeys(self.courses), getIdOfKeys(self.forwardLinks)) def __eq__(self, other): return isinstance(other, DependencyArcTail) and set(self.courses) == set(other.courses) and set(self.forwardLinks) == set(other.forwardLinks) def __hash__(self): return hash((tuple(self.courses), tuple(self.forwardLinks)))
[ "The first one is fine. The second one is problematic for two reasons:\n\nthere might be duplicates in .courses\ntwo entities with identical .courses but different .forwardLinks would compare equal but have different hashes\n\nI would fix the second one by making equality depend on both courses and forward links, but both changes to sets (hence no duplicates), and the same for hashing. I.e.:\ndef __eq__(self, other):\n if not isinstance(other, DependencyArcTail):\n return False\n\n return (set(self.courses) == set(other.courses) and\n set(self.forwardLinks) == set(other.forwardLinks))\n\ndef __hash__(self):\n return hash((frozenset(self.courses), frozenset(self.forwardLinks)))\n\nThis of course is assuming that the forward links are crucial to an object's \"real value\", otherwise they should be omitted from both __eq__ and __hash__.\nEdit: removed from __hash__ calls to tuple which were at best redundant (and possibly damaging, as suggested by a comment by @Mark [[tx!!!]]); changed set to frozenset in the hashing, as suggested by a comment by @Phillips [[tx!!!]].\n" ]
[ 17 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0003076967_hash_python.txt
Q: Quoting long strings without newlines in Python I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string is displayed when the code is run. For example, I want to write: parser.add_option("--my-option", dest="my_option", nargs=2, default=None, help='''Here is a long description of my option. It does many things but I want the shell to decide how to display this explanation. However, I want newlines in this string.''') the above way of doing things will make it so when I call my program with --help, the explanation of my-option will have many gaps in it. How can I fix this? thanks. A: You can concatenate string literals just like in C, so "foo" "bar" is the same as "foobar", meaning this should do what you want: parser.add_option("--my-option", dest="my_option", nargs=2, default=None, help="Here is a long description of my option. It does many things " "but I want the shell to decide how to display this explanation. However, " "I want newlines in this string.") Note that you don't need backslash line continuation characters because the whole thing is within parentheses. A: Just take advantage of string-literal juxtaposition -- in Python, like in C, if two string literals are next to each other with just whitespace in-between (including newlines), the compiler will merge them into a single string literal, ignoring the whitespace. I.e.: parser.add_option("--my-option", dest="my_option", nargs=2, default=None, help='Here is a long description of my option. It does ' 'many things but I want the shell to decide how to ' 'display this explanation. However, I do NOT want ' 'newlines in this string.') I'm assuming that by "I want" you actually mean "I do NOT want" here;-). Note the trailing spaces at the end of each piece of the literal you're passing as help: you have to put them there explicitly, or else the juxtaposition would make "words" such as doesmany and so on;-). Note that, very differently from what some answers and comments claim, you most definitely don't need ugly, redundant pluses and-or backslashes here -- no pluses needed because the compiler applies juxtaposition for you, no backslashes needed either because this set of physical lines is a single logical line (thanks to the open paren not being closed yet until the end of the set of physical lines!). A: Default help formatter reformats the string so you can use newlines in the help string as you like: >>> from optparse import OptionParser >>> parser = OptionParser() >>> parser.add_option('--my-option', help='''aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaa ... b ... c d ... e ... f''') >>> parser.print_help() Usage: bpython [options] Options: -h, --help show this help message and exit --my-option=MY_OPTION aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaa b c d e f To remove any common leading space you could use textwrap.dedent: >>> from optparse import OptionParser >>> from textwrap import dedent >>> parser = OptionParser() >>> parser.add_option('--my-option', help=dedent('''\ ... Here is a long description of my option. It does many things ... but I want the shell to decide how to display this ... explanation. However, I want newlines in this string.''')) >>> parser.print_help() Usage: [options] Options: -h, --help show this help message and exit --my-option=MY_OPTION Here is a long description of my option. It does many things but I want the shell to decide how to display this explanation. However, I want newlines in this string. A: This works: foo = "abc" + \ "def" + \ "ghi" print foo
Quoting long strings without newlines in Python
I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string is displayed when the code is run. For example, I want to write: parser.add_option("--my-option", dest="my_option", nargs=2, default=None, help='''Here is a long description of my option. It does many things but I want the shell to decide how to display this explanation. However, I want newlines in this string.''') the above way of doing things will make it so when I call my program with --help, the explanation of my-option will have many gaps in it. How can I fix this? thanks.
[ "You can concatenate string literals just like in C, so \"foo\" \"bar\" is the same as \"foobar\", meaning this should do what you want:\nparser.add_option(\"--my-option\", dest=\"my_option\", nargs=2, default=None, \n help=\"Here is a long description of my option. It does many things \"\n \"but I want the shell to decide how to display this explanation. However, \"\n \"I want newlines in this string.\") \n\nNote that you don't need backslash line continuation characters because the whole thing is within parentheses.\n", "Just take advantage of string-literal juxtaposition -- in Python, like in C, if two string literals are next to each other with just whitespace in-between (including newlines), the compiler will merge them into a single string literal, ignoring the whitespace. I.e.:\nparser.add_option(\"--my-option\", dest=\"my_option\", nargs=2, default=None,\n help='Here is a long description of my option. It does '\n 'many things but I want the shell to decide how to '\n 'display this explanation. However, I do NOT want '\n 'newlines in this string.')\n\nI'm assuming that by \"I want\" you actually mean \"I do NOT want\" here;-).\nNote the trailing spaces at the end of each piece of the literal you're passing as help: you have to put them there explicitly, or else the juxtaposition would make \"words\" such as doesmany and so on;-).\nNote that, very differently from what some answers and comments claim, you most definitely don't need ugly, redundant pluses and-or backslashes here -- no pluses needed because the compiler applies juxtaposition for you, no backslashes needed either because this set of physical lines is a single logical line (thanks to the open paren not being closed yet until the end of the set of physical lines!).\n", "Default help formatter reformats the string so you can use newlines in the help string as you like:\n>>> from optparse import OptionParser\n>>> parser = OptionParser()\n>>> parser.add_option('--my-option', help='''aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaaaaa\n... b\n... c d\n... e\n... f''')\n>>> parser.print_help()\nUsage: bpython [options]\n\nOptions:\n -h, --help show this help message and exit\n --my-option=MY_OPTION\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n aaa b c d e f\n\nTo remove any common leading space you could use textwrap.dedent:\n>>> from optparse import OptionParser\n>>> from textwrap import dedent\n>>> parser = OptionParser()\n>>> parser.add_option('--my-option', help=dedent('''\\\n... Here is a long description of my option. It does many things\n... but I want the shell to decide how to display this\n... explanation. However, I want newlines in this string.'''))\n>>> parser.print_help()\nUsage: [options]\n\nOptions:\n -h, --help show this help message and exit\n --my-option=MY_OPTION\n Here is a long description of my option. It does many\n things but I want the shell to decide how to display\n this explanation. However, I want newlines in this\n string.\n\n", "This works:\nfoo = \"abc\" + \\\n \"def\" + \\\n \"ghi\"\n\nprint foo\n\n" ]
[ 22, 10, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003076979_python.txt
Q: How to Exporter gae data to MySQL? I have a 'College' model data. My str_loader.py is: class MySQLExporter(bulkloader.Exporter): def output_entities(self, entity_generator): conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8") c = conn.cursor() for entity in entity_generator: c.execute("INSERT INTO haha (a,b) VALUES (%s, %s)", (entity['cid'], entity['name'])) class Mysql_download(MySQLExporter): def __init__(self): MySQLExporter.__init__(self,'College', [ ('cid', str,None), ('name', lambda x: unicode(x, 'utf8'),None), ]) exporters = [Mysql_download] And it running successful. However, it does not insert data to MySQL. A: Try calling .commit() on the connection after loading the entities.
How to Exporter gae data to MySQL?
I have a 'College' model data. My str_loader.py is: class MySQLExporter(bulkloader.Exporter): def output_entities(self, entity_generator): conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',charset="utf8") c = conn.cursor() for entity in entity_generator: c.execute("INSERT INTO haha (a,b) VALUES (%s, %s)", (entity['cid'], entity['name'])) class Mysql_download(MySQLExporter): def __init__(self): MySQLExporter.__init__(self,'College', [ ('cid', str,None), ('name', lambda x: unicode(x, 'utf8'),None), ]) exporters = [Mysql_download] And it running successful. However, it does not insert data to MySQL.
[ "Try calling .commit() on the connection after loading the entities.\n" ]
[ 1 ]
[]
[]
[ "download", "google_app_engine", "mysql", "python" ]
stackoverflow_0003076933_download_google_app_engine_mysql_python.txt
Q: Node.TEXT_NODE has the value, but I need the Attribute I have an xml file like so: <host name='ip-10-196-55-2.ec2.internal'> <hostvalue name='arch_string'>lx24-x86</hostvalue> <hostvalue name='num_proc'>1</hostvalue> <hostvalue name='load_avg'>0.01</hostvalue> </host> I can get get out the Node.data from a Node.TEXT_NODE, but I also need the Attribute name, like I want to know load_avg = 0.01, without writing load_avg, num_proc, etc, one by one. I want them all. My code looks like this, but I can't figure out what part of the Node has the attribute name for me. for stat in h.getElementsByTagName("hostvalue"): for node3 in stat.childNodes: attr = "foo" val = "poo" if node3.nodeType == Node.ATTRINUTE_NODE: attr = node3.tagName if node3.nodeType == Node.TEXT_NODE: #attr = node3.tagName val = node3.data From the above code, I'm able to get val, but not attr (compile error: A: here's a short example of what you could achieve: from xml.dom import minidom xmldoc = minidom.parse("so.xml") values = {} for stat in xmldoc.getElementsByTagName("hostvalue"): attr = stat.attributes["name"].value value = "\n".join([x.data for x in stat.childNodes]) values[attr] = value print repr(values) This outputs, given your XML file: $ ./parse.py {u'num_proc': u'1', u'arch_string': u'lx24-x86', u'load_avg': u'0.01'} Be warned that this is not failsafe, i.e. if you have nested elements inside <hostvalue>.
Node.TEXT_NODE has the value, but I need the Attribute
I have an xml file like so: <host name='ip-10-196-55-2.ec2.internal'> <hostvalue name='arch_string'>lx24-x86</hostvalue> <hostvalue name='num_proc'>1</hostvalue> <hostvalue name='load_avg'>0.01</hostvalue> </host> I can get get out the Node.data from a Node.TEXT_NODE, but I also need the Attribute name, like I want to know load_avg = 0.01, without writing load_avg, num_proc, etc, one by one. I want them all. My code looks like this, but I can't figure out what part of the Node has the attribute name for me. for stat in h.getElementsByTagName("hostvalue"): for node3 in stat.childNodes: attr = "foo" val = "poo" if node3.nodeType == Node.ATTRINUTE_NODE: attr = node3.tagName if node3.nodeType == Node.TEXT_NODE: #attr = node3.tagName val = node3.data From the above code, I'm able to get val, but not attr (compile error:
[ "here's a short example of what you could achieve:\nfrom xml.dom import minidom\n\nxmldoc = minidom.parse(\"so.xml\")\n\nvalues = {}\n\nfor stat in xmldoc.getElementsByTagName(\"hostvalue\"):\n attr = stat.attributes[\"name\"].value\n value = \"\\n\".join([x.data for x in stat.childNodes])\n values[attr] = value\n\nprint repr(values)\n\nThis outputs, given your XML file:\n$ ./parse.py \n{u'num_proc': u'1', u'arch_string': u'lx24-x86', u'load_avg': u'0.01'}\n\nBe warned that this is not failsafe, i.e. if you have nested elements inside <hostvalue>.\n" ]
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003073471_python_xml.txt
Q: Fastest way of deleting certain keys from dict in Python I'm looking for most fastest/effective way of deleting certain keys in a python dict Here are some options for k in somedict.keys(): if k.startswith("someprefix"): del somedict[k] or dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix')) Logically first snippet should be faster on smaller dicts, it doesn't create a copy of a dict but creates a list of all keys, however double lookups and dict rebuilding is time consuming. While the second is faster on bigger dicts, but requires 2x more memory. I've checked my assumption in some small benchmark. Anything faster? A: Not only is del more easily understood, but it seems slightly faster than pop(): $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "for k in d.keys():" " if k.startswith('f'):" " del d[k]" 1000000 loops, best of 3: 0.733 usec per loop $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "for k in d.keys():" " if k.startswith('f'):" " d.pop(k)" 1000000 loops, best of 3: 0.742 usec per loop Edit: thanks to Alex Martelli for providing instructions on how to do this benchmarking. Hopefully I have not slipped up anywhere. First measure the time required for copying: $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" 1000000 loops, best of 3: 0.278 usec per loop Benchmark on copied dict: $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" "for k in d1.keys():" " if k.startswith('f'):" " del d1[k]" 100000 loops, best of 3: 1.95 usec per loop $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "d1 = d.copy()" "for k in d1.keys():" " if k.startswith('f'):" " d1.pop(k)" 100000 loops, best of 3: 2.15 usec per loop Subtracting the cost of copying, we get 1.872 usec for pop() and 1.672 for del. A: If the dict is large enough, it may make sense to generate a whole new dict instead. dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))
Fastest way of deleting certain keys from dict in Python
I'm looking for most fastest/effective way of deleting certain keys in a python dict Here are some options for k in somedict.keys(): if k.startswith("someprefix"): del somedict[k] or dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix')) Logically first snippet should be faster on smaller dicts, it doesn't create a copy of a dict but creates a list of all keys, however double lookups and dict rebuilding is time consuming. While the second is faster on bigger dicts, but requires 2x more memory. I've checked my assumption in some small benchmark. Anything faster?
[ "Not only is del more easily understood, but it seems slightly faster than pop():\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"for k in d.keys():\" \" if k.startswith('f'):\" \" del d[k]\"\n1000000 loops, best of 3: 0.733 usec per loop\n\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"for k in d.keys():\" \" if k.startswith('f'):\" \" d.pop(k)\"\n1000000 loops, best of 3: 0.742 usec per loop\n\n\nEdit: thanks to Alex Martelli for providing instructions on how to do this benchmarking. Hopefully I have not slipped up anywhere.\nFirst measure the time required for copying:\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"d1 = d.copy()\"\n1000000 loops, best of 3: 0.278 usec per loop\n\nBenchmark on copied dict:\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"d1 = d.copy()\" \"for k in d1.keys():\" \" if k.startswith('f'):\" \" del d1[k]\"\n100000 loops, best of 3: 1.95 usec per loop\n\n$ python -m timeit -s \"d = {'f':1,'foo':2,'bar':3}\" \"d1 = d.copy()\" \"for k in d1.keys():\" \" if k.startswith('f'):\" \" d1.pop(k)\"\n100000 loops, best of 3: 2.15 usec per loop\n\nSubtracting the cost of copying, we get 1.872 usec for pop() and 1.672 for del.\n", "If the dict is large enough, it may make sense to generate a whole new dict instead.\ndict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))\n\n" ]
[ 18, 9 ]
[]
[]
[ "dictionary", "filter", "python" ]
stackoverflow_0003077145_dictionary_filter_python.txt
Q: Instrumentation for numerical linear algebra in Python I use numpy for numerical linear algebra. I suspect that I can get much better performance if I make small modifications in how I carry out certain computations so that they are more memory efficient, for example. I was wondering if there is any form of instrumentation available in python to detect cache and TLB misses. There is a very nice api, PAPI, that I learned about in a recent class but it doesn't have a Python interface: http://icl.cs.utk.edu/papi/overview/index.html Also, is there a good way in general to profile numpy or other python numerical code? The timeit module is hard to integrate into code. mpi4py has a nice way to profile using the MPE library. A snippet from demo code (demo/mpe-logging/cpilog.py): communication = MPE.newLogState("Comunicate", "red") with communication: comm.Bcast([n, MPI.INT], root=0) A log file is created that can be displayed graphically. But this is a bit MPI specific. Thanks. A: Maybe one of the provided profilers might help you find the hotspots? see profiling python These will probably not give enough detail to trigger direct action, but should indicate where to look for improvement and help to determine the point of diminishing returns. A: Robert Kern (one of the NumPy devs) wrote line_profiler for exactly this scenario. It is more suited to profiling NumPy-heavy code than hotspot/cProfile.
Instrumentation for numerical linear algebra in Python
I use numpy for numerical linear algebra. I suspect that I can get much better performance if I make small modifications in how I carry out certain computations so that they are more memory efficient, for example. I was wondering if there is any form of instrumentation available in python to detect cache and TLB misses. There is a very nice api, PAPI, that I learned about in a recent class but it doesn't have a Python interface: http://icl.cs.utk.edu/papi/overview/index.html Also, is there a good way in general to profile numpy or other python numerical code? The timeit module is hard to integrate into code. mpi4py has a nice way to profile using the MPE library. A snippet from demo code (demo/mpe-logging/cpilog.py): communication = MPE.newLogState("Comunicate", "red") with communication: comm.Bcast([n, MPI.INT], root=0) A log file is created that can be displayed graphically. But this is a bit MPI specific. Thanks.
[ "Maybe one of the provided profilers might help you find the hotspots? \nsee profiling python\nThese will probably not give enough detail to trigger direct action, but should indicate where to look for improvement and help to determine the point of diminishing returns.\n", "Robert Kern (one of the NumPy devs) wrote line_profiler for exactly this scenario. It is more suited to profiling NumPy-heavy code than hotspot/cProfile.\n" ]
[ 1, 1 ]
[]
[]
[ "instrumentation", "linear_algebra", "numpy", "python", "scipy" ]
stackoverflow_0003077061_instrumentation_linear_algebra_numpy_python_scipy.txt
Q: Mercurial/Python - What Does The Underscore Function Do? In Mercurial, many of the extensions wrap their help/syntax string in a call to an underscore function, like so: _('[OPTION] [QUEUE]') This confuses me, because it does not seem necessary (the Writing Extensions instructions don't mention it) and there doesn't seem to be a _ defined in the class, so I'm wondering if this is some special syntax that I don't understand, perhaps another way to say lambda, or maybe the identity function? Additionally I'm wondering what the benefit of this methodology (whatever it is) is over just the raw string like the documentation suggests. Nothing I've seen in the Python documentation mentions such a function, so I'm not sure if this is really a Python question, or a Mercurial question. Here are two examples that use this structure (look at the cmdtable dictionary near the bottom of the file) https://www.mercurial-scm.org/repo/hg/file/42408cd43f55/hgext/mq.py https://www.mercurial-scm.org/repo/hg/file/42408cd43f55/hgext/graphlog.py A: Look on line 45: from mercurial.i18n import _ This is the usual abbreviation in the internationalization package gettext, and possibly other packages too, for the function that returns a translation of its argument to the language the program is currently running in. It's abbreviated to _ for convenience, since it's used for just about every message displayed to the user. Looks like Mercurial wraps it in their own module. ("i18n" stands for "internationalization" because there are 18 letters in between "i" and "n".) A: _ (a function name of a single underscore) is often associated with internationalization, due to the precedent of gettext, a GNU approach that has also found a place in Python's standard library (same architecture, completely different implementation) -- per the module's docs, gettext.install(domain[, localedir[, unicode[, codeset[, names]]]]) This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation(). The unicode flag is passed to the resulting translation object’s install() method. For the names parameter, please see the description of the translation object’s install() method. As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the _() function, like this: print _('This string will be translated.') For convenience, you want the _() function to be installed in Python’s builtins namespace, so it is easily accessible in all modules of your application. As @ptomato mentions, Mercurial has followed this tradition by naming _ the equivalent function of their own that they use for the same internationalization purposes. There is also a separate tradition to use _ as the "I don't care" identifier, as in fee, fie, _, _, foo, _, fum = thesevenitemstuple but of course you'd better not be using both traditions at once in the same code;-)
Mercurial/Python - What Does The Underscore Function Do?
In Mercurial, many of the extensions wrap their help/syntax string in a call to an underscore function, like so: _('[OPTION] [QUEUE]') This confuses me, because it does not seem necessary (the Writing Extensions instructions don't mention it) and there doesn't seem to be a _ defined in the class, so I'm wondering if this is some special syntax that I don't understand, perhaps another way to say lambda, or maybe the identity function? Additionally I'm wondering what the benefit of this methodology (whatever it is) is over just the raw string like the documentation suggests. Nothing I've seen in the Python documentation mentions such a function, so I'm not sure if this is really a Python question, or a Mercurial question. Here are two examples that use this structure (look at the cmdtable dictionary near the bottom of the file) https://www.mercurial-scm.org/repo/hg/file/42408cd43f55/hgext/mq.py https://www.mercurial-scm.org/repo/hg/file/42408cd43f55/hgext/graphlog.py
[ "Look on line 45:\nfrom mercurial.i18n import _\n\nThis is the usual abbreviation in the internationalization package gettext, and possibly other packages too, for the function that returns a translation of its argument to the language the program is currently running in. It's abbreviated to _ for convenience, since it's used for just about every message displayed to the user.\nLooks like Mercurial wraps it in their own module. (\"i18n\" stands for \"internationalization\" because there are 18 letters in between \"i\" and \"n\".)\n", "_ (a function name of a single underscore) is often associated with internationalization, due to the precedent of gettext, a GNU approach that has also found a place in Python's standard library (same architecture, completely different implementation) -- per the module's docs,\ngettext.install(domain[, localedir[, unicode[, codeset[, names]]]])\n\n\nThis installs the function _() in\n Python’s builtins namespace, based on\n domain, localedir, and codeset which\n are passed to the function\n translation(). The unicode flag is\n passed to the resulting translation\n object’s install() method.\nFor the names parameter, please see\n the description of the translation\n object’s install() method.\nAs seen below, you usually mark the\n strings in your application that are\n candidates for translation, by\n wrapping them in a call to the _()\n function, like this:\n\nprint _('This string will be translated.') \n\n\nFor convenience, you\n want the _() function to be installed\n in Python’s builtins namespace, so it\n is easily accessible in all modules of\n your application.\n\nAs @ptomato mentions, Mercurial has followed this tradition by naming _ the equivalent function of their own that they use for the same internationalization purposes.\nThere is also a separate tradition to use _ as the \"I don't care\" identifier, as in\nfee, fie, _, _, foo, _, fum = thesevenitemstuple\n\nbut of course you'd better not be using both traditions at once in the same code;-)\n" ]
[ 8, 7 ]
[]
[]
[ "magic_function", "mercurial", "python" ]
stackoverflow_0003077227_magic_function_mercurial_python.txt
Q: Invoke Django template renderer in memory without any files from strings? I have built a Macro language for my users that is based upon the Django template language. Users enter into UITextFields their template/macro snippets that can be rendered in the context of larger documents. So I have large multi-line string snippets of django template code that should be populated with variables that are also stored in memory. I don't want to ever have to dump anything to files, I need to render these template How can I invoke the Django template renderer on a template that is stored in a string in memory (in python instance variables)? The variables that should populate that template are also instance variables stored in memory. A: from django.template import Context, Template template = Template("this is a template string! {{ foo }}") c = Context({"foo": "barbarbar"}) print template.render(c)
Invoke Django template renderer in memory without any files from strings?
I have built a Macro language for my users that is based upon the Django template language. Users enter into UITextFields their template/macro snippets that can be rendered in the context of larger documents. So I have large multi-line string snippets of django template code that should be populated with variables that are also stored in memory. I don't want to ever have to dump anything to files, I need to render these template How can I invoke the Django template renderer on a template that is stored in a string in memory (in python instance variables)? The variables that should populate that template are also instance variables stored in memory.
[ "from django.template import Context, Template\n\ntemplate = Template(\"this is a template string! {{ foo }}\")\nc = Context({\"foo\": \"barbarbar\"})\nprint template.render(c)\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003077272_django_django_templates_python.txt
Q: Python Apache local/internal server error? I am creating HTML form and using Python to code it. I have installed Apache version2.2 and Python version 2.6. Here is the code: #!C:\Python26\Python.exe -u #import cgi modules import cgi #create instances of field storage form = cgi.FieldStorage() #get data from the fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name, last_name) print "</body>" print "</html>" The code I have written gives me an internal error. But, when I remove the following lines it runs fine. #import cgi modules import cgi #create instances of field storage form = cgi.FieldStorage() #get data from the fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') I edited the httpd config file and added lines: AddHandler cgi-script .cgi .py .pl ScriptAlias /cgi-bin/ "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/cgi-bin/" Why is internal error message being displayed when the lines are added? And, I am new to building HTML forms in Python. Suggestions on tutorials on HTML form using Python for Windows would be really helpful. Thanks. PS: The files containing script are located in cgi-bin Apache folder. A: Something is definitely wrong is you subtracted those lines, and it still ran. print "<h2>Hello %s %s</h2>" % (first_name, last_name) in your HTML body should raise an exception, given that they are not defined yet. Please post the bits of your error.log for the Internal Server Error.
Python Apache local/internal server error?
I am creating HTML form and using Python to code it. I have installed Apache version2.2 and Python version 2.6. Here is the code: #!C:\Python26\Python.exe -u #import cgi modules import cgi #create instances of field storage form = cgi.FieldStorage() #get data from the fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name, last_name) print "</body>" print "</html>" The code I have written gives me an internal error. But, when I remove the following lines it runs fine. #import cgi modules import cgi #create instances of field storage form = cgi.FieldStorage() #get data from the fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') I edited the httpd config file and added lines: AddHandler cgi-script .cgi .py .pl ScriptAlias /cgi-bin/ "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/cgi-bin/" Why is internal error message being displayed when the lines are added? And, I am new to building HTML forms in Python. Suggestions on tutorials on HTML form using Python for Windows would be really helpful. Thanks. PS: The files containing script are located in cgi-bin Apache folder.
[ "Something is definitely wrong is you subtracted those lines, and it still ran. print \"<h2>Hello %s %s</h2>\" % (first_name, last_name) in your HTML body should raise an exception, given that they are not defined yet.\nPlease post the bits of your error.log for the Internal Server Error.\n" ]
[ 0 ]
[]
[]
[ "apache2", "apache2.2", "cgi_bin", "html", "python" ]
stackoverflow_0003077312_apache2_apache2.2_cgi_bin_html_python.txt
Q: I can't connect to socket from the outside I am trying to make a simple server/client program pair. On LAN they work fine, but when i try to connect from the "outside" it says connection refused. I shut down firewalls on both machines but i am still unable to connect, and i double checked the ip. What am i doing wrong? Thanks Jake Code: import socket host = '' port = 9888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) conn, adrr = s.accept() conn.send("Hello, world!") s.close() Client: import socket host = '68.x.x.x' port = 9888 s = socket.socket(socket.AF_INET, socket_SOCK_STREAM) s.connect((host,port)) print s.recv(200) s.close() A: You have one of two possible issues. Erroneous network configuration Bug(s) in code The way to debug this is to try and rule one out. If we can get rid of the Code issue then we know it is a network issue. Get a Socket Server and client that you know works and then try them as standalone programs. inside and outside of the firewall. Go to this site and download the examples. Change the ports in both the client and the server, compile and run them. First on same machine within network, second from two machines on same network and then server from within and client from outside of network. A: How's the argument you're passing to the .bind call for your server socket? That's the single likeliest cause -- e.g. if you're using 192.168.x.y for whatever values of x and y, or 10.x.y.z likewise, that's a local-network address only, not routed by inter-network routers by internet conventions (most routers can be programmed to forward some incoming packets to a specific local-network address, typically depending on ports, but that's very specific to router's brands and models).
I can't connect to socket from the outside
I am trying to make a simple server/client program pair. On LAN they work fine, but when i try to connect from the "outside" it says connection refused. I shut down firewalls on both machines but i am still unable to connect, and i double checked the ip. What am i doing wrong? Thanks Jake Code: import socket host = '' port = 9888 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) conn, adrr = s.accept() conn.send("Hello, world!") s.close() Client: import socket host = '68.x.x.x' port = 9888 s = socket.socket(socket.AF_INET, socket_SOCK_STREAM) s.connect((host,port)) print s.recv(200) s.close()
[ "You have one of two possible issues. \n\nErroneous network configuration\nBug(s) in code\n\nThe way to debug this is to try and rule one out. If we can get rid of the Code issue then we know it is a network issue.\nGet a Socket Server and client that you know works and then try them as standalone programs. inside and outside of the firewall. \nGo to this site and download the examples. Change the ports in both the client and the server, compile and run them. First on same machine within network, second from two machines on same network and then server from within and client from outside of network.\n", "How's the argument you're passing to the .bind call for your server socket? That's the single likeliest cause -- e.g. if you're using 192.168.x.y for whatever values of x and y, or 10.x.y.z likewise, that's a local-network address only, not routed by inter-network routers by internet conventions (most routers can be programmed to forward some incoming packets to a specific local-network address, typically depending on ports, but that's very specific to router's brands and models).\n" ]
[ 3, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003077390_python_sockets.txt
Q: Python: Run WSGI server from inetd? As the title suggests, is it possible to run a WSGI server from (x)inetd? A: Yes, but don't do it.
Python: Run WSGI server from inetd?
As the title suggests, is it possible to run a WSGI server from (x)inetd?
[ "Yes, but don't do it.\n" ]
[ 1 ]
[]
[]
[ "inetd", "python", "wsgi" ]
stackoverflow_0003077557_inetd_python_wsgi.txt
Q: Error in creating HTML form using Python-CGI I have to create a HTML form and get the data using python-cgi. HTML form requires user to submit firstname and lastname and then the python script is supposed to get the data generated in the form. I have read up tutorials and tried playing with it to make it work, but it does not seem to happen. HTML code: <form method = "POST" action ="http://localhost/cgi-bin/pyfile_test.py"> <p>First Name: <input type="text" name="firstname"> <p>Last Name: <input type="text" name="lastname"> <p>Click here to submit the form:<input type="submit" value="Submit"> <input type="hidden" name="session" value="1898fd"> </form> python script to extract data #!c:/Python26/python.exe -u import cgi, cgitb cgitb.enable() def main() print "Content-type: text/html\n" print form = cgi.FieldStorage() if form.has_key("firstname") amd form["firstname"].value !="": print "<h1>Hello", form["firstname"].value, "</h1>" else: print "<h1> Error!Wrong!</h1> main() when i direct html form to above script it does NOT work but when i direct it to the following script it works. #!c:/Python26/python.exe -u import cgi, cgitb cgitb.enable() print "Content-type: text/html" print print "The First Python Script On Server Side" print "The sum of two numbers evaluation" print "3+5 = ",3+5 I dont know what is going wrong. Any help will be highly appreciated! A: At least in what you just showed, there are syntax errors: if form.has_key("firstname") amd form["firstname"].value !="": print "<h1>Hello", form["firstname"].value, "</h1>" else: print "<h1> Error!Wrong!</h1> amd should be and, and both print statements should be indented deeper than the if and else keywords that control them. If you fix your syntax and try again, what exactly do you see in the browser (and what do you see if you use your browser's "show source" functionality)? Edit: One more syntax error: you're missing a closing " on the second print. It's really tiresome to spot all your syntax errors one by one, and Apache (or whatever your web server is) doesn't seem to be helping -- cgitb can't take control until the whole script is successfully parsed, so syntax errors are the one reason it can't show! And one more: missing colon at the end of the def main line. Why don't you just run it with python yourscript.py at the command line until you've made syntax-error-free, and only then try again to run it as a CGI? E.g. after fixing the two errors I spotted earlier but not the two I've just spotted, you'd be seeing (if python is on the PATH and the shell prompt is $): $ python acgi.py File "acgi.py", line 6 def main() ^ SyntaxError: invalid syntax because of the missing " at the end of the previous line and missing colon at line 6. Fixing the last two errors (total of four in the code you originally posted) you finally see: $ python acgi.py Content-type: text/html <h1> Error!Wrong!</h1> of course it says "wrong" because the field storage is empty, but this shows you can NOW (with all four errors fixed) sensibly try to run it as a CGI script at last;-)
Error in creating HTML form using Python-CGI
I have to create a HTML form and get the data using python-cgi. HTML form requires user to submit firstname and lastname and then the python script is supposed to get the data generated in the form. I have read up tutorials and tried playing with it to make it work, but it does not seem to happen. HTML code: <form method = "POST" action ="http://localhost/cgi-bin/pyfile_test.py"> <p>First Name: <input type="text" name="firstname"> <p>Last Name: <input type="text" name="lastname"> <p>Click here to submit the form:<input type="submit" value="Submit"> <input type="hidden" name="session" value="1898fd"> </form> python script to extract data #!c:/Python26/python.exe -u import cgi, cgitb cgitb.enable() def main() print "Content-type: text/html\n" print form = cgi.FieldStorage() if form.has_key("firstname") amd form["firstname"].value !="": print "<h1>Hello", form["firstname"].value, "</h1>" else: print "<h1> Error!Wrong!</h1> main() when i direct html form to above script it does NOT work but when i direct it to the following script it works. #!c:/Python26/python.exe -u import cgi, cgitb cgitb.enable() print "Content-type: text/html" print print "The First Python Script On Server Side" print "The sum of two numbers evaluation" print "3+5 = ",3+5 I dont know what is going wrong. Any help will be highly appreciated!
[ "At least in what you just showed, there are syntax errors:\nif form.has_key(\"firstname\") amd form[\"firstname\"].value !=\"\":\nprint \"<h1>Hello\", form[\"firstname\"].value, \"</h1>\"\nelse:\nprint \"<h1> Error!Wrong!</h1>\n\namd should be and, and both print statements should be indented deeper than the if and else keywords that control them.\nIf you fix your syntax and try again, what exactly do you see in the browser (and what do you see if you use your browser's \"show source\" functionality)?\nEdit:\nOne more syntax error: you're missing a closing \" on the second print. It's really tiresome to spot all your syntax errors one by one, and Apache (or whatever your web server is) doesn't seem to be helping -- cgitb can't take control until the whole script is successfully parsed, so syntax errors are the one reason it can't show!\nAnd one more: missing colon at the end of the def main line.\nWhy don't you just run it with python yourscript.py at the command line until you've made syntax-error-free, and only then try again to run it as a CGI?\nE.g. after fixing the two errors I spotted earlier but not the two I've just spotted, you'd be seeing (if python is on the PATH and the shell prompt is $):\n$ python acgi.py \n File \"acgi.py\", line 6\n def main()\n ^\nSyntaxError: invalid syntax\n\nbecause of the missing \" at the end of the previous line and missing colon at line 6.\nFixing the last two errors (total of four in the code you originally posted) you finally see:\n$ python acgi.py \nContent-type: text/html\n\n\n<h1> Error!Wrong!</h1>\n\nof course it says \"wrong\" because the field storage is empty, but this shows you can NOW (with all four errors fixed) sensibly try to run it as a CGI script at last;-)\n" ]
[ 0 ]
[]
[]
[ "apache", "cgi", "forms", "python" ]
stackoverflow_0003077724_apache_cgi_forms_python.txt
Q: MySQL_Python on Snow Leopard I've tried to solve this myself searching and searching but I can't get it to work. :( I'm in Snow Leopard 10.6.4 and tried to setup my Django environment, first I upgraded my python to 2.6.5, installed django and then mysql_python. All seems to be smooth until I to connect to mysql using syncdb. Got this error/trace message: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I've tried following the solution provided http://forums.mysql.com/read.php?50,282410,286676 but still the same. I believe it has something to do with my python version because when I execute /usr/bin/python it returns Python 2.6.1 but when I just typed python it says 'Python 2.6.5 '. Anyone? I think when I build and install mysql_python using the ARCHFLAGS="-arch x86_64" /usr/bin/python setup.py build command its using the default django version (2.6.1) on SL and not the new one (2.6.5). Anychance I can get this to work with 2.6.5? Thanks. A: type: which python figure out where it is pulling python 2.6.5 (which is not the current python as distributed by Apple). You might be able to symlink /usr/bin/python to your 2.6.5 installation, but, that just seems like you're asking for trouble. You could install your mysqldb within your virtual environment which would put it in the right place. I'm guessing you installed python from a .dmg or source but it didn't completely install, or, didn't overwrite the Apple provided version on purpose. A: You may be using either Python version depending on what's the value of the PATH environment variable at the time you're invoking Python. It's important that Apple's own Python remains in the system in /usr/bin since it's used by some other parts of the operating system and you don't want to risk breaking those, so your alternative Python is most likely installed in /usr/local/bin (unless you used Darwinports or the like to install it, in which case it will be somewhere under /opt). You can install extensions under either or both versions of Python -- if you're using a normal python setup.py install terminal command for the installation, the add-on will be installed for the version of python that you're running setup.py with, for example. Simplest might be to install on both (or use virtualenv as the other answer suggests) -- all that takes is two commands, /usr/bin/python setup.py install for the system version and (if your add-on version is in /usr/local/bin) /usr/local/bin/python setup.py install. (Either or both might need to be prefixed by sudo depending on how you set up permissions and ownerships for the various directories involved). A: First thanks for the answers! :) Made me think and helped me sort things out. So what I did was to determine what architecture my python 2.6.5 shell is running. Got this How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? and found out that it is running in 32bit. I must be the sole reason why mysql python won't work because I've got the 64bit mysql installed. I then deleted mysql on /usr/local and applied this handy little tip http://egopoly.com/2009/09/01/how-to-uninstall-mysql-5-1-on-snow-leopard/ just to make sure the 32bit mysql installer won't complain. I downloaded mysql_python] again and edited line 26 on setup_posix.py file from mysql_config.path = "mysql_config"to mysql_config.path = "/usr/local/mysql-5.1.48-osx10.6-x86/bin/mysql_config"and then executed the following commandspython setup.py build and sudo python setup.py install And then voila! :D it's working! Now I can sleep. Again thanks for the help!
MySQL_Python on Snow Leopard
I've tried to solve this myself searching and searching but I can't get it to work. :( I'm in Snow Leopard 10.6.4 and tried to setup my Django environment, first I upgraded my python to 2.6.5, installed django and then mysql_python. All seems to be smooth until I to connect to mysql using syncdb. Got this error/trace message: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I've tried following the solution provided http://forums.mysql.com/read.php?50,282410,286676 but still the same. I believe it has something to do with my python version because when I execute /usr/bin/python it returns Python 2.6.1 but when I just typed python it says 'Python 2.6.5 '. Anyone? I think when I build and install mysql_python using the ARCHFLAGS="-arch x86_64" /usr/bin/python setup.py build command its using the default django version (2.6.1) on SL and not the new one (2.6.5). Anychance I can get this to work with 2.6.5? Thanks.
[ "type:\nwhich python\n\nfigure out where it is pulling python 2.6.5 (which is not the current python as distributed by Apple). You might be able to symlink /usr/bin/python to your 2.6.5 installation, but, that just seems like you're asking for trouble.\nYou could install your mysqldb within your virtual environment which would put it in the right place. I'm guessing you installed python from a .dmg or source but it didn't completely install, or, didn't overwrite the Apple provided version on purpose.\n", "You may be using either Python version depending on what's the value of the PATH environment variable at the time you're invoking Python. It's important that Apple's own Python remains in the system in /usr/bin since it's used by some other parts of the operating system and you don't want to risk breaking those, so your alternative Python is most likely installed in /usr/local/bin (unless you used Darwinports or the like to install it, in which case it will be somewhere under /opt).\nYou can install extensions under either or both versions of Python -- if you're using a normal python setup.py install terminal command for the installation, the add-on will be installed for the version of python that you're running setup.py with, for example. Simplest might be to install on both (or use virtualenv as the other answer suggests) -- all that takes is two commands, /usr/bin/python setup.py install for the system version and (if your add-on version is in /usr/local/bin) /usr/local/bin/python setup.py install. (Either or both might need to be prefixed by sudo depending on how you set up permissions and ownerships for the various directories involved).\n", "First thanks for the answers! :) Made me think and helped me sort things out.\nSo what I did was to determine what architecture my python 2.6.5 shell is running. Got this How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? and found out that it is running in 32bit. I must be the sole reason why mysql python won't work because I've got the 64bit mysql installed. \nI then deleted mysql on /usr/local and applied this handy little tip http://egopoly.com/2009/09/01/how-to-uninstall-mysql-5-1-on-snow-leopard/ just to make sure the 32bit mysql installer won't complain. \nI downloaded mysql_python] again and edited line 26 on setup_posix.py file from mysql_config.path = \"mysql_config\"to mysql_config.path = \"/usr/local/mysql-5.1.48-osx10.6-x86/bin/mysql_config\"and then executed the following commandspython setup.py build and sudo python setup.py install \nAnd then voila! :D it's working! Now I can sleep. Again thanks for the help!\n" ]
[ 0, 0, 0 ]
[]
[]
[ "django", "macos", "mysql", "osx_snow_leopard", "python" ]
stackoverflow_0003076746_django_macos_mysql_osx_snow_leopard_python.txt
Q: Broken Link On Django Admin Interface I'm currently reading Practical Django Projects and in the Django admin interface there is an option to "View on site" when entering information. But after finishing chapter 5 of the book I started to tinker with the admin interface and found that clicking this link with my categories app doesn't work as it isn't appending weblog to the URL, so they appear like this: http://127.0.0.1:8000/categories/test-cat when they should be like this... http://127.0.0.1:8000/weblog/categories/test-cat However on my entries model they work perfectly well. So I tried to see what was right in the in the Entries application to find out what was incorrect on the Categories application. I'm been looking for about 2 hours and I can't identify where Django does this. I have even copied the source code from online although some of it appears to be missing. My get_absolute_url() is as follows: def get_absolute_url(self): return "/categories/%s/" % self.slug I edited to: def get_absolute_url(self): return "/weblog/categories/%s/" % self.slug and it resolves the issue. My question now is, why does the Entries application not require this but the Categories application does? My code from class Entry: def get_absolute_url(self): return ('coltrane_entry_detail', (), { 'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug }) get_absolute_url = models.permalink(get_absolute_url) A: It uses the get_absolute_url() method on the model. Change that and it should work :) [edit] For the edited question. In your category model you are using a hardcoded link while you are using a permalink at the entries model. I suggest you use permalinks at both locations to solve the problem. Here's the documentation on how to use it: http://docs.djangoproject.com/en/dev/ref/models/instances/#the-permalink-decorator
Broken Link On Django Admin Interface
I'm currently reading Practical Django Projects and in the Django admin interface there is an option to "View on site" when entering information. But after finishing chapter 5 of the book I started to tinker with the admin interface and found that clicking this link with my categories app doesn't work as it isn't appending weblog to the URL, so they appear like this: http://127.0.0.1:8000/categories/test-cat when they should be like this... http://127.0.0.1:8000/weblog/categories/test-cat However on my entries model they work perfectly well. So I tried to see what was right in the in the Entries application to find out what was incorrect on the Categories application. I'm been looking for about 2 hours and I can't identify where Django does this. I have even copied the source code from online although some of it appears to be missing. My get_absolute_url() is as follows: def get_absolute_url(self): return "/categories/%s/" % self.slug I edited to: def get_absolute_url(self): return "/weblog/categories/%s/" % self.slug and it resolves the issue. My question now is, why does the Entries application not require this but the Categories application does? My code from class Entry: def get_absolute_url(self): return ('coltrane_entry_detail', (), { 'year': self.pub_date.strftime("%Y"), 'month': self.pub_date.strftime("%b").lower(), 'day': self.pub_date.strftime("%d"), 'slug': self.slug }) get_absolute_url = models.permalink(get_absolute_url)
[ "It uses the get_absolute_url() method on the model. Change that and it should work :)\n[edit]\nFor the edited question.\nIn your category model you are using a hardcoded link while you are using a permalink at the entries model. I suggest you use permalinks at both locations to solve the problem.\nHere's the documentation on how to use it: http://docs.djangoproject.com/en/dev/ref/models/instances/#the-permalink-decorator\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "django_urls", "python" ]
stackoverflow_0003077909_django_django_admin_django_urls_python.txt
Q: Does GQL automatically add an "ID" Property I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically? regards, A: An object has a Key, part of which is either an automatically-generated numeric ID, or an assigned key name. IDs are not guaranteed to be increasing, and they're almost never going to be consecutive because they're allocated to an instance in big chunks, and IDs unused by the instance to which they're allocated will never be used by another instance (at least, not currently). They're also only unique within the same entity group for a kind; they're not unique to the entire kind if you have parent relationships. A: Yes, they have id's by default, and it is named ID as you mentioned. A: I'd also add that, per the documentation, the id is not guaranteed to increase: An application should not rely on numeric IDs being assigned in increasing order with the order of entity creation. This is generally the case, but not guaranteed.
Does GQL automatically add an "ID" Property
I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically? regards,
[ "An object has a Key, part of which is either an automatically-generated numeric ID, or an assigned key name. IDs are not guaranteed to be increasing, and they're almost never going to be consecutive because they're allocated to an instance in big chunks, and IDs unused by the instance to which they're allocated will never be used by another instance (at least, not currently). They're also only unique within the same entity group for a kind; they're not unique to the entire kind if you have parent relationships.\n", "Yes, they have id's by default, and it is named ID as you mentioned.\n", "I'd also add that, per the documentation, the id is not guaranteed to increase:\n\nAn application should not rely on\n numeric IDs being assigned in\n increasing order with the order of\n entity creation. This is generally the\n case, but not guaranteed.\n\n" ]
[ 4, 3, 2 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003077156_google_app_engine_gql_python.txt
Q: Optimization: Python String Repetition I have a piece of code that will take a string and repeat it such that the length of the string is x. >>> import math >>> def repeat(data, length): return (data * int(math.ceil(float(length) / len(data))))[:length] >>> repeat("Hello World", 22) 'Hello WorldHello World' >>> repeat("Hello World", 20) 'Hello WorldHello Wor' Is there any way to optimize it? I need this operation to be fast, as it will be used a lot. Note that this also needs to work with lists. A: This might be marginally faster: def repeat(string, length): L = len(string) return string * (length // L) + string[:length % L] I say "might" because a LOT depends on the typical string and length! With 'Hello World' and 61, I've timed this (on an old Mac laptop) at 1 microsecond vs 1.66 microseconds for yours; with 'Hello World'*100 and 61*123, 2.08 microseconds vs 2.68 for yours. Just how fast are you requiring, on what length strings, and for what typical values of length? Note // is "divide by truncation" (just to ensure this works in Python 3 as well as Python 2;-) even though Stack Overflow is coloring things as if it was a comment mark (as in C++). A: There is no need to do floating point here; in old Python versions, just say "int(length) / len(string)", and in new versions you can use the "//" operator. When you get the result, you can just add 1 to make sure it's long enough. Or, at the cost of a few more additions, you can be more precise and never make the initial string too long: ... return (data * ((int(length) + len(data) - 1) / len(data)))[:length] A: Instead of int(math.ceil(float(length) / len(data))) you could just use length/len(data) + 1. That's not exactly the same but should work as well. And before trying to make this faster, are you sure that this function is a performance bottleneck? How many thousands of times will you call it each second? To find out which variant of a function is the fastest one you should profile it, the timeit module is usually useful there. A: If you really want optimizate that you need to rewrite your function in C as an extention for python. You can find information here. Sorry for my English, I'm new in this.
Optimization: Python String Repetition
I have a piece of code that will take a string and repeat it such that the length of the string is x. >>> import math >>> def repeat(data, length): return (data * int(math.ceil(float(length) / len(data))))[:length] >>> repeat("Hello World", 22) 'Hello WorldHello World' >>> repeat("Hello World", 20) 'Hello WorldHello Wor' Is there any way to optimize it? I need this operation to be fast, as it will be used a lot. Note that this also needs to work with lists.
[ "This might be marginally faster:\ndef repeat(string, length):\n L = len(string)\n return string * (length // L) + string[:length % L]\n\nI say \"might\" because a LOT depends on the typical string and length! With 'Hello World' and 61, I've timed this (on an old Mac laptop) at 1 microsecond vs 1.66 microseconds for yours; with 'Hello World'*100 and 61*123, 2.08 microseconds vs 2.68 for yours. Just how fast are you requiring, on what length strings, and for what typical values of length?\nNote // is \"divide by truncation\" (just to ensure this works in Python 3 as well as Python 2;-) even though Stack Overflow is coloring things as if it was a comment mark (as in C++).\n", "There is no need to do floating point here; in old Python versions, just say \"int(length) / len(string)\", and in new versions you can use the \"//\" operator. When you get the result, you can just add 1 to make sure it's long enough. Or, at the cost of a few more additions, you can be more precise and never make the initial string too long:\n...\n return (data * ((int(length) + len(data) - 1) / len(data)))[:length]\n\n", "Instead of int(math.ceil(float(length) / len(data))) you could just use length/len(data) + 1. That's not exactly the same but should work as well.\nAnd before trying to make this faster, are you sure that this function is a performance bottleneck? How many thousands of times will you call it each second?\nTo find out which variant of a function is the fastest one you should profile it, the timeit module is usually useful there.\n", "If you really want optimizate that you need to rewrite your function in C as an extention for python.\nYou can find information here.\nSorry for my English, I'm new in this.\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "python", "repeat", "string" ]
stackoverflow_0003077899_python_repeat_string.txt
Q: How does the right-shift operator work in a python print statement? I've seen someone using "print" with ">>" to write stuffs into a file: In [7]: with open('text', 'w') as f: ...: print >> f, "Hello, world!" ...: In [8]: !type text Hello, world! How does it work? When should I use this instead of just using the "write" method? A: From https://docs.python.org/2/reference/simple_stmts.html#the-print-statement print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.
How does the right-shift operator work in a python print statement?
I've seen someone using "print" with ">>" to write stuffs into a file: In [7]: with open('text', 'w') as f: ...: print >> f, "Hello, world!" ...: In [8]: !type text Hello, world! How does it work? When should I use this instead of just using the "write" method?
[ "From https://docs.python.org/2/reference/simple_stmts.html#the-print-statement\n\nprint also has an extended form,\n defined by the second portion of the\n syntax described above. This form is\n sometimes referred to as “print\n chevron.” In this form, the first\n expression after the >> must evaluate\n to a “file-like” object, specifically\n an object that has a write() method as\n described above. With this extended\n form, the subsequent expressions are\n printed to this file object. If the\n first expression evaluates to None,\n then sys.stdout is used as the file\n for output.\n\n" ]
[ 16 ]
[]
[]
[ "grammar", "python" ]
stackoverflow_0003078042_grammar_python.txt
Q: Python output out of order I needed some really simple XML output so I decided to write my own functions. This was just the first step, but something has gone terribly wrong. While I would expect the output to look like this: <A> <D> <I></I> <J></J> <K></K> </D> <E> <I></I> <J></J> <K></K> </E> ...and so on. Instead the output looks like this: <I></I> <J></J> <K></K> <D> </D> <E> </E> <F> </F> <G> </G> <H> </H> <A> </A> <B> </B> <C> </C> I'm sure my mistake is something very simple, but I just can't see it. This is the entire file that I'm using: def XMLChild(list, depth): for arg in list: print '\t' * depth + '<' + arg + '></' + arg + '>' def XMLParent(list, depth, child): for arg in list: print '\t' * depth + '<' + arg + '>' child print '\t' * depth + '</' + arg + '>' list1 = ['A', 'B', 'C'] list2 = ['D', 'E', 'F', 'G', 'H'] list3 = ['I', 'J', 'K', ] XMLParent(list1, 0, XMLParent(list2, 1, XMLChild(list3, 2))) As you can see, both functions are supposed to print tags. XMLParent should allow the passing of a child function, either another parent or a child. No matter how much I look at it I can't figure out why it's printing the way it is. A: You're not returning the result, but rather printing it directly. Therefore it will be outputted in the order that the functions execute. Your code is equivalent to the following, which clarifies the order in which the functions are called: a = XMLChild(list3, 2) b = XMLParent(list2, 1, a) XMLParent(list1, 0, b) Try building a string in each of the functions, returning it to the caller. The caller can then append it to it's own string buffer and in turn return it. Then you can output the combined string like such, and do all the printing in a single place: a = XMLChild(list3, 2) b = XMLParent(list2, 1, a) print XMLParent(list1, 0, b)
Python output out of order
I needed some really simple XML output so I decided to write my own functions. This was just the first step, but something has gone terribly wrong. While I would expect the output to look like this: <A> <D> <I></I> <J></J> <K></K> </D> <E> <I></I> <J></J> <K></K> </E> ...and so on. Instead the output looks like this: <I></I> <J></J> <K></K> <D> </D> <E> </E> <F> </F> <G> </G> <H> </H> <A> </A> <B> </B> <C> </C> I'm sure my mistake is something very simple, but I just can't see it. This is the entire file that I'm using: def XMLChild(list, depth): for arg in list: print '\t' * depth + '<' + arg + '></' + arg + '>' def XMLParent(list, depth, child): for arg in list: print '\t' * depth + '<' + arg + '>' child print '\t' * depth + '</' + arg + '>' list1 = ['A', 'B', 'C'] list2 = ['D', 'E', 'F', 'G', 'H'] list3 = ['I', 'J', 'K', ] XMLParent(list1, 0, XMLParent(list2, 1, XMLChild(list3, 2))) As you can see, both functions are supposed to print tags. XMLParent should allow the passing of a child function, either another parent or a child. No matter how much I look at it I can't figure out why it's printing the way it is.
[ "You're not returning the result, but rather printing it directly. Therefore it will be outputted in the order that the functions execute. Your code is equivalent to the following, which clarifies the order in which the functions are called:\na = XMLChild(list3, 2)\nb = XMLParent(list2, 1, a)\nXMLParent(list1, 0, b)\n\nTry building a string in each of the functions, returning it to the caller. The caller can then append it to it's own string buffer and in turn return it. Then you can output the combined string like such, and do all the printing in a single place:\na = XMLChild(list3, 2)\nb = XMLParent(list2, 1, a)\nprint XMLParent(list1, 0, b)\n\n" ]
[ 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003078044_python_xml.txt
Q: Is there an open-source eMail message (headers, attachments, etc.) parser? Is there a free open-source solution taking raw e-mail message (as a piece of text) and returning each header field, each attachment and the message body as separate fields? A: Yes... For each language you pointed out, I've used the one in Python myself. Try perusing the library documentation for your chosen library. (Note: You may be expecting a "nice", high-level library for this parsing... That's a tricky area, email has evolved and grown without much design, there are a lot of dark corners, and API's reflect that). A: Yes, this is a common task and there are a number of apis out there to help you. If working with Java, I'd look at JavaMail. If working with PHP, I'd look at PECL mailparse or Pear Mail. A: javax.mail.internet.MimeMessage protected void parse(InputStream is)
Is there an open-source eMail message (headers, attachments, etc.) parser?
Is there a free open-source solution taking raw e-mail message (as a piece of text) and returning each header field, each attachment and the message body as separate fields?
[ "Yes... For each language you pointed out, I've used the one in Python myself. Try perusing the library documentation for your chosen library.\n(Note: You may be expecting a \"nice\", high-level library for this parsing... That's a tricky area, email has evolved and grown without much design, there are a lot of dark corners, and API's reflect that).\n", "Yes, this is a common task and there are a number of apis out there to help you.\nIf working with Java, I'd look at JavaMail.\nIf working with PHP, I'd look at PECL mailparse or Pear Mail.\n", "javax.mail.internet.MimeMessage\n protected void parse(InputStream is)\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "email", "java", "parsing", "php", "python" ]
stackoverflow_0003078189_email_java_parsing_php_python.txt
Q: easy, straightforward way to package a python program for debian? i'm having trouble navigating the maze of distribution tools for python and debian; cdbs, debhelper, python-support, python-central, blah blah blah .. my application is a fairly straightforward one - a single python package (directory containing modules and a __init__.py), a script for running the program (script.py) and some icons (.png) and menu items (.desktop files). from these files, how can i construct a simple, clean .deb file from scratch without using the nonsensical tools listed above? i'm mainly targeting ubuntu, but would like it if the package worked on straight debian A: python-stdeb should work for you. It's on Debian testing/unstable and Ubuntu (Lucid onwards). apt-get install python-stdeb It is less a shortcut method than a tool that tries to generate as much of the source package as possible. It can actualy build a package that both works properly and is almost standards compliant. If you want your package to meet the quality standards for inclusion in Debian, Ubuntu, etc you will need to fill out files like debian/copyright, etc. As much as people claim cdbs is really easy, I'd like to point out that the rules file Nick mentioned could easily have been done with debhelper7. Not to forget, dh7 can be customized far more easily than cdbs can. #!/usr/bin/make -f %: dh $@ Note: You should check whether your package meets the Debian Policy, Debian Python Policy, etc before you submit to Debian. You will actually need to read documents for that - no shortcut. A: First, the answer is that there is no straightforward way to make a dpkg, and the documentation is parceled out in a million tiny morsels from as many places. However, the ubuntu Python Packaging Guide is pretty useful. For simple packages (ones easy to describe to setuptools), the steps are pretty simple once you have a debian control structure set up: Run setup.py --sdist --prune and also make sure to set dist-dir to something reasonable Invoke dpkg-buildpackage with the proper options for your package (probably -b at least) You will need a debian/rules file for buildpackage to function from, but luckily the work is done for you if you use cdbs, you'll want something very similar to: #!/usr/bin/make -f DEB_PYTHON_SYSTEM := pysupport include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk If you're not using distutils, you might want to take a look at the DebianPython/Policy page on the wiki (under "CDBS + the hard way"). There is a pycentral option for DEB_PYTHON_SYSTEM as well, which you can google if you want to find some more information about.
easy, straightforward way to package a python program for debian?
i'm having trouble navigating the maze of distribution tools for python and debian; cdbs, debhelper, python-support, python-central, blah blah blah .. my application is a fairly straightforward one - a single python package (directory containing modules and a __init__.py), a script for running the program (script.py) and some icons (.png) and menu items (.desktop files). from these files, how can i construct a simple, clean .deb file from scratch without using the nonsensical tools listed above? i'm mainly targeting ubuntu, but would like it if the package worked on straight debian
[ "python-stdeb should work for you. It's on Debian testing/unstable and Ubuntu (Lucid onwards). apt-get install python-stdeb\nIt is less a shortcut method than a tool that tries to generate as much of the source package as possible. It can actualy build a package that both works properly and is almost standards compliant. If you want your package to meet the quality standards for inclusion in Debian, Ubuntu, etc you will need to fill out files like debian/copyright, etc.\nAs much as people claim cdbs is really easy, I'd like to point out that the rules file Nick mentioned could easily have been done with debhelper7. Not to forget, dh7 can be customized far more easily than cdbs can.\n#!/usr/bin/make -f\n%:\n dh $@\n\nNote: You should check whether your package meets the Debian Policy, Debian Python Policy, etc before you submit to Debian. You will actually need to read documents for that - no shortcut.\n", "First, the answer is that there is no straightforward way to make a dpkg, and the documentation is parceled out in a million tiny morsels from as many places. However, the ubuntu Python Packaging Guide is pretty useful.\nFor simple packages (ones easy to describe to setuptools), the steps are pretty simple once you have a debian control structure set up:\n\nRun setup.py --sdist --prune and also make sure to set dist-dir to something reasonable\nInvoke dpkg-buildpackage with the proper options for your package (probably -b at least)\n\nYou will need a debian/rules file for buildpackage to function from, but luckily the work is done for you if you use cdbs, you'll want something very similar to:\n#!/usr/bin/make -f\n\nDEB_PYTHON_SYSTEM := pysupport\n\ninclude /usr/share/cdbs/1/rules/debhelper.mk\ninclude /usr/share/cdbs/1/class/python-distutils.mk\n\nIf you're not using distutils, you might want to take a look at the DebianPython/Policy page on the wiki (under \"CDBS + the hard way\"). There is a pycentral option for DEB_PYTHON_SYSTEM as well, which you can google if you want to find some more information about.\n" ]
[ 5, 3 ]
[]
[]
[ "cdbs", "deb", "debhelper", "debian", "python" ]
stackoverflow_0002927615_cdbs_deb_debhelper_debian_python.txt
Q: How to make a cost effective but scalable site? Portal Technology Assessment in which we will be creating a placement portal for the campuses and industry to help place students. The portal will handle large volumes of data and people logging in, approximately 1000 users/day in a concurrent mode. What technology should i use? PHP with CakePHP as a framework, Ruby on Rails, ASP.NET, Python, or should I opt for cloud computing? Which of those are the most cost beneficial? A: Any of those will do, it really depends on what you know. If you're comfortable with Python, use Django. If you like Ruby go with ROR. These modern frameworks are built to scale, assuming you're not going to be developing something on the scale of facebook then they should suffice. I personally recommend nginx as your main server to host static content and possibly reverse-proxy to Django/mod_wsgi/Apache2. Another important aspect is caching, make sure to use something like memcached and make sure the framework has some sort of plugin or it's easily attachable. A: Language choice is important as you must choose language that you and your team feel the most comfortable with as you must develop mid-large size application. Of course use framework with Python it must be Django, with ASP.NET .NET or MVC.NET whatever you feel better with with Ruby ROR and with PHP there are too large amount of frameworks. 1000 concurrent users is not that much, especially it depends what users will do. Places where users will get large amount of data are better to Cache with with any caching engine you want. You need to design application this what so you can easily swap between real DB calls and calls to cache. For that use Data Objects like for Logins create an Object array of course if you need it. Save some information in cookies when user logins for example his last login, password in case he wants to change it, email and such so you will make less calls to DB in read mode ( select queries ). use cookie less domain for static content like images, js and css files. setup on this domain the fastest system you can with simplest server you can, probably something based on Linux. For servers, best advice is to either get large machine and set Virtual Boxes on it with vmware or other Linux based solution or to get few servers which is better because if on big server down you lost everything if one of 1 is down you still can do some stuff. Especially if you set railroad mode. Railroad mode is simple you set up Application server (IIS or Apache) on one server and make it master while you set up SQL on the same server and make it slave. On other server you set up SQL as master and Application server as slave. So server one serves IIS/Apache and Other one SQL, if one down you just need to change line in host.etc in order to set something somewhere else ( i don't know how to do that in Linux ). last server for static content. Cloud Computing, you will use if you want it or not. You will share resources with some applications as Google API for jquery and jqueryUI for instance but you create unique application and i don't believe making core of application based on cloud computing will do any good. Use large site's CDNs for good.
How to make a cost effective but scalable site?
Portal Technology Assessment in which we will be creating a placement portal for the campuses and industry to help place students. The portal will handle large volumes of data and people logging in, approximately 1000 users/day in a concurrent mode. What technology should i use? PHP with CakePHP as a framework, Ruby on Rails, ASP.NET, Python, or should I opt for cloud computing? Which of those are the most cost beneficial?
[ "Any of those will do, it really depends on what you know. If you're comfortable with Python, use Django. If you like Ruby go with ROR. These modern frameworks are built to scale, assuming you're not going to be developing something on the scale of facebook then they should suffice.\nI personally recommend nginx as your main server to host static content and possibly reverse-proxy to Django/mod_wsgi/Apache2.\nAnother important aspect is caching, make sure to use something like memcached and make sure the framework has some sort of plugin or it's easily attachable.\n", "Language choice is important as you must choose language that you and your team feel the most comfortable with as you must develop mid-large size application. Of course use framework with Python it must be Django, with ASP.NET .NET or MVC.NET whatever you feel better with with Ruby ROR and with PHP there are too large amount of frameworks.\n1000 concurrent users is not that much, especially it depends what users will do. Places where users will get large amount of data are better to Cache with with any caching engine you want. You need to design application this what so you can easily swap between real DB calls and calls to cache. For that use Data Objects like for Logins create an Object array of course if you need it. Save some information in cookies when user logins for example his last login, password in case he wants to change it, email and such so you will make less calls to DB in read mode ( select queries ).\nuse cookie less domain for static content like images, js and css files. setup on this domain the fastest system you can with simplest server you can, probably something based on Linux.\nFor servers, best advice is to either get large machine and set Virtual Boxes on it with vmware or other Linux based solution or to get few servers which is better because if on big server down you lost everything if one of 1 is down you still can do some stuff. Especially if you set railroad mode. Railroad mode is simple you set up Application server (IIS or Apache) on one server and make it master while you set up SQL on the same server and make it slave. On other server you set up SQL as master and Application server as slave. So server one serves IIS/Apache and Other one SQL, if one down you just need to change line in host.etc in order to set something somewhere else ( i don't know how to do that in Linux ).\nlast server for static content.\nCloud Computing, you will use if you want it or not. You will share resources with some applications as Google API for jquery and jqueryUI for instance but you create unique application and i don't believe making core of application based on cloud computing will do any good. Use large site's CDNs for good.\n" ]
[ 2, 1 ]
[]
[]
[ "lamp", "python" ]
stackoverflow_0003078364_lamp_python.txt
Q: Save PyML.classifiers.multi.OneAgainstRest(SVM()) object? I'm using PYML to construct a multiclass linear support vector machine (SVM). After training the SVM, I would like to be able to save the classifier, so that on subsequent runs I can use the classifier right away without retraining. Unfortunately, the .save() function is not implemented for that classifier, and attempting to pickle it (both with standard pickle and cPickle) yield the following error message: pickle.PicklingError: Can't pickle : it's not found as __builtin__.PySwigObject Does anyone know of a way around this or of an alternative library without this problem? Thanks. Edit/Update I am now training and attempting to save the classifier with the following code: mc = multi.OneAgainstRest(SVM()); mc.train(dataset_pyml,saveSpace=False); for i, classifier in enumerate(mc.classifiers): filename=os.path.join(prefix,labels[i]+".svm"); classifier.save(filename); Notice that I am now saving with the PyML save mechanism rather than with pickling, and that I have passed "saveSpace=False" to the training function. However, I am still gettting an error: ValueError: in order to save a dataset you need to train as: s.train(data, saveSpace = False) However, I am passing saveSpace=False... so, how do I save the classifier(s)? P.S. The project I am using this in is pyimgattr, in case you would like a complete testable example... the program is run with "./pyimgattr.py train"... that will get you this error. Also, a note on version information: [michaelsafyan@codemage /Volumes/Storage/classes/cse559/pyimgattr]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import PyML >>> print PyML.__version__ 0.7.0 A: In multi.py on line 96 "self.classifiers[i].train(datai)" is called without passing "**args", so that if you call "mc.train(data, saveSpace=False)", this saveSpace-Argument gets lost. This is why you get an error message if you try to save the classifiers in your multiclass-classifier individually. But if you change this line to pass all arguments, you can save each classifier individually: #!/usr/bin/python import numpy from PyML.utils import misc from PyML.evaluators import assess from PyML.classifiers.svm import SVM, loadSVM from PyML.containers.labels import oneAgainstRest from PyML.classifiers.baseClassifiers import Classifier from PyML.containers.vectorDatasets import SparseDataSet from PyML.classifiers.composite import CompositeClassifier class OneAgainstRestFixed(CompositeClassifier) : '''A one-against-the-rest multi-class classifier''' def train(self, data, **args) : '''train k classifiers''' Classifier.train(self, data, **args) numClasses = self.labels.numClasses if numClasses <= 2: raise ValueError, 'Not a multi class problem' self.classifiers = [self.classifier.__class__(self.classifier) for i in range(numClasses)] for i in range(numClasses) : # make a copy of the data; this is done in case the classifier modifies the data datai = data.__class__(data, deepcopy = self.classifier.deepcopy) datai = oneAgainstRest(datai, data.labels.classLabels[i]) self.classifiers[i].train(datai, **args) self.log.trainingTime = self.getTrainingTime() def classify(self, data, i): r = numpy.zeros(self.labels.numClasses, numpy.float_) for j in range(self.labels.numClasses) : r[j] = self.classifiers[j].decisionFunc(data, i) return numpy.argmax(r), numpy.max(r) def preproject(self, data) : for i in range(self.labels.numClasses) : self.classifiers[i].preproject(data) test = assess.test train_data = """ 0 1:1.0 2:0.0 3:0.0 4:0.0 0 1:0.9 2:0.0 3:0.0 4:0.0 1 1:0.0 2:1.0 3:0.0 4:0.0 1 1:0.0 2:0.8 3:0.0 4:0.0 2 1:0.0 2:0.0 3:1.0 4:0.0 2 1:0.0 2:0.0 3:0.9 4:0.0 3 1:0.0 2:0.0 3:0.0 4:1.0 3 1:0.0 2:0.0 3:0.0 4:0.9 """ file("foo_train.data", "w").write(train_data.lstrip()) test_data = """ 0 1:1.1 2:0.0 3:0.0 4:0.0 1 1:0.0 2:1.2 3:0.0 4:0.0 2 1:0.0 2:0.0 3:0.6 4:0.0 3 1:0.0 2:0.0 3:0.0 4:1.4 """ file("foo_test.data", "w").write(test_data.lstrip()) train = SparseDataSet("foo_train.data") mc = OneAgainstRestFixed(SVM()) mc.train(train, saveSpace=False) test = SparseDataSet("foo_test.data") print [mc.classify(test, i) for i in range(4)] for i, classifier in enumerate(mc.classifiers): classifier.save("foo.model.%d" % i) classifiers = [] for i in range(4): classifiers.append(loadSVM("foo.model.%d" % i)) mcnew = OneAgainstRestFixed(SVM()) mcnew.labels = misc.Container() mcnew.labels.addAttributes(test.labels, ['numClasses', 'classLabels']) mcnew.classifiers = classifiers print [mcnew.classify(test, i) for i in range(4)] A: Get a newer version of PyML. Since version 0.7.4, it is possible to save the OneAgainstRest classifier (with .save() and .load()); prior to that version, saving/loading the classifier is non-trivial and error-prone.
Save PyML.classifiers.multi.OneAgainstRest(SVM()) object?
I'm using PYML to construct a multiclass linear support vector machine (SVM). After training the SVM, I would like to be able to save the classifier, so that on subsequent runs I can use the classifier right away without retraining. Unfortunately, the .save() function is not implemented for that classifier, and attempting to pickle it (both with standard pickle and cPickle) yield the following error message: pickle.PicklingError: Can't pickle : it's not found as __builtin__.PySwigObject Does anyone know of a way around this or of an alternative library without this problem? Thanks. Edit/Update I am now training and attempting to save the classifier with the following code: mc = multi.OneAgainstRest(SVM()); mc.train(dataset_pyml,saveSpace=False); for i, classifier in enumerate(mc.classifiers): filename=os.path.join(prefix,labels[i]+".svm"); classifier.save(filename); Notice that I am now saving with the PyML save mechanism rather than with pickling, and that I have passed "saveSpace=False" to the training function. However, I am still gettting an error: ValueError: in order to save a dataset you need to train as: s.train(data, saveSpace = False) However, I am passing saveSpace=False... so, how do I save the classifier(s)? P.S. The project I am using this in is pyimgattr, in case you would like a complete testable example... the program is run with "./pyimgattr.py train"... that will get you this error. Also, a note on version information: [michaelsafyan@codemage /Volumes/Storage/classes/cse559/pyimgattr]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import PyML >>> print PyML.__version__ 0.7.0
[ "In multi.py on line 96 \"self.classifiers[i].train(datai)\" is called without passing \"**args\", so that if you call \"mc.train(data, saveSpace=False)\", this saveSpace-Argument gets lost. This is why you get an error message if you try to save the classifiers in your multiclass-classifier individually. But if you change this line to pass all arguments, you can save each classifier individually:\n#!/usr/bin/python\n\nimport numpy\n\nfrom PyML.utils import misc\nfrom PyML.evaluators import assess\nfrom PyML.classifiers.svm import SVM, loadSVM\nfrom PyML.containers.labels import oneAgainstRest\nfrom PyML.classifiers.baseClassifiers import Classifier\nfrom PyML.containers.vectorDatasets import SparseDataSet\nfrom PyML.classifiers.composite import CompositeClassifier\n\nclass OneAgainstRestFixed(CompositeClassifier) :\n\n '''A one-against-the-rest multi-class classifier'''\n\n def train(self, data, **args) :\n '''train k classifiers'''\n\n Classifier.train(self, data, **args)\n\n numClasses = self.labels.numClasses\n if numClasses <= 2:\n raise ValueError, 'Not a multi class problem'\n\n self.classifiers = [self.classifier.__class__(self.classifier)\n for i in range(numClasses)]\n\n for i in range(numClasses) :\n # make a copy of the data; this is done in case the classifier modifies the data\n datai = data.__class__(data, deepcopy = self.classifier.deepcopy)\n datai = oneAgainstRest(datai, data.labels.classLabels[i])\n\n self.classifiers[i].train(datai, **args)\n\n self.log.trainingTime = self.getTrainingTime()\n\n def classify(self, data, i):\n\n r = numpy.zeros(self.labels.numClasses, numpy.float_)\n for j in range(self.labels.numClasses) :\n r[j] = self.classifiers[j].decisionFunc(data, i)\n\n return numpy.argmax(r), numpy.max(r)\n\n def preproject(self, data) :\n\n for i in range(self.labels.numClasses) :\n self.classifiers[i].preproject(data)\n\n test = assess.test\n\ntrain_data = \"\"\"\n0 1:1.0 2:0.0 3:0.0 4:0.0\n0 1:0.9 2:0.0 3:0.0 4:0.0\n1 1:0.0 2:1.0 3:0.0 4:0.0\n1 1:0.0 2:0.8 3:0.0 4:0.0\n2 1:0.0 2:0.0 3:1.0 4:0.0\n2 1:0.0 2:0.0 3:0.9 4:0.0\n3 1:0.0 2:0.0 3:0.0 4:1.0\n3 1:0.0 2:0.0 3:0.0 4:0.9\n\"\"\"\nfile(\"foo_train.data\", \"w\").write(train_data.lstrip())\n\ntest_data = \"\"\"\n0 1:1.1 2:0.0 3:0.0 4:0.0\n1 1:0.0 2:1.2 3:0.0 4:0.0\n2 1:0.0 2:0.0 3:0.6 4:0.0\n3 1:0.0 2:0.0 3:0.0 4:1.4\n\"\"\"\nfile(\"foo_test.data\", \"w\").write(test_data.lstrip())\n\ntrain = SparseDataSet(\"foo_train.data\")\nmc = OneAgainstRestFixed(SVM())\nmc.train(train, saveSpace=False)\n\ntest = SparseDataSet(\"foo_test.data\")\nprint [mc.classify(test, i) for i in range(4)]\n\nfor i, classifier in enumerate(mc.classifiers):\n classifier.save(\"foo.model.%d\" % i)\n\nclassifiers = []\nfor i in range(4):\n classifiers.append(loadSVM(\"foo.model.%d\" % i))\n\nmcnew = OneAgainstRestFixed(SVM())\nmcnew.labels = misc.Container()\nmcnew.labels.addAttributes(test.labels, ['numClasses', 'classLabels'])\nmcnew.classifiers = classifiers\nprint [mcnew.classify(test, i) for i in range(4)]\n\n", "Get a newer version of PyML. Since version 0.7.4, it is possible to save the OneAgainstRest classifier (with .save() and .load()); prior to that version, saving/loading the classifier is non-trivial and error-prone.\n" ]
[ 2, 0 ]
[]
[]
[ "libsvm", "pickle", "pyml", "python", "svm" ]
stackoverflow_0002674123_libsvm_pickle_pyml_python_svm.txt
Q: how to check if an ip address or proxy is working or not How can I check if a specific ip address or proxy is alive or dead A: Because there may be any level of filtering or translation between you and the remote host, the only way to determine whether you can connect to a specific host is to actually try to connect. If the connection succeeds, then you can, else you can't. Pinging isn't sufficient because ICMP ECHO requests may be blocked yet TCP connections might go through fine. A: Maybe this question here will help, its about pinging in python. Post A: An IP address corresponds to a device. You can't "connect" to a device in the general sense. You can connect to services on the device identified by ports. So, you find the ip address and port of the proxy server you're interested in and then try connecting to it using a simple socket.connect. If it connects fine, you can alteast be sure that something is running on that port of that ip address. Then you go ahead and use it and if things are not as you expect, you can make further decisions.
how to check if an ip address or proxy is working or not
How can I check if a specific ip address or proxy is alive or dead
[ "Because there may be any level of filtering or translation between you and the remote host, the only way to determine whether you can connect to a specific host is to actually try to connect. If the connection succeeds, then you can, else you can't.\nPinging isn't sufficient because ICMP ECHO requests may be blocked yet TCP connections might go through fine.\n", "Maybe this question here will help, its about pinging in python.\nPost\n", "An IP address corresponds to a device. You can't \"connect\" to a device in the general sense. You can connect to services on the device identified by ports. So, you find the ip address and port of the proxy server you're interested in and then try connecting to it using a simple socket.connect. If it connects fine, you can alteast be sure that something is running on that port of that ip address. Then you go ahead and use it and if things are not as you expect, you can make further decisions.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "proxy", "python", "sockets" ]
stackoverflow_0003078704_proxy_python_sockets.txt
Q: Adding printf to the starting of all functions in a file I have some very large C files, having lots of functions. I need to trace the execution path at run time. There is no way I can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translations. Can anyone point me to some script in Perl or Python which can add a printf at the starting of all functions and the text could be something like "I am in < function name >"? A: Just pass -finstrument-functions to gcc when compiling. See the gcc(1) man page for details. A: Here is a nice example of what you want.
Adding printf to the starting of all functions in a file
I have some very large C files, having lots of functions. I need to trace the execution path at run time. There is no way I can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translations. Can anyone point me to some script in Perl or Python which can add a printf at the starting of all functions and the text could be something like "I am in < function name >"?
[ "Just pass -finstrument-functions to gcc when compiling. See the gcc(1) man page for details.\n", "Here is a nice example of what you want.\n" ]
[ 24, 2 ]
[]
[]
[ "c", "perl", "python" ]
stackoverflow_0003078680_c_perl_python.txt
Q: Tornado handler thinks POST is missing argument when Firebug shows the argument being sent I have a simple form using a POST method, consisting of a text box and a file. After hitting submit, I can see the post in Firebug as follows: Parts multipart/form-data posttext Some text image BlahJFIFBlahExifBlahPhotoshopBlahBinaryStuff etc... The Tornado handler that receives it looks like: class NewPostHandler(BaseHandler, MessageMixin): @tornado.web.authenticated def post(self): message = { 'posttext':self.get_argument('posttext'), 'image':self.get_argument('image'), etc But Tornado's handler returns: [W 100618 23:07:32 web:775] 404 POST /a/message/new (127.0.0.1): Missing argument image I'm not quite sure what I'm doing wrong here. Am I correct in thinking 'argument' means a input element's 'name' attribute? How can I make the handler see the argument? Thanks for your help, I've been struggling with this for an hour and must admit I'm stumped! A: For file uploads you should use self.request.files instead of self.get_argument().
Tornado handler thinks POST is missing argument when Firebug shows the argument being sent
I have a simple form using a POST method, consisting of a text box and a file. After hitting submit, I can see the post in Firebug as follows: Parts multipart/form-data posttext Some text image BlahJFIFBlahExifBlahPhotoshopBlahBinaryStuff etc... The Tornado handler that receives it looks like: class NewPostHandler(BaseHandler, MessageMixin): @tornado.web.authenticated def post(self): message = { 'posttext':self.get_argument('posttext'), 'image':self.get_argument('image'), etc But Tornado's handler returns: [W 100618 23:07:32 web:775] 404 POST /a/message/new (127.0.0.1): Missing argument image I'm not quite sure what I'm doing wrong here. Am I correct in thinking 'argument' means a input element's 'name' attribute? How can I make the handler see the argument? Thanks for your help, I've been struggling with this for an hour and must admit I'm stumped!
[ "For file uploads you should use self.request.files instead of self.get_argument().\n" ]
[ 4 ]
[]
[]
[ "handler", "post", "python", "tornado" ]
stackoverflow_0003073462_handler_post_python_tornado.txt
Q: Python urllib2 HTTPBasicAuthHandler Here is the code: import urllib2 as URL def get_unread_msgs(user, passwd): auth = URL.HTTPBasicAuthHandler() auth.add_password( realm='New mail feed', uri='https://mail.google.com', user='%s'%user, passwd=passwd ) opener = URL.build_opener(auth) URL.install_opener(opener) try: feed= URL.urlopen('https://mail.google.com/mail/feed/atom') return feed.read() except: return None It works just fine. The only problem is that when a wrong username or password is used, it takes forever to open to url @ feed= URL.urlopen('https://mail.google.com/mail/feed/atom') It doesn't throw up any errors, just keep executing the urlopen statement forever. How can i know if username/password is incorrect. I thought of a timeout for the function but then that would turn all error and even slow internet into a authentication error. A: It should throw an error, more precisely an urllib2.HTTPError, with the code field set to 401, you can see some adapted code below. I left your general try/except structure, but really, do not use general except statements, catch only what you expect that could happen! def get_unread_msgs(user, passwd): auth = URL.HTTPBasicAuthHandler() auth.add_password( realm='New mail feed', uri='https://mail.google.com', user='%s'%user, passwd=passwd ) opener = URL.build_opener(auth) URL.install_opener(opener) try: feed= URL.urlopen('https://mail.google.com/mail/feed/atom') return feed.read() except HTTPError, e: if e.code == 401: print "authorization failed" else: raise e # or do something else except: #A general except clause is discouraged, I let it in because you had it already return None I just tested it here, works perfectly
Python urllib2 HTTPBasicAuthHandler
Here is the code: import urllib2 as URL def get_unread_msgs(user, passwd): auth = URL.HTTPBasicAuthHandler() auth.add_password( realm='New mail feed', uri='https://mail.google.com', user='%s'%user, passwd=passwd ) opener = URL.build_opener(auth) URL.install_opener(opener) try: feed= URL.urlopen('https://mail.google.com/mail/feed/atom') return feed.read() except: return None It works just fine. The only problem is that when a wrong username or password is used, it takes forever to open to url @ feed= URL.urlopen('https://mail.google.com/mail/feed/atom') It doesn't throw up any errors, just keep executing the urlopen statement forever. How can i know if username/password is incorrect. I thought of a timeout for the function but then that would turn all error and even slow internet into a authentication error.
[ "It should throw an error, more precisely an urllib2.HTTPError, with the code field set to 401, you can see some adapted code below. I left your general try/except structure, but really, do not use general except statements, catch only what you expect that could happen!\ndef get_unread_msgs(user, passwd):\n auth = URL.HTTPBasicAuthHandler()\n auth.add_password(\n realm='New mail feed',\n uri='https://mail.google.com',\n user='%s'%user,\n passwd=passwd\n )\n opener = URL.build_opener(auth)\n URL.install_opener(opener)\n try:\n feed= URL.urlopen('https://mail.google.com/mail/feed/atom')\n return feed.read()\n except HTTPError, e:\n if e.code == 401:\n print \"authorization failed\" \n else:\n raise e # or do something else\n except: #A general except clause is discouraged, I let it in because you had it already\n return None\n\nI just tested it here, works perfectly\n" ]
[ 3 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003078638_python_urllib2.txt
Q: Call the Python interactive interpreter from within a Python script Is there any way to start up the Python interpreter from within a script , in a manner similar to just using python -i so that the objects/namespace, etc. from the current script are retained? The reason for not using python -i is that the script initializes a connection to an XML-RPC server, and I need to be able to stop the entire program if there's an error. I can't loop until there's valid input because apparently, I can't do something like this: #!/usr/bin/python -i # -*- coding: utf-8 -*- import xmlrpclib # Create an object to represent our server. server_url = str(raw_input("Server: ")) while not server = xmlrpclib.Server(server_url): print 'Unable to connect to server. Please try again' else: print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created" break # Python interpreter starts... because: % chmod u+x ./rpcclient.py % ./rpclient.py Traceback (most recent call last): File "./rpcclient.py", line 8 while not server = xmlrpclib.Server(server_url): ^ SyntaxError: invalid syntax >>> Unfortunately, python -i starts the interpreter just after it prints out the traceback, so I somehow have to call the interactive interpreter - replacing the execution of the script so it retains the server connection - from within the script A: Have you tried reading the error message? :) = is assignment, you want the comparison operator == instead. A: Well, I finally got it to work. Basically, I put the entire try/except/else clause in a while True: loop, with the else suite being a break statement and the end of the except suite being a continue statement. The result is that it now continually loops if the user puts in an address that doesn't have a fully compliant XML-RPC2 server listening. Here's how it turned out: #!/usr/bin/python -i # -*- coding: utf-8 -*- import xmlrpclib, socket from sys import exit # Create an object to represent our server. #server = xmlrpclib.Server(server_url) and print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created" server_url = str(raw_input("Server: ")) server = xmlrpclib.ServerProxy(server_url) while True: try: server.system.listMethods() except xmlrpclib.ProtocolError, socket.error: print 'Unable to connect to server. Please try again' server_url = str(raw_input("Server: ")) server = xmlrpclib.ServerProxy(server_url) continue except EOFError: exit(1) else: break print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created" # Python interpreter starts... Thank you very much! ...and I have to wait another day to accept this...
Call the Python interactive interpreter from within a Python script
Is there any way to start up the Python interpreter from within a script , in a manner similar to just using python -i so that the objects/namespace, etc. from the current script are retained? The reason for not using python -i is that the script initializes a connection to an XML-RPC server, and I need to be able to stop the entire program if there's an error. I can't loop until there's valid input because apparently, I can't do something like this: #!/usr/bin/python -i # -*- coding: utf-8 -*- import xmlrpclib # Create an object to represent our server. server_url = str(raw_input("Server: ")) while not server = xmlrpclib.Server(server_url): print 'Unable to connect to server. Please try again' else: print 'Xmlrpclib.Server object `__main__.server\' of URL `', server_url, "' created" break # Python interpreter starts... because: % chmod u+x ./rpcclient.py % ./rpclient.py Traceback (most recent call last): File "./rpcclient.py", line 8 while not server = xmlrpclib.Server(server_url): ^ SyntaxError: invalid syntax >>> Unfortunately, python -i starts the interpreter just after it prints out the traceback, so I somehow have to call the interactive interpreter - replacing the execution of the script so it retains the server connection - from within the script
[ "Have you tried reading the error message? :)\n= is assignment, you want the comparison operator == instead.\n", "Well, I finally got it to work.\nBasically, I put the entire try/except/else clause in a while True: loop, with the else suite being a break statement and the end of the except suite being a continue statement. The result is that it now continually loops if the user puts in an address that doesn't have a fully compliant XML-RPC2 server listening. Here's how it turned out:\n#!/usr/bin/python -i\n# -*- coding: utf-8 -*-\n\nimport xmlrpclib, socket\nfrom sys import exit\n\n# Create an object to represent our server.\n\n#server = xmlrpclib.Server(server_url) and print 'Xmlrpclib.Server object `__main__.server\\' of URL `', server_url, \"' created\"\nserver_url = str(raw_input(\"Server: \"))\nserver = xmlrpclib.ServerProxy(server_url)\nwhile True:\n try:\n server.system.listMethods()\n except xmlrpclib.ProtocolError, socket.error:\n print 'Unable to connect to server. Please try again'\n server_url = str(raw_input(\"Server: \"))\n server = xmlrpclib.ServerProxy(server_url)\n continue\n except EOFError:\n exit(1)\n else:\n break\n\nprint 'Xmlrpclib.Server object `__main__.server\\' of URL `', server_url, \"' created\"\n\n# Python interpreter starts...\n\nThank you very much!\n...and I have to wait another day to accept this...\n" ]
[ 2, 0 ]
[]
[]
[ "python", "python_interactive", "while_loop", "xmlrpclib" ]
stackoverflow_0003075827_python_python_interactive_while_loop_xmlrpclib.txt
Q: Override DEFINEs in setup.cfg in source eggs The source egg of PySQLite 2.6.0 contains a file setup.cfg that looks like this: [build_ext] #define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define=SQLITE_OMIT_LOAD_EXTENSION I'd like to build the egg with the SQLITE_OMIT_LOAD_EXTENSION define disabled (not set). I could do that by uncommenting that line in setup.cfg, but I'd like to do this in a zc.buildout environment, using zc.recipe.egg, zc.recipe.cmmi, or any other recipe that could help me. So, is there an easy way to install PySQLite with extensions enabled but without tampering setup.cfg? A: Yes, there is: [buildout] parts = pysql [pysql] recipe = zc.recipe.egg:custom egg = PySQLite undef=SQLITE_OMIT_LOAD_EXTENSION
Override DEFINEs in setup.cfg in source eggs
The source egg of PySQLite 2.6.0 contains a file setup.cfg that looks like this: [build_ext] #define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define=SQLITE_OMIT_LOAD_EXTENSION I'd like to build the egg with the SQLITE_OMIT_LOAD_EXTENSION define disabled (not set). I could do that by uncommenting that line in setup.cfg, but I'd like to do this in a zc.buildout environment, using zc.recipe.egg, zc.recipe.cmmi, or any other recipe that could help me. So, is there an easy way to install PySQLite with extensions enabled but without tampering setup.cfg?
[ "Yes, there is:\n[buildout]\nparts = pysql\n\n[pysql]\nrecipe = zc.recipe.egg:custom\negg = PySQLite\nundef=SQLITE_OMIT_LOAD_EXTENSION\n\n" ]
[ 4 ]
[]
[]
[ "buildout", "egg", "pysqlite", "python" ]
stackoverflow_0003013075_buildout_egg_pysqlite_python.txt
Q: Python: How to access variable declared in parent module Using the structure from the Python docs: sound/ __init__.py effects/ __init__.py echo.py surround.py reverse.py Say I want to import sound.effects and get a list of available effects. I could do this by declaring a module-level variable in sound.effects and then appending to it when each .py file is imported. So sound/effects/__init__.py might look like this: effectList = [] import echo import surround # Could write code to import *.py instead ... From my main code I can now access sound.effects.effectList to get a list of effects, but how do I access effectList from within echo.py to do the actual append? I'm stuck trying to get access to the variable: # None of these work :-( # from . import self # from .. import effects # import sound.effects sound.effect.effectList.append({'name': 'echo'}) A: What people commonly do in this situation is create a common.py file in the module. sound/ __init__.py effect/ __init__.py common.py echo.py surround.py reverse.py Then you move the code from __init__.py to common.py: effectList = [] import echo import surround # Could write code to import *.py instead ... Inside __init__.py you have this: from common import * So now in echo.py you'd have this: import common common.effectList.append({'name': 'echo'}) Anything importing sound would use it like this import sound.effect for effect_name,effect in sound.effect.effectlist.items(): #.... I've only just started using this myself, but I believe it's common practice in the python community. A: I think you should leave the "making available" to the __init__.py inside the effects package rather than have all the modules auto populate the effectList. A couple of reasons I can think of. You can't import any of the effects except via the package if you did manage to get this work somehow (they'd except an effectList in the importing module). You have to manually do the append in every effect you write. It would be better if you just implemented an import *.py like thing in your __init__.py that loaded everything up in the current directory and made it available. Something like this in your __init__.py. import os, glob effectslist = [] for i in glob.glob("*.py"): if i == "__init__.py": next print "Attempting to import %s"%i try: mod = __import__(os.path.splitext(i)[0]) effectslist.append(mod) except ImportError,m: print "Error while importing %s - %s"%(i,m)
Python: How to access variable declared in parent module
Using the structure from the Python docs: sound/ __init__.py effects/ __init__.py echo.py surround.py reverse.py Say I want to import sound.effects and get a list of available effects. I could do this by declaring a module-level variable in sound.effects and then appending to it when each .py file is imported. So sound/effects/__init__.py might look like this: effectList = [] import echo import surround # Could write code to import *.py instead ... From my main code I can now access sound.effects.effectList to get a list of effects, but how do I access effectList from within echo.py to do the actual append? I'm stuck trying to get access to the variable: # None of these work :-( # from . import self # from .. import effects # import sound.effects sound.effect.effectList.append({'name': 'echo'})
[ "What people commonly do in this situation is create a common.py file in the module.\nsound/\n __init__.py\n effect/\n __init__.py\n common.py\n echo.py\n surround.py\n reverse.py\n\nThen you move the code from __init__.py to common.py:\neffectList = []\nimport echo\nimport surround # Could write code to import *.py instead\n...\n\nInside __init__.py you have this:\nfrom common import *\n\nSo now in echo.py you'd have this:\nimport common\ncommon.effectList.append({'name': 'echo'})\n\nAnything importing sound would use it like this\nimport sound.effect\n\nfor effect_name,effect in sound.effect.effectlist.items():\n #....\n\nI've only just started using this myself, but I believe it's common practice in the python community.\n", "I think you should leave the \"making available\" to the __init__.py inside the effects package rather than have all the modules auto populate the effectList. A couple of reasons I can think of.\n\nYou can't import any of the effects except via the package if you did manage to get this work somehow (they'd except an effectList in the importing module). \nYou have to manually do the append in every effect you write. It would be better if you just implemented an import *.py like thing in your __init__.py that loaded everything up in the current directory and made it available. \n\nSomething like this in your __init__.py.\nimport os, glob\n\neffectslist = []\n\nfor i in glob.glob(\"*.py\"):\n if i == \"__init__.py\":\n next\n print \"Attempting to import %s\"%i\n try:\n mod = __import__(os.path.splitext(i)[0])\n effectslist.append(mod)\n except ImportError,m:\n print \"Error while importing %s - %s\"%(i,m)\n\n" ]
[ 8, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003078927_import_python.txt
Q: Upload a file with python using httplib conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/") conn.request("POST", path, chunk, headers) Above is the site "www.encodable.com/uploaddemo/" where I want to upload an image. I am better versed in php so I am unable to understand the meaning of path and headers here. In the code above, chunk is an object consisting of my image file. The following code produces an error as I was trying to implement without any knowledge of headers and path. import httplib def upload_image_to_url(): filename = '//home//harshit//Desktop//h1.jpg' f = open(filename, "rb") chunk = f.read() f.close() headers = { "Content−type": "application/octet−stream", "Accept": "text/plain" } conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/") conn.request("POST", "/uploaddemo/files/", chunk) response = conn.getresponse() remote_file = response.read() conn.close() print remote_file upload_image_to_url() A: Currently, you aren't using the headers you've declared earlier in the code. You should provide them as the fourth argument to conn.request: conn.request("POST", "/uploaddemo/files/", chunk, headers) Also, side note: you can pass open("h1.jpg", "rb") directly into conn.request without reading it fully into chunk first. conn.request accepts file-like objects and it will be more efficient to stream the file a little at a time: conn.request("POST", "/uploaddemo/files/", open("h1.jpg", "rb"), headers)
Upload a file with python using httplib
conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/") conn.request("POST", path, chunk, headers) Above is the site "www.encodable.com/uploaddemo/" where I want to upload an image. I am better versed in php so I am unable to understand the meaning of path and headers here. In the code above, chunk is an object consisting of my image file. The following code produces an error as I was trying to implement without any knowledge of headers and path. import httplib def upload_image_to_url(): filename = '//home//harshit//Desktop//h1.jpg' f = open(filename, "rb") chunk = f.read() f.close() headers = { "Content−type": "application/octet−stream", "Accept": "text/plain" } conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/") conn.request("POST", "/uploaddemo/files/", chunk) response = conn.getresponse() remote_file = response.read() conn.close() print remote_file upload_image_to_url()
[ "Currently, you aren't using the headers you've declared earlier in the code. You should provide them as the fourth argument to conn.request:\nconn.request(\"POST\", \"/uploaddemo/files/\", chunk, headers)\n\nAlso, side note: you can pass open(\"h1.jpg\", \"rb\") directly into conn.request without reading it fully into chunk first. conn.request accepts file-like objects and it will be more efficient to stream the file a little at a time:\nconn.request(\"POST\", \"/uploaddemo/files/\", open(\"h1.jpg\", \"rb\"), headers)\n\n" ]
[ 5 ]
[]
[]
[ "httplib", "python" ]
stackoverflow_0003079562_httplib_python.txt
Q: doesn't python uses copy by reference?why is the following code not working then? class x: def __init__(self): self.y=None self.sillyFunc(self.y) def sillyFunc(self,argument): if argument is None: argument='my_name_as_argument' self.printy() def printy(self): print self.y According to me the above code should print >my_name_as_argument,where am i going wrong? A: The assigment argument='my_name_as_argument' only affects the local variable argument. It doesn't change what self.y points to. A: In Python everything is an object and variables contain references to objects. When you make a function call it makes copies of the references. Some people including Guido van Rossum call this "Call by object reference". Important note from Wikipedia: a function cannot change the value a variable references in its calling function. The code as you posted it prints nothing at all. I think you mean to add this extra line to your program: x() This then results in the output: None. This is not surprising because you are printing the value of self.y but the only value you ever assign to self.y is None. In Python, strings are immutable. Reassigning the value of argument only overwrites the local copy of the reference. It does not modify the original string. As you asked in a comment, if you use a mutable object and you reassign the reference, again this doesn't do what you want - the original object is not affected. If you want to mutate a mutable object you can call a method that mutates it. Simply reassigning a reference does not change the original object. If you want self.y to point to a new object then you have to assign the object reference directly to self.y. A: it depends on if you are changing the referenced object itself (and if this object is mutable) or replacing the reference to another object. See the following example, which uses a mutable list... >>> def test(arg): ... arg.append(123) ... ... >>> s = [] >>> print s [] >>> test(s) >>> print s [123]
doesn't python uses copy by reference?why is the following code not working then?
class x: def __init__(self): self.y=None self.sillyFunc(self.y) def sillyFunc(self,argument): if argument is None: argument='my_name_as_argument' self.printy() def printy(self): print self.y According to me the above code should print >my_name_as_argument,where am i going wrong?
[ "The assigment\nargument='my_name_as_argument'\n\nonly affects the local variable argument. It doesn't change what self.y points to.\n", "In Python everything is an object and variables contain references to objects. When you make a function call it makes copies of the references. Some people including Guido van Rossum call this \"Call by object reference\". Important note from Wikipedia:\n\na function cannot change the value a variable references in its calling function.\n\nThe code as you posted it prints nothing at all. I think you mean to add this extra line to your program:\nx()\n\nThis then results in the output: None. This is not surprising because you are printing the value of self.y but the only value you ever assign to self.y is None.\nIn Python, strings are immutable. Reassigning the value of argument only overwrites the local copy of the reference. It does not modify the original string.\nAs you asked in a comment, if you use a mutable object and you reassign the reference, again this doesn't do what you want - the original object is not affected. If you want to mutate a mutable object you can call a method that mutates it. Simply reassigning a reference does not change the original object.\nIf you want self.y to point to a new object then you have to assign the object reference directly to self.y.\n", "it depends on if you are changing the referenced object itself (and if this object is mutable) or replacing the reference to another object. See the following example, which uses a mutable list...\n>>> def test(arg):\n... arg.append(123)\n... \n... \n>>> s = []\n>>> print s\n[]\n>>> test(s)\n>>> print s\n[123]\n\n" ]
[ 5, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003079533_python.txt
Q: socket.error: [Errno 10054] import socket, sys if len(sys.argv) !=3 : print "Usage: ./supabot.py <host> <port>" sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN #darkunderground' + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print data elif data.find('!info') != -1: sck.send('PRIVMSG #darkunderground supaBOT v1.0 by sourD' + '\r\n') print sck.recv(1024) when I run this code I get this error.. socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host it says that the error is in line 16, in data = sck.recv(1024) A: You need to check the IRC protocol a little it more; your IRC session is not considered conncted (by the server) until certain actions have been completed which the server will inform your client about using IRC protocol codes. And if the server or network is busy when you are connecting it will take longer for these actions to complete. In this case attempting to join a channel before the server has given you the MOTD (message of the day) would cause a disconnection by the server. The end of MOTD protocol code is 376 and indicates that the IRC connection sequence is over, and you can proceed with your IRC session eg: enter commands (like join). I would suggest entering a RECV loop and monitoring data received from the server for the IRC code 376 before you attempt to join a channel, in Perl this would look somthing like this: sub chan_join{ while(my $input = <SOCK>){ if($input =~ /376/){ my $talk = "JOIN $channel"; &send_data($talk); &monitor; } else { print "$input"; } } } Pretty poor but you get the idea right? (please note its only necessary to check for 376 once, once seen you are connected and you only need to maintain the connection by responding to the server 'PING's) A: That probably means that you're not supplying the expected handshake or protocol exchange for the server, and it is closing the connection. What happens if you telnet to the same machine and port and type in the same text? A: The remote host is issuing a TCP reset (RST), after accepting the connection. This can happen for a lot of reasons, including: Firewall rules Remote application error Remote application simply closes the connection etc. As John Weldon said, try telnetting to the same machine and port and entering the commands manually. Also, a good wire sniffer (Ethereal, WireShark, etc.) is highly useful for diagnosing this kind of problem.
socket.error: [Errno 10054]
import socket, sys if len(sys.argv) !=3 : print "Usage: ./supabot.py <host> <port>" sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((irc, port)) sck.send('NICK supaBOT\r\n') sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') sck.send('JOIN #darkunderground' + '\r\n') data = '' while True: data = sck.recv(1024) if data.find('PING') != -1: sck.send('PONG ' + data.split() [1] + '\r\n') print data elif data.find('!info') != -1: sck.send('PRIVMSG #darkunderground supaBOT v1.0 by sourD' + '\r\n') print sck.recv(1024) when I run this code I get this error.. socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host it says that the error is in line 16, in data = sck.recv(1024)
[ "You need to check the IRC protocol a little it more; your IRC session is not considered conncted (by the server) until certain actions have been completed which the server will inform your client about using IRC protocol codes. And if the server or network is busy when you are connecting it will take longer for these actions to complete.\nIn this case attempting to join a channel before the server has given you the MOTD (message of the day) would cause a disconnection by the server. The end of MOTD protocol code is 376 and indicates that the IRC connection sequence is over, and you can proceed with your IRC session eg: enter commands (like join).\nI would suggest entering a RECV loop and monitoring data received from the server for the IRC code 376 before you attempt to join a channel, in Perl this would look somthing like this:\n sub chan_join{\n while(my $input = <SOCK>){\n if($input =~ /376/){\n my $talk = \"JOIN $channel\";\n &send_data($talk);\n &monitor;\n }\n else { print \"$input\"; }\n }\n}\n\nPretty poor but you get the idea right? (please note its only necessary to check for 376 once, once seen you are connected and you only need to maintain the connection by responding to the server 'PING's)\n", "That probably means that you're not supplying the expected handshake or protocol exchange for the server, and it is closing the connection.\nWhat happens if you telnet to the same machine and port and type in the same text?\n", "The remote host is issuing a TCP reset (RST), after accepting the connection. This can happen for a lot of reasons, including:\n\nFirewall rules\nRemote application error\nRemote application simply closes the connection\netc.\n\nAs John Weldon said, try telnetting to the same machine and port and entering the commands manually.\nAlso, a good wire sniffer (Ethereal, WireShark, etc.) is highly useful for diagnosing this kind of problem.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "irc", "network_protocols", "python", "sockets" ]
stackoverflow_0003058932_irc_network_protocols_python_sockets.txt
Q: how to make a chat room on gae ,has any audio python-framework to do this? i want to make a chat room on gae ,(audio chat) has any framework to do this ? thanks A: App Engine doesn't directly support audio chat of any sort, and since it's based around a request-response system with (primarily) HTTP requests, you can't implement it yourself. A: Try Adobe Stratus (it works with p2p connections) and you could use Google App Engine only for exchanging peer ids. A: If you support Jingle then all you have to do is pass the XMPP packets around. There's lots of modules that support that. A: You'll need two things: A browser plugin to get audio. You could build this on top of eg. http://code.google.com/p/libjingle/'>libjingle which has the advantage of being cross-platform and allowing P2P communication, not to mention being able to talk to arbitrary other XMPP endoints. Or you could use Flash to grab the audio and bounce the stream off a server you build (I think trying to do STUN in Flash for P2P would be impossible), but this would be very tricky to do in App Engine because you'd need it to be long-running. A way to get signaling messages between your clients. You'll have to poll until the Channel API is released (soon). This is a big hairy problem, to put it mildly, but it would be awesome if you did it.
how to make a chat room on gae ,has any audio python-framework to do this?
i want to make a chat room on gae ,(audio chat) has any framework to do this ? thanks
[ "App Engine doesn't directly support audio chat of any sort, and since it's based around a request-response system with (primarily) HTTP requests, you can't implement it yourself.\n", "Try Adobe Stratus (it works with p2p connections) and you could use Google App Engine only for exchanging peer ids.\n", "If you support Jingle then all you have to do is pass the XMPP packets around. There's lots of modules that support that.\n", "You'll need two things:\nA browser plugin to get audio. You could build this on top of eg. http://code.google.com/p/libjingle/'>libjingle which has the advantage of being cross-platform and allowing P2P communication, not to mention being able to talk to arbitrary other XMPP endoints. Or you could use Flash to grab the audio and bounce the stream off a server you build (I think trying to do STUN in Flash for P2P would be impossible), but this would be very tricky to do in App Engine because you'd need it to be long-running.\nA way to get signaling messages between your clients. You'll have to poll until the Channel API is released (soon).\nThis is a big hairy problem, to put it mildly, but it would be awesome if you did it.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "audio", "chat", "google_app_engine", "python" ]
stackoverflow_0003012661_audio_chat_google_app_engine_python.txt
Q: GAEUnit: Trouble with long strings in assert statements? I'm having an odd error where GAEUnit seems to be hung on assertion statements that have error strings that are too long. I'm running these tests on the GAE Dev server 1.3.3. This works just fine: self.assertEquals(2 + 2, 5, "[2, 3, 4]") # works However, if I defined a longer string, and try to print that out: jsonTest = '''[ { 'id': '0', 'name': 'CS 1110', 'adjacencies': [ { nodeTo: '1.5', data: { $direction: ['0', '1.5'] } }, { nodeTo: '1', data: { $direction: ['0', '1'] } } ] }, { 'id': '1.5', 'name': 'INFO 2300', 'adjacencies': [ { nodeTo: '2', data: { $direction: ['1.5', '2'] } } ] }] ''' self.assertEquals(2 + 2, 5, jsonTest) It freezes up. (The "Runs: 2/3" counter stops.) If I select a shorter segment of jsonTest, it does work: self.assertEquals(2 + 2, 5, jsonTest[0:3]) # works self.assertEquals(2 + 2, 5, jsonTest[0:10]) # works self.assertEquals(2 + 2, 5, jsonTest[0:20]) # works self.assertEquals(2 + 2, 5, jsonTest[0:-1]) # frozen What's going on here? Am I doing something wrong? Is this a bug in GAEUnit? A: Workaround: the ?format=plain option returns plaintext results that seem to work just fine.
GAEUnit: Trouble with long strings in assert statements?
I'm having an odd error where GAEUnit seems to be hung on assertion statements that have error strings that are too long. I'm running these tests on the GAE Dev server 1.3.3. This works just fine: self.assertEquals(2 + 2, 5, "[2, 3, 4]") # works However, if I defined a longer string, and try to print that out: jsonTest = '''[ { 'id': '0', 'name': 'CS 1110', 'adjacencies': [ { nodeTo: '1.5', data: { $direction: ['0', '1.5'] } }, { nodeTo: '1', data: { $direction: ['0', '1'] } } ] }, { 'id': '1.5', 'name': 'INFO 2300', 'adjacencies': [ { nodeTo: '2', data: { $direction: ['1.5', '2'] } } ] }] ''' self.assertEquals(2 + 2, 5, jsonTest) It freezes up. (The "Runs: 2/3" counter stops.) If I select a shorter segment of jsonTest, it does work: self.assertEquals(2 + 2, 5, jsonTest[0:3]) # works self.assertEquals(2 + 2, 5, jsonTest[0:10]) # works self.assertEquals(2 + 2, 5, jsonTest[0:20]) # works self.assertEquals(2 + 2, 5, jsonTest[0:-1]) # frozen What's going on here? Am I doing something wrong? Is this a bug in GAEUnit?
[ "Workaround: the ?format=plain option returns plaintext results that seem to work just fine.\n" ]
[ 0 ]
[]
[]
[ "gaeunit", "google_app_engine", "python", "unit_testing" ]
stackoverflow_0003077576_gaeunit_google_app_engine_python_unit_testing.txt
Q: customizing basic existing Django apps that already have "nice looking" CSS/HTML templates? I am looking for a basic Django application that "looks good" and has basic menus etc. that I could adapt for my own use. I am not doing any fancy processing of user input, but I do want to reuse an existing templates so that I don't have to worry about writing my own CSS/HTML to get clean, valid good looking webpages. Many of the Django websites themselves have a formatting that I could adapt, but I do not see anywhere an archive of templates. Is there such an archive, where users post their templates for other Django users to adapt, kind of like Wordpress has many templates? Examples of nice looking websites about Django that it'd be helpful to have templates for: http://www.django-apps.com/browse/ The Django website itself: http://www.djangoproject.com/ -- looks great. I think Django is a great framework for writing the actual content of the web app. My problem is that I want to start with a base that has the template already in Django's template, because I am not a web designer and I don't want to reinvent the wheel of writing nice looking HTML / CSS for a simple website that just has a couple of menu items. thanks. A: In my opinion this is really in no way django-specific. I think you would be better suited if you search for something like "web templates download" in your favourite search engine. Find a layout that you like, pay for it (if you can't find anything gratis) and use it. Oh, and no, there is regrettably no such archive (yet).
customizing basic existing Django apps that already have "nice looking" CSS/HTML templates?
I am looking for a basic Django application that "looks good" and has basic menus etc. that I could adapt for my own use. I am not doing any fancy processing of user input, but I do want to reuse an existing templates so that I don't have to worry about writing my own CSS/HTML to get clean, valid good looking webpages. Many of the Django websites themselves have a formatting that I could adapt, but I do not see anywhere an archive of templates. Is there such an archive, where users post their templates for other Django users to adapt, kind of like Wordpress has many templates? Examples of nice looking websites about Django that it'd be helpful to have templates for: http://www.django-apps.com/browse/ The Django website itself: http://www.djangoproject.com/ -- looks great. I think Django is a great framework for writing the actual content of the web app. My problem is that I want to start with a base that has the template already in Django's template, because I am not a web designer and I don't want to reinvent the wheel of writing nice looking HTML / CSS for a simple website that just has a couple of menu items. thanks.
[ "In my opinion this is really in no way django-specific. I think you would be better suited if you search for something like \"web templates download\" in your favourite search engine. Find a layout that you like, pay for it (if you can't find anything gratis) and use it.\nOh, and no, there is regrettably no such archive (yet).\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003080194_django_django_templates_python.txt
Q: Some questions about Django localisation I intend to localise my Django application and began reading up on localisation on the Django site. This put a few questions in my mind: It seems that when you run the 'django-admin.py makemessages' command, it scans the files for embedded strings and generates a message file that contains the translations. These translations are mapped to the strings in the file. For example, if I have a string in HTML that reads "Please enter the recipients name", Django would consider it to be the message id. What would happen if i changed something in the string. Let's say I added the missing apostrophe to the word "recipient". Would this break the translation? In relation to the above scenario, Is it better to use full fledged sentences in the source (which might change) or would I be better off using a word like "RECIPIENT_NAME" which is less likely to change and easier to map to? Does the 'django-admin.py makemessages' command scan the Python sources as well? Thanks. A: It very probably would, in some cases 'similar' strings can be detected and your translation will be marked with fuzzy. But it depends on the type of string, I don't know what adding an apostrophe would do. Read the GNU gettext docs for more information about this. However, an easy solution for your problem would be: don't fix the typo in the original, but make a translation like english to english where the translated string is the correct one :). I personally wouldn't recommend this approach, but If you're afraid to break tens of translation files, it can be considered. No it isn't, it throws away all sense of context. It might look clearer for sites where only a few translation strings are required and you know the exact context by heart. But as soon as you have 100s of strings in the translation file, short names like that will say nothing, you'll always have to look up the exact context. Even worse, it can be you use the same 'short name' for something that actually has to be translated differently, which will end up giving you weirder short names to handle both cases. Finally, if you use one normal language as default, you don't need to translate this language explicitly anymore. Yes it does, there exist multiple functions to mark strings in python for translation, an overview can be found here.
Some questions about Django localisation
I intend to localise my Django application and began reading up on localisation on the Django site. This put a few questions in my mind: It seems that when you run the 'django-admin.py makemessages' command, it scans the files for embedded strings and generates a message file that contains the translations. These translations are mapped to the strings in the file. For example, if I have a string in HTML that reads "Please enter the recipients name", Django would consider it to be the message id. What would happen if i changed something in the string. Let's say I added the missing apostrophe to the word "recipient". Would this break the translation? In relation to the above scenario, Is it better to use full fledged sentences in the source (which might change) or would I be better off using a word like "RECIPIENT_NAME" which is less likely to change and easier to map to? Does the 'django-admin.py makemessages' command scan the Python sources as well? Thanks.
[ "\nIt very probably would, in some cases 'similar' strings can be detected and your translation will be marked with fuzzy. But it depends on the type of string, I don't know what adding an apostrophe would do. Read the GNU gettext docs for more information about this.\nHowever, an easy solution for your problem would be: don't fix the typo in the original, but make a translation like english to english where the translated string is the correct one :). I personally wouldn't recommend this approach, but If you're afraid to break tens of translation files, it can be considered.\nNo it isn't, it throws away all sense of context. It might look clearer for sites where only a few translation strings are required and you know the exact context by heart. But as soon as you have 100s of strings in the translation file, short names like that will say nothing, you'll always have to look up the exact context. Even worse, it can be you use the same 'short name' for something that actually has to be translated differently, which will end up giving you weirder short names to handle both cases. Finally, if you use one normal language as default, you don't need to translate this language explicitly anymore.\nYes it does, there exist multiple functions to mark strings in python for translation, an overview can be found here.\n\n" ]
[ 2 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0003080331_django_localization_python.txt
Q: How do you create a python package with a built in "test/main.py" main function? Desired directory tree: Fibo |-- src | `-- Fibo.py `-- test `-- main.py What I want is to call python main.py after cd'ing into test and executing main.py will run all the unit tests for this package. Currently if I do: import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() I get an error: "ImportError: No module named Fibo". But if I do: import sys def main(): sys.path.append("/home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src") import Fibo Fibo.fib(100) if __name__ == "__main__": main() This seems to fix my error. And I could move forward... but this isn't a python package. This is more of a "collection of files" approach. How would you setup your testing to work in this directory structure? A: If I want to import a module that lives at a fixed, relative location to the file I'm evaluating, I often do something like this: try: import Fibo except ImportError: import sys from os.path import join, abspath, dirname parentpath = abspath(join(dirname(__file__), '..')) srcpath = join(parentpath, 'src') sys.path.append(srcpath) import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() If you want to be a good namespace-citizen, you could del the no longer needed symbols at the end of the except block. A: Adding /home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src to your PYTHONPATH environment variable would allow you to write import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() and have it import .../Fibo/src/Fibo.py correctly. A: Quick and dirty way: create a symbolic link
How do you create a python package with a built in "test/main.py" main function?
Desired directory tree: Fibo |-- src | `-- Fibo.py `-- test `-- main.py What I want is to call python main.py after cd'ing into test and executing main.py will run all the unit tests for this package. Currently if I do: import Fibo def main(): Fibo.fib(100) if __name__ == "__main__": main() I get an error: "ImportError: No module named Fibo". But if I do: import sys def main(): sys.path.append("/home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src") import Fibo Fibo.fib(100) if __name__ == "__main__": main() This seems to fix my error. And I could move forward... but this isn't a python package. This is more of a "collection of files" approach. How would you setup your testing to work in this directory structure?
[ "If I want to import a module that lives at a fixed, relative location to the file I'm evaluating, I often do something like this:\ntry:\n import Fibo\nexcept ImportError:\n import sys\n from os.path import join, abspath, dirname\n parentpath = abspath(join(dirname(__file__), '..'))\n srcpath = join(parentpath, 'src')\n sys.path.append(srcpath)\n import Fibo\n\ndef main():\n Fibo.fib(100)\n\nif __name__ == \"__main__\":\n main()\n\nIf you want to be a good namespace-citizen, you could del the no longer needed symbols at the end of the except block.\n", "Adding /home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src to your PYTHONPATH environment variable \nwould allow you to write\nimport Fibo\n\ndef main():\n Fibo.fib(100)\n\nif __name__ == \"__main__\":\n main()\n\nand have it import .../Fibo/src/Fibo.py correctly.\n", "Quick and dirty way: create a symbolic link\n" ]
[ 1, 0, 0 ]
[]
[]
[ "module", "package", "python", "unit_testing" ]
stackoverflow_0003079670_module_package_python_unit_testing.txt
Q: Dealing with multi-language directories (Python) I'm trying to open a file and I just realized that py is having trouble with my username (It's in Russian). Any suggestions on how to properly decode/encode this to make idle happy? I'm using py 2.6.5 xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r") Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r") UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128) os.sys.getfilesystemencoding() 'mbcs' xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") Traceback (most recent call last): File "", line 1, in xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") IOError: [Errno 22] invalid mode ('r') or filename: 'D:\Users\Y?ee\Downloads\temp.xml' A: The first problem is that the parser tries to interpret backslashes in strings unless you use the r"raw quote" prefix. In 2.6.5, you needn't treat your Unicode string specially, but you may need a file encoding declaration in your source code like: # -*- coding: utf-8 -*- as defined in PEP 263. Here is an example of it working interactively: $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 >>> f = r"D:\Users\Эрик\Downloads\temp.xml" >>> f 'D:\\Users\\\xd0\xad\xd1\x80\xd0\xb8\xd0\xba\\Downloads\\temp.xml' >>> x = open(f, 'w') >>> x.close() >>> $ ls D* D:\Users\Эрик\Downloads\temp.xml Yes, this is on a Unix system so the \ isn't meaningful and my terminal encoding is utf-8, but it works. You just may have to give the coding hint to the parser when it is reading a file. A: First problem: xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r") ### The above line should be OK, provided that you have the correct coding line ### For example # coding: cp1251 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r") ### HOWEVER the above traceback line shows you actually using str() ### which is DIRECTLY causing the error because it is attempting ### to decode your filename using the default ASCII codec -- DON'T DO THAT. ### Please copy/paste; don't type from memory. UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128) Second problem: os.sys.getfilesystemencoding() produces 'mbcs' xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") ### (a) \t is interpreted as a TAB character, hence the file name is invalid. ### (b) encoding with mbcs seems not to be useful; it messes up your name ("Y?ee"). Traceback (most recent call last): File "", line 1, in xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") IOError: [Errno 22] invalid mode ('r') or filename: 'D:\Users\Y?ee\Downloads\temp.xml' General advice on hard-coding filenames in Windows, in descending order of preference: (1) Don't (2) Use / e.g. "c:/temp.xml" (3) Use raw strings with backslashes r"c:\temp.xml" (4) Use doubled backslashes "c:\\temp.xml"
Dealing with multi-language directories (Python)
I'm trying to open a file and I just realized that py is having trouble with my username (It's in Russian). Any suggestions on how to properly decode/encode this to make idle happy? I'm using py 2.6.5 xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r") Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r") UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128) os.sys.getfilesystemencoding() 'mbcs' xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") Traceback (most recent call last): File "", line 1, in xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") IOError: [Errno 22] invalid mode ('r') or filename: 'D:\Users\Y?ee\Downloads\temp.xml'
[ "The first problem is that the parser tries to interpret backslashes in strings unless you use the r\"raw quote\" prefix. In 2.6.5, you needn't treat your Unicode string specially, but you may need a file encoding declaration in your source code like:\n# -*- coding: utf-8 -*-\n\nas defined in PEP 263. Here is an example of it working interactively:\n$ python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2\n>>> f = r\"D:\\Users\\Эрик\\Downloads\\temp.xml\"\n>>> f\n'D:\\\\Users\\\\\\xd0\\xad\\xd1\\x80\\xd0\\xb8\\xd0\\xba\\\\Downloads\\\\temp.xml'\n>>> x = open(f, 'w')\n>>> x.close()\n>>> \n$ ls D*\nD:\\Users\\Эрик\\Downloads\\temp.xml\n\nYes, this is on a Unix system so the \\ isn't meaningful and my terminal encoding is utf-8, but it works. You just may have to give the coding hint to the parser when it is reading a file.\n", "First problem:\nxmlfile = open(u\"D:\\\\Users\\\\Эрик\\\\Downloads\\\\temp.xml\", \"r\")\n### The above line should be OK, provided that you have the correct coding line\n### For example # coding: cp1251\n\nTraceback (most recent call last):\n File \"<pyshell#23>\", line 1, in <module>\n xmlfile = open(str(u\"D:\\\\Users\\\\Эрик\\\\Downloads\\\\temp.xml\"), \"r\")\n### HOWEVER the above traceback line shows you actually using str()\n### which is DIRECTLY causing the error because it is attempting\n### to decode your filename using the default ASCII codec -- DON'T DO THAT.\n### Please copy/paste; don't type from memory.\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128)\n\nSecond problem:\nos.sys.getfilesystemencoding() produces 'mbcs'\nxmlfile = open(u\"D:\\Users\\Эрик\\Downloads\\temp.xml\".encode(\"mbcs\"), \"r\")\n### (a) \\t is interpreted as a TAB character, hence the file name is invalid.\n### (b) encoding with mbcs seems not to be useful; it messes up your name (\"Y?ee\").\n\nTraceback (most recent call last):\nFile \"\", line 1, in xmlfile = open(u\"D:\\Users\\Эрик\\Downloads\\temp.xml\".encode(\"mbcs\"), \"r\")\nIOError: [Errno 22] invalid mode ('r') or filename: 'D:\\Users\\Y?ee\\Downloads\\temp.xml'\n\nGeneral advice on hard-coding filenames in Windows, in descending order of preference: \n(1) Don't\n(2) Use / e.g. \"c:/temp.xml\"\n(3) Use raw strings with backslashes r\"c:\\temp.xml\"\n(4) Use doubled backslashes \"c:\\\\temp.xml\" \n" ]
[ 0, 0 ]
[]
[]
[ "decode", "python", "unicode" ]
stackoverflow_0003080373_decode_python_unicode.txt
Q: Reconstituting Strings in Python I would like to do something like: temp=a.split() #do some stuff with this new list b=" ".join(temp) where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlines? A: I assume in your third line you mean join(temp), not join(a). To split and yet keep the exact "splitters", you need the re.split function (or split method of RE objects) with a capturing group: >>> import re >>> f='tanto va\nla gatta al lardo' >>> re.split(r'(\s+)', f) ['tanto', ' ', 'va', '\n', 'la', ' ', 'gatta', ' ', 'al', ' ', 'lardo'] The pieces you'd get from just re.split are at index 0, 2, 4, ... while the odd indices have the "separators" -- the exact sequences of whitespace that you'll use to re-join the list at the end (with ''.join) to get the same whitespace the original string had. You can either work directly on the even-spaced items, or you can first extract them: >>> x = re.split(r'(\s+)', f) >>> y = x[::2] >>> y ['tanto', 'va', 'la', 'gatta', 'al', 'lardo'] then alter y as you will, e.g.: >>> y[:] = [z+z for z in y] >>> y ['tantotanto', 'vava', 'lala', 'gattagatta', 'alal', 'lardolardo'] then reinsert and join up: >>> x[::2] = y >>> ''.join(x) 'tantotanto vava\nlala gattagatta alal lardolardo' Note that the \n is exactly in the position equivalent to where it was in the original, as desired. A: You need to use regular expressions to rip your string apart. The resulting match object can give you the character ranges of the parts that match various sub-expressions. Since you might have an arbitrarily large number of sections separated by whitespace, you're going to have to match the string multiple times at different starting points within the string. If this answer is confusing to you, I can look up the appropriate references and put in some sample code. I don't really have all the libraries memorized, just what they do. :-) A: It depends in what you want to split. For default split use '\n', ' ' as delimitador, you can use a.split(" ") if you only want spaces as delimitador. http://docs.python.org/library/stdtypes.html#str.split A: I don't really understand your question. Can you give an example of what you want to do? Anyway, maybe this can help: b = '\n'.join(a) A: First of all, I assume that when you say b = " ".join(a) You actually mean b = " ".join(temp) When you call split() without specifying a separator, the function will interpret whitespace of any length as a separator. I believe whitespace includes newlines, so those dissapear when you split the string. Try explicitly passing a separator (such as a simple " " space character) to split(). If you have multiple spaces in a row, using split this way will remove them all and include a series of "" empty strings in the returned list. To restore the original spacing, just make sure that you call join() from the same string which you used as your separator in split(), and that you don't remove any elements from your intermediary list of strings.
Reconstituting Strings in Python
I would like to do something like: temp=a.split() #do some stuff with this new list b=" ".join(temp) where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlines?
[ "I assume in your third line you mean join(temp), not join(a).\nTo split and yet keep the exact \"splitters\", you need the re.split function (or split method of RE objects) with a capturing group:\n>>> import re\n>>> f='tanto va\\nla gatta al lardo'\n>>> re.split(r'(\\s+)', f)\n['tanto', ' ', 'va', '\\n', 'la', ' ', 'gatta', ' ', 'al', ' ', 'lardo']\n\nThe pieces you'd get from just re.split are at index 0, 2, 4, ... while the odd indices have the \"separators\" -- the exact sequences of whitespace that you'll use to re-join the list at the end (with ''.join) to get the same whitespace the original string had.\nYou can either work directly on the even-spaced items, or you can first extract them:\n>>> x = re.split(r'(\\s+)', f)\n>>> y = x[::2]\n>>> y\n['tanto', 'va', 'la', 'gatta', 'al', 'lardo']\n\nthen alter y as you will, e.g.:\n>>> y[:] = [z+z for z in y]\n>>> y\n['tantotanto', 'vava', 'lala', 'gattagatta', 'alal', 'lardolardo']\n\nthen reinsert and join up:\n>>> x[::2] = y\n>>> ''.join(x)\n'tantotanto vava\\nlala gattagatta alal lardolardo'\n\nNote that the \\n is exactly in the position equivalent to where it was in the original, as desired.\n", "You need to use regular expressions to rip your string apart. The resulting match object can give you the character ranges of the parts that match various sub-expressions.\nSince you might have an arbitrarily large number of sections separated by whitespace, you're going to have to match the string multiple times at different starting points within the string.\nIf this answer is confusing to you, I can look up the appropriate references and put in some sample code. I don't really have all the libraries memorized, just what they do. :-)\n", "It depends in what you want to split.\nFor default split use '\\n', ' ' as delimitador, you can use\na.split(\" \") \n\nif you only want spaces as delimitador.\nhttp://docs.python.org/library/stdtypes.html#str.split\n", "I don't really understand your question. Can you give an example of what you want to do?\nAnyway, maybe this can help:\nb = '\\n'.join(a)\n\n", "First of all, I assume that when you say\nb = \" \".join(a)\n\nYou actually mean\nb = \" \".join(temp)\n\nWhen you call split() without specifying a separator, the function will interpret whitespace of any length as a separator. I believe whitespace includes newlines, so those dissapear when you split the string. Try explicitly passing a separator (such as a simple \" \" space character) to split(). If you have multiple spaces in a row, using split this way will remove them all and include a series of \"\" empty strings in the returned list.\nTo restore the original spacing, just make sure that you call join() from the same string which you used as your separator in split(), and that you don't remove any elements from your intermediary list of strings.\n" ]
[ 7, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003081184_python.txt
Q: Can I use Ruby and Python together? Is there something like JRuby but for Ruby and Python? Not that it would actually be useful to me, but just wondering. A: If you develop for the .NET Framework Version 4.0, you can write code in IronRuby that calls methods that were written in IronPython and vice versa. A: Jython A: Parrot aims. Not quite sure about its progress, though. A: _why was working on something called unholy, which converted ruby to Python bytecode.
Can I use Ruby and Python together?
Is there something like JRuby but for Ruby and Python? Not that it would actually be useful to me, but just wondering.
[ "If you develop for the .NET Framework Version 4.0, you can write code in IronRuby that calls methods that were written in IronPython and vice versa.\n", "Jython\n", "Parrot aims. Not quite sure about its progress, though.\n", "_why was working on something called unholy, which converted ruby to Python bytecode.\n" ]
[ 8, 2, 1, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0003079531_python_ruby.txt
Q: Find previous calendar day in python Possible Duplicate: How can I subtract a day from a python date? I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text file for some processing. How do I find the previous day's date in python? A: Here you go: >>> print datetime.date.today()-datetime.timedelta(1) >>> 2010-06-19 A: Say you start with a string '2010_05_1'. Then the similar string for the previous day is: >>> import datetime >>> s = '2010_05_1' >>> theday = datetime.date(*map(int, s.split('_'))) >>> prevday = theday - datetime.timedelta(days=1) >>> prevday.strftime('%Y_%m_%d') '2010_04_30' >>> Of course you'll encapsulate all of this into one handy function! A: You can use the datetime module. import datetime print (datetime.date(year, month, day) - datetime.timedelta(1)).isoformat() A: In short: Convert the year/month/day to a number. Subtract 1 from that number. Convert the number to year/month/day. You will find the localtime and mktime functions from the time module helpful. (Also, since the time module deals with seconds, you would subtract 86400 instead of 1.)
Find previous calendar day in python
Possible Duplicate: How can I subtract a day from a python date? I have a set of files that I'm saving by date, year_month_day.txt format. I need to open the previous day's text file for some processing. How do I find the previous day's date in python?
[ "Here you go:\n>>> print datetime.date.today()-datetime.timedelta(1)\n>>> 2010-06-19\n\n", "Say you start with a string '2010_05_1'. Then the similar string for the previous day is:\n>>> import datetime\n>>> s = '2010_05_1'\n>>> theday = datetime.date(*map(int, s.split('_')))\n>>> prevday = theday - datetime.timedelta(days=1)\n>>> prevday.strftime('%Y_%m_%d')\n'2010_04_30'\n>>> \n\nOf course you'll encapsulate all of this into one handy function!\n", "You can use the datetime module.\nimport datetime\nprint (datetime.date(year, month, day) - datetime.timedelta(1)).isoformat()\n\n", "In short:\n\nConvert the year/month/day to a number.\nSubtract 1 from that number.\nConvert the number to year/month/day.\n\nYou will find the localtime and mktime functions from the time module helpful.\n(Also, since the time module deals with seconds, you would subtract 86400 instead of 1.)\n" ]
[ 44, 7, 5, 0 ]
[]
[]
[ "calendar", "date", "datetime", "file", "python" ]
stackoverflow_0003081339_calendar_date_datetime_file_python.txt
Q: Python: Any way to declare constant parameters? I have a method: def foo(bar): # ... Is there a way to mark bar as constant? Such as "The value in bar cannot change" or "The object pointed to by bar cannot change". A: If bar is an inmutable object, bar won't change during the function. You can also create your own constant object. The recipe here.
Python: Any way to declare constant parameters?
I have a method: def foo(bar): # ... Is there a way to mark bar as constant? Such as "The value in bar cannot change" or "The object pointed to by bar cannot change".
[ "If bar is an inmutable object, bar won't change during the function.\nYou can also create your own constant object.\nThe recipe here.\n" ]
[ 6 ]
[ "No.\nWhat's the point? If you're writing the function, isn't it up to you to make sure bar doesn't change? Or if you're calling the function, who cares?\n" ]
[ -6 ]
[ "constants", "language_construct", "python" ]
stackoverflow_0003081464_constants_language_construct_python.txt
Q: is mac good for python programming? I am programming a django based website. I actually use a small computer under Ubuntu 10.04. I would like to buy something more professional, so I am wondering whether an iMac is good for that, because : Is there a free IDE as good as eclipse on MacOS ? Is there a remote python debugger like pydev for eclipse ? Is there some typical issues with python on MacOS ? does apache+mod_wsgi works well on MacOS ? A: Why do you consider iMac to be more or less professional than anything else? Hardware? System? Note: I'm myself a MacOSX and Linux user. Unless it's a requisite, most times I'd say it's only a matter of personal taste. As said by others earlier, everything you cited works fine on MacOSX. However, you should consider the 3rd party libraries you're going to use with Python. I would cite a problem I had with MySQLdb (MySQL-python) on MacOSX, but it has been solved. You might face other problems in the way, but nothing that could stop you from using Django, Eclipse, etc. A: All of the things you mentioned (Eclipse+plugins, Python, Apache, mod_wsgi) can run fine on OS X. A: My answers based on several years spent developing with Python on OsX: Eclipse is multiplatform, you can have it on OsX too. I would not call pydev a python debugger, anyway you have it on Eclipse for Osx You would have probably the same issues you had under Ubuntu (OsX is Unix based) Yes it works without problem One thing I always recommend is to install macports; with macports installing Eclipse, different Python versions, apache, mod_wsgi is really easy. A: FWIW, mod_wsgi is developed on MacOS X. My experience in supporting users of mod_wsgi is however that MacPorts and fink are an absolute PITA. Specifically, trying to use Python and Apache from those third party systems usually causes nothing but hurt. This is based on problems encountered over the last couple of years. I haven't heard much lately though, so it may be the case that those systems have finally fixed up their 32/64 bit issues and Python build problems.
is mac good for python programming?
I am programming a django based website. I actually use a small computer under Ubuntu 10.04. I would like to buy something more professional, so I am wondering whether an iMac is good for that, because : Is there a free IDE as good as eclipse on MacOS ? Is there a remote python debugger like pydev for eclipse ? Is there some typical issues with python on MacOS ? does apache+mod_wsgi works well on MacOS ?
[ "Why do you consider iMac to be more or less professional than anything else? Hardware? System?\nNote: I'm myself a MacOSX and Linux user.\nUnless it's a requisite, most times I'd say it's only a matter of personal taste.\nAs said by others earlier, everything you cited works fine on MacOSX.\nHowever, you should consider the 3rd party libraries you're going to use with Python.\nI would cite a problem I had with MySQLdb (MySQL-python) on MacOSX, but it has been solved. You might face other problems in the way, but nothing that could stop you from using Django, Eclipse, etc.\n", "All of the things you mentioned (Eclipse+plugins, Python, Apache, mod_wsgi) can run fine on OS X.\n", "My answers based on several years spent developing with Python on OsX:\n\nEclipse is multiplatform, you can have it on OsX too. \nI would not call pydev a python debugger, anyway you have it on Eclipse for Osx \nYou would have probably the same issues you had under Ubuntu (OsX is Unix based) \nYes it works without problem\n\nOne thing I always recommend is to install macports;\nwith macports installing Eclipse, different Python versions, apache, mod_wsgi is really easy.\n", "FWIW, mod_wsgi is developed on MacOS X. My experience in supporting users of mod_wsgi is however that MacPorts and fink are an absolute PITA. Specifically, trying to use Python and Apache from those third party systems usually causes nothing but hurt. This is based on problems encountered over the last couple of years. I haven't heard much lately though, so it may be the case that those systems have finally fixed up their 32/64 bit issues and Python build problems.\n" ]
[ 6, 5, 4, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003080019_macos_python.txt
Q: Python CGI-based frameworks for web development and templates? What are my choices for frameworks for doing Python web development and having a nice language for writing templates for CSS/HTML? A key goal for me is not to have to run a server or install many extra dependencies -- I'd like something that works just by using CGI and hopefully does not force me to do any fancy reconfiguration of Apache etc. My goal is to write pages that look pretty very easily using templates for generating nice looking HTML with CSS, as opposed to painfully writing out HTML using print statements, and have it be modular. I don't need fancy database support and I am not planning to complex forms for user input that I need to process. The ideal framework will also have a set of templates written in it that I can use for my website. I essentially just want to make pages programmatically from Python that look good using CSS/HTML without much work. How can I do this? Something like Django for example would be overkill, since what I am doing is very simple. (Django is great, don't get me wrong, but my purposes are way too simple). More specifics about my app: I want to make a gallery of photos and also display Python code next to each photo. So I'd like to have a way to easily get syntax highlighting etc. in HTML for Python code. Just like Wordpress has many nice templates for blogs, I'd like a combination of web framework and templating language that has a gallery examples of components I can reuse, so that I don't have to write my own CSS/HTML for making menus/headers/other components of a page look good. thanks. A: There's some docs, some tools, and some more tools. Plus, flup can turn any WSGI framework into a CGI app. And there's Pygments for syntax highlighting. A: Well, you're probably not going to find a framework with templates like that included, simply because that's out of most frameworks' scopes. The page structure, variables, and the like of any given Web application are going to be considerably different from each other, so good generic templates are hard to write. The reason people have so many templates and themes for Wordpress (which, though its authors sometimes promote it as a framework, is just an application) is because there are limits on what you can do with it. Frameworks don't have as many such limits. You are probably going to have to find the templates somewhere else and adapt them to the template language you want to use. On the subject of template languages, as far as a good, modular template language is concerned, Jinja2 is hard to beat. It's fast, easy to write in, and powerful. I have taken quite a few templates from other Web sites and added the Jinja2 markup relatively effortlessly. Flask is a nice, light framework that works well with it, and it can deploy to CGI. And as for syntax highlighting, I'm going to have to go with Ignacio and recommend Pygments. All of these libraries are well-documented, so you should be able to figure them out easily. Unfortunately, as much as I would like to have a gallery of reusable theme components, those are not easy to find. You're going to have to scrounge around the Web and hack stuff together yourself.
Python CGI-based frameworks for web development and templates?
What are my choices for frameworks for doing Python web development and having a nice language for writing templates for CSS/HTML? A key goal for me is not to have to run a server or install many extra dependencies -- I'd like something that works just by using CGI and hopefully does not force me to do any fancy reconfiguration of Apache etc. My goal is to write pages that look pretty very easily using templates for generating nice looking HTML with CSS, as opposed to painfully writing out HTML using print statements, and have it be modular. I don't need fancy database support and I am not planning to complex forms for user input that I need to process. The ideal framework will also have a set of templates written in it that I can use for my website. I essentially just want to make pages programmatically from Python that look good using CSS/HTML without much work. How can I do this? Something like Django for example would be overkill, since what I am doing is very simple. (Django is great, don't get me wrong, but my purposes are way too simple). More specifics about my app: I want to make a gallery of photos and also display Python code next to each photo. So I'd like to have a way to easily get syntax highlighting etc. in HTML for Python code. Just like Wordpress has many nice templates for blogs, I'd like a combination of web framework and templating language that has a gallery examples of components I can reuse, so that I don't have to write my own CSS/HTML for making menus/headers/other components of a page look good. thanks.
[ "There's some docs, some tools, and some more tools. Plus, flup can turn any WSGI framework into a CGI app. And there's Pygments for syntax highlighting.\n", "Well, you're probably not going to find a framework with templates like that included, simply because that's out of most frameworks' scopes. The page structure, variables, and the like of any given Web application are going to be considerably different from each other, so good generic templates are hard to write. The reason people have so many templates and themes for Wordpress (which, though its authors sometimes promote it as a framework, is just an application) is because there are limits on what you can do with it. Frameworks don't have as many such limits. You are probably going to have to find the templates somewhere else and adapt them to the template language you want to use.\nOn the subject of template languages, as far as a good, modular template language is concerned, Jinja2 is hard to beat. It's fast, easy to write in, and powerful. I have taken quite a few templates from other Web sites and added the Jinja2 markup relatively effortlessly. Flask is a nice, light framework that works well with it, and it can deploy to CGI. And as for syntax highlighting, I'm going to have to go with Ignacio and recommend Pygments. All of these libraries are well-documented, so you should be able to figure them out easily.\nUnfortunately, as much as I would like to have a gallery of reusable theme components, those are not easy to find. You're going to have to scrounge around the Web and hack stuff together yourself.\n" ]
[ 2, 2 ]
[]
[]
[ "cgi", "css", "html", "python" ]
stackoverflow_0003078114_cgi_css_html_python.txt
Q: virtualenv yolk problem yolk -l gives me information that I've got 114 packages installed on my Ubuntu 10.04. After creating new virtualenv directory using virtualenv virt_env/virt1 --no-site-packages --clear I switched to that, my prompt changed and then yolk -l gives me again the same 114 packages. What is going on there? A: Activating a virtualenv works by changing your shell PATH so the virtualenv's bin/ directory is first. This is all it does. This means that when you run "python" it runs the virtualenv's copy of the Python binary instead of your global system python. If you have yolk installed globally, however, the only "yolk" binary on your PATH is /usr/local/bin/yolk or some such; activating the virtualenv doesn't change this (because there's no "yolk" script in your virtualenv bin/ dir). And the /usr/local/bin/yolk script naturally has your system Python interpreter in its shebang line. This is why installing yolk into the virtualenv fixes the problem; because it adds a yolk script in your virtualenv bin/ dir that has the virtualenv's python in its shebang line. If you don't want to install yolk in each virtualenv, you could also just copy the yolk script-wrapper from /usr/local/bin or wherever it is into your virtualenv's bin dir, and manually change the shebang line to point to your virtualenv's python. This won't work with a --no-site-packages virtualenv, though, because the script wrapper then won't be able to find the actual yolk packages it needs to import! If you want to use yolk within a --no-site-packages virtualenv, really your only choice is to install it there. A: If the problem isnt relating to your path (I suppose it is) delete your lib and scripts folder in your project directory to clear out the virtualenv settings. Recreate the virtual env using the command line you posted. Activate the virtualenv and then install yolk.
virtualenv yolk problem
yolk -l gives me information that I've got 114 packages installed on my Ubuntu 10.04. After creating new virtualenv directory using virtualenv virt_env/virt1 --no-site-packages --clear I switched to that, my prompt changed and then yolk -l gives me again the same 114 packages. What is going on there?
[ "Activating a virtualenv works by changing your shell PATH so the virtualenv's bin/ directory is first. This is all it does. This means that when you run \"python\" it runs the virtualenv's copy of the Python binary instead of your global system python.\nIf you have yolk installed globally, however, the only \"yolk\" binary on your PATH is /usr/local/bin/yolk or some such; activating the virtualenv doesn't change this (because there's no \"yolk\" script in your virtualenv bin/ dir). And the /usr/local/bin/yolk script naturally has your system Python interpreter in its shebang line.\nThis is why installing yolk into the virtualenv fixes the problem; because it adds a yolk script in your virtualenv bin/ dir that has the virtualenv's python in its shebang line.\nIf you don't want to install yolk in each virtualenv, you could also just copy the yolk script-wrapper from /usr/local/bin or wherever it is into your virtualenv's bin dir, and manually change the shebang line to point to your virtualenv's python. This won't work with a --no-site-packages virtualenv, though, because the script wrapper then won't be able to find the actual yolk packages it needs to import! If you want to use yolk within a --no-site-packages virtualenv, really your only choice is to install it there.\n", "If the problem isnt relating to your path (I suppose it is) delete your lib and scripts folder in your project directory to clear out the virtualenv settings. Recreate the virtual env using the command line you posted. Activate the virtualenv and then install yolk.\n" ]
[ 18, 0 ]
[]
[]
[ "python", "virtualenv", "yolk" ]
stackoverflow_0002742980_python_virtualenv_yolk.txt
Q: python win32com Causes Program crash I wrote program to control iTunes by monitoring keystrokes from with pyHooks and then interfaceing with the iTunes COM interface. The program works fine, the only problem I have is when I try to compile it with py2exe. The program always crashes with this traceback: Traceback (most recent call last): File "threading.pyc", line 527, in __bootstrap_inner File "iTunesControl.py", line 24, in run File "win32com\client\gencache.pyc", line 540, in EnsureDispatch File "win32com\client\CLSIDToClass.pyc", line 46, in GetClass KeyError: '{9DD6680B-3EDC-40DB-A771-E6FE4832E34A}' py2exe reports no errors... A: The problem is probably that the py2exe version isn't able to access the cache of wrappers generated by win32com. Here's a recipe for dealing with this problem.
python win32com Causes Program crash
I wrote program to control iTunes by monitoring keystrokes from with pyHooks and then interfaceing with the iTunes COM interface. The program works fine, the only problem I have is when I try to compile it with py2exe. The program always crashes with this traceback: Traceback (most recent call last): File "threading.pyc", line 527, in __bootstrap_inner File "iTunesControl.py", line 24, in run File "win32com\client\gencache.pyc", line 540, in EnsureDispatch File "win32com\client\CLSIDToClass.pyc", line 46, in GetClass KeyError: '{9DD6680B-3EDC-40DB-A771-E6FE4832E34A}' py2exe reports no errors...
[ "The problem is probably that the py2exe version isn't able to access the cache of wrappers generated by win32com.\nHere's a recipe for dealing with this problem.\n" ]
[ 4 ]
[]
[]
[ "com", "itunes", "py2exe", "python" ]
stackoverflow_0003081822_com_itunes_py2exe_python.txt
Q: using 'variable.xyz' format in Python This is a silly question, but I can't figure it out so I had to ask. I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False. Variable Car has not been defined in this situation. I know I can do dicts (Car['store'] = False) etc... but it has to be in the format above. Appreciate any help Thanks. A: I think the closest you can get to what you want is by adding one extra line (assuming you have defined a class called Car): car = Car() car.store = False Without the first line you will get an error. If you want brevity you could set store to False in __init__ so that only the first line is necessary. A: I'm a bit late to the party, but also check out the namedtuple function in the collections module. It lets you access fields of a tuple as if they were named members of a class, and it's nice when all you want is a C-style "structure". Of course, tuples are immutable so you'd probably have to rearrange your existing code quite a bit; perhaps not the best thing for this example, but maybe keep it in mind in the future.
using 'variable.xyz' format in Python
This is a silly question, but I can't figure it out so I had to ask. I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False. Variable Car has not been defined in this situation. I know I can do dicts (Car['store'] = False) etc... but it has to be in the format above. Appreciate any help Thanks.
[ "I think the closest you can get to what you want is by adding one extra line (assuming you have defined a class called Car):\ncar = Car()\ncar.store = False\n\nWithout the first line you will get an error.\nIf you want brevity you could set store to False in __init__ so that only the first line is necessary.\n", "I'm a bit late to the party, but also check out the namedtuple function in the collections module. It lets you access fields of a tuple as if they were named members of a class, and it's nice when all you want is a C-style \"structure\". Of course, tuples are immutable so you'd probably have to rearrange your existing code quite a bit; perhaps not the best thing for this example, but maybe keep it in mind in the future.\n" ]
[ 2, 0 ]
[ "Maybe you can try whith this:\ntry:\n car.store = False\nexcept NameError:\n #This means that car doesn't exists\n pass\nexcept AttributeError:\n #This means that car.store doesn't exists\n pass\n\n", "car, car.store = car if \"car\" in locals() else lambda:1, False\n\n" ]
[ -1, -1 ]
[ "python" ]
stackoverflow_0003081500_python.txt
Q: question regarding postgresql sequences I have a question regarding postgresql sequences. For instance, for bigserial datatype, is it true that the sequence is advanced, then the number is retrieved and even if the insertion/committing is not successful, the sequence doesn't backtracks. Which means the next time I might be doing insertion to the table, that might be a gap in the sequence number. Theres a before insert row trigger on my table and Im using psycopg2. thanks in advance. A: even if the insertion/committing is not successful, the sequence doesn't backtracks. Which means the next time I might be doing insertion to the table, that might be a gap in the sequence number. Yes, that's true, And that's fine. One usually wants a sequence to get values in a table that are unique (typically for a PK) and gaps don't matter at all. If you are curious: this is natural behaviour if one thinks about concurrency. Suppose a transaction T1 inserts a row, getting a PK1 from a sequence, uses that value to build another records in other tables... in the meantime (before T1 commits) another transaction T2 inserts a row in the same table. Then T1 rollbacks and T2 commits... BTW: If you want a "gap-less" sequence ... first ask yourself if you really want that (usually you really don't - and requiring that frequently points to a conceptual problem in your design)... but if you really need it, you can read this. A: Backtracking would require locking until completion. This would be bad, especially when 10 tables can all utilize the same sequence. If you want an order don't use a sequence use a window function like row_number().
question regarding postgresql sequences
I have a question regarding postgresql sequences. For instance, for bigserial datatype, is it true that the sequence is advanced, then the number is retrieved and even if the insertion/committing is not successful, the sequence doesn't backtracks. Which means the next time I might be doing insertion to the table, that might be a gap in the sequence number. Theres a before insert row trigger on my table and Im using psycopg2. thanks in advance.
[ "\neven if the insertion/committing is\n not successful, the sequence doesn't\n backtracks. Which means the next time I might be doing insertion to the table, that might be a gap in the sequence number.\n\nYes, that's true, And that's fine.\nOne usually wants a sequence to get values in a table that are unique (typically for a PK)\nand gaps don't matter at all. \nIf you are curious: this is natural behaviour if one thinks about concurrency. Suppose a transaction T1 inserts a row, getting a PK1 from a sequence, uses that value to build another records in other tables... in the meantime (before T1 commits) another transaction T2 inserts a row in the same table. Then T1 rollbacks and T2 commits... \nBTW: If you want a \"gap-less\" sequence ... first ask yourself if you really want that (usually you really don't - and requiring that frequently points to a conceptual problem in your design)... but if you really need it, you can read this.\n", "Backtracking would require locking until completion. This would be bad, especially when 10 tables can all utilize the same sequence. If you want an order don't use a sequence use a window function like row_number().\n" ]
[ 4, 3 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0003081899_postgresql_psycopg2_python.txt
Q: python multiprocessing - text processing I am trying to create a multiprocessing version of text categorization code i found here (amongst other cool things). I've appended the full code below. I've tried a couple of things - tried a lambda function first, but it complained of not being serializable (!?), so attempted a stripped down version of the original code: negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') p = Pool(2) negfeats =[] posfeats =[] for f in negids: words = movie_reviews.words(fileids=[f]) negfeats = p.map(featx, words) #not same form as below - using for debugging print len(negfeats) Unfortunately even this doesnt work - i get the following trace: File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value ZeroDivisionError: float division Any idea what i might be doing wrong? should i be using pool.apply_async instead (in of itself that doesnt seem to solve the problem either - but perhaps i am barking up the wrong tree) ? import collections import nltk.classify.util, nltk.metrics from nltk.classify import NaiveBayesClassifier from nltk.corpus import movie_reviews def evaluate_classifier(featx): negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') negfeats = [(featx(movie_reviews.words(fileids=[f])), 'neg') for f in negids] posfeats = [(featx(movie_reviews.words(fileids=[f])), 'pos') for f in posids] negcutoff = len(negfeats)*3/4 poscutoff = len(posfeats)*3/4 trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff] testfeats = negfeats[negcutoff:] + posfeats[poscutoff:] classifier = NaiveBayesClassifier.train(trainfeats) refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classifier.classify(feats) testsets[observed].add(i) print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats) print 'pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos']) print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos']) print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg']) print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg']) classifier.show_most_informative_features() A: Are you trying to parallelize the classification, the training, or both? You can probably make the word counting and scoring parallel fairly easily, but I'm not sure about the feature extraction & training. For the classification, I'd recommend execnet. I've had good results using it for parallel/distributed part-of-speech tagging. The basic idea with execnet is that you'd train a single classifier once, then send it to each execnet node. Next, divide the files up to each node, then have it classify each file it's given. The results are then sent back to the master node. I haven't tried pickling a classifier yet, so I don't know for sure if this will work, but if a pos tagger can be pickled, I'd assume a classifier can be too. A: Regarding your stripped down version, are you using a different featx function than the one used in http://streamhacker.com/2010/06/16/text-classification-sentiment-analysis-eliminate-low-information-features/? The exception most probably happens inside featx and multiprocessing just re-raises it, though it does not really include the original traceback which makes it a bit unhelpful. Try running it without pool.map() first (i.e. negfeats = [feat(x) for x in words]) or include something in featx that you can debug. If that still doesn't help, post the whole script you are working on in your original question (simplified already if possible) so others can run that and provide more directed answers. Note that the following code fragment actually works (adapting your stripped down version): from nltk.corpus import movie_reviews from multiprocessing import Pool def featx(words): return dict([(word, True) for word in words]) if __name__ == "__main__": negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') p = Pool(2) negfeats =[] posfeats =[] for f in negids: words = movie_reviews.words(fileids=[f]) negfeats = p.map(featx, words) print len(negfeats)
python multiprocessing - text processing
I am trying to create a multiprocessing version of text categorization code i found here (amongst other cool things). I've appended the full code below. I've tried a couple of things - tried a lambda function first, but it complained of not being serializable (!?), so attempted a stripped down version of the original code: negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') p = Pool(2) negfeats =[] posfeats =[] for f in negids: words = movie_reviews.words(fileids=[f]) negfeats = p.map(featx, words) #not same form as below - using for debugging print len(negfeats) Unfortunately even this doesnt work - i get the following trace: File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value ZeroDivisionError: float division Any idea what i might be doing wrong? should i be using pool.apply_async instead (in of itself that doesnt seem to solve the problem either - but perhaps i am barking up the wrong tree) ? import collections import nltk.classify.util, nltk.metrics from nltk.classify import NaiveBayesClassifier from nltk.corpus import movie_reviews def evaluate_classifier(featx): negids = movie_reviews.fileids('neg') posids = movie_reviews.fileids('pos') negfeats = [(featx(movie_reviews.words(fileids=[f])), 'neg') for f in negids] posfeats = [(featx(movie_reviews.words(fileids=[f])), 'pos') for f in posids] negcutoff = len(negfeats)*3/4 poscutoff = len(posfeats)*3/4 trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff] testfeats = negfeats[negcutoff:] + posfeats[poscutoff:] classifier = NaiveBayesClassifier.train(trainfeats) refsets = collections.defaultdict(set) testsets = collections.defaultdict(set) for i, (feats, label) in enumerate(testfeats): refsets[label].add(i) observed = classifier.classify(feats) testsets[observed].add(i) print 'accuracy:', nltk.classify.util.accuracy(classifier, testfeats) print 'pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos']) print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos']) print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg']) print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg']) classifier.show_most_informative_features()
[ "Are you trying to parallelize the classification, the training, or both? You can probably make the word counting and scoring parallel fairly easily, but I'm not sure about the feature extraction & training. For the classification, I'd recommend execnet. I've had good results using it for parallel/distributed part-of-speech tagging.\nThe basic idea with execnet is that you'd train a single classifier once, then send it to each execnet node. Next, divide the files up to each node, then have it classify each file it's given. The results are then sent back to the master node. I haven't tried pickling a classifier yet, so I don't know for sure if this will work, but if a pos tagger can be pickled, I'd assume a classifier can be too.\n", "Regarding your stripped down version, are you using a different featx function than the one used in http://streamhacker.com/2010/06/16/text-classification-sentiment-analysis-eliminate-low-information-features/?\nThe exception most probably happens inside featx and multiprocessing just re-raises it, though it does not really include the original traceback which makes it a bit unhelpful.\nTry running it without pool.map() first (i.e. negfeats = [feat(x) for x in words]) or include something in featx that you can debug.\nIf that still doesn't help, post the whole script you are working on in your original question (simplified already if possible) so others can run that and provide more directed answers. Note that the following code fragment actually works (adapting your stripped down version):\nfrom nltk.corpus import movie_reviews\nfrom multiprocessing import Pool\n\ndef featx(words):\n return dict([(word, True) for word in words])\n\nif __name__ == \"__main__\":\n negids = movie_reviews.fileids('neg')\n posids = movie_reviews.fileids('pos')\n\n p = Pool(2)\n negfeats =[]\n posfeats =[]\n\n for f in negids:\n words = movie_reviews.words(fileids=[f]) \n negfeats = p.map(featx, words)\n\n print len(negfeats)\n\n" ]
[ 1, 1 ]
[]
[]
[ "multicore", "multithreading", "python" ]
stackoverflow_0003081044_multicore_multithreading_python.txt
Q: Python out params? Is it possible to do something like this: def foo(bar, success) success = True # ... >>> success = False >>> foo(bar1, success) >>> success True Does Python have out params, or an easy way to simulate them? (Aside from messing with parent's stack frames.) A: You have multiple return values. def foo(bar) return 1, 2, True x, y, success = foo(bar1) A: Yes, put them in a dict as pass the dict as a parameter. I think it's somewhere in the main python official tutorial. A: In python you can not update an immutable type from inside a function (like the boolean in your example or an int or a string or a tuple, ...). Period. So your options are as illustrated in previous answers: Wrap the immutable type in a mutable type (like a list, array or object). Use multiple return values
Python out params?
Is it possible to do something like this: def foo(bar, success) success = True # ... >>> success = False >>> foo(bar1, success) >>> success True Does Python have out params, or an easy way to simulate them? (Aside from messing with parent's stack frames.)
[ "You have multiple return values.\ndef foo(bar)\n return 1, 2, True\n\nx, y, success = foo(bar1)\n\n", "Yes, put them in a dict as pass the dict as a parameter. I think it's somewhere in the main python official tutorial.\n", "In python you can not update an immutable type from inside a function (like the boolean in your example or an int or a string or a tuple, ...). Period. So your options are as illustrated in previous answers:\n\nWrap the immutable type in a mutable type (like a list, array or object).\nUse multiple return values\n\n" ]
[ 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003081807_python.txt
Q: Python Module Initialization Order? I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask: Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inability to decide which global/static variable would be initialized first across compilation units, thus a global/static variable depending on another one in different compilation units might be initialized earlier than its dependency counterparts, and when dependant started to use the services provided by the dependency object, we would have undefined behavior. Here I don't want to go too deep on how C++ solves this problem. :) On the Python world, I do see uses of global variables, even across different .py files, and one typycal usage case I saw was: initialize one global object in one .py file, and on other .py files, the code just fearlessly start using the global object, assuming that it must have been initialized somewhere else, which under C++ is definitely unaccept by myself, due to the problem I specified above. I am not sure if the above use case is common practice in Python (Pythonic), and how does Python solve this kind of global variable initialization order problem in general? A: Python import executes new Python modules from beginning to end. Subsequent imports only result in a copy of the existing reference in sys.modules, even if still in the middle of importing the module due to a circular import. Module attributes ("global variables" are actually at the module scope) that have been initialized before the circular import will exist. main.py: import a a.py: var1 = 'foo' import b var2 = 'bar' b.py: import a print a.var1 # works print a.var2 # fails A: Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inability to decide which global/static variable would be initialized first across compilation units, I think that statement highlights a key difference between Python and C++: in Python, there is no such thing as different compilation units. What I mean by that is, in C++ (as you know), two different source files might be compiled completely independently from each other, and thus if you compare a line in file A and a line in file B, there is nothing to tell you which will get placed first in the program. It's kind of like the situation with multiple threads: you cannot say whether a particular statement in thread 1 will be executed before or after a particular statement in thread 2. You could say C++ programs are compiled in parallel. In contrast, in Python, execution begins at the top of one file and proceeds in a well-defined order through each statement in the file, branching out to other files at the points where they are imported. In fact, you could almost think of the import directive as an #include, and in that way you could identify the order of execution of all the lines of code in all the source files in the program. (Well, it's a little more complicated than that, since a module only really gets executed the first time it's imported, and for other reasons.) If C++ programs are compiled in parallel, Python programs are interpreted serially. Your question also touches on the deeper meaning of modules in Python. A Python module - which is everything that is in a single .py file - is an actual object. Everything declared at "global" scope in a single source file is actually an attribute of that module object. There is no true global scope in Python. (Python programmers often say "global" and in fact there is a global keyword in the language, but it always really refers to the top level of the current module.) I could see that being a bit of a strange concept to get used to coming from a C++ background. It took some getting used to for me, coming from Java, and in this respect Java is a lot more similar to Python than C++ is. (There is also no global scope in Java) I will mention that in Python it is perfectly normal to use a variable without having any idea whether it has been initialized/defined or not. Well, maybe not normal, but at least acceptable under appropriate circumstances. In Python, trying to use an undefined variable raises a NameError; you don't get arbitrary behavior as you might in C or C++, so you can easily handle the situation. You may see this pattern: try: duck.quack() except NameError: pass which does nothing if duck does not exist. Actually, what you'll more commonly see is try: duck.quack() except AttributeError: pass which does nothing if duck does not have a method named quack. (AttributeError is the kind of error you get when you try to access an attribute of an object, but the object does not have any attribute by that name.) This is what passes for a type check in Python: we figure that if all we need the duck to do is quack, we can just ask it to quack, and if it does, we don't care whether it's really a duck or not. (It's called duck typing ;-)
Python Module Initialization Order?
I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask: Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inability to decide which global/static variable would be initialized first across compilation units, thus a global/static variable depending on another one in different compilation units might be initialized earlier than its dependency counterparts, and when dependant started to use the services provided by the dependency object, we would have undefined behavior. Here I don't want to go too deep on how C++ solves this problem. :) On the Python world, I do see uses of global variables, even across different .py files, and one typycal usage case I saw was: initialize one global object in one .py file, and on other .py files, the code just fearlessly start using the global object, assuming that it must have been initialized somewhere else, which under C++ is definitely unaccept by myself, due to the problem I specified above. I am not sure if the above use case is common practice in Python (Pythonic), and how does Python solve this kind of global variable initialization order problem in general?
[ "Python import executes new Python modules from beginning to end. Subsequent imports only result in a copy of the existing reference in sys.modules, even if still in the middle of importing the module due to a circular import. Module attributes (\"global variables\" are actually at the module scope) that have been initialized before the circular import will exist.\nmain.py:\nimport a\n\na.py:\nvar1 = 'foo'\nimport b\nvar2 = 'bar'\n\nb.py:\nimport a\nprint a.var1 # works\nprint a.var2 # fails\n\n", "\nUnder C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inability to decide which global/static variable would be initialized first across compilation units, \n\nI think that statement highlights a key difference between Python and C++: in Python, there is no such thing as different compilation units. What I mean by that is, in C++ (as you know), two different source files might be compiled completely independently from each other, and thus if you compare a line in file A and a line in file B, there is nothing to tell you which will get placed first in the program. It's kind of like the situation with multiple threads: you cannot say whether a particular statement in thread 1 will be executed before or after a particular statement in thread 2. You could say C++ programs are compiled in parallel.\nIn contrast, in Python, execution begins at the top of one file and proceeds in a well-defined order through each statement in the file, branching out to other files at the points where they are imported. In fact, you could almost think of the import directive as an #include, and in that way you could identify the order of execution of all the lines of code in all the source files in the program. (Well, it's a little more complicated than that, since a module only really gets executed the first time it's imported, and for other reasons.) If C++ programs are compiled in parallel, Python programs are interpreted serially.\nYour question also touches on the deeper meaning of modules in Python. A Python module - which is everything that is in a single .py file - is an actual object. Everything declared at \"global\" scope in a single source file is actually an attribute of that module object. There is no true global scope in Python. (Python programmers often say \"global\" and in fact there is a global keyword in the language, but it always really refers to the top level of the current module.) I could see that being a bit of a strange concept to get used to coming from a C++ background. It took some getting used to for me, coming from Java, and in this respect Java is a lot more similar to Python than C++ is. (There is also no global scope in Java)\nI will mention that in Python it is perfectly normal to use a variable without having any idea whether it has been initialized/defined or not. Well, maybe not normal, but at least acceptable under appropriate circumstances. In Python, trying to use an undefined variable raises a NameError; you don't get arbitrary behavior as you might in C or C++, so you can easily handle the situation. You may see this pattern:\ntry:\n duck.quack()\nexcept NameError:\n pass\n\nwhich does nothing if duck does not exist. Actually, what you'll more commonly see is\ntry:\n duck.quack()\nexcept AttributeError:\n pass\n\nwhich does nothing if duck does not have a method named quack. (AttributeError is the kind of error you get when you try to access an attribute of an object, but the object does not have any attribute by that name.) This is what passes for a type check in Python: we figure that if all we need the duck to do is quack, we can just ask it to quack, and if it does, we don't care whether it's really a duck or not. (It's called duck typing ;-)\n" ]
[ 12, 11 ]
[]
[]
[ "initialization", "python" ]
stackoverflow_0003082015_initialization_python.txt
Q: The book about integration Django and Flex There is a remarkable book "Flexible Rails" http://www.manning.com/armstrong/ about how to use Ruby on Rails and Adobe Flex to build next-generation rich Internet applications (RIAs). Does anybody know any similar resource about integrating Django and Flex? A: I'm not aware of any similar books, but all you really need is an API integration from your flex app to your django app. I've used the following 2 methods with success: REST API with simple HTTP access on the flex side. See django-piston and flex's mx.rpc.http.HTTPService/built-in XML deserializer. AMF protocol: See django-amf-gateway w/ pyamf for examples.
The book about integration Django and Flex
There is a remarkable book "Flexible Rails" http://www.manning.com/armstrong/ about how to use Ruby on Rails and Adobe Flex to build next-generation rich Internet applications (RIAs). Does anybody know any similar resource about integrating Django and Flex?
[ "I'm not aware of any similar books, but all you really need is an API integration from your flex app to your django app.\nI've used the following 2 methods with success:\n\nREST API with simple HTTP access on the flex side. See django-piston and flex's mx.rpc.http.HTTPService/built-in XML deserializer.\nAMF protocol: See django-amf-gateway w/ pyamf for examples.\n\n" ]
[ 1 ]
[]
[]
[ "apache_flex", "django", "python" ]
stackoverflow_0003082272_apache_flex_django_python.txt
Q: Accessing the Microphone in Python My laptop has a microphone in it. Is there any method of obtaining numbers in Python from it? For example pitch, volume, or the duration of a noise. I'm trying to use ambient noise to create random numbers. A: Accessing the amplitude is easy. Depending on the plattform your app is running on you can use a framework like http://people.csail.mit.edu/hubert/pyaudio/ or http://pyalsaaudio.sourceforge.net/pyalsaaudio.html to access the the pitch you will need a framework that performs a fft-analysis like the scipy/numpy package
Accessing the Microphone in Python
My laptop has a microphone in it. Is there any method of obtaining numbers in Python from it? For example pitch, volume, or the duration of a noise. I'm trying to use ambient noise to create random numbers.
[ "Accessing the amplitude is easy. Depending on the plattform your app is running on you can use \na framework like http://people.csail.mit.edu/hubert/pyaudio/ or http://pyalsaaudio.sourceforge.net/pyalsaaudio.html \nto access the the pitch you will need a framework that performs a fft-analysis like the scipy/numpy package\n" ]
[ 1 ]
[]
[]
[ "microphone", "python" ]
stackoverflow_0003082635_microphone_python.txt
Q: Where can I read about import _{module name} in Python? I've notice this. Example: create an empty text file called for example ast.py $ touch ast.py run Python $ python >>> from ast import * >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> from _ast import * >>> dir() ['AST', 'Add', 'And', 'Assert', 'Assign', ...] ast is a python module. So... what's happening here? I tried with an empty os.py and didn't work. A: There's nothing special with _xxx modules except they are private (e.g. _abcoll) or low-level (e.g. _thread) and not intended to be used in general. The _ast module is special, e.g. $ touch _ast.py $ python -c 'from _ast import *; print(dir())' ['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute ... But this is not because of the leading _, but that _ast is a built-in module. Similar thing happens with the sys module. $ touch sys.py $ python -c 'from sys import *; print(dir())' ['__builtins__', '__doc__', '__name__', '__package__', 'api_version', 'argv', ... In Python _ast and ast are two separate modules. There is a line from _ast import * in the built-in ast.py, so importing ast will also bring everything from the _ast module in. This gives you the illusion that _ast and ast have the same content, but actually _ast is a lower level module of ast. A: This is because _ast is also a module. There is no magic here. Also, _ast is a builtin module (i.e. a module that doesn't exist as a separate file, but is compiled in the interpreter itself), so it is always loaded and creating a file of the same same won't get rid of it. And the reason why _ast will not be overloaded by a file, is that once a module is loaded, python will not look again at the files. You can find the list of all the modules currently loaded in sys.modules. And if you want a complete documentation about modules, look at the python documentation. Everything is specified, like here: http://docs.python.org/tutorial/modules.html or here: http://docs.python.org/reference/simple_stmts.html#the-import-statement
Where can I read about import _{module name} in Python?
I've notice this. Example: create an empty text file called for example ast.py $ touch ast.py run Python $ python >>> from ast import * >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> from _ast import * >>> dir() ['AST', 'Add', 'And', 'Assert', 'Assign', ...] ast is a python module. So... what's happening here? I tried with an empty os.py and didn't work.
[ "There's nothing special with _xxx modules except they are private (e.g. _abcoll) or low-level (e.g. _thread) and not intended to be used in general.\nThe _ast module is special, e.g.\n$ touch _ast.py\n$ python -c 'from _ast import *; print(dir())'\n['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute ...\n\nBut this is not because of the leading _, but that _ast is a built-in module. Similar thing happens with the sys module.\n$ touch sys.py\n$ python -c 'from sys import *; print(dir())'\n['__builtins__', '__doc__', '__name__', '__package__', 'api_version', 'argv', ...\n\n\nIn Python _ast and ast are two separate modules. There is a line \nfrom _ast import *\n\nin the built-in ast.py, so importing ast will also bring everything from the _ast module in. This gives you the illusion that _ast and ast have the same content, but actually _ast is a lower level module of ast.\n", "This is because _ast is also a module. There is no magic here. Also, _ast is a builtin module (i.e. a module that doesn't exist as a separate file, but is compiled in the interpreter itself), so it is always loaded and creating a file of the same same won't get rid of it.\nAnd the reason why _ast will not be overloaded by a file, is that once a module is loaded, python will not look again at the files. You can find the list of all the modules currently loaded in sys.modules. And if you want a complete documentation about modules, look at the python documentation. Everything is specified, like here: http://docs.python.org/tutorial/modules.html or here: http://docs.python.org/reference/simple_stmts.html#the-import-statement\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003082889_python.txt
Q: Is there a tool to do ast 2 python source code for Python 2.x? I've seen codegen http://dev.pocoo.org/hg/sandbox/file/868ea20c2c1d/ast/ but doent works with all the files and ast2src which only works with Python 3.1. A: Ive patched codegen con make it work with my sources: http://svn.juanjoconti.com.ar/dyntaint/trunk/wrapstrings/gen/ A: You could convert the 3.1 source to 2x using 3to2. It's a utility for back-porting python3 scripts back to python2. Note: 3to2 isn't the standard user-submitted PYPI project. It has been vetted by the core dev team and was the one of the Google Summer of Code projects last year
Is there a tool to do ast 2 python source code for Python 2.x?
I've seen codegen http://dev.pocoo.org/hg/sandbox/file/868ea20c2c1d/ast/ but doent works with all the files and ast2src which only works with Python 3.1.
[ "Ive patched codegen con make it work with my sources: http://svn.juanjoconti.com.ar/dyntaint/trunk/wrapstrings/gen/\n", "You could convert the 3.1 source to 2x using 3to2.\nIt's a utility for back-porting python3 scripts back to python2.\nNote: 3to2 isn't the standard user-submitted PYPI project. It has been vetted by the core dev team and was the one of the Google Summer of Code projects last year\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003082921_python.txt
Q: python solutions for managing scientific data dependency graph by specification values I have a scientific data management problem which seems general, but I can't find an existing solution or even a description of it, which I have long puzzled over. I am about to embark on a major rewrite (python) but I thought I'd cast about one last time for existing solutions, so I can scrap my own and get back to the biology, or at least learn some appropriate language for better googling. The problem: I have expensive (hours to days to calculate) and big (GB's) data attributes that are typically built as transformations of one or more other data attributes. I need to keep track of exactly how this data is built so I can reuse it as input for another transformation if it fits the problem (built with right specification values) or construct new data as needed. Although it shouldn't matter, I typically I start with 'value-added' somewhat heterogeneous molecular biology info, for example, genomes with genes and proteins annotated by other processes by other researchers. I need to combine and compare these data to make my own inferences. A number of intermediate steps are often required, and these can be expensive. In addition, the end results can become the input for additional transformations. All of these transformations can be done in multiple ways: restricting with different initial data (eg using different organisms), by using different parameter values in the same inferences, or by using different inference models, etc. The analyses change frequently and build on others in unplanned ways. I need to know what data I have (what parameters or specifications fully define it), both so I can reuse it if appropriate, as well as for general scientific integrity. My efforts in general: I design my python classes with the problem of description in mind. All data attributes built by a class object are described by a single set of parameter values. I call these defining parameters or specifications the 'def_specs', and these def_specs with their values the 'shape' of the data atts. The entire global parameter state for the process might be quite large (eg a hundred parameters), but the data atts provided by any one class require only a small number of these, at least directly. The goal is to check whether previously built data atts are appropriate by testing if their shape is a subset of the global parameter state. Within a class it is easy to find the needed def_specs that define the shape by examining the code. The rub arises when a module needs a data att from another module. These data atts will have their own shape, perhaps passed as args by the calling object, but more often filtered from the global parameter state. The calling class should be augmented with the shape of its dependencies in order to maintain a complete description of its data atts. In theory this could be done manually by examining the dependency graph, but this graph can get deep, and there are many modules, which I am constantly changing and adding, and ... I'm too lazy and careless to do it by hand. So, the program dynamically discovers the complete shape of the data atts by tracking calls to other classes attributes and pushing their shape back up to the caller(s) through a managed stack of __get__ calls. As I rewrite I find that I need to strictly control attribute access to my builder classes to prevent arbitrary info from influencing the data atts. Fortunately python is making this easy with descriptors. I store the shape of the data atts in a db so that I can query whether appropriate data (i.e. its shape is a subset of the current parameter state) already exists. In my rewrite I am moving from mysql via the great SQLAlchemy to an object db (ZODB or couchdb?) as the table for each class has to be altered when additional def_specs are discovered, which is a pain, and because some of the def_specs are python lists or dicts, which are a pain to translate to sql. I don't think this data management can be separated from my data transformation code because of the need for strict attribute control, though I am trying to do so as much as possible. I can use existing classes by wrapping them with a class that provides their def_specs as class attributes, and db management via descriptors, but these classes are terminal in that no further discovery of additional dependency shape can take place. If the data management cannot easily be separated from the data construction, I guess it is unlikely that there is an out of the box solution but a thousand specific ones. Perhaps there is an applicable pattern? I'd appreciate any hints at how to go about looking or better describing the problem. To me it seems a general issue, though managing deeply layered data is perhaps at odds with the prevailing winds of the web. A: I don't have specific python-related suggestions for you, but here are a few thoughts: You're encountering a common challenge in bioinformatics. The data is large, heterogeneous, and comes in constantly changing formats as new technologies are introduced. My advice is to not overthink your pipelines, as they're likely to be changing tomorrow. Choose a few well defined file formats, and massage incoming data into those formats as often as possible. In my experience, it's also usually best to have loosely coupled tools that do one thing well, so that you can chain them together for different analyses quickly. You might also consider taking a version of this question over to the bioinformatics stack exchange at http://biostar.stackexchange.com/ A: ZODB has not been designed to handle massive data, it is just for web-based applications and in any case it is a flat-file based database. I recommend you to try PyTables, a python library to handle HDF5 files, which is a format used in astronomy and physics to store results from big calculations and simulations. It can be used as an hierarchical-like database and has also an efficient way to pickle python objects. By the way, the author of pytables explained that ZOdb was too slow for what he needed to do, and I can confirm you that. If you are interested in HDF5, there is also another library, h5py. As a tool for managing the versioning of the different calculations you have, you can have a try at sumatra, which is something like an extension to git/trac but designed for simulations. You should ask this question on biostar, you will find better answers there.
python solutions for managing scientific data dependency graph by specification values
I have a scientific data management problem which seems general, but I can't find an existing solution or even a description of it, which I have long puzzled over. I am about to embark on a major rewrite (python) but I thought I'd cast about one last time for existing solutions, so I can scrap my own and get back to the biology, or at least learn some appropriate language for better googling. The problem: I have expensive (hours to days to calculate) and big (GB's) data attributes that are typically built as transformations of one or more other data attributes. I need to keep track of exactly how this data is built so I can reuse it as input for another transformation if it fits the problem (built with right specification values) or construct new data as needed. Although it shouldn't matter, I typically I start with 'value-added' somewhat heterogeneous molecular biology info, for example, genomes with genes and proteins annotated by other processes by other researchers. I need to combine and compare these data to make my own inferences. A number of intermediate steps are often required, and these can be expensive. In addition, the end results can become the input for additional transformations. All of these transformations can be done in multiple ways: restricting with different initial data (eg using different organisms), by using different parameter values in the same inferences, or by using different inference models, etc. The analyses change frequently and build on others in unplanned ways. I need to know what data I have (what parameters or specifications fully define it), both so I can reuse it if appropriate, as well as for general scientific integrity. My efforts in general: I design my python classes with the problem of description in mind. All data attributes built by a class object are described by a single set of parameter values. I call these defining parameters or specifications the 'def_specs', and these def_specs with their values the 'shape' of the data atts. The entire global parameter state for the process might be quite large (eg a hundred parameters), but the data atts provided by any one class require only a small number of these, at least directly. The goal is to check whether previously built data atts are appropriate by testing if their shape is a subset of the global parameter state. Within a class it is easy to find the needed def_specs that define the shape by examining the code. The rub arises when a module needs a data att from another module. These data atts will have their own shape, perhaps passed as args by the calling object, but more often filtered from the global parameter state. The calling class should be augmented with the shape of its dependencies in order to maintain a complete description of its data atts. In theory this could be done manually by examining the dependency graph, but this graph can get deep, and there are many modules, which I am constantly changing and adding, and ... I'm too lazy and careless to do it by hand. So, the program dynamically discovers the complete shape of the data atts by tracking calls to other classes attributes and pushing their shape back up to the caller(s) through a managed stack of __get__ calls. As I rewrite I find that I need to strictly control attribute access to my builder classes to prevent arbitrary info from influencing the data atts. Fortunately python is making this easy with descriptors. I store the shape of the data atts in a db so that I can query whether appropriate data (i.e. its shape is a subset of the current parameter state) already exists. In my rewrite I am moving from mysql via the great SQLAlchemy to an object db (ZODB or couchdb?) as the table for each class has to be altered when additional def_specs are discovered, which is a pain, and because some of the def_specs are python lists or dicts, which are a pain to translate to sql. I don't think this data management can be separated from my data transformation code because of the need for strict attribute control, though I am trying to do so as much as possible. I can use existing classes by wrapping them with a class that provides their def_specs as class attributes, and db management via descriptors, but these classes are terminal in that no further discovery of additional dependency shape can take place. If the data management cannot easily be separated from the data construction, I guess it is unlikely that there is an out of the box solution but a thousand specific ones. Perhaps there is an applicable pattern? I'd appreciate any hints at how to go about looking or better describing the problem. To me it seems a general issue, though managing deeply layered data is perhaps at odds with the prevailing winds of the web.
[ "I don't have specific python-related suggestions for you, but here are a few thoughts:\nYou're encountering a common challenge in bioinformatics. The data is large, heterogeneous, and comes in constantly changing formats as new technologies are introduced. My advice is to not overthink your pipelines, as they're likely to be changing tomorrow. Choose a few well defined file formats, and massage incoming data into those formats as often as possible. In my experience, it's also usually best to have loosely coupled tools that do one thing well, so that you can chain them together for different analyses quickly.\nYou might also consider taking a version of this question over to the bioinformatics stack exchange at http://biostar.stackexchange.com/\n", "ZODB has not been designed to handle massive data, it is just for web-based applications and in any case it is a flat-file based database. \nI recommend you to try PyTables, a python library to handle HDF5 files, which is a format used in astronomy and physics to store results from big calculations and simulations. It can be used as an hierarchical-like database and has also an efficient way to pickle python objects. By the way, the author of pytables explained that ZOdb was too slow for what he needed to do, and I can confirm you that. If you are interested in HDF5, there is also another library, h5py.\nAs a tool for managing the versioning of the different calculations you have, you can have a try at sumatra, which is something like an extension to git/trac but designed for simulations.\nYou should ask this question on biostar, you will find better answers there.\n" ]
[ 2, 2 ]
[]
[]
[ "aop", "bioinformatics", "nosql", "python", "scientific_computing" ]
stackoverflow_0003076953_aop_bioinformatics_nosql_python_scientific_computing.txt
Q: How C# use python program? If it doesn't use ironpython, how C# use cpython program(py file)? Because there are some bugs that ironpython load cpython code. A: If you need strict CPython behavior and do not want to change Python program I am afraid that in this case you should spawn separate CPython process and interact with it via some RPC protocol (there are plenty to choose from) via pipe or network connection to localhost. As alternative to "serialized" RPC you might use system's facilities e.g. COM if you're on Windows or D-Bus on Linux - but this would make code platform dependent and not necessarily simpler.
How C# use python program?
If it doesn't use ironpython, how C# use cpython program(py file)? Because there are some bugs that ironpython load cpython code.
[ "If you need strict CPython behavior and do not want to change Python program I am afraid that in this case you should spawn separate CPython process and interact with it via some RPC protocol (there are plenty to choose from) via pipe or network connection to localhost.\nAs alternative to \"serialized\" RPC you might use system's facilities e.g. COM if you're on Windows or D-Bus on Linux - but this would make code platform dependent and not necessarily simpler.\n" ]
[ 0 ]
[]
[]
[ "c#", "cpython", "python" ]
stackoverflow_0003083167_c#_cpython_python.txt
Q: Use python to get friendslists on facebook How can i use python to login to facebook, grab a friendlist from my friends and use the data to see if my friends are facebook buddies ? Thanks for your help :-) A: First off, you won't be able to get access to your friends' friends list unless they themselves authorize your application. This being said, you can try the pyfacebook library with the friends.get() method or the new graph API. https://graph.facebook.com/me/friends will get a list of your friends then https://graph.facebook.com/{{ID}}/friends will get the friends of your friend with id {{ID}} HTH
Use python to get friendslists on facebook
How can i use python to login to facebook, grab a friendlist from my friends and use the data to see if my friends are facebook buddies ? Thanks for your help :-)
[ "First off, you won't be able to get access to your friends' friends list unless they themselves authorize your application.\nThis being said, you can try the pyfacebook library with the friends.get() method or the new graph API.\nhttps://graph.facebook.com/me/friends will get a list of your friends then\nhttps://graph.facebook.com/{{ID}}/friends will get the friends of your friend with id {{ID}}\n\nHTH\n" ]
[ 4 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003083401_facebook_python.txt
Q: python help django navigation I would like to understand how I can access and navigate Python and Django help. in Django I cd to my directory and entered the following command to access help of the manage.py: python manage.py help And I would like to get info on the commands. Here I have to type: Type 'manage.py help ' for help on a specific subcommand. But either combination did not work. How do I get help in Python? Is there a way to list everything python has to offer? If not is there a online resource that gives an excellent overview? Thanks L. A: you have to do python manage.py --help Here is the django admin.py/manage.py doc http://docs.djangoproject.com/en/dev/ref/django-admin/ To getting help in general in python you can use builtin help function e.g. >>> help('help') Welcome to Python 2.5! This is the online help utility. ....
python help django navigation
I would like to understand how I can access and navigate Python and Django help. in Django I cd to my directory and entered the following command to access help of the manage.py: python manage.py help And I would like to get info on the commands. Here I have to type: Type 'manage.py help ' for help on a specific subcommand. But either combination did not work. How do I get help in Python? Is there a way to list everything python has to offer? If not is there a online resource that gives an excellent overview? Thanks L.
[ "you have to do \npython manage.py --help\n\nHere is the django admin.py/manage.py doc http://docs.djangoproject.com/en/dev/ref/django-admin/\nTo getting help in general in python you can use builtin help function e.g.\n>>> help('help')\n\nWelcome to Python 2.5! This is the online help utility.\n....\n\n" ]
[ 1 ]
[]
[]
[ "django", "navigation", "python" ]
stackoverflow_0003083583_django_navigation_python.txt
Q: Clear sqlalchemy reflection cache I'm using sqlalchemy's reflection tools to get a Table object. I do this because these tables are dynamic and tables/columns can change. Here's the code I'm using: def getTableByReflection(self, tableName, metadata, engine): return Table(tableName, metadata, autoload = True, autoload_with = engine) The problem is that when the above code is run twice it seems to return the same results regardless of whether or not the columns have changed. I have tried refreshing using the mysession.refresh(mytable) but that fails because the table is not attached to any metadata - which makes sense but then why am I seeing cached results? Is there any way to tell the metadata/engine/session to forget about this table and let me load it cleanly? A: Pass in a newly created, fresh metadata instance. A: With thanks to codeape's comment above I was able to fix the problem by changing the syntax to: def getTableByReflection(self, tableName, metadata, engine): return Table(tableName, MetaData(), autoload = True, autoload_with = engine) So passing in a new MetaData() instance each time. This probably affects performance but it's ok for me in this part of my app. All credit to codeape
Clear sqlalchemy reflection cache
I'm using sqlalchemy's reflection tools to get a Table object. I do this because these tables are dynamic and tables/columns can change. Here's the code I'm using: def getTableByReflection(self, tableName, metadata, engine): return Table(tableName, metadata, autoload = True, autoload_with = engine) The problem is that when the above code is run twice it seems to return the same results regardless of whether or not the columns have changed. I have tried refreshing using the mysession.refresh(mytable) but that fails because the table is not attached to any metadata - which makes sense but then why am I seeing cached results? Is there any way to tell the metadata/engine/session to forget about this table and let me load it cleanly?
[ "Pass in a newly created, fresh metadata instance.\n", "With thanks to codeape's comment above I was able to fix the problem by changing the syntax to:\ndef getTableByReflection(self, tableName, metadata, engine):\n\n return Table(tableName, MetaData(), autoload = True, autoload_with = engine)\n\nSo passing in a new MetaData() instance each time. This probably affects performance but it's ok for me in this part of my app.\nAll credit to codeape\n" ]
[ 6, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003068408_python_sqlalchemy.txt
Q: Forcing scons to use older compiler? I have a C++ project which is using boost. The whole project is built using scons + Visual Studio 2008. We've installed Visual Studio 2010 and it turned out scons was attempting to use the later compiler instead of the old one - and failed to build the project as boost and visual studio 2010 don't like each other very much - yet. We'd like to suppress this and force scons to use the 2008 version. Is this possible? How do we do this? A: You can modify the scons Environment() by just choosing the version you want: env = Environment(MSVC_VERSION=<someversion>) From the scons manpage: MSVC_VERSION Sets the preferred version of Microsoft Visual C/C++ to use. If $MSVC_VERSION is not set, SCons will (by default) select the latest version of Visual C/C++ installed on your system. If the specified version isn't installed, tool initialization will fail. This variable must be passed as an argument to the Environment() constructor; setting it later has no effect. Set it to an unexpected value (e.g. "XXX") to see the valid values on your system. A: You'll need to redefine the CXX construction variable, ideally in your Environment: env = Environment(CXX = "C:\\path\to\vs2008\executable")
Forcing scons to use older compiler?
I have a C++ project which is using boost. The whole project is built using scons + Visual Studio 2008. We've installed Visual Studio 2010 and it turned out scons was attempting to use the later compiler instead of the old one - and failed to build the project as boost and visual studio 2010 don't like each other very much - yet. We'd like to suppress this and force scons to use the 2008 version. Is this possible? How do we do this?
[ "You can modify the scons Environment() by just choosing\nthe version you want:\nenv = Environment(MSVC_VERSION=<someversion>)\nFrom the scons manpage:\n\nMSVC_VERSION Sets the preferred \n version of Microsoft Visual C/C++ to\n use.\nIf $MSVC_VERSION is not set, SCons\n will (by default) select the latest\n version of Visual C/C++ installed on\n your system. If the specified version\n isn't installed, tool initialization\n will fail. This variable must be \n passed as an argument to the\n Environment() constructor; setting it\n later has no effect. Set it to an\n unexpected value (e.g. \"XXX\") to see\n the valid values on your system.\n\n", "You'll need to redefine the CXX construction variable, ideally in your Environment:\nenv = Environment(CXX = \"C:\\\\path\\to\\vs2008\\executable\")\n\n" ]
[ 17, 2 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0003079344_python_scons.txt
Q: Multiple in same file I have a multiple html files in one file: <html> <body> </body> </html> <html> <body> </body> </html> <html> <body> </body> </html> and the result is that I get a messed up html file. How to correct this without removing tags from the rest. I am using python to generate the html file. If I use the self.response.out.write(function(query)) I get a nice html page. If I use it a second time self.response.out.write(function(query2)) then the page gets distorted. A: Have one HTML file per file. Anything else is invalid and won’t be processed properly. If you’re not sure if your HTML files are valid, the W3C’s validator will tell you.
Multiple in same file
I have a multiple html files in one file: <html> <body> </body> </html> <html> <body> </body> </html> <html> <body> </body> </html> and the result is that I get a messed up html file. How to correct this without removing tags from the rest. I am using python to generate the html file. If I use the self.response.out.write(function(query)) I get a nice html page. If I use it a second time self.response.out.write(function(query2)) then the page gets distorted.
[ "Have one HTML file per file. Anything else is invalid and won’t be processed properly.\nIf you’re not sure if your HTML files are valid, the W3C’s validator will tell you.\n" ]
[ 3 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003083711_html_python.txt
Q: Starting multiple instances of a python script at once from linux command line I'd like to start a piece of python script a thousand times! instead of trying to start them one-by-one how can I do that from linux command line? Right now, I am doing it like this: nohup python test.py & nohup python test.py & nohup python test.py & nohup python test.py & nohup python test.py & ... Thanks in advance. A: As a one-liner, in Bash: for i in {1..1000}; do nohup python test.py & done A: I would recommend that you keep the spawning logic in a Python program. Perhaps use the multiprocessing library to do the processes. It'll be hard to manage all of these without some non-trivial scaffolding if you're going to spawn them off in bash. A: Simplest is to make a loop using shell script, this will work for anything: #!/bin/bash X=0 COUNT=1000 while [ $X -lt $COUNT ]; do nohup python test.py & X=$((X+1)) done
Starting multiple instances of a python script at once from linux command line
I'd like to start a piece of python script a thousand times! instead of trying to start them one-by-one how can I do that from linux command line? Right now, I am doing it like this: nohup python test.py & nohup python test.py & nohup python test.py & nohup python test.py & nohup python test.py & ... Thanks in advance.
[ "As a one-liner, in Bash:\nfor i in {1..1000}; do nohup python test.py & done\n\n", "I would recommend that you keep the spawning logic in a Python program. Perhaps use the multiprocessing library to do the processes. It'll be hard to manage all of these without some non-trivial scaffolding if you're going to spawn them off in bash. \n", "Simplest is to make a loop using shell script, this will work for anything:\n#!/bin/bash\nX=0\nCOUNT=1000\nwhile [ $X -lt $COUNT ]; do\n nohup python test.py &\n X=$((X+1))\ndone\n\n" ]
[ 7, 4, 2 ]
[]
[]
[ "command_line", "console", "linux", "python", "shell" ]
stackoverflow_0003083922_command_line_console_linux_python_shell.txt
Q: What's a good document standard to use programmatically? I'm writing a program that requires input in the form of a document, it needs to replace a few values, insert a table, and convert it to PDF. It's written in Python + Qt (PyQt). Is there any well known document standard which can be easily used programmatically? It must be cross platform, and preferably open. I have looked into Microsoft Doc and Docx, which are binary formats and I can't edit them. Python has bindings for it, but they're only on Windows. Open Office's ODT/ODF is zipped in an xml file, so I can edit that one but there's no command line utilities or any way to programmatically convert the file to a PDF. Open Office provides bindings, but you need to run Open Office from the command line, start a server, etc. And my clients may not have Open Office installed. RTF is readable from Python, but I couldn't find any way/libraries to convert RTF documents to PDF. At the moment I'm exporting from Microsoft Word to HTML, replacing the values and using PyQt to convert it to a PDF. However it loses formatting features and looks awful. I'm surprised there isn't a well known library which lets you edit a variety of document formats and convert them into other formats, am I missing something? Update: Thanks for the advice, I'll have a look at using Latex. Thanks, Jackson A: Have you looked into using LaTeX documents? They are perfect to use programatically (compiling documents? You gotta love that...), and you have several Python frameworks you can use such as plasTeX and PyTex. Exporting a LaTeX documents to PDF is almost immediate. A: Since you're already using PyQt anyway, it might be worth looking at Qt's built-in RTF processing module which looks decent. Here's the documentation on detailed content manipulation including inserting tables. Also the QPrinter module's default print-to-file format happens to be PDF. Without knowing more about your particular needs it's hard to say if these would do what you want, but since your application already has PyQt as a dependency, seems silly to introduce any more without evaluating the functionality you've already got available. The non-GUI parts of the Qt framework are often overlooked though. edit: included more links. A: You might want to try ReportLab. The open source version can write PDFs, and the commercial version has a lot of really nice abstractions to allow output to a variety of different formats from a single input. A: I don't know the kind of odience of your program, Tex is good and i would go with it. Another possible choice is Excel format, parsing it with xlrd. I've used it a couple of time and it's pretty straightforward. Excel file is a good for the following reasons: Well known format easy to edit You could prepare a predefined template with constrains and table A: Creating XML documents, transforming them to XSL/fo and rendering with Fop or RenderX. If you use docbook as the primary input, there are toolchains freely available for converting that to PDF, RTF, HTML and so forth. It is rather quirky to use and not my idea of fun, but is does deliver and can be embedded in an application, AFAICT. Creating docbook is very straightforward as it has a wide range of semantic tags, table support etc to give a "meaningful" markup which can be reliably formatted. The XSL stylesheets are modular and allow parts to be customized or replaced to generate your own look and feel. It works well for relatively free flow documents with lots of text. For filling in the blanks kind of documents, a regular reporting engine may be a better fit, or some straighforward XSL stylesheets spitting out the XSL-fo directly.
What's a good document standard to use programmatically?
I'm writing a program that requires input in the form of a document, it needs to replace a few values, insert a table, and convert it to PDF. It's written in Python + Qt (PyQt). Is there any well known document standard which can be easily used programmatically? It must be cross platform, and preferably open. I have looked into Microsoft Doc and Docx, which are binary formats and I can't edit them. Python has bindings for it, but they're only on Windows. Open Office's ODT/ODF is zipped in an xml file, so I can edit that one but there's no command line utilities or any way to programmatically convert the file to a PDF. Open Office provides bindings, but you need to run Open Office from the command line, start a server, etc. And my clients may not have Open Office installed. RTF is readable from Python, but I couldn't find any way/libraries to convert RTF documents to PDF. At the moment I'm exporting from Microsoft Word to HTML, replacing the values and using PyQt to convert it to a PDF. However it loses formatting features and looks awful. I'm surprised there isn't a well known library which lets you edit a variety of document formats and convert them into other formats, am I missing something? Update: Thanks for the advice, I'll have a look at using Latex. Thanks, Jackson
[ "Have you looked into using LaTeX documents?\nThey are perfect to use programatically (compiling documents? You gotta love that...), and you have several Python frameworks you can use such as plasTeX and PyTex.\nExporting a LaTeX documents to PDF is almost immediate.\n", "Since you're already using PyQt anyway, it might be worth looking at Qt's built-in RTF processing module which looks decent. Here's the documentation on detailed content manipulation including inserting tables. Also the QPrinter module's default print-to-file format happens to be PDF.\nWithout knowing more about your particular needs it's hard to say if these would do what you want, but since your application already has PyQt as a dependency, seems silly to introduce any more without evaluating the functionality you've already got available.\nThe non-GUI parts of the Qt framework are often overlooked though.\nedit: included more links.\n", "You might want to try ReportLab. The open source version can write PDFs, and the commercial version has a lot of really nice abstractions to allow output to a variety of different formats from a single input.\n", "I don't know the kind of odience of your program, Tex is good and i would go with it.\nAnother possible choice is Excel format, parsing it with xlrd.\nI've used it a couple of time and it's pretty straightforward.\nExcel file is a good for the following reasons:\n\nWell known format easy to edit\nYou could prepare a predefined template with constrains and table\n\n", "Creating XML documents, transforming them to XSL/fo and rendering with Fop or RenderX. If you use docbook as the primary input, there are toolchains freely available for converting that to PDF, RTF, HTML and so forth.\nIt is rather quirky to use and not my idea of fun, but is does deliver and can be embedded in an application, AFAICT.\nCreating docbook is very straightforward as it has a wide range of semantic tags, table support etc to give a \"meaningful\" markup which can be reliably formatted. The XSL stylesheets are modular and allow parts to be customized or replaced to generate your own look and feel.\nIt works well for relatively free flow documents with lots of text.\nFor filling in the blanks kind of documents, a regular reporting engine may be a better fit, or some straighforward XSL stylesheets spitting out the XSL-fo directly. \n" ]
[ 9, 2, 1, 0, 0 ]
[]
[]
[ "document", "pyqt", "python" ]
stackoverflow_0003082502_document_pyqt_python.txt
Q: can someone help me with tags in canvas? i tried to figure out what tags were in canvas however i am having a hard time understanding it. can someone explain what tags do and how to use them in canvas when using python. A: Every object in a canvas has an id. You can reference that object by that id to delete it, modify it, move it, etc. Objects can also have one or more tags. A tag can be associated with a single object, in which case it is just another name for that object. For example, if you draw a red rectangle and a blue rectangle, you can give the first one the tag "red_rect" and the second "blue_rect". Then, anywhere you might need the id you could instead use the tag. One tag can be associated with more than a single item. So, for example, in addition to the "red_rect" and "blue_rect" tags, you could also give each item a "rect" tag. Then, when you use "rect" where you might use an id (such as to move the object), this will affect all objects with the tag. In this way you can move, configure or delete whole groups of items at a time. You can use tags to implement such common features as letting the user name objects that they draw interactively, or to logically group multiple objects into a single composite object.
can someone help me with tags in canvas?
i tried to figure out what tags were in canvas however i am having a hard time understanding it. can someone explain what tags do and how to use them in canvas when using python.
[ "Every object in a canvas has an id. You can reference that object by that id to delete it, modify it, move it, etc.\nObjects can also have one or more tags. A tag can be associated with a single object, in which case it is just another name for that object. For example, if you draw a red rectangle and a blue rectangle, you can give the first one the tag \"red_rect\" and the second \"blue_rect\". Then, anywhere you might need the id you could instead use the tag. \nOne tag can be associated with more than a single item. So, for example, in addition to the \"red_rect\" and \"blue_rect\" tags, you could also give each item a \"rect\" tag. Then, when you use \"rect\" where you might use an id (such as to move the object), this will affect all objects with the tag. In this way you can move, configure or delete whole groups of items at a time. \nYou can use tags to implement such common features as letting the user name objects that they draw interactively, or to logically group multiple objects into a single composite object. \n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003081749_python_tkinter.txt
Q: Facebook Python-SDK VS. PyFacebook? I'm starting to develop a facebook application using Django. I'm trying to choose the appropriate API wrapper for my application and I can't decide whether to use PyFacebook (very well documented but no official release) or the official Facebook Python SDK (which is surprisingly poorly documented). Are there any major differences between the two that I'm missing? Thank you, Liz A: I believe PyFacebook was made for the old Facebook API (used to be the way to go) while the Facebook Platform Python SDK is a new official library from facebook and is aimed towards the new Graph API So I suggest you start using the latter. And yeah the documentation totally sucks in both cases, took me a while to figure it out. UPDATE: For you latecomers: The most recent up-to-date seems to be: https://github.com/pythonforfacebook/facebook-sdk/
Facebook Python-SDK VS. PyFacebook?
I'm starting to develop a facebook application using Django. I'm trying to choose the appropriate API wrapper for my application and I can't decide whether to use PyFacebook (very well documented but no official release) or the official Facebook Python SDK (which is surprisingly poorly documented). Are there any major differences between the two that I'm missing? Thank you, Liz
[ "I believe PyFacebook was made for the old Facebook API (used to be the way to go) while the Facebook Platform Python SDK is a new official library from facebook and is aimed towards the new Graph API\nSo I suggest you start using the latter. And yeah the documentation totally sucks in both cases, took me a while to figure it out.\nUPDATE:\nFor you latecomers: The most recent up-to-date seems to be: https://github.com/pythonforfacebook/facebook-sdk/\n" ]
[ 11 ]
[]
[]
[ "facebook", "pyfacebook", "python" ]
stackoverflow_0003084230_facebook_pyfacebook_python.txt
Q: Using class/static methods as default parameter values within methods of the same class I'd like to do something like this: class SillyWalk(object): @staticmethod def is_silly_enough(walk): return (False, "It's never silly enough") def walk(self, appraisal_method=is_silly_enough): self.do_stuff() (was_good_enough, reason) = appraisal_method(self) if not was_good_enough: self.execute_self_modifying_code(reason) return appraisal_method def do_stuff(self): pass def execute_self_modifying_code(self, problem): from __future__ import deepjuju deepjuju.kiss_booboo_better(self, problem) with the idea being that someone can do >>> silly_walk = SillyWalk() >>> appraise = walk() >>> is_good_walk = appraise(silly_walk) and also get some magical machine learning happening; this last bit is not of particular interest to me, it was just the first thing that occurred to me as a way to exemplify the use of the static method in both an in-function context and from the caller's perspective. Anyway, this doesn't work, because is_silly_enough is not actually a function: it is an object whose __get__ method will return the original is_silly_enough function. This means that it only works in the "normal" way when it's referenced as an object attribute. The object in question is created by the staticmethod() function that the decorator puts in between SillyWalk's is_silly_enough attribute and the function that's originally defined with that name. This means that in order to use the default value of appraisal_method from within either SillyWalk.walk or its caller, we have to either call appraisal_method.__get__(instance, owner)(...) instead of just calling appraisal_method(...) or assign it as the attribute of some object, then reference that object property as a method that we call as we would call appraisal_method. Given that neither of these solutions seem particularly Pythonic™, I'm wondering if there is perhaps a better way to get this sort of functionality. I essentially want a way to specify that a method should, by default, use a particular class or static method defined within the scope of the same class to carry out some portion of its daily routine. I'd prefer not to use None, because I'd like to allow None to convey the message that that particular function should not be called. I guess I could use some other value, like False or NotImplemented, but it seems a) hackety b) annoying to have to write an extra couple of lines of code, as well as otherwise-redundant documentation, for something that seems like it could be expressed quite succinctly as a default parameter. What's the best way to do this? A: I ended up writing an (un)wrapper function, to be used within function definition headers, eg def walk(self, appraisal_method=unstaticmethod(is_silly_enough)): This actually seems to work, at least it makes my doctests that break without it pass. Here it is: def unstaticmethod(static): """Retrieve the original function from a `staticmethod` object. This is intended for use in binding class method default values to static methods of the same class. For example: >>> class C(object): ... @staticmethod ... def s(*args, **kwargs): ... return (args, kwargs) ... def m(self, args=[], kwargs={}, f=unstaticmethod(s)): ... return f(*args, **kwargs) >>> o = C() >>> o.s(1, 2, 3) ((1, 2, 3), {}) >>> o.m((1, 2, 3)) ((1, 2, 3), {}) """ # TODO: Technically we should be passing the actual class of the owner # instead of `object`, but # I don't know if there's a way to get that info dynamically, # since the class is not actually declared # when this function is called during class method definition. # I need to figure out if passing `object` instead # is going to be an issue. return static.__get__(None, object) update: I wrote doctests for the unstaticmethod function itself; they pass too. I'm still not totally sure that this is an actual smart thing to do, but it does seem to work. A: Maybe all you need is to use the function (and not the method) in the first place? class SillyWalk(object): def is_silly_enough(walk): return (False, "It's never silly enough") def walk(self, appraisal_function=is_silly_enough): self.do_stuff() (was_good_enough, reason) = appraisal_function(self) if not was_good_enough: self.execute_self_modifying_code(reason) return appraisal_function def do_stuff(self): pass def execute_self_modifying_code(self, problem): deepjuju.kiss_booboo_better(self, problem) Note that the default for appraisal_function will now be a function and not a method, even though is_silly_enough will be bound as a class method once the class is created (at the end of the code). This means that >>> SillyWalk.is_silly_enough <unbound method SillyWalk.is_silly_enough> but >>> SillyWalk.walk.im_func.func_defaults[0] # the default argument to .walk <function is_silly_enough at 0x0000000002212048> And you can call is_silly_enough with a walk argument, or call a walk instance with .is_silly_enough(). If you really wanted is_silly_enough to be a static method, you could always add is_silly_enough = staticmethod(is_silly_enough) anywhere after the definition of walk. A: Not sure if I get exactly what you're after, but would it be cleaner to use getattr? >>> class SillyWalk(object): @staticmethod def ise(walk): return (False, "boo") def walk(self, am="ise"): wge, r = getattr(self, am)(self) print wge, r >>> sw = SillyWalk() >>> sw.walk("ise") False boo
Using class/static methods as default parameter values within methods of the same class
I'd like to do something like this: class SillyWalk(object): @staticmethod def is_silly_enough(walk): return (False, "It's never silly enough") def walk(self, appraisal_method=is_silly_enough): self.do_stuff() (was_good_enough, reason) = appraisal_method(self) if not was_good_enough: self.execute_self_modifying_code(reason) return appraisal_method def do_stuff(self): pass def execute_self_modifying_code(self, problem): from __future__ import deepjuju deepjuju.kiss_booboo_better(self, problem) with the idea being that someone can do >>> silly_walk = SillyWalk() >>> appraise = walk() >>> is_good_walk = appraise(silly_walk) and also get some magical machine learning happening; this last bit is not of particular interest to me, it was just the first thing that occurred to me as a way to exemplify the use of the static method in both an in-function context and from the caller's perspective. Anyway, this doesn't work, because is_silly_enough is not actually a function: it is an object whose __get__ method will return the original is_silly_enough function. This means that it only works in the "normal" way when it's referenced as an object attribute. The object in question is created by the staticmethod() function that the decorator puts in between SillyWalk's is_silly_enough attribute and the function that's originally defined with that name. This means that in order to use the default value of appraisal_method from within either SillyWalk.walk or its caller, we have to either call appraisal_method.__get__(instance, owner)(...) instead of just calling appraisal_method(...) or assign it as the attribute of some object, then reference that object property as a method that we call as we would call appraisal_method. Given that neither of these solutions seem particularly Pythonic™, I'm wondering if there is perhaps a better way to get this sort of functionality. I essentially want a way to specify that a method should, by default, use a particular class or static method defined within the scope of the same class to carry out some portion of its daily routine. I'd prefer not to use None, because I'd like to allow None to convey the message that that particular function should not be called. I guess I could use some other value, like False or NotImplemented, but it seems a) hackety b) annoying to have to write an extra couple of lines of code, as well as otherwise-redundant documentation, for something that seems like it could be expressed quite succinctly as a default parameter. What's the best way to do this?
[ "I ended up writing an (un)wrapper function, to be used within function definition headers, eg\ndef walk(self, appraisal_method=unstaticmethod(is_silly_enough)):\n\nThis actually seems to work, at least it makes my doctests that break without it pass.\nHere it is:\ndef unstaticmethod(static):\n \"\"\"Retrieve the original function from a `staticmethod` object.\n\n This is intended for use in binding class method default values\n to static methods of the same class.\n\n For example:\n >>> class C(object):\n ... @staticmethod\n ... def s(*args, **kwargs):\n ... return (args, kwargs)\n ... def m(self, args=[], kwargs={}, f=unstaticmethod(s)):\n ... return f(*args, **kwargs)\n >>> o = C()\n >>> o.s(1, 2, 3)\n ((1, 2, 3), {})\n >>> o.m((1, 2, 3))\n ((1, 2, 3), {})\n \"\"\"\n # TODO: Technically we should be passing the actual class of the owner\n # instead of `object`, but\n # I don't know if there's a way to get that info dynamically,\n # since the class is not actually declared\n # when this function is called during class method definition.\n # I need to figure out if passing `object` instead\n # is going to be an issue.\n return static.__get__(None, object)\n\nupdate:\nI wrote doctests for the unstaticmethod function itself; they pass too. I'm still not totally sure that this is an actual smart thing to do, but it does seem to work.\n", "Maybe all you need is to use the function (and not the method) in the first place?\nclass SillyWalk(object):\n def is_silly_enough(walk):\n return (False, \"It's never silly enough\")\n\n def walk(self, appraisal_function=is_silly_enough):\n self.do_stuff()\n (was_good_enough, reason) = appraisal_function(self)\n if not was_good_enough:\n self.execute_self_modifying_code(reason)\n return appraisal_function\n def do_stuff(self):\n pass\n def execute_self_modifying_code(self, problem):\n deepjuju.kiss_booboo_better(self, problem)\n\nNote that the default for appraisal_function will now be a function and not a method, even though is_silly_enough will be bound as a class method once the class is created (at the end of the code).\nThis means that\n>>> SillyWalk.is_silly_enough\n<unbound method SillyWalk.is_silly_enough>\n\nbut\n>>> SillyWalk.walk.im_func.func_defaults[0] # the default argument to .walk\n<function is_silly_enough at 0x0000000002212048>\n\nAnd you can call is_silly_enough with a walk argument, or call a walk instance with .is_silly_enough().\nIf you really wanted is_silly_enough to be a static method, you could always add\n is_silly_enough = staticmethod(is_silly_enough)\n\nanywhere after the definition of walk.\n", "Not sure if I get exactly what you're after, but would it be cleaner to use getattr?\n>>> class SillyWalk(object):\n @staticmethod\n def ise(walk):\n return (False, \"boo\")\n def walk(self, am=\"ise\"):\n wge, r = getattr(self, am)(self)\n print wge, r\n\n\n>>> sw = SillyWalk()\n>>> sw.walk(\"ise\")\nFalse boo\n\n" ]
[ 2, 2, 1 ]
[]
[]
[ "class_method", "decorator", "default_value", "python", "static_methods" ]
stackoverflow_0003083692_class_method_decorator_default_value_python_static_methods.txt
Q: How to use float ** in Python with Swig? I am writing swig bindings for some c functions. One of these functions takes a float**. I am already using cpointer.i for the normal pointers and looked into carrays.i, but I did not find a way to declare a float**. What do you recommend? interface file: extern int read_data(const char *file,int *n_,int *m_,float **data_,int **classes_); A: This answer is a repost of one to a related question Framester posted about using ctypes instead of swig. I've included it here in case any web-searches turn up a link to his original question. I've used ctypes for several projects now and have been quite happy with the results. I don't think I've personally needed a pointer-to-pointer wrapper yet but, in theory, you should be able to do the following: from ctypes import * your_dll = cdll.LoadLibrary("your_dll.dll") PFloat = POINTER(c_float) PInt = POINTER(c_int) p_data = PFloat() p_classes = PInt() buff = create_string_buffer(1024) n1 = c_int( 0 ) n2 = c_int( 0 ) ret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) ) print('Data: ', p_data.contents) print('Classes: ', p_classes.contents)
How to use float ** in Python with Swig?
I am writing swig bindings for some c functions. One of these functions takes a float**. I am already using cpointer.i for the normal pointers and looked into carrays.i, but I did not find a way to declare a float**. What do you recommend? interface file: extern int read_data(const char *file,int *n_,int *m_,float **data_,int **classes_);
[ "This answer is a repost of one to a related question Framester posted about using ctypes instead of swig. I've included it here in case any web-searches turn up a link to his original question.\n\nI've used ctypes for several projects\n now and have been quite happy with the\n results. I don't think I've personally\n needed a pointer-to-pointer wrapper\n yet but, in theory, you should be able\n to do the following:\n\nfrom ctypes import * \n\nyour_dll = cdll.LoadLibrary(\"your_dll.dll\") \n\nPFloat = POINTER(c_float) \nPInt = POINTER(c_int) \n\np_data = PFloat() \np_classes = PInt() \nbuff = create_string_buffer(1024) \nn1 = c_int( 0 ) \nn2 = c_int( 0 ) \n\nret = your_dll.read_data( buff, byref(n1), byref(n2), byref(p_data), byref(p_classes) ) \n\nprint('Data: ', p_data.contents) \nprint('Classes: ', p_classes.contents) \n\n" ]
[ 1 ]
[]
[]
[ "c", "pointers", "python", "swig" ]
stackoverflow_0003068317_c_pointers_python_swig.txt
Q: closing a connection with twisted Various connections - e.g. those created with twisted.web.client.getPage() seem to leak - they hang around indefinitely, since the OS time-out is measured in hours - if the server doesn't respond timely. And putting a time-out on the deferred you get back is deprecated. How can you track the requests you have open, and close them forcefully in your twisted program? (Forcefully closing connections that have timed-out in application logic is important to making a twisted server that scales; various reactors have different limits on the number of open file descriptors they allow - select being as low as 1024! So please help twisted users keep the open connections count nice and trimmed.) A: getPage accepts a timeout parameter. If you pass a value for it and the response is not fully received within that number of seconds, the connection will be closed and the Deferred returned by getPage will errback.
closing a connection with twisted
Various connections - e.g. those created with twisted.web.client.getPage() seem to leak - they hang around indefinitely, since the OS time-out is measured in hours - if the server doesn't respond timely. And putting a time-out on the deferred you get back is deprecated. How can you track the requests you have open, and close them forcefully in your twisted program? (Forcefully closing connections that have timed-out in application logic is important to making a twisted server that scales; various reactors have different limits on the number of open file descriptors they allow - select being as low as 1024! So please help twisted users keep the open connections count nice and trimmed.)
[ "getPage accepts a timeout parameter. If you pass a value for it and the response is not fully received within that number of seconds, the connection will be closed and the Deferred returned by getPage will errback.\n" ]
[ 2 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0003084369_python_tcp_twisted.txt
Q: Force download of files on App Engine How would I go about forcing the browser to download media files instead of attempting to stream them? These are static files in my application directory. A: You need to modify app.yaml in your project, setting application/octect-stream as mime_type. Check this example: - url: /download static_dir: static/download mime_type : application/octect-stream As correctly stated in comment, it is not a good idea to force a certain mime_type on download. If your users would prefer to stream your content rather than downloading them, it's their decision and you shouldn't force them to download your files. You could provide two different links, one with stream and one forcing the save dialog. A: if you are using java then you can use following code. //Set content type resp.setContentType("text/csv" + .getContentType()); //Set header for attachement resp.setHeader("Content-Disposition","attachment;filename=Myfile.csv"); //Retrieve file from database and convert to byte resp.getOutputStream().write(b.getFile().getBytes()); //Close stream resp.getOutputStream().close();
Force download of files on App Engine
How would I go about forcing the browser to download media files instead of attempting to stream them? These are static files in my application directory.
[ "You need to modify app.yaml in your project, setting application/octect-stream as mime_type.\nCheck this example:\n- url: /download\n static_dir: static/download\n mime_type : application/octect-stream\n\nAs correctly stated in comment, it is not a good idea to force a certain mime_type on download.\nIf your users would prefer to stream your content rather than downloading them, it's their decision and you shouldn't force them to download your files.\nYou could provide two different links, one with stream and one forcing the save dialog.\n", "if you are using java then you can use following code.\n//Set content type\nresp.setContentType(\"text/csv\" + .getContentType());\n\n//Set header for attachement\nresp.setHeader(\"Content-Disposition\",\"attachment;filename=Myfile.csv\");\n\n//Retrieve file from database and convert to byte\nresp.getOutputStream().write(b.getFile().getBytes());\n\n//Close stream \nresp.getOutputStream().close();\n\n" ]
[ 0, 0 ]
[]
[]
[ "content_disposition", "download", "google_app_engine", "python" ]
stackoverflow_0003076045_content_disposition_download_google_app_engine_python.txt