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: Where do I put common code for if and elif? For the example below: if a == 100: # Five lines of code elif a == 200: # Five lines of code Five lines of code is common and repeating how can I avoid it? I know about putting it a function or if a == 100 or a == 200: # Five lines of code if a == 100: # Do something elif a == 200: # Do something Any other cleaner solution? A: Alternative (1): put your 5 lines in a function, and just call it Alternative (2) if a in (100, 200): # five lines of code if a == 100: # ... else: # ... A little less verbose than your code A: def five_lines(arg): ... if a in [100,200]: five_lines(i) A: Remember that with functions, you can have local functions with a closure. This means you can avoid passing repetitive arguments and still modify locals. (Just be careful with assignments in that local function. Also see the nonlocal keyword in Python 3.) def some_func(a): L = [] def append(): L.append(a) # for the sake of example #... if a == 100: append() #... elif a == 200: append() #...
Where do I put common code for if and elif?
For the example below: if a == 100: # Five lines of code elif a == 200: # Five lines of code Five lines of code is common and repeating how can I avoid it? I know about putting it a function or if a == 100 or a == 200: # Five lines of code if a == 100: # Do something elif a == 200: # Do something Any other cleaner solution?
[ "Alternative (1): put your 5 lines in a function, and just call it\nAlternative (2)\nif a in (100, 200):\n # five lines of code\n if a == 100:\n # ...\n else:\n # ...\n\nA little less verbose than your code\n", "def five_lines(arg):\n ...\n\nif a in [100,200]:\n five_lines(i)\n\n", "Remember that with functions, you can have local functions with a closure. This means you can avoid passing repetitive arguments and still modify locals. (Just be careful with assignments in that local function. Also see the nonlocal keyword in Python 3.)\ndef some_func(a):\n L = []\n\n def append():\n L.append(a) # for the sake of example\n #...\n\n if a == 100:\n append()\n #...\n elif a == 200:\n append()\n #...\n\n" ]
[ 4, 1, 1 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0002605425_conditional_python.txt
Q: 'NoneType' object has no attribute 'get' error using SQLAlchemy I've been trying to map an object to a database using SQLAlchemy but have run into a snag. Edit: Basically changed a whole bunch of stuff. Version info if handy: [OS: Mac OSX 10.5.8 | Python: 2.6.4 | SQLAlchemy: 0.5.8] The class I'm going to map: class Student(object): def __init__(self, id, name): self.id = id self.name = name def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.id, self.name) Background: Now, I've got a function that reads in the necessary information from a text database into these objects. The function more or less works and I can easily access the information from the objects. Before the SQLAlchemy code runs, the function will read in the necessary info and store it into the Class. There is a dictionary called students which stores this as such: students = {} students[id] = Student(<all the info from the various "reader" functions>) Afterwards, there is an "allocation" algorithm that will allocate projects to student. It does that well enough. The allocated_project remains as None if a student is unsuccessful in getting a project. SQLAlchemy bit: So after all this happens, I'd like to map my object to a database table. from sqlalchemy import * from sqlalchemy.orm import * engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('id', Integer, primary_key=True), Column('name', String) ) metadata.create_all(engine) mapper(Student, students_table) Now after that, I was curious to see if I could print out all the students from my students dictionary. for student in students.itervalues(): print student What do I get but an error. This error only takes place if try to print as I am, after calling the mapper: Traceback (most recent call last): File "~/FYP_Tests/FYP_Tests.py", line 140, in <module> print student File "~/FYP_Tests/Parties.py", line 30, in __str__ return "%s %s" %(self.id, self.name) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/attributes.py", line 158, in __get__ return self.impl.get(instance_state(instance), instance_dict(instance)) AttributeError: 'NoneType' object has no attribute 'get' I'm at a loss as to how to resolve this issue, if it is an issue. If more information is required, please ask and I will provide it. Questions: Does the SQLAlchemy mapper change anything about the original Class/dictionary? Does this have anything specific to way the get works with dictionaries? A: You are creating Student instances before mapping class which modifies class to SQLAlchemy needs. So your instance is not properly initialized. Just put the lines creating Student instances after calling mapper(Student, students_table) and everything will work as expected. A: It looks like you might have a name shadowing conflict where Column('id'...) hides Student.id. Changing Student.__init__.id to Student._init__.sid would be a quick test to confirm or refute this conjecture. There is mention of this connection in the third code block of the SQLAlchemy tutorial on mappings. For example, replacing your first code snippet with this fragement: class Student(object): def __init__(self, name, id): self.sid = id self.name = name # and so on Obviously other references to Student.id would have to change as well.
'NoneType' object has no attribute 'get' error using SQLAlchemy
I've been trying to map an object to a database using SQLAlchemy but have run into a snag. Edit: Basically changed a whole bunch of stuff. Version info if handy: [OS: Mac OSX 10.5.8 | Python: 2.6.4 | SQLAlchemy: 0.5.8] The class I'm going to map: class Student(object): def __init__(self, id, name): self.id = id self.name = name def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.id, self.name) Background: Now, I've got a function that reads in the necessary information from a text database into these objects. The function more or less works and I can easily access the information from the objects. Before the SQLAlchemy code runs, the function will read in the necessary info and store it into the Class. There is a dictionary called students which stores this as such: students = {} students[id] = Student(<all the info from the various "reader" functions>) Afterwards, there is an "allocation" algorithm that will allocate projects to student. It does that well enough. The allocated_project remains as None if a student is unsuccessful in getting a project. SQLAlchemy bit: So after all this happens, I'd like to map my object to a database table. from sqlalchemy import * from sqlalchemy.orm import * engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('id', Integer, primary_key=True), Column('name', String) ) metadata.create_all(engine) mapper(Student, students_table) Now after that, I was curious to see if I could print out all the students from my students dictionary. for student in students.itervalues(): print student What do I get but an error. This error only takes place if try to print as I am, after calling the mapper: Traceback (most recent call last): File "~/FYP_Tests/FYP_Tests.py", line 140, in <module> print student File "~/FYP_Tests/Parties.py", line 30, in __str__ return "%s %s" %(self.id, self.name) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/attributes.py", line 158, in __get__ return self.impl.get(instance_state(instance), instance_dict(instance)) AttributeError: 'NoneType' object has no attribute 'get' I'm at a loss as to how to resolve this issue, if it is an issue. If more information is required, please ask and I will provide it. Questions: Does the SQLAlchemy mapper change anything about the original Class/dictionary? Does this have anything specific to way the get works with dictionaries?
[ "You are creating Student instances before mapping class which modifies class to SQLAlchemy needs. So your instance is not properly initialized. Just put the lines creating Student instances after calling mapper(Student, students_table) and everything will work as expected.\n", "It looks like you might have a name shadowing conflict where Column('id'...) hides Student.id. Changing Student.__init__.id to Student._init__.sid would be a quick test to confirm or refute this conjecture. \nThere is mention of this connection in the third code block of the SQLAlchemy tutorial on mappings. \nFor example, replacing your first code snippet with this fragement:\nclass Student(object):\n def __init__(self, name, id):\n self.sid = id\n self.name = name\n # and so on\n\nObviously other references to Student.id would have to change as well.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002605205_python_sqlalchemy.txt
Q: functional-style datatypes in Python For anyone who's spent some time with sml, ocaml, haskell, etc. when you go back to using C, Python, Java, etc. you start to notice things you never knew were missing. I'm doing some stuff in Python and I realized what I really want is a functional-style datatype like (for example) datatype phoneme = Vowel of string | Consonant of voice * place * manner datatype voice = Voiced | Voiceless datatype place = Labial | Dental | Retroflex | Palatal | Velar | Glottal datatype manner = Stop | Affricate | Fricative | Nasal | Lateral type syllable = phoneme list Does anyone have a particular way that they like to simulate this in Python? A: For the simple enumerations like voice, place and manner you could use a class like this: class Enum(object): def __init__(self, *values): self._values = set(values) for value in values: setattr(self, value, value) def __iter__(self): return iter(self._values) place = Enum('Labial', 'Dental', 'Retroflex', 'Palatal', 'Velar', 'Glottal') a = place.Retroflex if a == place.Labial: print "How did this happen?" for p in place: print "possible value:", p A: As sth indicated, your voice, place, and manner types are just enumerated types. There are a number of ways to implement those, such as class voice(object): Voiced, Voiceless = range(2) Then you can refer to voice.Voiced and voice.Voiceless, and so forth. The problem is types like phoneme. In C the usual way to implement something like that would be to hold your nose and use a union. In something like python, you use polymorphism. First, figure out what operations you're going to perform on the phoneme type. Then, implement those operations as member functions of a Vowel class and a Consonant class. In C++ you'd make those member functions virtual and make an abstract base class for Vowel and Consonant; in python you can get away without doing that thanks to duck typing, although you might still find a base class to be useful. So, class Vowel(object): def SomeInitialMethod(self): # ... class Consonant(object): def SomeInitialMethod(self): # ... p.SomeInitialMethod() # p can be either vowel or consonant def SomeLaterFunction(p) # p is assumed to be either a Vowel or a Consonant if isinstance(p, Vowel): # ... elif isinstance(p, Consonant): # ... A: You could create classes that contain the attributes you need. class Phoneme: # ... class Consonant(Phoneme): def __init__(self, voice, place, manner): self.voice = voice self.place = place self.manner = manner # ... h = Consonant('Voiceless', 'Glottal', 'Fricative') # ...
functional-style datatypes in Python
For anyone who's spent some time with sml, ocaml, haskell, etc. when you go back to using C, Python, Java, etc. you start to notice things you never knew were missing. I'm doing some stuff in Python and I realized what I really want is a functional-style datatype like (for example) datatype phoneme = Vowel of string | Consonant of voice * place * manner datatype voice = Voiced | Voiceless datatype place = Labial | Dental | Retroflex | Palatal | Velar | Glottal datatype manner = Stop | Affricate | Fricative | Nasal | Lateral type syllable = phoneme list Does anyone have a particular way that they like to simulate this in Python?
[ "For the simple enumerations like voice, place and manner you could use a class like this:\nclass Enum(object):\n def __init__(self, *values):\n self._values = set(values)\n for value in values:\n setattr(self, value, value)\n def __iter__(self):\n return iter(self._values)\n\nplace = Enum('Labial', 'Dental', 'Retroflex', 'Palatal', 'Velar', 'Glottal')\n\na = place.Retroflex \nif a == place.Labial:\n print \"How did this happen?\"\n\nfor p in place:\n print \"possible value:\", p\n\n", "As sth indicated, your voice, place, and manner types are just enumerated types. There are a number of ways to implement those, such as\nclass voice(object):\n Voiced, Voiceless = range(2)\n\nThen you can refer to voice.Voiced and voice.Voiceless, and so forth.\nThe problem is types like phoneme. In C the usual way to implement something like that would be to hold your nose and use a union. In something like python, you use polymorphism. First, figure out what operations you're going to perform on the phoneme type. Then, implement those operations as member functions of a Vowel class and a Consonant class. In C++ you'd make those member functions virtual and make an abstract base class for Vowel and Consonant; in python you can get away without doing that thanks to duck typing, although you might still find a base class to be useful.\nSo,\nclass Vowel(object):\n def SomeInitialMethod(self):\n # ...\n\nclass Consonant(object):\n def SomeInitialMethod(self):\n # ...\n\np.SomeInitialMethod() # p can be either vowel or consonant\n\ndef SomeLaterFunction(p)\n # p is assumed to be either a Vowel or a Consonant\n if isinstance(p, Vowel):\n # ...\n elif isinstance(p, Consonant):\n # ...\n\n", "You could create classes that contain the attributes you need.\nclass Phoneme:\n # ...\n\nclass Consonant(Phoneme):\n def __init__(self, voice, place, manner):\n self.voice = voice\n self.place = place\n self.manner = manner\n # ...\n\nh = Consonant('Voiceless', 'Glottal', 'Fricative')\n# ...\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "functional_programming", "python", "types" ]
stackoverflow_0002604666_functional_programming_python_types.txt
Q: Scraping a page from a secure URL which is possibly using a session ID How to scrape a page like this: https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0 It is secure, and looks like it requires a referrer. I can't get anything using wget or httplib2. If you go through this page, you get a list and it works on a browser but not the command line. https://www.procom.ca/jobsearch.aspx I am interested in command line fetching. A: As you suspect, it requires a referer. This works: import urllib2 urlopen = urllib2.urlopen Request = urllib2.Request url = 'https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0' headers = {'Referer' : 'http://www.stackoverflow.com'} req = Request(url, None, headers) handle = urlopen(req) print handle.read() A: What data are you sending in POST or Get, I would recommend look thru the POST/GET messages in Firebug Net Panel, in that page there are many hidden values which I think are time dependent and changes on each page load and may be valid once so load page , get those values and send them with POST messages e.g. see these <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> <input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" /> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEwODIzNjMxMzEPFgIeEUdyaWRTb3J0RGlyZWN0aW9uCyo..." />
Scraping a page from a secure URL which is possibly using a session ID
How to scrape a page like this: https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0 It is secure, and looks like it requires a referrer. I can't get anything using wget or httplib2. If you go through this page, you get a list and it works on a browser but not the command line. https://www.procom.ca/jobsearch.aspx I am interested in command line fetching.
[ "As you suspect, it requires a referer. This works:\n import urllib2\n urlopen = urllib2.urlopen\n Request = urllib2.Request\n url = 'https://www.procom.ca/JobList.aspx?keywords=&Cities=&reference=&JobType=0'\n headers = {'Referer' : 'http://www.stackoverflow.com'}\n req = Request(url, None, headers)\n handle = urlopen(req)\n print handle.read()\n\n", "What data are you sending in POST or Get, I would recommend look thru the POST/GET messages in Firebug Net Panel, in that page there are many hidden values which I think are time dependent and changes on each page load and may be valid once so load page , get those values and send them with POST messages e.g. see these\n<input type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\" value=\"\" />\n<input type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\" value=\"\" />\n<input type=\"hidden\" name=\"__LASTFOCUS\" id=\"__LASTFOCUS\" value=\"\" />\n<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"/wEPDwULLTEwODIzNjMxMzEPFgIeEUdyaWRTb3J0RGlyZWN0aW9uCyo...\" />\n\n" ]
[ 3, 0 ]
[]
[]
[ "mechanize", "python", "referrer", "scrapy", "screen_scraping" ]
stackoverflow_0002604914_mechanize_python_referrer_scrapy_screen_scraping.txt
Q: Reading path in templates is there any way to read the path to the current page? For example, I am at www.example.com/foo/bar/ - and I want to read '/foo/bar/'. I have to do this in the template file without modifying views, and I have too many view files to edit each one. Cheers. A: If you add django.core.context_processors.request to your TEMPLATE_CONTEXT_PROCESSORS setting, it will add the request variable to every template-rendering that uses a RequestContext (which is most of the built-in ones). This is the HTTPRequest object for the current request, the path attribute of which is the requested path. More information can be found in the docs. A: request.path A: I ended up using this but ran into a little hiccup along the way. Here's my solution path in the hopes that I save someone else some time. At first I added this line to my settings.py file: TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.request",) I found that it allowed me to access the request path from within a template which had been passed a RequestContext by using the template variable {{ request.path }}. However, it also disabled all the other context processors. To fix this I tried adding the defaults to the TEMPLATE_CONTEXT_PROCESSORS tuple. At first this failed because I had used the context processors for Django 1.2 (I have Django 1.1 installed). After fixing that problem I was left with the following settings file: TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", )
Reading path in templates
is there any way to read the path to the current page? For example, I am at www.example.com/foo/bar/ - and I want to read '/foo/bar/'. I have to do this in the template file without modifying views, and I have too many view files to edit each one. Cheers.
[ "If you add django.core.context_processors.request to your TEMPLATE_CONTEXT_PROCESSORS setting, it will add the request variable to every template-rendering that uses a RequestContext (which is most of the built-in ones). This is the HTTPRequest object for the current request, the path attribute of which is the requested path. More information can be found in the docs.\n", "request.path\n", "I ended up using this but ran into a little hiccup along the way. Here's my solution path in the hopes that I save someone else some time.\nAt first I added this line to my settings.py file:\nTEMPLATE_CONTEXT_PROCESSORS = (\"django.core.context_processors.request\",)\n\nI found that it allowed me to access the request path from within a template which had been passed a RequestContext by using the template variable {{ request.path }}. However, it also disabled all the other context processors. To fix this I tried adding the defaults to the TEMPLATE_CONTEXT_PROCESSORS tuple. At first this failed because I had used the context processors for Django 1.2 (I have Django 1.1 installed). After fixing that problem I was left with the following settings file:\nTEMPLATE_CONTEXT_PROCESSORS = (\"django.core.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.request\",\n )\n\n" ]
[ 3, 2, 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002127937_django_django_templates_python.txt
Q: How do you determine an acceptable response time for App Engine DB requests? According to this discussion of Google App Engine on Hacker News, A DB (read) request takes over 100ms on the datastore. That's insane and unusable for about 90% of applications. How do you determine what is an acceptable response time for a DB read request? I have been using App Engine without noticing any issues with DB responsiveness. But, on the other hand, I'm not sure I would even know what to look for in that regard :) A: You can measure precisely how much each RPC call (datastore or otherwise) is taking, thanks to Guido van Rossum's AppStats relatively-new component (it's part of the standard SDK since 1.3.1). See here for more. 100 milliseconds is fine for most well-designed apps -- if you need to make two or three queries to serve a page, you can still serve in less than half a seconds even if there's lots of processing and rendering involved... not too shabby. Plus, you can use memcache to reduce many of those latencies, etc. A: What do you mean by acceptable? What kind of application are you writing? Acceptable means different things for different domains/applications/people. First, you should decide how quickly you want your app to respond to a request. Let's pick 1 second, just for argument's sake. Now, how many DB requests do you need to make to fulfill that request? Let's say 5. Let's also say that we also have 400ms worth of other processing to do. OK, so that's 5 reads times 100ms each, plus 400ms of other stuff. 900ms total, which is less than our goal of 1 second. Perfect! 100ms is an acceptable read rate. In fact, 120ms would still be acceptable, just barely. Now, let's generalize: numberOfReads * readTime + otherStuffTime = TotalTime Fill in your numbers, and you can see what is an acceptable time for your particular situation. A: The poster is wrong. Datastore get operations are much faster - about 15-20ms each, currently. Datastore query operations can be slower, because they're much more involved and return more data, but they still complete in anywhere from 30-100ms for a typical query. Other posters have amply addressed whether that's "acceptable" or not. A: If you haven't noticed any issues then it is by definition an acceptable response time. The only question is how long your users are happy to wait. A: An "an acceptable response time for a DB read request" depends entirely on your application and your users. If the net result is that your site runs fast enough to satisfy you and your users then the slow response time of the services provided by Google in their AppEngine are acceptable. Now, looking deeper at this particular issue, it sounds like we are talking about GET's. Here are the figures for GET latency and it looks to me that the average latency is closer to 50ms then 100. I'm not saying that is good, but I don't think it is accurate to say 100ms.
How do you determine an acceptable response time for App Engine DB requests?
According to this discussion of Google App Engine on Hacker News, A DB (read) request takes over 100ms on the datastore. That's insane and unusable for about 90% of applications. How do you determine what is an acceptable response time for a DB read request? I have been using App Engine without noticing any issues with DB responsiveness. But, on the other hand, I'm not sure I would even know what to look for in that regard :)
[ "You can measure precisely how much each RPC call (datastore or otherwise) is taking, thanks to Guido van Rossum's AppStats relatively-new component (it's part of the standard SDK since 1.3.1). See here for more. 100 milliseconds is fine for most well-designed apps -- if you need to make two or three queries to serve a page, you can still serve in less than half a seconds even if there's lots of processing and rendering involved... not too shabby. Plus, you can use memcache to reduce many of those latencies, etc.\n", "What do you mean by acceptable? What kind of application are you writing? Acceptable means different things for different domains/applications/people. First, you should decide how quickly you want your app to respond to a request. Let's pick 1 second, just for argument's sake. Now, how many DB requests do you need to make to fulfill that request? Let's say 5. Let's also say that we also have 400ms worth of other processing to do. OK, so that's 5 reads times 100ms each, plus 400ms of other stuff. 900ms total, which is less than our goal of 1 second. Perfect! 100ms is an acceptable read rate. In fact, 120ms would still be acceptable, just barely.\nNow, let's generalize:\nnumberOfReads * readTime + otherStuffTime = TotalTime\n\nFill in your numbers, and you can see what is an acceptable time for your particular situation.\n", "The poster is wrong. Datastore get operations are much faster - about 15-20ms each, currently. Datastore query operations can be slower, because they're much more involved and return more data, but they still complete in anywhere from 30-100ms for a typical query. Other posters have amply addressed whether that's \"acceptable\" or not.\n", "If you haven't noticed any issues then it is by definition an acceptable response time. The only question is how long your users are happy to wait.\n", "An \"an acceptable response time for a DB read request\" depends entirely on your application and your users.\nIf the net result is that your site runs fast enough to satisfy you and your users then the slow response time of the services provided by Google in their AppEngine are acceptable.\nNow, looking deeper at this particular issue, it sounds like we are talking about GET's. Here are the figures for GET latency and it looks to me that the average latency is closer to 50ms then 100. I'm not saying that is good, but I don't think it is accurate to say 100ms.\n" ]
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "database", "google_app_engine", "java", "python", "response_time" ]
stackoverflow_0002602527_database_google_app_engine_java_python_response_time.txt
Q: Run Python CGI Script on Windows XP I have a Windows XP machine that has Apache installed via a VisualSVNServer installation. I am . trying to get a simple python cgi script to run in my browser e.g. http://build.procepts.com.au:8080/hg/cgi-bin/test.cgi. However despite trying all the recommended approaches the browser only ever displays the plain text from the cgi script. Amongst many other attempted solutions I have followed the instructions contained here. My ultimate aim is to be able to use the Apache web server to serve repositories from a new Mercurial installation. Seeing as Apache is already installed from VisualSVNServer I thought I might as well make use of it. Is there some other trick to get this working? A: The apache server that comes with VisualSVNServer is a minimal build supporting just enough to serve SVN repositories. It does not include cgi support. That said, it's pretty easy to add cgi support (or any other module for that matter). For CGI support specifically, you'll need to obtain "mod_cgi.so" built for Apache 2.2 Win32 and place it in "C:\Program Files\VisualSVN Server\bin", then add: LoadModule cgi_module bin/mod_cgi.so ScriptAlias /cgi-bin/ cgi-bin/ to "C:\Program Files\VisualSVN Server\conf\httpd-custom.conf". Restart VisualSVN and it should start working. A: I am not sure if it applies to the VisualSVNServer, but in ususal Apache you will need at least the following: Uncomment loading CGI module in Apache config: LoadModule cgi_module modules/mod_cgi.so (or similar) Allow executing of CGI scripts in your directory and add a handler for py scripts: <Directory /path/to/scripts/directory> Options +ExecCGI AddHandler cgi-script py </Directory> Insert a shebang line in the executed script: #!/usr/local/bin/python
Run Python CGI Script on Windows XP
I have a Windows XP machine that has Apache installed via a VisualSVNServer installation. I am . trying to get a simple python cgi script to run in my browser e.g. http://build.procepts.com.au:8080/hg/cgi-bin/test.cgi. However despite trying all the recommended approaches the browser only ever displays the plain text from the cgi script. Amongst many other attempted solutions I have followed the instructions contained here. My ultimate aim is to be able to use the Apache web server to serve repositories from a new Mercurial installation. Seeing as Apache is already installed from VisualSVNServer I thought I might as well make use of it. Is there some other trick to get this working?
[ "The apache server that comes with VisualSVNServer is a minimal build supporting just enough to serve SVN repositories. It does not include cgi support.\nThat said, it's pretty easy to add cgi support (or any other module for that matter). \nFor CGI support specifically, you'll need to obtain \"mod_cgi.so\" built for Apache 2.2 Win32 and place it in \"C:\\Program Files\\VisualSVN Server\\bin\", then add:\nLoadModule cgi_module bin/mod_cgi.so\nScriptAlias /cgi-bin/ cgi-bin/\n\nto \"C:\\Program Files\\VisualSVN Server\\conf\\httpd-custom.conf\". Restart VisualSVN and it should start working.\n", "I am not sure if it applies to the VisualSVNServer, but in ususal Apache you will need at least the following:\n\nUncomment loading CGI module in Apache config:\nLoadModule cgi_module modules/mod_cgi.so (or similar)\n\nAllow executing of CGI scripts in your directory and add a handler for py scripts:\n<Directory /path/to/scripts/directory>\n Options +ExecCGI\n AddHandler cgi-script py\n</Directory>\n\nInsert a shebang line in the executed script:\n#!/usr/local/bin/python\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "apache", "cgi", "python", "scripting" ]
stackoverflow_0002605270_apache_cgi_python_scripting.txt
Q: Change process name of Python script Windows Task Manager lists all running processes in the "Processes" tab. The image name of Python scripts is always python.exe, or pythonw.exe, or the name of the Python interpreter. Is there a nice way to change the image name of a Python script, other than changing the name of the Python interpreter? A: You could use py2exe to turn your Python program into a self-contained executable with whatever name that you choose to give it. A: There's no nice way that I've found to change the name of a running process in Windows, but you can create small .exe stubs with ExeMaker rather than resorting to py2exe packaging or copying the interpreter The exe stub uses its own module name to calculate the .py script invoked. You should be able to use an exe resource editor to change the icon.
Change process name of Python script
Windows Task Manager lists all running processes in the "Processes" tab. The image name of Python scripts is always python.exe, or pythonw.exe, or the name of the Python interpreter. Is there a nice way to change the image name of a Python script, other than changing the name of the Python interpreter?
[ "You could use py2exe to turn your Python program into a self-contained executable with whatever name that you choose to give it.\n", "There's no nice way that I've found to change the name of a running process in Windows, but you can create small .exe stubs with ExeMaker rather than resorting to py2exe packaging or copying the interpreter\nThe exe stub uses its own module name to calculate the .py script invoked. You should be able to use an exe resource editor to change the icon.\n" ]
[ 1, 1 ]
[]
[]
[ "process", "python", "windows" ]
stackoverflow_0002155042_process_python_windows.txt
Q: assigning a list in python pt=[2] pt[0]=raw_input() when i do this , and give an input suppose 1011 , it says list indexing error- " list assignment index out of range" . may i know why? i think i am not able to assign a list properly . how to assign an array of 2 elements in python then? A: Try this: pt = list() pt.append(raw_input()) pt.append(raw_input()) print pt You now have two elements in your list. Once you are more familiar with python syntax, you might write this as: pt = [raw_input(), raw_input()] Also, note that lists are not to be confused with arrays in Java or C: Lists grow dynamically. You don't have to declare the size when you create a new list. BTW: I tried out your example in the interactive shell. It works, but probably not as you expected: >>> pt = [2] >>> pt[0] = raw_input() 1011 >>> pt ['1011'] I'm guessing you thought pt = [2] would create a list of length 2, so a pt[1] = raw_input() would fail like you mentioned: >>> pt = [2] >>> pt[0] = raw_input() 1011 >>> pt[1] = raw_input() # this is an assignment to an index not yet created. 1012 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range Actually, pt = [2] creates a list with one element, having the value 2 at index 0: >>> pt = [2] >>> pt [2] >>> So you can assign to the index 0 as demonstrated above, but assigning to index 1 will not work - use append for appending to a list. A: It's not clear what you are trying to do. My guess is that you are trying to do this: pt = [2] # Create array with two elements? for i in range(2): pt[i] = raw_input() Note that the first line does not create an array with two elements, it creates a list with one element: the number 2. You could try this instead, although there are more Pythonic ways to do it: pt = [None] * 2 for i in range(2): pt[i] = raw_input()
assigning a list in python
pt=[2] pt[0]=raw_input() when i do this , and give an input suppose 1011 , it says list indexing error- " list assignment index out of range" . may i know why? i think i am not able to assign a list properly . how to assign an array of 2 elements in python then?
[ "Try this:\npt = list()\npt.append(raw_input())\npt.append(raw_input())\nprint pt\n\nYou now have two elements in your list. Once you are more familiar with python syntax, you might write this as:\npt = [raw_input(), raw_input()]\n\nAlso, note that lists are not to be confused with arrays in Java or C: Lists grow dynamically. You don't have to declare the size when you create a new list.\nBTW: I tried out your example in the interactive shell. It works, but probably not as you expected:\n>>> pt = [2]\n>>> pt[0] = raw_input()\n1011\n>>> pt\n['1011']\n\nI'm guessing you thought pt = [2] would create a list of length 2, so a pt[1] = raw_input() would fail like you mentioned:\n>>> pt = [2]\n>>> pt[0] = raw_input()\n1011\n>>> pt[1] = raw_input() # this is an assignment to an index not yet created.\n1012\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIndexError: list assignment index out of range\n\nActually, pt = [2] creates a list with one element, having the value 2 at index 0:\n>>> pt = [2]\n>>> pt\n[2]\n>>>\n\nSo you can assign to the index 0 as demonstrated above, but assigning to index 1 will not work - use append for appending to a list.\n", "It's not clear what you are trying to do. My guess is that you are trying to do this:\npt = [2] # Create array with two elements?\nfor i in range(2):\n pt[i] = raw_input()\n\nNote that the first line does not create an array with two elements, it creates a list with one element: the number 2. You could try this instead, although there are more Pythonic ways to do it:\npt = [None] * 2\nfor i in range(2):\n pt[i] = raw_input()\n\n" ]
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002606303_python.txt
Q: Problem's running unittest test suite OO I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): self.suite() if __name__ == '__main__': run = CallTests() run.integration() And the test suite: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') This output's an error: Attribute Error: 'module' object has no attribute 'suite' So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so: class InternalSanityTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeInternalSanityTestSuite(): suite = unittest.TestSuite() suite.addTest(TestInternalSanity("BasicInternalSanity")) suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail")) return suite def suite(): return unittest.makeSuite(TestInternalSanity) If I have someSuite() inside the class SmokeTests python cannot find the attribute suite but if I remove the class it work's. I run this as a script and call in variables into the tests. I do not want to have to run the tests by os.system('python tests.py'). I was hoping to call the tests through the class I have like any other function Can anyone help me with getting this running? Thanks for any help in advance. A: I know this is not the answer, but I'd suggest using library that can use test discovery, like nose or unittest capability from Python 2.7+. Possibility to do nosetests module.submodule or nosetests module.submodule:TestCase.test_method is priceless :) A: This can't work: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') This output's an error: Attribute Error: 'module' object has no attribute 'suite'. Your suite the value of the SmokeTests().suite() method. Note a variable named suite, since you have no such variable. It's easier to use a simple function for your suite. def someSuite(): modules_to_test ... return alltests if __name__ == "__main__": unittest.main( defaultTest= someSuite() ) Something like that would be closer to correct.
Problem's running unittest test suite OO
I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): self.suite() if __name__ == '__main__': run = CallTests() run.integration() And the test suite: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') This output's an error: Attribute Error: 'module' object has no attribute 'suite' So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so: class InternalSanityTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeInternalSanityTestSuite(): suite = unittest.TestSuite() suite.addTest(TestInternalSanity("BasicInternalSanity")) suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail")) return suite def suite(): return unittest.makeSuite(TestInternalSanity) If I have someSuite() inside the class SmokeTests python cannot find the attribute suite but if I remove the class it work's. I run this as a script and call in variables into the tests. I do not want to have to run the tests by os.system('python tests.py'). I was hoping to call the tests through the class I have like any other function Can anyone help me with getting this running? Thanks for any help in advance.
[ "I know this is not the answer, but I'd suggest using library that can use test discovery, like nose or unittest capability from Python 2.7+.\nPossibility to do\nnosetests module.submodule\n\nor\nnosetests module.submodule:TestCase.test_method\n\nis priceless :)\n", "This can't work:\nclass SmokeTests():\n\n def suite(self): #Function stores all the modules to be tested \n modules_to_test = ('external_sanity', 'internal_sanity')\n alltests = unittest.TestSuite()\n for module in map(__import__, modules_to_test):\n alltests.addTest(unittest.findTestCases(module))\n return alltests\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n\nThis output's an error: Attribute Error: 'module' object has no attribute 'suite'.\nYour suite the value of the SmokeTests().suite() method. Note a variable named suite, since you have no such variable.\nIt's easier to use a simple function for your suite.\ndef someSuite():\n modules_to_test\n ...\n return alltests\n\nif __name__ == \"__main__\":\n unittest.main( defaultTest= someSuite() )\n\nSomething like that would be closer to correct.\n" ]
[ 3, 1 ]
[]
[]
[ "class", "python", "unit_testing" ]
stackoverflow_0002606515_class_python_unit_testing.txt
Q: How to use the validation rules on both client-side and server-side? I'm using jQuery validation system for client-side validation. The backend works with django. jQuery use an interesting set of rules in JSON format. Does exists something to use the same rules on django side or I need to code it myself? A: No, no such thing exists. Yes, you need to code it yourself. However, I imagine you could possibly create widgets which are able to deliver generic validation js routines based on the modelFields. Such as "This should be chars not more than max_length". However they could not trivially generate client-side code to validate any custom validation written in python, nor even something like "This must be the username of an existing user". But if you take this trouble to build widgets which do basic validation based on the modelFields please contribute them to open source :-D A: This article describes some level of integration: http://streamhacker.com/2010/03/08/jquery-validation-django-forms/ It doesn't look like it actually generates the clientside metadata based on the serverside metadata, but at least puts all rules in one place. May be a good starting point for generating those rules based on the existing Django rules. A: I haven't used it myself, but there is the django-ajax-forms project.
How to use the validation rules on both client-side and server-side?
I'm using jQuery validation system for client-side validation. The backend works with django. jQuery use an interesting set of rules in JSON format. Does exists something to use the same rules on django side or I need to code it myself?
[ "No, no such thing exists.\nYes, you need to code it yourself.\nHowever, I imagine you could possibly create widgets which are able to deliver generic validation js routines based on the modelFields. Such as \"This should be chars not more than max_length\". However they could not trivially generate client-side code to validate any custom validation written in python, nor even something like \"This must be the username of an existing user\". But if you take this trouble to build widgets which do basic validation based on the modelFields please contribute them to open source :-D\n", "This article describes some level of integration: http://streamhacker.com/2010/03/08/jquery-validation-django-forms/\nIt doesn't look like it actually generates the clientside metadata based on the serverside metadata, but at least puts all rules in one place. May be a good starting point for generating those rules based on the existing Django rules.\n", "I haven't used it myself, but there is the django-ajax-forms project.\n" ]
[ 2, 2, 0 ]
[]
[]
[ "django", "jquery", "python", "validation" ]
stackoverflow_0002606283_django_jquery_python_validation.txt
Q: how to define an array in python? i want to define an array in python . how would i do that ? do i have to use list? A: Normally you would use a list. If you really want an array you can import array: import array a = array.array('i', [5, 6]) # array of signed ints If you want to work with multidimensional arrays, you could try numpy. A: List is better, but you can use array like this : array('l') array('c', 'hello world') array('u', u'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.14]) More infos there A: Why do you want to use an array over a list? Here is a comparison of the two that clearly states the advantages of lists. A: There are several types of arrays in Python, if you want a classic array it would be with the array module: import array a = array.array('i', [1,2,3]) But you can also use tuples without needing import other modules: t = (4,5,6) Or lists: l = [7,8,9] A Tuple is more efficient in use, but it has a fixed size, while you can easily add new elements to lists: >>> l.append(10) >>> l [7, 8, 9, 10] >>> t[1] 5 >>> l[1] 8 A: If you need an array because you're working with other low-level constructs (such as you would in C), you can use ctypes. import ctypes UINT_ARRAY_30 = ctypes.c_uint*30 # create a type of array of uint, length 30 my_array = UINT_ARRAY_30() my_array[0] = 1 my_array[3] == 0
how to define an array in python?
i want to define an array in python . how would i do that ? do i have to use list?
[ "Normally you would use a list. If you really want an array you can import array:\nimport array\na = array.array('i', [5, 6]) # array of signed ints\n\nIf you want to work with multidimensional arrays, you could try numpy.\n", "List is better, but you can use array like this :\narray('l')\narray('c', 'hello world')\narray('u', u'hello \\u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.14])\n\nMore infos there\n", "Why do you want to use an array over a list? Here is a comparison of the two that clearly states the advantages of lists.\n", "There are several types of arrays in Python, if you want a classic array it would be with the array module:\nimport array\na = array.array('i', [1,2,3])\n\nBut you can also use tuples without needing import other modules:\nt = (4,5,6)\n\nOr lists:\nl = [7,8,9]\n\nA Tuple is more efficient in use, but it has a fixed size, while you can easily add new elements to lists:\n>>> l.append(10)\n>>> l\n[7, 8, 9, 10]\n>>> t[1]\n5\n>>> l[1]\n8\n\n", "If you need an array because you're working with other low-level constructs (such as you would in C), you can use ctypes.\nimport ctypes\nUINT_ARRAY_30 = ctypes.c_uint*30 # create a type of array of uint, length 30\nmy_array = UINT_ARRAY_30()\nmy_array[0] = 1\nmy_array[3] == 0\n\n" ]
[ 5, 4, 4, 3, 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0002606793_arrays_python.txt
Q: How do I find out if the variable is declared in Python? I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main__': pass singleton.py variable1 = '' variable2 = '' def Init(var1, var2) variable1 = var1 variable2 = var2 printer.py import singleton def Print() print singleton.variable1 print singleton.variable2 I expect to get output 1/2, but instead get empty space. I understand that after I imported singleton to the print.py module the variables got initialized again. So I think that I must check if they were intialized before in singleton.py: if not (variable1): variable1 = '' if not (variable2) variable2 = '' But I don't know how to do that. Or there is a better way to use singleton modules in python that I'm not aware of :) A: The assignment inside Init is forcing the variables to be treated as locals. Use the global keyword to fix this: variable1 = '' variable2 = '' def Init(var1, var2) global variable1, variable2 variable1 = var1 variable2 = var2 A: You can use de dictionaries vars and globals: vars().has_key('variable1') or globals().has_key('variable1') Edit: Also... 'variable1' in vars() e.g. if not 'variable1' in vars(): variable1 = ''
How do I find out if the variable is declared in Python?
I want to use a module as a singleton referenced in other modules. It looks something like this (that's not actually a code I'm working on, but I simplified it to throw away all unrelated stuff): main.py import singleton import printer def main(): singleton.Init(1,2) printer.Print() if __name__ == '__main__': pass singleton.py variable1 = '' variable2 = '' def Init(var1, var2) variable1 = var1 variable2 = var2 printer.py import singleton def Print() print singleton.variable1 print singleton.variable2 I expect to get output 1/2, but instead get empty space. I understand that after I imported singleton to the print.py module the variables got initialized again. So I think that I must check if they were intialized before in singleton.py: if not (variable1): variable1 = '' if not (variable2) variable2 = '' But I don't know how to do that. Or there is a better way to use singleton modules in python that I'm not aware of :)
[ "The assignment inside Init is forcing the variables to be treated as locals. Use the global keyword to fix this:\nvariable1 = ''\nvariable2 = ''\n\ndef Init(var1, var2)\n global variable1, variable2\n variable1 = var1\n variable2 = var2\n\n", "You can use de dictionaries vars and globals:\nvars().has_key('variable1')\n\nor\nglobals().has_key('variable1')\n\nEdit:\nAlso...\n'variable1' in vars()\n\ne.g.\nif not 'variable1' in vars():\n variable1 = ''\n\n" ]
[ 7, 2 ]
[]
[]
[ "declaration", "python", "singleton", "variables" ]
stackoverflow_0002607037_declaration_python_singleton_variables.txt
Q: Python ctypes and dynamic linking I'm writing some libraries in C which contain functions that I want to call from Python via ctypes. I've done this successfully another library, but that library had only very vanilla dependencies (namely fstream, math, malloc, stdio, stdlib). The other library I'm working on has more complicated dependencies. For example, I'll try to use fftw3. As a test, I'll just try to compile a simple .cpp file containing: int foo() { void *p = fftw_malloc( sizeof(fftw_complex)*64 ); fftw_free(p); printf("foo called.\n"); return 0; } I compile it as: icpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link icpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o cp waveprop.so.1.0 /usr/local/lib/ rm waveprop.so.1.0 ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1 This all works. Now I test it with another .cpp file containing: int main() { foo(); } Result: icpc test.cpp -lwaveprop /lib/../lib64/libwaveprop.so: undefined reference to `fftw_free' /lib/../lib64/libwaveprop.so: undefined reference to `fftw_malloc' Which is entirely reasonable. Next I try: icpc test.cpp -lwaveprop -lfftw3 ./a.out foo called. Great! But now when I try to load the library with ctypes: >>> from ctypes import * >>> print cdll.LoadLibrary('/usr/local/lib/libwaveprop.so.1') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib64/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: /usr/local/lib/libwaveprop.so.1: undefined symbol: fftw_free So it's the same problem, but I have no idea how to resolve it for ctypes. I've tried various things without any success, and I'm pretty stuck at this point. A: OK, thanks for your help. to get this to work I had to include the dependencies when linking (duh). I had tried this before but got an error, so solve this I had to recompile fftw with '-fpic' as a CPP flag. all works now. icpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link icpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o -lfftw3 cp waveprop.so.1.0 /usr/local/lib/ rm waveprop.so.1.0 ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1 thanks, -nick A: You need to link libwaveprop.so itself against the fftw3 library. Otherwise Python simply won't know where to go to get those missing symbols; mind-reading isn't implemented in any programming language.
Python ctypes and dynamic linking
I'm writing some libraries in C which contain functions that I want to call from Python via ctypes. I've done this successfully another library, but that library had only very vanilla dependencies (namely fstream, math, malloc, stdio, stdlib). The other library I'm working on has more complicated dependencies. For example, I'll try to use fftw3. As a test, I'll just try to compile a simple .cpp file containing: int foo() { void *p = fftw_malloc( sizeof(fftw_complex)*64 ); fftw_free(p); printf("foo called.\n"); return 0; } I compile it as: icpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link icpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o cp waveprop.so.1.0 /usr/local/lib/ rm waveprop.so.1.0 ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so ln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1 This all works. Now I test it with another .cpp file containing: int main() { foo(); } Result: icpc test.cpp -lwaveprop /lib/../lib64/libwaveprop.so: undefined reference to `fftw_free' /lib/../lib64/libwaveprop.so: undefined reference to `fftw_malloc' Which is entirely reasonable. Next I try: icpc test.cpp -lwaveprop -lfftw3 ./a.out foo called. Great! But now when I try to load the library with ctypes: >>> from ctypes import * >>> print cdll.LoadLibrary('/usr/local/lib/libwaveprop.so.1') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib64/python2.6/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: /usr/local/lib/libwaveprop.so.1: undefined symbol: fftw_free So it's the same problem, but I have no idea how to resolve it for ctypes. I've tried various things without any success, and I'm pretty stuck at this point.
[ "OK, thanks for your help.\nto get this to work I had to include the dependencies when linking (duh). I had tried this before but got an error, so solve this I had to recompile fftw with '-fpic' as a CPP flag. all works now.\nicpc -Wall -fPIC -c waveprop.cpp -o libwaveprop.o $std_link\nicpc -shared -Wl,-soname,libwaveprop.so.1 -o libwaveprop.so.1.0 libwaveprop.o -lfftw3\n\ncp waveprop.so.1.0 /usr/local/lib/\nrm waveprop.so.1.0\nln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so\nln -sf /usr/local/lib/waveprop.so.1.0 /usr/local/lib/waveprop.so.1\n\nthanks,\n-nick\n", "You need to link libwaveprop.so itself against the fftw3 library. Otherwise Python simply won't know where to go to get those missing symbols; mind-reading isn't implemented in any programming language.\n" ]
[ 4, 0 ]
[]
[]
[ "ctypes", "dynamic_linking", "python" ]
stackoverflow_0002606450_ctypes_dynamic_linking_python.txt
Q: Django vs. Pylons I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. Any suggestions? Pylons maybe? A: I'm using Pylons right now. The flexibility is great. It's all about best-of-breed rather than The Django Way. It's more oriented toward custom application development, as opposed to content-based web sites. You can certainly do content sites in it; it's just not specifically designed for them. On the other hand, you do end up needing to read a lot of different documentation, in different places, of different quality, to grok all the components. Whereas one of the nice things about Django is that for all the core components, you just read "the" documentation. The Mako (templates) + SQLAlchemy (DB & ORM) combo is really nice, though. Back when I used Django, I replaced its templating and DB system with them (giving up some of its integration features in the process) and they are standard with Pylons. Mako lets you use Python expressions, which is nice because even though you should separate business logic from design, dynamic sites do require significant display logic, and Django's template tags are clumsy to work with. SQLAlchemy lets you work with the same data model anywhere from the raw SQL level to the object-oriented ORM level. I think it's worth the time to at least go through the docs and do the QuickWiki tutorial. A: Pylons is not that much simpler than Django and it doesn't seem to have the same community. For lightweight apps I would recommend web.py. Even though there is a little magic, it doesn't feel like it. You see everything you do. For lots of other ideas see this very current list of web resources on python. A: Something as simple as adding CSS classes to Django form fields IS possible. A: With the risk of going a bit off-topic here, "I want to be able (and free) to do something as simple as adding a css class to an auto-generated form" might not be the best indicator of the power (or lack of power) of a framework. Form generation is notoriously hard to do in a flexible way (cf. http://blog.ianbicking.org/on-form-libraries.html), and frameworks will always need to weigh ease-of-use versus supporting advanced use-cases. I've used form generation in Pylons before, and didn't find it to be particularly better or easier than how things work in Django (but not harder either).
Django vs. Pylons
I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. Any suggestions? Pylons maybe?
[ "I'm using Pylons right now. The flexibility is great. It's all about best-of-breed rather than The Django Way. It's more oriented toward custom application development, as opposed to content-based web sites. You can certainly do content sites in it; it's just not specifically designed for them.\nOn the other hand, you do end up needing to read a lot of different documentation, in different places, of different quality, to grok all the components. Whereas one of the nice things about Django is that for all the core components, you just read \"the\" documentation.\nThe Mako (templates) + SQLAlchemy (DB & ORM) combo is really nice, though. Back when I used Django, I replaced its templating and DB system with them (giving up some of its integration features in the process) and they are standard with Pylons. Mako lets you use Python expressions, which is nice because even though you should separate business logic from design, dynamic sites do require significant display logic, and Django's template tags are clumsy to work with. SQLAlchemy lets you work with the same data model anywhere from the raw SQL level to the object-oriented ORM level.\nI think it's worth the time to at least go through the docs and do the QuickWiki tutorial.\n", "Pylons is not that much simpler than Django and it doesn't seem to have the same community. For lightweight apps I would recommend web.py. Even though there is a little magic, it doesn't feel like it. You see everything you do. For lots of other ideas see this very current list of web resources on python.\n", "Something as simple as adding CSS classes to Django form fields IS possible.\n", "With the risk of going a bit off-topic here, \"I want to be able (and free) to do something as simple as adding a css class to an auto-generated form\" might not be the best indicator of the power (or lack of power) of a framework. Form generation is notoriously hard to do in a flexible way (cf. http://blog.ianbicking.org/on-form-libraries.html), and frameworks will always need to weigh ease-of-use versus supporting advanced use-cases. I've used form generation in Pylons before, and didn't find it to be particularly better or easier than how things work in Django (but not harder either).\n" ]
[ 20, 5, 1, 1 ]
[]
[]
[ "django", "grails", "pylons", "python" ]
stackoverflow_0001344824_django_grails_pylons_python.txt
Q: Help with python list-comprehension A simplified version of my problem: I have a list comprehension that i use to set bitflags on a two dimensional list so: s = FLAG1 | FLAG2 | FLAG3 [[c.set_state(s) for c in row] for row in self.__map] All set_state does is: self.state |= f This works fine but I have to have this function "set_state" in every cell in __map. Every cell in __map has a .state so what I'm trying to do is something like: [[c.state |= s for c in row] for row in self.map] or map(lambda c: c.state |= s, [c for c in row for row in self.__map]) Except that neither works (Syntax error). Perhaps I'm barking up the wrong tree with map/lamda but I would like to get rid on set_state. And perhaps know why assignment does not work in the list-comprehension A: List comprehensions are for creating lists. You don't seem to care about the actual lists you are making, so you should just use a for statement, like so: for row in self.__map: for c in row: c.state |= s A: Yes, you're using the wrong tool. A list comprehension returns a completely new value, so you might be able to do this: self.__map = [[c.state | s for c in row] for row in self.__map] But my instinct is that you should just be using two for loops: for row in self.__map: for c in row: c.state |= s In a list comprehension, the result has to be an expression. That's because your double comprehension is just sugar for this: list1 = [] for row in self.__map: list2 = [] for c in row: list2.append(c.state | s) list1.append(list2) self.__map = list1 It makes no sense to say list2.append(c.state |= s) Because the innermost expression has to return something to be appended to list2. Basically, the list comprehensions make a complete new copy of self.__map each time you update the flags. If that's what you want, then go with it. But I suspect you just want to change the existing map. In that case, use the double for loops. A: You don't want a list comprehension, since you're modifying your data in-place, not creating a new list. Do a loop. A: Use the setattr function: setattr(c, "state", s) And then read up on Statementless Python. A: In python assignments are statements, not expressions which are only allowed in lambdas and list comprehension.
Help with python list-comprehension
A simplified version of my problem: I have a list comprehension that i use to set bitflags on a two dimensional list so: s = FLAG1 | FLAG2 | FLAG3 [[c.set_state(s) for c in row] for row in self.__map] All set_state does is: self.state |= f This works fine but I have to have this function "set_state" in every cell in __map. Every cell in __map has a .state so what I'm trying to do is something like: [[c.state |= s for c in row] for row in self.map] or map(lambda c: c.state |= s, [c for c in row for row in self.__map]) Except that neither works (Syntax error). Perhaps I'm barking up the wrong tree with map/lamda but I would like to get rid on set_state. And perhaps know why assignment does not work in the list-comprehension
[ "List comprehensions are for creating lists. You don't seem to care about the actual lists you are making, so you should just use a for statement, like so:\nfor row in self.__map:\n for c in row:\n c.state |= s\n\n", "Yes, you're using the wrong tool. A list comprehension returns a completely new value, so you might be able to do this:\nself.__map = [[c.state | s for c in row] for row in self.__map]\n\nBut my instinct is that you should just be using two for loops:\nfor row in self.__map:\n for c in row:\n c.state |= s\n\nIn a list comprehension, the result has to be an expression. That's because your double comprehension is just sugar for this:\nlist1 = []\nfor row in self.__map:\n list2 = []\n for c in row:\n list2.append(c.state | s)\n list1.append(list2)\nself.__map = list1\n\nIt makes no sense to say\n list2.append(c.state |= s)\n\nBecause the innermost expression has to return something to be appended to list2.\nBasically, the list comprehensions make a complete new copy of self.__map each time you update the flags. If that's what you want, then go with it. But I suspect you just want to change the existing map. In that case, use the double for loops.\n", "You don't want a list comprehension, since you're modifying your data in-place, not creating a new list.\nDo a loop.\n", "Use the setattr function:\nsetattr(c, \"state\", s)\n\nAnd then read up on Statementless Python.\n", "In python assignments are statements, not expressions which are only allowed in lambdas and list comprehension.\n" ]
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "lambda", "list_comprehension", "python" ]
stackoverflow_0002607488_lambda_list_comprehension_python.txt
Q: Access to content of Lotus Notes database without Lotus Notes software installed I am looking for a programatic way to access content in a Lotus Notes database (.nsf file) without having Lotus Notes software installed. Python would be preferred but I'm also willing to look at other languages e.g. C/C++ or other means e.g. SQL From what I have read, all of the methods e.g. Python COM access, pyodbc rely on having Lotus Notes server software installed. The problem I am trying to solve is to read the content and look for references (URL's back to a web site that is undergoing maintenance and the addresses in the web site will change) As a start, I want to get a list of references and hope to be able to replace them with the new references to the modified web site. Any ideas on how best to do this welcome :) A: The short answer is, unfortunately you will need the Notes client installed. There are a few ways to access data from an NSF such as NotesSQL, COM, C/C++, but all rely on the Lotus C API at the core, and you'll need a notes client and a notes ID file to gain access via that API. A: If this is a one-time need, you may be able to find sites that will do some simple Domino/Notes hosting for free. If you could put the NSF up to a service like that, you could then use Domino URL's (REST) to extract the data and search for links, etc. A: Like Ken says, inevitably there has to be a server in the mix. If you're searching for specific text in a Notes / Domino application, and looking to replace it, there's a tool out there which does this: Teamstudio Configurator. Configurator also has an API (written in Lotusscript, which is very like old-skool VB) so you can code a solution pretty quickly. I've done the exact same thing you're doing with an old Domino-based website, using this API. Not the answer you're looking for I guess, but always good to have choices!
Access to content of Lotus Notes database without Lotus Notes software installed
I am looking for a programatic way to access content in a Lotus Notes database (.nsf file) without having Lotus Notes software installed. Python would be preferred but I'm also willing to look at other languages e.g. C/C++ or other means e.g. SQL From what I have read, all of the methods e.g. Python COM access, pyodbc rely on having Lotus Notes server software installed. The problem I am trying to solve is to read the content and look for references (URL's back to a web site that is undergoing maintenance and the addresses in the web site will change) As a start, I want to get a list of references and hope to be able to replace them with the new references to the modified web site. Any ideas on how best to do this welcome :)
[ "The short answer is, unfortunately you will need the Notes client installed. There are a few ways to access data from an NSF such as NotesSQL, COM, C/C++, but all rely on the Lotus C API at the core, and you'll need a notes client and a notes ID file to gain access via that API. \n", "If this is a one-time need, you may be able to find sites that will do some simple Domino/Notes hosting for free. If you could put the NSF up to a service like that, you could then use Domino URL's (REST) to extract the data and search for links, etc.\n", "Like Ken says, inevitably there has to be a server in the mix. If you're searching for specific text in a Notes / Domino application, and looking to replace it, there's a tool out there which does this: Teamstudio Configurator.\nConfigurator also has an API (written in Lotusscript, which is very like old-skool VB) so you can code a solution pretty quickly. I've done the exact same thing you're doing with an old Domino-based website, using this API.\nNot the answer you're looking for I guess, but always good to have choices!\n" ]
[ 3, 1, 0 ]
[]
[]
[ "lotus", "lotus_notes", "python" ]
stackoverflow_0002541702_lotus_lotus_notes_python.txt
Q: Django syncdb error: One or more models did not validate /mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error saying Error: One or more models did not validate: project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'. How can this be solved.. thanks.. A: Gee we just had this one; and I answered... You have a number of foreign keys which django is unable to generate unique names for. You can help out by adding "related_name" arguments to the foreignkey field definitions in your models. Eg: class notes(models.Model): created_by = models.ForeignKey(User, related_name="note_created_by_user") detail = models.ForeignKey(Details, related_name="noted_and_detailed") See here for more. http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
Django syncdb error: One or more models did not validate
/mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error saying Error: One or more models did not validate: project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'. How can this be solved.. thanks..
[ "Gee we just had this one; and I answered...\nYou have a number of foreign keys which django is unable to generate unique names for.\nYou can help out by adding \"related_name\" arguments to the foreignkey field definitions in your models. Eg:\n class notes(models.Model):\n created_by = models.ForeignKey(User, related_name=\"note_created_by_user\")\n detail = models.ForeignKey(Details, related_name=\"noted_and_detailed\")\n\nSee here for more. http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name\n" ]
[ 8 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002608017_django_django_models_django_views_python.txt
Q: Best option for Google App Engine Datastore and external database? I need to get an App Engine app talking to and sharing data with an external database, The best option i can come up with is outputting the external database data to an xml file and then processing this in my app engine app and storing it inside the datastore, although the data being shared is sensitive data such as login details so outputting this to an xml file is not exactly a great idea, is it possible for the app engine app to directly query the database? or is there a secure option for using xml files? oh and im using python/django and the external database will be hosted on another domain A: Google Apps' Secure Data Connector (SDC) is designed for this kind of tasks -- indeed, it even works when the "other database" lives behind a firewall (a common case for enterprise data), and for other Google Apps (Docs, Spreadsheets, ...) as well as App Engine. As the docs summarize things, the flow is: Google Apps forwards authorized data requests from users who are within the Google Apps domain to the Google tunnel protocol servers. The tunnel servers validate that a user is authorized to make the request to the specified resource. Google tunnel servers are connected by an encrypted tunnel to SDC, which runs within a company's internal network. The tunnel protocol allows SDC to connect to a Google tunnel server, authenticate, and encrypt the data that flows across the Internet. SDC uses resource rules to validate if a user is authorized to make a request to a specified resource. An optional intranet firewall can be used to provide extra network security. SDC performs a network request to the specified resource or services. The service validates the signed request, checks the credentials, and if the user is authorized, returns the data. If you don't have to worry about firewalls, and have no security worries whatsoever, you can simplify things (as Daniel's answer suggests) by just using urlfetch directly (no tunnels, no validation, no encryption, no filtering, ...) -- but your worry about "the data being shared is sensitive data such as login details" suggests that this is not the case. It's not a problem of XML vs other formats -- the problem is that sensitive data should not travel "in clear" over unprotected channels, nor be made available to all and sundry, and it's often nicer to have specialized infrastructure deal with encryption, filtering, and authorization problems, as the SDC does, rather than having to code all of this (and make it totally secure and locked-down) in your own app or specialized infrastructure middleware. For these purposes, the SDC can be very helpful, even if you only need a fraction of its functionality. A: You may want to consider exposing a set of web services on the external domain where your database is hosted, and then use the App Engine's URL Fetch API to communicate with your external domain via HTTPS.
Best option for Google App Engine Datastore and external database?
I need to get an App Engine app talking to and sharing data with an external database, The best option i can come up with is outputting the external database data to an xml file and then processing this in my app engine app and storing it inside the datastore, although the data being shared is sensitive data such as login details so outputting this to an xml file is not exactly a great idea, is it possible for the app engine app to directly query the database? or is there a secure option for using xml files? oh and im using python/django and the external database will be hosted on another domain
[ "Google Apps' Secure Data Connector (SDC) is designed for this kind of tasks -- indeed, it even works when the \"other database\" lives behind a firewall (a common case for enterprise data), and for other Google Apps (Docs, Spreadsheets, ...) as well as App Engine.\nAs the docs summarize things, the flow is:\n\nGoogle Apps forwards authorized data\nrequests from users who are within\nthe Google Apps domain to the Google\ntunnel protocol servers.\nThe tunnel servers validate that a\nuser is authorized to make the\nrequest to the specified resource.\nGoogle tunnel servers are connected\nby an encrypted tunnel to SDC, which\nruns within a company's internal\nnetwork.\nThe tunnel protocol allows SDC to\nconnect to a Google tunnel server,\nauthenticate, and encrypt the data\nthat flows across the Internet.\nSDC uses resource rules to validate\nif a user is authorized to make a\nrequest to a specified resource.\nAn optional intranet firewall can be\nused to provide extra network\nsecurity.\nSDC performs a network request to\nthe specified resource or services.\nThe service validates the signed\nrequest, checks the credentials, and\nif the user is authorized, returns\nthe data.\n\nIf you don't have to worry about firewalls, and have no security worries whatsoever, you can simplify things (as Daniel's answer suggests) by just using urlfetch directly (no tunnels, no validation, no encryption, no filtering, ...) -- but your worry about \"the data being shared is sensitive data such as login details\" suggests that this is not the case.\nIt's not a problem of XML vs other formats -- the problem is that sensitive data should not travel \"in clear\" over unprotected channels, nor be made available to all and sundry, and it's often nicer to have specialized infrastructure deal with encryption, filtering, and authorization problems, as the SDC does, rather than having to code all of this (and make it totally secure and locked-down) in your own app or specialized infrastructure middleware. For these purposes, the SDC can be very helpful, even if you only need a fraction of its functionality.\n", "You may want to consider exposing a set of web services on the external domain where your database is hosted, and then use the App Engine's URL Fetch API to communicate with your external domain via HTTPS.\n" ]
[ 6, 3 ]
[]
[]
[ "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002606707_django_google_app_engine_google_cloud_datastore_python.txt
Q: What's the right way to use idlestartup on python 2.6.5? Idlestartup is analogous to pythonstartup variable, but for IDLE, instead of command line. But it seems not to work properly. I'm using python 2.6.5 on Windows. I have the following script assigned to it: from pprint import pprint import sys newPath = 'C:\\Python26\test') sys.path.append(newPath) print "initial config loaded" Both variables Idlestartup and pythonstartup are assigned to the same file (script above). When running IDLE, pprint and sys are NOT available, the final message is NOT printed, but newPath was added to sys.path. Running the command line, pprint and sys are available, the final message is printed and newPath was added to sys.path. Is it a bug? Am I doing something wrong? Thanks A: sys.stdout may not be in its final state at the time idlestartup's getting loaded - so it's quite possible that a print to it tries to go to the "original" standard-output, and then immediately the standard output is redirected to idle's command window and so the effects of the print are never seen. In other words, no bugs, I think -- it's just not obvious how idlestartup may be guaranteed to send an important message to the user, if delivery of that message must be guaranteed (a message such as your example is no big deal, but if you did have important ones I'd look into Tk ways of delivering them in a guaranteed way). Edit: as for making sure that certain names are added to the main namespace, the latter's named __main__ (both with and without idle), so adding to your code a few statements such as sys.modules['__main__'].pprint = pprint &c should work.
What's the right way to use idlestartup on python 2.6.5?
Idlestartup is analogous to pythonstartup variable, but for IDLE, instead of command line. But it seems not to work properly. I'm using python 2.6.5 on Windows. I have the following script assigned to it: from pprint import pprint import sys newPath = 'C:\\Python26\test') sys.path.append(newPath) print "initial config loaded" Both variables Idlestartup and pythonstartup are assigned to the same file (script above). When running IDLE, pprint and sys are NOT available, the final message is NOT printed, but newPath was added to sys.path. Running the command line, pprint and sys are available, the final message is printed and newPath was added to sys.path. Is it a bug? Am I doing something wrong? Thanks
[ "sys.stdout may not be in its final state at the time idlestartup's getting loaded - so it's quite possible that a print to it tries to go to the \"original\" standard-output, and then immediately the standard output is redirected to idle's command window and so the effects of the print are never seen. In other words, no bugs, I think -- it's just not obvious how idlestartup may be guaranteed to send an important message to the user, if delivery of that message must be guaranteed (a message such as your example is no big deal, but if you did have important ones I'd look into Tk ways of delivering them in a guaranteed way).\nEdit: as for making sure that certain names are added to the main namespace, the latter's named __main__ (both with and without idle), so adding to your code a few statements such as\nsys.modules['__main__'].pprint = pprint\n\n&c should work.\n" ]
[ 4 ]
[]
[]
[ "python", "startup" ]
stackoverflow_0002608092_python_startup.txt
Q: Problems with umlauts in python appdata environvent variable I can't find a correct way to get the environment variable for the appdata path in python. The problem is that my user name includes special characters (the german ae and ue). I made a workaround wit PyQt for Vista and Windows 7 but it doesn't work for XP Systems. Does anybody know the correct encoding of these environment variables or another solution for this problem? A: As Mike says, you can get the system codepage from getfilesystemencoding. This encoding is used to convert Windows's native Unicode strings into bytes for all C stdio functions used by Python, including the filesystem calls that use byte string filepaths, and os.environ. What this means is that you will be able to read a string with non-ASCII characters from os.environ and use it directly as a filepath without any special encode/decode step. Unfortunately, if the %APPDATA% variable contains Unicode characters that are not present in the system codepage — for example, if on a German (cp1252) Windows install, your path was C:\Documents and Settings\αβγ\Application Data — then those characters will have already been mangled before you get the chance to use them. Decoding the byte string you get to Unicode using the filesystemencoding won't help in that case. Here's a function you can use on recent Python versions that have the ctypes extension, to read Windows native Unicode environment variables. def getEnvironmentVariable(name): name= unicode(name) # make sure string argument is unicode n= ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0) if n==0: return None buf= ctypes.create_unicode_buffer(u'\0'*n) ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n) return buf.value In Python 3, the os.environ dictionary contains Unicode strings taken directly from Windows with no codepage encoding, so you don't have to worry about this problem there.
Problems with umlauts in python appdata environvent variable
I can't find a correct way to get the environment variable for the appdata path in python. The problem is that my user name includes special characters (the german ae and ue). I made a workaround wit PyQt for Vista and Windows 7 but it doesn't work for XP Systems. Does anybody know the correct encoding of these environment variables or another solution for this problem?
[ "As Mike says, you can get the system codepage from getfilesystemencoding. This encoding is used to convert Windows's native Unicode strings into bytes for all C stdio functions used by Python, including the filesystem calls that use byte string filepaths, and os.environ.\nWhat this means is that you will be able to read a string with non-ASCII characters from os.environ and use it directly as a filepath without any special encode/decode step.\nUnfortunately, if the %APPDATA% variable contains Unicode characters that are not present in the system codepage — for example, if on a German (cp1252) Windows install, your path was C:\\Documents and Settings\\αβγ\\Application Data — then those characters will have already been mangled before you get the chance to use them. Decoding the byte string you get to Unicode using the filesystemencoding won't help in that case.\nHere's a function you can use on recent Python versions that have the ctypes extension, to read Windows native Unicode environment variables.\ndef getEnvironmentVariable(name):\n name= unicode(name) # make sure string argument is unicode\n n= ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)\n if n==0:\n return None\n buf= ctypes.create_unicode_buffer(u'\\0'*n)\n ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n)\n return buf.value\n\nIn Python 3, the os.environ dictionary contains Unicode strings taken directly from Windows with no codepage encoding, so you don't have to worry about this problem there.\n" ]
[ 10 ]
[]
[]
[ "appdata", "encoding", "environment", "python", "variables" ]
stackoverflow_0002608200_appdata_encoding_environment_python_variables.txt
Q: Getting the attribute name that the created object will be given Before I ask this, do note: I want this for debugging purposes. I know that this is going to be some bad black magic, but I want to use it just during debugging so I could identify my objects more easily. It's like this. I have some object from class A that creates a few B instances as attributes: class A(object): def __init__(self) self.vanilla_b = B() self.chocolate_b = B() class B(object): def __init__(self): # ... What I want is that in B.__init__, it will figure out the "vanilla_b" or whatever attribute name it was given, and then put that as the .name attribute to this specific B. Then in debugging when I see some B object floating around, I could know which one it is. Is there any way to do this? A: You can use sys._getframe to get the line number where B() is called, then you can use inspect.getsourcelines to get the actual line of code. From there you can parse the line of code to get the thing to which B() is being assigned: import sys import inspect class A(object): def __init__(self): self.vanilla_b = B() self.chocolate_b = B() class B(object): def __init__(self): line_num = sys._getframe().f_back.f_lineno lines = inspect.getsourcelines( sys.modules[__name__] )[0] line = lines[line_num - 1] attr = line.split("=")[0].split(".")[1].strip() print "B() is being assigned to", attr A() If you put the above code into a python script and run it, then it will print B() is being assigned to vanilla_b B() is being assigned to chocolate_b However, this won't work at the Python command prompt, since __main__ is a builtin module, and thus the inspect module can't retrieve its source lines. So you might want to wrap this in a try/catch block or something just in case your code ever gets called from any builtin module. For the record, this is probably a bad idea, but you say that you're aware that it's not good practice and you're only doing it for debugging, so hopefully you'll be able to use this kind of trickery wisely. A: This is probably not the answer you are looking for but perhaps you could do something along this: class A(object): def __init__(self): attrs = ('vanilla_b', 'chocolate_b') for attr in attrs: instance = B() setattr(self, attr, instance) instance.name = attr Try wrapping that behavior to some superclass and you might be good to go. A: If you have control over code then it is better to do it simply then rely on some black magic e.g. do class A(object): def __init__(self) self.vanilla_b = B(name="vanilla_b") self.chocolate_b = B(name="chocolate_b") otherwise you can use inspect module to go thru locals and self in prev frame and do some vodoo.
Getting the attribute name that the created object will be given
Before I ask this, do note: I want this for debugging purposes. I know that this is going to be some bad black magic, but I want to use it just during debugging so I could identify my objects more easily. It's like this. I have some object from class A that creates a few B instances as attributes: class A(object): def __init__(self) self.vanilla_b = B() self.chocolate_b = B() class B(object): def __init__(self): # ... What I want is that in B.__init__, it will figure out the "vanilla_b" or whatever attribute name it was given, and then put that as the .name attribute to this specific B. Then in debugging when I see some B object floating around, I could know which one it is. Is there any way to do this?
[ "You can use sys._getframe to get the line number where B() is called, then you can use inspect.getsourcelines to get the actual line of code. From there you can parse the line of code to get the thing to which B() is being assigned:\nimport sys\nimport inspect\n\nclass A(object):\n def __init__(self):\n self.vanilla_b = B()\n self.chocolate_b = B()\n\nclass B(object):\n def __init__(self):\n line_num = sys._getframe().f_back.f_lineno\n lines = inspect.getsourcelines( sys.modules[__name__] )[0]\n line = lines[line_num - 1]\n attr = line.split(\"=\")[0].split(\".\")[1].strip()\n print \"B() is being assigned to\", attr\n\nA()\n\nIf you put the above code into a python script and run it, then it will print\nB() is being assigned to vanilla_b\nB() is being assigned to chocolate_b\n\nHowever, this won't work at the Python command prompt, since __main__ is a builtin module, and thus the inspect module can't retrieve its source lines. So you might want to wrap this in a try/catch block or something just in case your code ever gets called from any builtin module.\nFor the record, this is probably a bad idea, but you say that you're aware that it's not good practice and you're only doing it for debugging, so hopefully you'll be able to use this kind of trickery wisely.\n", "This is probably not the answer you are looking for but perhaps you could do something along this:\nclass A(object):\n def __init__(self):\n attrs = ('vanilla_b', 'chocolate_b')\n\n for attr in attrs:\n instance = B()\n setattr(self, attr, instance)\n instance.name = attr\n\nTry wrapping that behavior to some superclass and you might be good to go.\n", "If you have control over code then it is better to do it simply then rely on some black magic e.g. do\nclass A(object):\n def __init__(self)\n self.vanilla_b = B(name=\"vanilla_b\")\n self.chocolate_b = B(name=\"chocolate_b\")\n\notherwise you can use inspect module to go thru locals and self in prev frame and do some vodoo.\n" ]
[ 2, 0, 0 ]
[ "Not very magical, but:\nclass A(object):\n def __init__(self)\n self.vanilla_b = B(self)\n self.chocolate_b = B(self)\n\nand:\nclass B(object):\n def __init__(self, a):\n for i in dir(a):\n if getattr(a, i) == self:\n pass # store it somewhere now\n\nEDIT: Sorry, this won't work. B.init is executed before references in A are set.\n" ]
[ -1 ]
[ "debugging", "introspection", "magic_methods", "python" ]
stackoverflow_0002608645_debugging_introspection_magic_methods_python.txt
Q: GUI freezes when executing def function. Use threads? I've made a small program which has 2 buttons and each does certain thing. Here's a simplified version of the code. Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed. As far as I know threads would be best to use in this situation, but I have no idea how to implement it in this example. I use glade and pygtk for gui. def do1: t = 2 #do something time.sleep(t) #do something time.sleep(t) def do2: t = 3 #do something time.sleep(t) #do something time.sleep(t) class we: wTree = None def __init__( self ): self.wTree = gtk.glade.XML( "ui.glade" ) dic = { "on_buttonSone" : self.sone, "on_buttonStwo" : self.stwo, } self.wTree.signal_autoconnect( dic ) gtk.main() def sone(self, widget): i = 0 while i < 3: t = 1 #do something i += 1 time.sleep(t) self.wTree.get_widget("entryResult").set_text("Done.") def stwo(self, widget): start = time.clock() array = ['A','B'] adict = {'A':do1,'B':do2} for f in array: adict[f]() end = time.clock() elapsed = end - start gg = round(elapsed,2) self.wTree.get_widget("entryResult").set_text(str(gg)) go=we() A: pyGTK has a whole section of there FAQ devoted to threading. 20.6 seems like a good minimal example.
GUI freezes when executing def function. Use threads?
I've made a small program which has 2 buttons and each does certain thing. Here's a simplified version of the code. Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed. As far as I know threads would be best to use in this situation, but I have no idea how to implement it in this example. I use glade and pygtk for gui. def do1: t = 2 #do something time.sleep(t) #do something time.sleep(t) def do2: t = 3 #do something time.sleep(t) #do something time.sleep(t) class we: wTree = None def __init__( self ): self.wTree = gtk.glade.XML( "ui.glade" ) dic = { "on_buttonSone" : self.sone, "on_buttonStwo" : self.stwo, } self.wTree.signal_autoconnect( dic ) gtk.main() def sone(self, widget): i = 0 while i < 3: t = 1 #do something i += 1 time.sleep(t) self.wTree.get_widget("entryResult").set_text("Done.") def stwo(self, widget): start = time.clock() array = ['A','B'] adict = {'A':do1,'B':do2} for f in array: adict[f]() end = time.clock() elapsed = end - start gg = round(elapsed,2) self.wTree.get_widget("entryResult").set_text(str(gg)) go=we()
[ "pyGTK has a whole section of there FAQ devoted to threading. \n20.6 seems like a good minimal example.\n" ]
[ 0 ]
[]
[]
[ "glade", "pygtk", "python" ]
stackoverflow_0002608922_glade_pygtk_python.txt
Q: Splitting tuples in Python - best practice? I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me) A: @Staale There is a better way: job = dict(zip(keys, values)) A: I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: job={} job['jobid'], job['label'], job['username']=<querycode> A: This is an old question, but... I'd suggest using a named tuple in this situation: collections.namedtuple This is the part, in particular, that you'd find useful: Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute. A: Perhaps this is overkill for your case, but I would be tempted to create a "Job" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead. A: I would use a dictionary. You can convert the tuple to a dictionary this way: values = <querycode> keys = ["jobid", "label", "username"] job = dict([[keys[i], values [i]] for i in xrange(len(values ))]) This will first create an array [["jobid", val1], ["label", val2], ["username", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result. PS still fresh on Python myself, so there might be better ways off doing this. A: An old question, but since no one mentioned it I'll add this from the Python Cookbook: Recipe 81252: Using dtuple for Flexible Query Result Access This recipe is specifically designed for dealing with database results, and the dtuple solution allows you to access the results by name OR index number. This avoids having to access everything by subscript which is very difficult to maintain, as noted in your question. A: With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better. If you want something with slightly friendlier syntax you might want to take a look at the answers this question about a simple 'struct-like' object. That way you can pass around an object, say job, and access its fields even more easily than a tuple or dict: job.jobId, job.username = jobId, username A: If you're using the MySQLdb package, you can set up your cursor objects to return dicts instead of tuples. import MySQLdb, MySQLdb.cursors conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor) cur = conn.cursor() # a DictCursor cur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a "normal" tuple cursor
Splitting tuples in Python - best practice?
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
[ "@Staale\nThere is a better way:\njob = dict(zip(keys, values))\n\n", "I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.\nFor example:\njob={}\njob['jobid'], job['label'], job['username']=<querycode>\n\n", "This is an old question, but...\nI'd suggest using a named tuple in this situation: collections.namedtuple\nThis is the part, in particular, that you'd find useful:\n\nSubclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute.\n\n", "Perhaps this is overkill for your case, but I would be tempted to create a \"Job\" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.\n", "I would use a dictionary. You can convert the tuple to a dictionary this way:\nvalues = <querycode>\nkeys = [\"jobid\", \"label\", \"username\"]\njob = dict([[keys[i], values [i]] for i in xrange(len(values ))])\n\nThis will first create an array [[\"jobid\", val1], [\"label\", val2], [\"username\", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result.\nPS still fresh on Python myself, so there might be better ways off doing this.\n", "An old question, but since no one mentioned it I'll add this from the Python Cookbook: \nRecipe 81252: Using dtuple for Flexible Query Result Access \nThis recipe is specifically designed for dealing with database results, and the dtuple solution allows you to access the results by name OR index number. This avoids having to access everything by subscript which is very difficult to maintain, as noted in your question.\n", "With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better. \nIf you want something with slightly friendlier syntax you might want to take a look at the answers this question about a simple 'struct-like' object. That way you can pass around an object, say job, and access its fields even more easily than a tuple or dict:\njob.jobId, job.username = jobId, username\n\n", "If you're using the MySQLdb package, you can set up your cursor objects to return dicts instead of tuples.\nimport MySQLdb, MySQLdb.cursors\nconn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)\ncur = conn.cursor() # a DictCursor\ncur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a \"normal\" tuple cursor\n\n" ]
[ 14, 13, 5, 3, 2, 2, 0, 0 ]
[ "How about this:\nclass TypedTuple:\n def __init__(self, fieldlist, items):\n self.fieldlist = fieldlist\n self.items = items\n def __getattr__(self, field):\n return self.items[self.fieldlist.index(field)]\n\nYou could then do:\nj = TypedTuple([\"jobid\", \"label\", \"username\"], job)\nprint j.jobid\n\nIt should be easy to swap self.fieldlist.index(field) with a dictionary lookup later on... just edit your __init__ method! Something like Staale does.\n" ]
[ -2 ]
[ "python", "tuples" ]
stackoverflow_0000041701_python_tuples.txt
Q: Python: needs more than 1 value to unpack What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacements["@@"] = ("<code>", "</code>") for delimiter, (open_tag, close_tag) in replacements: # error here message = self.replaceFormatting(delimiter, message, open_tag, close_tag); The error: Traceback (most recent call last): File "", line 1, in for doot, (a, b) in replacements: ValueError: need more than 1 value to unpack All the values tuples have two values. Right? A: It should be: for delimiter, (open_tag, close_tag) in replacements.iteritems(): # or .items() in py3k A: I think you need to call .items() like the third example in this link for delimiter, (open_tag, close_tag) in replacements.items(): # error here message = self.replaceFormatting(delimiter, message, open_tag, close_tag)
Python: needs more than 1 value to unpack
What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacements["@@"] = ("<code>", "</code>") for delimiter, (open_tag, close_tag) in replacements: # error here message = self.replaceFormatting(delimiter, message, open_tag, close_tag); The error: Traceback (most recent call last): File "", line 1, in for doot, (a, b) in replacements: ValueError: need more than 1 value to unpack All the values tuples have two values. Right?
[ "It should be:\nfor delimiter, (open_tag, close_tag) in replacements.iteritems(): # or .items() in py3k\n\n", "I think you need to call .items() like the third example in this link\nfor delimiter, (open_tag, close_tag) in replacements.items(): # error here\n message = self.replaceFormatting(delimiter, message, open_tag, close_tag)\n\n" ]
[ 10, 3 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002609136_python_syntax.txt
Q: Problem with literal arguments in the PATTERN string for a python 2to3 fixer I'm writing a fixer for the 2to3 tool in python. In my pattern string, I have a section where I'd like to match an empty string as an argument, or an empty unicode string. The relevant chunk of my pattern looks like: (args='""' | args='u""') My issue is the second option never matches. Even if it's alone, it won't match. However, if I simply say args=any and then output args, I can catch cases where args is exactly equal to the second option. Is there some weird unicode handling thing going on? Why won't the second literal option ever match? A: Because 2to3 pattern matching is designed to match tokens not literals, there is no way to do this directly. Instead you could match (args=STRING) and then determine the value of the string argument inside the transformation function and handle it appropriately.
Problem with literal arguments in the PATTERN string for a python 2to3 fixer
I'm writing a fixer for the 2to3 tool in python. In my pattern string, I have a section where I'd like to match an empty string as an argument, or an empty unicode string. The relevant chunk of my pattern looks like: (args='""' | args='u""') My issue is the second option never matches. Even if it's alone, it won't match. However, if I simply say args=any and then output args, I can catch cases where args is exactly equal to the second option. Is there some weird unicode handling thing going on? Why won't the second literal option ever match?
[ "Because 2to3 pattern matching is designed to match tokens not literals, there is no way to do this directly.\nInstead you could match (args=STRING) and then determine the value of the string argument inside the transformation function and handle it appropriately.\n" ]
[ 1 ]
[]
[]
[ "pattern_matching", "python", "python_2to3", "special_characters", "unicode" ]
stackoverflow_0002588286_pattern_matching_python_python_2to3_special_characters_unicode.txt
Q: Converting string with UTC offset to a datetime object Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object? After doing some reading I feel like this should work, but it doesn't... >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fmt) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z' It should be noted that this works without a problem: >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50' >>> fmt = '%a, %d %b %Y %H:%M:%S' >>> datetime.strptime(str, fmt) datetime.datetime(2010, 4, 9, 14, 10, 50) But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way. A: It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform. Note: from Python 3.2 onwards it will always work.
Converting string with UTC offset to a datetime object
Given this string: "Fri, 09 Apr 2010 14:10:50 +0000" how does one convert it to a datetime object? After doing some reading I feel like this should work, but it doesn't... >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fmt) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z' It should be noted that this works without a problem: >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50' >>> fmt = '%a, %d %b %Y %H:%M:%S' >>> datetime.strptime(str, fmt) datetime.datetime(2010, 4, 9, 14, 10, 50) But I'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way.
[ "It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.\nNote: from Python 3.2 onwards it will always work.\n" ]
[ 40 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002609259_datetime_python.txt
Q: Running a python script on all the files in a directory I have a Python script that reads through a text csv file and creates a playlist file. However I can only do one at a time, like: python playlist.py foo.csv foolist.txt However, I have a directory of files that need to be made into a playlist, with different names, and sometimes a different number of files. So far I have looked at creating a txt file with a list of all the names of the file in the directory, then loop through each line of that, however I know there must be an easier way to do it. A: for f in *.csv; do python playlist.py "$f" "${f%.csv}list.txt" done Will that do the trick? This will put foo.csv in foolist.txt and abc.csv in abclist.txt. Or do you want them all in the same file? A: Just use a for loop with the asterisk glob, making sure you quote things appropriately for spaces in filenames for file in *.csv; do python playlist.py "$file" >> outputfile.txt; done A: Is it a single directory, or nested? Ex. topfile.csv topdir --dir1 --file1.csv --file2.txt --dir2 --file3.csv --file4.csv For nested, you can use os.walk(topdir) to get all the files and dirs recursively within a directory. You could set up your script to accept dirs or files: python playlist.py topfile.csv topdir import sys import os def main(): files_toprocess = set() paths = sys.argv[1:] for p in paths: if os.path.isfile(p) and p.endswith('.csv'): files_toprocess.add(p) elif os.path.isdir(p): for root, dirs, files in os.walk(p): files_toprocess.update([os.path.join(root, f) for f in files if f.endswith('.csv')]) A: if you have directory name you can use os.listdir os.listdir(dirname) if you want to select only a certain type of file, e.g., only csv file you could use glob module.
Running a python script on all the files in a directory
I have a Python script that reads through a text csv file and creates a playlist file. However I can only do one at a time, like: python playlist.py foo.csv foolist.txt However, I have a directory of files that need to be made into a playlist, with different names, and sometimes a different number of files. So far I have looked at creating a txt file with a list of all the names of the file in the directory, then loop through each line of that, however I know there must be an easier way to do it.
[ "for f in *.csv; do\n python playlist.py \"$f\" \"${f%.csv}list.txt\"\ndone\n\nWill that do the trick? This will put foo.csv in foolist.txt and abc.csv in abclist.txt.\nOr do you want them all in the same file?\n", "Just use a for loop with the asterisk glob, making sure you quote things appropriately for spaces in filenames\nfor file in *.csv; do\n python playlist.py \"$file\" >> outputfile.txt;\ndone\n\n", "Is it a single directory, or nested?\nEx.\ntopfile.csv\ntopdir\n --dir1\n --file1.csv\n --file2.txt\n --dir2\n --file3.csv\n --file4.csv\n\nFor nested, you can use os.walk(topdir) to get all the files and dirs recursively within a directory.\nYou could set up your script to accept dirs or files:\npython playlist.py topfile.csv topdir\nimport sys\nimport os\n\ndef main():\n files_toprocess = set()\n paths = sys.argv[1:]\n for p in paths:\n if os.path.isfile(p) and p.endswith('.csv'):\n files_toprocess.add(p)\n elif os.path.isdir(p):\n for root, dirs, files in os.walk(p):\n files_toprocess.update([os.path.join(root, f) \n for f in files if f.endswith('.csv')])\n\n", "if you have directory name you can use os.listdir\nos.listdir(dirname)\n\nif you want to select only a certain type of file, e.g., only csv file you could use glob module.\n" ]
[ 11, 6, 4, 2 ]
[]
[]
[ "command_line", "python", "scripting" ]
stackoverflow_0002609159_command_line_python_scripting.txt
Q: How to correctly relay TCP traffic between sockets? I'm trying to write some Python code that will establish an invisible relay between two TCP sockets. My current technique is to set up two threads, each one reading and subsequently writing 1kb of data at a time in a particular direction (i.e. 1 thread for A to B, 1 thread for B to A). This works for some applications and protocols, but it isn't foolproof - sometimes particular applications will behave differently when running through this Python-based relay. Some even crash. I think that this is because when I finish performing a read on socket A, the program running there considers its data to have already arrived at B, when in fact I - the devious man in the middle - have yet to send it to B. In a situation where B isn't ready to receive the data (whereby send() blocks for a while), we are now in a state where A believes it has successfully sent data to B, yet I am still holding the data, waiting for the send() call to execute. I think this is the cause of the difference in behaviour that I've found in some applications, while using my current relaying code. Have I missed something, or does that sound correct? If so, my real question is: is there a way around this problem? Is it possible to only read from socket A when we know that B is ready to receive data? Or is there another technique that I can use to establish a truly 'invisible' two-way relay between [already open & established] TCP sockets? A: Is it possible to only read from socket A when we know that B is ready to receive data? Sure: use select.select on both sockets A and B (if it returns saying only one of them is ready, use it on the other one), and only read from A and write to B when you know they're both ready. E.g.: import select def fromAtoB(A, B): r, w = select.select([A], [B], []) if not r: select.select([A], [], []) elif not w: select.select([], [B], []) B.sendall(A.recv(4096)) A: I don't think that's likely to be your problem. In general, the sending application can't tell when the receiving application actually calls recv() to read the data: the sender's send() may have completed, but the TCP implementations in the source & destination OS will be doing buffering, flow control, retransmission, etc. Even without your relay in the middle, the only way for A to "consider its data to have already arrived at B" is to receive a response from B saying "yep, I got it". A: Perhaps the application you're proxying is poorly written. For instance, if I call recv(fd, buf, 4096, 0); I'm not promised 4096 bytes. The system makes a best-effort to provide it. If 1k isn't a multiple of your application's recv or send sizes, and the application is broken, then grouping the data sent into 1k blocks will break the app.
How to correctly relay TCP traffic between sockets?
I'm trying to write some Python code that will establish an invisible relay between two TCP sockets. My current technique is to set up two threads, each one reading and subsequently writing 1kb of data at a time in a particular direction (i.e. 1 thread for A to B, 1 thread for B to A). This works for some applications and protocols, but it isn't foolproof - sometimes particular applications will behave differently when running through this Python-based relay. Some even crash. I think that this is because when I finish performing a read on socket A, the program running there considers its data to have already arrived at B, when in fact I - the devious man in the middle - have yet to send it to B. In a situation where B isn't ready to receive the data (whereby send() blocks for a while), we are now in a state where A believes it has successfully sent data to B, yet I am still holding the data, waiting for the send() call to execute. I think this is the cause of the difference in behaviour that I've found in some applications, while using my current relaying code. Have I missed something, or does that sound correct? If so, my real question is: is there a way around this problem? Is it possible to only read from socket A when we know that B is ready to receive data? Or is there another technique that I can use to establish a truly 'invisible' two-way relay between [already open & established] TCP sockets?
[ "\nIs it possible to only read from\n socket A when we know that B is ready\n to receive data?\n\nSure: use select.select on both sockets A and B (if it returns saying only one of them is ready, use it on the other one), and only read from A and write to B when you know they're both ready. E.g.:\nimport select\n\ndef fromAtoB(A, B):\n r, w = select.select([A], [B], [])\n if not r: select.select([A], [], [])\n elif not w: select.select([], [B], [])\n B.sendall(A.recv(4096))\n\n", "I don't think that's likely to be your problem. \nIn general, the sending application can't tell when the receiving application actually calls recv() to read the data: the sender's send() may have completed, but the TCP implementations in the source & destination OS will be doing buffering, flow control, retransmission, etc. \nEven without your relay in the middle, the only way for A to \"consider its data to have already arrived at B\" is to receive a response from B saying \"yep, I got it\".\n", "Perhaps the application you're proxying is poorly written.\nFor instance, if I call recv(fd, buf, 4096, 0); I'm not promised 4096 bytes. The system makes a best-effort to provide it.\nIf 1k isn't a multiple of your application's recv or send sizes, and the application is broken, then grouping the data sent into 1k blocks will break the app.\n" ]
[ 5, 1, 1 ]
[]
[]
[ "portforwarding", "python", "sockets", "tcp" ]
stackoverflow_0002604740_portforwarding_python_sockets_tcp.txt
Q: Python Mindstorms RCX I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kits with RCX bricks - not the newer NXT ones, so most of the projects like NXT_Python can't help me. Is there any way to make that happen? A: Running Python on the brick itself is probably hard (for the reason others already stated - size of the interpreter, available RAM on the brick for example) but this might be of interest: According to this thread you should be able to use pylnp (remote) combined with BrickOS (on the brick; formerly legOS). A: I doubt it. The RCX bricks used an 8 bit microcontroller. While it might be possible to run some sort of a Python interpreter on it, I haven't seen one ported to it. The closest you can get is Java: http://lejos.sourceforge.net/ So theoretically, you could look at Jython and try to run class files compiled with it on the lejos JVM... Sounds like a long shot, though. The microcontroller in an RCX brick just doesn't have a whole lot of room for a big runtime.
Python Mindstorms RCX
I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kits with RCX bricks - not the newer NXT ones, so most of the projects like NXT_Python can't help me. Is there any way to make that happen?
[ "Running Python on the brick itself is probably hard (for the reason others already stated - size of the interpreter, available RAM on the brick for example) but this might be of interest:\nAccording to this thread you should be able to use pylnp (remote) combined with BrickOS (on the brick; formerly legOS).\n", "I doubt it.\nThe RCX bricks used an 8 bit microcontroller. While it might be possible to run some sort of a Python interpreter on it, I haven't seen one ported to it.\nThe closest you can get is Java:\nhttp://lejos.sourceforge.net/\nSo theoretically, you could look at Jython and try to run class files compiled with it on the lejos JVM... Sounds like a long shot, though. The microcontroller in an RCX brick just doesn't have a whole lot of room for a big runtime.\n" ]
[ 3, 2 ]
[]
[]
[ "lego_mindstorms", "python" ]
stackoverflow_0002596929_lego_mindstorms_python.txt
Q: "cannot concatenate 'str' and 'list' objects" keeps coming up :( I'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program: #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgi import cgitb cgitb.enable() def template(file, **vars): return open(file, 'r').read() % vars print "Content-type: text/html\n" print form = cgi.FieldStorage() # instantiate only once! num_1 = form.getfirst('num_1') num_2 = form.getfirst('num_2') int1r = str(num_1) int2r = str(num_2) def calc_range(int2r, int1r): start = range(int2r, int1r + 1) end = range(1, int2r) return start+end int1 = int(int1r) int2 = int(int2r) out_str = '' for i in range(0, int1): first_line_num = (int2 + i) % int1 if first_line_num == 0: first_line_num = int1 line = calc_range(first_line_num, int1) out_str += line print template('results.html', output=out_str, title="Latin Squares") A: range returns a list object, so when you say line = calc_range(first_line_num, int1) You are assigning a list to line. This is why out_str += line throws the error. You can use str() to convert a list to a string, or you can build up a string a different way to get the results you are looking for. A: By doing out_str += line, you're trying to add a list (from calc_range) to a string. I don't even know what this is supposed to be doing, but that's where the problem lies. A: You didn't say what line you're getting the error from, but I'm guessing it's: out_str += line The first variable is a string. The second is a list of numbers. You can't concatenate a list onto a string. I don't know what you're trying to do exactly, but how about: out_str += ", ".join(line) That will add the numbers joined by commas onto out_str. A: calc_range() returns a list; however, you are attempting to add it to a string (out_str). It looks like your code is unfinished - don't you want to do something with the range of numbers returned by calc_range()? Like, say, something with the form? line = ''.join(num_1[index] for index in calc_range(first_line_num, int1)) I don't know if that's what you want - but maybe something like that?
"cannot concatenate 'str' and 'list' objects" keeps coming up :(
I'm writing a python program. The program calculates Latin Squares using two numbers the user enters on a previous page. But but an error keeps coming up, "cannot concatenate 'str' and 'list' objects" here is the program: #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgi import cgitb cgitb.enable() def template(file, **vars): return open(file, 'r').read() % vars print "Content-type: text/html\n" print form = cgi.FieldStorage() # instantiate only once! num_1 = form.getfirst('num_1') num_2 = form.getfirst('num_2') int1r = str(num_1) int2r = str(num_2) def calc_range(int2r, int1r): start = range(int2r, int1r + 1) end = range(1, int2r) return start+end int1 = int(int1r) int2 = int(int2r) out_str = '' for i in range(0, int1): first_line_num = (int2 + i) % int1 if first_line_num == 0: first_line_num = int1 line = calc_range(first_line_num, int1) out_str += line print template('results.html', output=out_str, title="Latin Squares")
[ "range returns a list object, so when you say \nline = calc_range(first_line_num, int1)\n\nYou are assigning a list to line. This is why out_str += line throws the error.\nYou can use str() to convert a list to a string, or you can build up a string a different way to get the results you are looking for.\n", "By doing out_str += line, you're trying to add a list (from calc_range) to a string. I don't even know what this is supposed to be doing, but that's where the problem lies.\n", "You didn't say what line you're getting the error from, but I'm guessing it's:\nout_str += line\n\nThe first variable is a string. The second is a list of numbers. You can't concatenate a list onto a string. I don't know what you're trying to do exactly, but how about:\nout_str += \", \".join(line)\n\nThat will add the numbers joined by commas onto out_str.\n", "calc_range() returns a list; however, you are attempting to add it to a string (out_str).\nIt looks like your code is unfinished - don't you want to do something with the range of numbers returned by calc_range()? Like, say, something with the form?\nline = ''.join(num_1[index] for index in calc_range(first_line_num, int1))\n\nI don't know if that's what you want - but maybe something like that?\n" ]
[ 4, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002609460_python.txt
Q: What are the differences among sqlite3 from python2.5, pysqlite and apsw I would like to know the differences among sqlite3 from python2.5, pysqlite and apsw? I have a bumpy run when trying to install pysqlite on windows vista with python2.5, see following: download sqlite from http://sqlite.org/download.html and unzip them into windows/system32 folder and put sqlite3.dll into c:/python25/Lib folder download pysqlite windows installer when trying to run following in python shell: >>> from pysqlite2 import test Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pysqlite2\test\__init__.py", line 35, in <module> from pysqlite2.test import dbapi, types, userfunctions, factory, transactions,\ File "pysqlite2\test\dbapi.py", line 27, in <module> import pysqlite2.dbapi2 as sqlite File "pysqlite2\dbapi2.py", line 27, in <module> from pysqlite2._sqlite import * ImportError: No module named _sqlite I am wondering anybody with experiences of the above three types of sqlite binding to python can comment their pros and cons such as performances I am wondering is it worthwhile to try the pysqlite or apsw thanks A: pysqlite is the same as sqlite3 (which is built in to the windows binary package for python 2.5) A: Still, the pysqlite site-package includes more patches. It is version 2.6.0 whereas the built-in module is version 2.3.2. The error when importing pysqlite2.test may occur if you are in the pysqlite package directory (i've read somewhere). The difference with apsw is best explained on http://code.google.com/p/apsw
What are the differences among sqlite3 from python2.5, pysqlite and apsw
I would like to know the differences among sqlite3 from python2.5, pysqlite and apsw? I have a bumpy run when trying to install pysqlite on windows vista with python2.5, see following: download sqlite from http://sqlite.org/download.html and unzip them into windows/system32 folder and put sqlite3.dll into c:/python25/Lib folder download pysqlite windows installer when trying to run following in python shell: >>> from pysqlite2 import test Traceback (most recent call last): File "<stdin>", line 1, in <module> File "pysqlite2\test\__init__.py", line 35, in <module> from pysqlite2.test import dbapi, types, userfunctions, factory, transactions,\ File "pysqlite2\test\dbapi.py", line 27, in <module> import pysqlite2.dbapi2 as sqlite File "pysqlite2\dbapi2.py", line 27, in <module> from pysqlite2._sqlite import * ImportError: No module named _sqlite I am wondering anybody with experiences of the above three types of sqlite binding to python can comment their pros and cons such as performances I am wondering is it worthwhile to try the pysqlite or apsw thanks
[ "pysqlite is the same as sqlite3 (which is built in to the windows binary package for python 2.5)\n", "Still, the pysqlite site-package includes more patches. It is version 2.6.0 whereas the built-in module is version 2.3.2. The error when importing pysqlite2.test may occur if you are in the pysqlite package directory (i've read somewhere). \nThe difference with apsw is best explained on http://code.google.com/p/apsw \n" ]
[ 3, 2 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0002608958_pysqlite_python_sqlite.txt
Q: smtp text message code not sending I have a python code to send a text message to your cellphone using SMTP. when I run it I don't get any errors, but it doesn't send the text message. My code isn't finished, right now I am just getting the basics down. Any help on making it send would be appreciated. #infile = open('companyname.txt', 'r') import sys import smtplib li_name = ["3 RIVER WIRELESS", "ACS WIRELESS", "ADVANTAGE COMMUNICATIONS", "AIRTOUCH PAGERS", "ALPHNOW", "ALLTEL", "ALLTELL PCS", "AMERITECH PAGING", "AMERITECH MESSAGING", "AMERITECH CLEARPATH", "ARCH PAGERS", "AT&T", "AT&T FREE2GO", "AT&T PCS", "AT&T POCKETNET PCS", "BELL MOBILITY", "BELL SOUTH BLACKBERRY", "BELL SOUTH MOBILITY", "BOOST", "CELLULAR ONE EAST COAST", "CELLULAR ONE SOUTH WEST", "CELLULAR ONE PCS", "CELLULAR ONE", "CELLULAR ONE WEST", "CELLULAR SOUTH", "CENTENNIAL WIRELESS", "CINGULAR", "CINGULAR WIRELESS", "COMCAST", "HOUSTON CELLULAR", "ILLINOIS VALLY CELLULAR", "NEXTELL", "SPRINT", "SPRINT PCS", "T-MOBILE", "TRACFONE", "VERIZON PAGERS", "VERIZON", "VIRGIN MOBILE", "VIRGIN MOBILE CANADA"] li_num = ["@sms.3rivers.net", "@paging.acswireless.com", "@advantagepaging.com", "@alphapage.airtouch.com", "@alphanow.net", "@message.alltel.com", "@message.alltel.com", "@paging.acswireless.com", "@page.americanmessaging.net", "@clearpath.acswireless.com", "@archwireless.net", "@txt.att.net", "@mmode.com", "@mobile.att.net", "@dpcs.mobile.att.net", "@txt.bellmobility.ca", "@bellsouthtips.com", "@blsdcs.net", "@myboostmobile.com", "@phone.cellone.net", "@swmsg.com", "@paging.cellone-sf.com", "@mobile.celloneusa.com", "@mycellone.com", "@csouth1.com", "@cwemail.com", "@mycingular.com", "@mycingular.textmsg.com", "@comcastpcs.textmsg.com", "@text.houstoncellular.net", "@ivctext.com", "@messaging.nextel.com", "@sprintpaging.com", "@messaging.sprintpcs.com", "@tmomail.net", "@txt.att.net", "@myairmail.com", "@vtext.com", "@vmobl.com", "@vmobile.ca"] again = 'y' while again == 'y': company_domain = '' usr_company = str.upper(raw_input("Enter company: ")) if usr_company in li_name: idx = li_name.index(usr_company) company_domain = li_num[idx] usr_number = raw_input("Enter phone number: ") text_adr = usr_number + company_domain sender = raw_input('enter "from" E-Mail address: ') #if smtplib.SMTPSenderRefused(SMTPResponseException): #print ('your email has been rejected by the server') reciever = text_adr message = ('Testing') smtpObj = smtplib.SMTP('smtp.comcast.net') smtpObj.sendmail(sender,reciever , message) print "Successfully sent email" smtpObj.quit() else: text_adr = "Company Not Found" print ("your phone's email is:") print text_adr again = raw_input('Do you want to ask again?') while again != 'y' and again != 'n': print ('sorry that is an invalid answer!') again = raw_input('Do you want to ask again?') print #old code: #addr_from = raw_input ('enter your email address') #addr_to = text_adr #SMTP = 'smtp.comcast.net' #msg = ('From: %s\r\nTo: %s\r\n\r\n' #% (addr_from, ', '.join(addr_to))) #msg = msg + 'This is the message' #SMTP.sendmail(addr_from, addr_to, msg) A: Start with the basics, enable debugging for the smtp object and see what you get. smtpObj = smtplib.SMTP('smtp.comcast.net') smtpObj.set_debuglevel(10) smtpObj.sendmail(sender,reciever , message) You can read about the set_debuglevel call here. A: Change smtpObj.sendmail(sender,reciever , message) to smtpObj.sendmail(sender,[reciever] , message) since the second argument to sendmail should be a list of email addresses. PS: You might want to change reciever to receiver too... :)
smtp text message code not sending
I have a python code to send a text message to your cellphone using SMTP. when I run it I don't get any errors, but it doesn't send the text message. My code isn't finished, right now I am just getting the basics down. Any help on making it send would be appreciated. #infile = open('companyname.txt', 'r') import sys import smtplib li_name = ["3 RIVER WIRELESS", "ACS WIRELESS", "ADVANTAGE COMMUNICATIONS", "AIRTOUCH PAGERS", "ALPHNOW", "ALLTEL", "ALLTELL PCS", "AMERITECH PAGING", "AMERITECH MESSAGING", "AMERITECH CLEARPATH", "ARCH PAGERS", "AT&T", "AT&T FREE2GO", "AT&T PCS", "AT&T POCKETNET PCS", "BELL MOBILITY", "BELL SOUTH BLACKBERRY", "BELL SOUTH MOBILITY", "BOOST", "CELLULAR ONE EAST COAST", "CELLULAR ONE SOUTH WEST", "CELLULAR ONE PCS", "CELLULAR ONE", "CELLULAR ONE WEST", "CELLULAR SOUTH", "CENTENNIAL WIRELESS", "CINGULAR", "CINGULAR WIRELESS", "COMCAST", "HOUSTON CELLULAR", "ILLINOIS VALLY CELLULAR", "NEXTELL", "SPRINT", "SPRINT PCS", "T-MOBILE", "TRACFONE", "VERIZON PAGERS", "VERIZON", "VIRGIN MOBILE", "VIRGIN MOBILE CANADA"] li_num = ["@sms.3rivers.net", "@paging.acswireless.com", "@advantagepaging.com", "@alphapage.airtouch.com", "@alphanow.net", "@message.alltel.com", "@message.alltel.com", "@paging.acswireless.com", "@page.americanmessaging.net", "@clearpath.acswireless.com", "@archwireless.net", "@txt.att.net", "@mmode.com", "@mobile.att.net", "@dpcs.mobile.att.net", "@txt.bellmobility.ca", "@bellsouthtips.com", "@blsdcs.net", "@myboostmobile.com", "@phone.cellone.net", "@swmsg.com", "@paging.cellone-sf.com", "@mobile.celloneusa.com", "@mycellone.com", "@csouth1.com", "@cwemail.com", "@mycingular.com", "@mycingular.textmsg.com", "@comcastpcs.textmsg.com", "@text.houstoncellular.net", "@ivctext.com", "@messaging.nextel.com", "@sprintpaging.com", "@messaging.sprintpcs.com", "@tmomail.net", "@txt.att.net", "@myairmail.com", "@vtext.com", "@vmobl.com", "@vmobile.ca"] again = 'y' while again == 'y': company_domain = '' usr_company = str.upper(raw_input("Enter company: ")) if usr_company in li_name: idx = li_name.index(usr_company) company_domain = li_num[idx] usr_number = raw_input("Enter phone number: ") text_adr = usr_number + company_domain sender = raw_input('enter "from" E-Mail address: ') #if smtplib.SMTPSenderRefused(SMTPResponseException): #print ('your email has been rejected by the server') reciever = text_adr message = ('Testing') smtpObj = smtplib.SMTP('smtp.comcast.net') smtpObj.sendmail(sender,reciever , message) print "Successfully sent email" smtpObj.quit() else: text_adr = "Company Not Found" print ("your phone's email is:") print text_adr again = raw_input('Do you want to ask again?') while again != 'y' and again != 'n': print ('sorry that is an invalid answer!') again = raw_input('Do you want to ask again?') print #old code: #addr_from = raw_input ('enter your email address') #addr_to = text_adr #SMTP = 'smtp.comcast.net' #msg = ('From: %s\r\nTo: %s\r\n\r\n' #% (addr_from, ', '.join(addr_to))) #msg = msg + 'This is the message' #SMTP.sendmail(addr_from, addr_to, msg)
[ "Start with the basics, enable debugging for the smtp object and see what you get.\nsmtpObj = smtplib.SMTP('smtp.comcast.net') \nsmtpObj.set_debuglevel(10)\nsmtpObj.sendmail(sender,reciever , message)\n\nYou can read about the set_debuglevel call here.\n", "Change\nsmtpObj.sendmail(sender,reciever , message)\n\nto\nsmtpObj.sendmail(sender,[reciever] , message)\n\nsince the second argument to sendmail should be a list of email addresses.\nPS: You might want to change reciever to receiver too... :)\n" ]
[ 1, 1 ]
[]
[]
[ "message", "python", "smtp", "text" ]
stackoverflow_0002609879_message_python_smtp_text.txt
Q: Dumping one class type with Django dumpdata I use dumpdata to output all my apps's classes. One of my app has one class that never get's outputted and I don't know where to start looking to know what's wrong. The class is used regularly, every other classes in the app are dumped fine and dumpdata doesn't throw any error. Any clue ? A: You might try serializing it to json and see if you get any errors there -- maybe there's a subtle inconsistency that's messing up the serialization. >>> from django.core import serializers >>> from myapp.mymodels import mymodel >>> serializers.serialize('json', mymodel.objects.all()) [...] This might be worth a try too: >>> serializers.serialize('python', mymodel.objects.all()) [...]
Dumping one class type with Django dumpdata
I use dumpdata to output all my apps's classes. One of my app has one class that never get's outputted and I don't know where to start looking to know what's wrong. The class is used regularly, every other classes in the app are dumped fine and dumpdata doesn't throw any error. Any clue ?
[ "You might try serializing it to json and see if you get any errors there -- maybe there's a subtle inconsistency that's messing up the serialization.\n>>> from django.core import serializers\n>>> from myapp.mymodels import mymodel\n>>> serializers.serialize('json', mymodel.objects.all())\n[...]\n\nThis might be worth a try too:\n>>> serializers.serialize('python', mymodel.objects.all())\n[...]\n\n" ]
[ 1 ]
[]
[]
[ "django", "dump", "python" ]
stackoverflow_0002603427_django_dump_python.txt
Q: Fast math operations on an array in python I have a fairly simple math operation I'd like to perform on a array. Let me write out the example: A = numpy.ndarray((255, 255, 3), dtype=numpy.single) # .. for i in range(A.shape[0]): for j in range(A.shape[1]): x = simple_func1(i) y = simple_func2(j) A[i, j] = (alpha * x * y + beta * x**2 + gamma * y**2, 1, 0) So basically, there's a mapping between (i, j) and the 3 values of that value (this is for visualization). I'd like to roll this up and somehow vectorize this, but I'm not sure how to or if I can. Thanks. A: Here is the vectorized version: i = arange(255) j = arange(255) x = simple_func1(i) y = simple_func2(j) y = y.reshape(-1,1) A = alpha * x * y + beta * x**2 + gamma * y**2 # broadcasting is your friend here If you want to fill the last coordinates with 1 and 0: B = empty(A.shape+(3,)) B[:,:,0] = A B[:,:,1] = 1 # broadcasting again B[:,:,2] = 0 A: You have to change simple_funcN so that they take arrays as input, and create arrays as output. After that, you could look into the numpy.meshgrid() or the cartesian() function here to build coordinate arrays. After that, you should be able to use the coordinate array(s) to fill A with a one-liner.
Fast math operations on an array in python
I have a fairly simple math operation I'd like to perform on a array. Let me write out the example: A = numpy.ndarray((255, 255, 3), dtype=numpy.single) # .. for i in range(A.shape[0]): for j in range(A.shape[1]): x = simple_func1(i) y = simple_func2(j) A[i, j] = (alpha * x * y + beta * x**2 + gamma * y**2, 1, 0) So basically, there's a mapping between (i, j) and the 3 values of that value (this is for visualization). I'd like to roll this up and somehow vectorize this, but I'm not sure how to or if I can. Thanks.
[ "Here is the vectorized version:\ni = arange(255)\nj = arange(255)\nx = simple_func1(i)\ny = simple_func2(j)\ny = y.reshape(-1,1) \n\nA = alpha * x * y + beta * x**2 + gamma * y**2 # broadcasting is your friend here\n\nIf you want to fill the last coordinates with 1 and 0:\nB = empty(A.shape+(3,))\nB[:,:,0] = A\nB[:,:,1] = 1 # broadcasting again\nB[:,:,2] = 0\n\n", "You have to change simple_funcN so that they take arrays as input, and create arrays as output. After that, you could look into the numpy.meshgrid() or the cartesian() function here to build coordinate arrays. After that, you should be able to use the coordinate array(s) to fill A with a one-liner.\n" ]
[ 3, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002610184_numpy_python.txt
Q: Python Script to check website for a tag I'm trying to figure out how to go about writing a website monitoring script (cron job in the end) to open up a given URL, check to see if a tag exists, and if the tag does not exist, or doesn't contain the expected data, then to write some to a log file, or to send an e-mail. The tag would be something like or something relatively similar. Anyone have any ideas? A: Your best bet imo is to check out BeautifulSoup. Something like so: import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://yoursite.com") soup = BeautifulSoup(page) # See the docs on how to search through the soup. I'm not sure what # you're looking for so my example stops here :) After that, emailing it or logging it is pretty standard fare. A: This is a sample code (untested) that log and send mail: #!/usr/bin/env python import logging import urllib2 import smtplib #Log config logging.basicConfig(filename='/tmp/yourscript.log',level=logging.INFO,) #Open requested url url = "http://yoursite.com/tags/yourTag" data = urllib2.urlopen(url) if check_content(data): #Report to log logging.info('Content found') else: #Send mail send_mail('Content not found') def check_content(data): #Your BeautifulSoup logic here return content_found def send_mail(message_body): server = 'localhost' recipients = ['you@yourdomain.com'] sender = 'script@yourdomain.com' message = 'From: %s \n Subject: script result \n\n %s' % (sender, message_body) session = smtplib.SMTP(server) session.sendmail(sender,recipients,message); I would code check_content() function using beautifulSoup A: The following (untested) code uses urllib2 to grab the page and re to search it. import urllib2,StringIO pageString = urllib2.urlopen('**insert url here**').read() m = re.search(r'**insert regex for the tag you want to find here**',pageString) if m == None: #take action for NOT found here else: #take action for found here The following (untested) code uses pycurl and StringIO to grab the page and re to search it. import pycurl,re,StringIO b = StringIO.StringIO() c = pycurl.Curl() c.setopt(pycurl.URL, '**insert url here**') c.setopt(pycurl.WRITEFUNCTION, b.write) c.perform() c.close() m = re.search(r'**insert regex for the tag you want to find here**',b.getvalue()) if m == None: #take action for NOT found here else: #take action for found here
Python Script to check website for a tag
I'm trying to figure out how to go about writing a website monitoring script (cron job in the end) to open up a given URL, check to see if a tag exists, and if the tag does not exist, or doesn't contain the expected data, then to write some to a log file, or to send an e-mail. The tag would be something like or something relatively similar. Anyone have any ideas?
[ "Your best bet imo is to check out BeautifulSoup. Something like so:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://yoursite.com\")\nsoup = BeautifulSoup(page)\n\n# See the docs on how to search through the soup. I'm not sure what\n# you're looking for so my example stops here :)\n\nAfter that, emailing it or logging it is pretty standard fare.\n", "This is a sample code (untested) that log and send mail:\n#!/usr/bin/env python\nimport logging\nimport urllib2\nimport smtplib\n\n#Log config\nlogging.basicConfig(filename='/tmp/yourscript.log',level=logging.INFO,)\n\n#Open requested url\nurl = \"http://yoursite.com/tags/yourTag\"\ndata = urllib2.urlopen(url)\n\nif check_content(data):\n #Report to log\n logging.info('Content found')\nelse:\n #Send mail\n send_mail('Content not found')\n\ndef check_content(data):\n #Your BeautifulSoup logic here\n return content_found\n\ndef send_mail(message_body):\n server = 'localhost'\n recipients = ['you@yourdomain.com']\n sender = 'script@yourdomain.com'\n message = 'From: %s \\n Subject: script result \\n\\n %s' % (sender, message_body)\n session = smtplib.SMTP(server)\n session.sendmail(sender,recipients,message);\n\nI would code check_content() function using beautifulSoup\n", "The following (untested) code uses urllib2 to grab the page and re to search it.\nimport urllib2,StringIO\n\npageString = urllib2.urlopen('**insert url here**').read()\nm = re.search(r'**insert regex for the tag you want to find here**',pageString)\nif m == None:\n #take action for NOT found here\nelse:\n #take action for found here\n\nThe following (untested) code uses pycurl and StringIO to grab the page and re to search it.\nimport pycurl,re,StringIO\n\nb = StringIO.StringIO()\nc = pycurl.Curl()\nc.setopt(pycurl.URL, '**insert url here**')\nc.setopt(pycurl.WRITEFUNCTION, b.write)\nc.perform()\nc.close()\nm = re.search(r'**insert regex for the tag you want to find here**',b.getvalue())\nif m == None:\n #take action for NOT found here\nelse:\n #take action for found here\n\n" ]
[ 5, 2, 1 ]
[]
[]
[ "crontab", "html", "linux", "python", "scripting" ]
stackoverflow_0002610395_crontab_html_linux_python_scripting.txt
Q: Hide deprecated methods from tab completion I would like to control which methods appear when a user uses tab-completion on a custom object in ipython - in particular, I want to hide functions that I have deprecated. I still want these methods to be callable, but I don't want users to see them and start using them if they are inspecting the object. Is this something that is possible? A: Partial answer for you. I'll post the example code and then explain why its only a partial answer. Code: class hidden(object): # or whatever its parent class is def __init__(self): self.value = 4 def show(self): return self.value def change(self,n): self.value = n def __getattr__(self, attrname): # put the dep'd method/attribute names here deprecateds = ['dep_show','dep_change'] if attrname in deprecateds: print("These aren't the methods you're looking for.") def dep_change(n): self.value = n def dep_show(): return self.value return eval(attrname) else: raise AttributeError, attrname So now the caveat: they're not methods (note the lack of self as the first variable). If you need your users (or your code) to be able to call im_class, im_func, or im_self on any of your deprecated methods, then this hack won't work. Also, i'm pretty sure there's going to be a performance hit because you're defining each dep'd function inside __getattr__. This won't affect your other attribute lookups (had I put them in __getattribute__, that would be a different matter), but it will slow down access to those deprecated methods. This can be (largely, but not entirely) negated by putting each function definition inside its own if block, instead of doing a list-membership check, but, depending on how big your function is, that could be really annoying to maintain. UPDATE: 1) If you want to make the deprecated functions methods (and you do), just use import types return types.MethodType(eval(attrname), self) instead of return eval(attrname) in the above snippet, and add self as the first argument to the function defs. It turns them into instancemethods (so you can use im_class, im_func, and im_self to your heart's content). 2) If the __getattr__ hook didn't thrill you, there's another option (that I know of) (albiet, with its own caveats, and we'll get to those): Put the deprecated functions definitions inside __init__, and hide them with a custom __dir__. Here's what the above code would look like done this way: class hidden(object): def __init__(self): self.value = 4 from types import MethodType def dep_show(self): return self.value self.__setattr__('dep_show', MethodType(dep_show, self)) def dep_change(self, n): self.value = n self.__setattr__('dep_change', MethodType(dep_change, self)) def show(self): return self.value def change(self, n): self.value = n def __dir__(self): heritage = dir(super(self.__class__, self)) # inherited attributes hide = ['dep_show', 'dep_change'] show = [k for k in self.__class__.__dict__.keys() + self.__dict__.keys() if not k in heritage + private] return sorted(heritage + show) The advantage here is that you're not defining the functions anew every lookup, which nets you speed. The disadvantage here is that because you're not defining functions anew each lookup, they have to 'persist' (if you will). So, while the custom __dir__ method hides your deprecateds from dir(hiddenObj) and, therefore, IPython's tab-completion, they still exist in the instance's __dict__ attribute, where users can discover them. A: Seems like there is a special magic method for the introcpection which is called by dir(): __dir__(). Isn't it what you are lookin for? A: The DeprecationWarning isn't emitted until the method is called, so you'd have to have a separate attribute on the class that stores the names of deprecated methods, then check that before suggesting a completion. Alternatively, you could walk the AST for the method looking for DeprecationWarning, but that will fail if either the class is defined in C, or if the method may emit a DeprecationWarning based on the type or value of the arguments. A: About the completion mechanism in IPython, it is documented here: http://ipython.scipy.org/doc/manual/html/api/generated/IPython.core.completer.html#ipcompleter But a really interesting example for you is the traits completer, that does precisely what you want to do: it hides some methods (based on their names) from the autocompletion. Here is the code: http://projects.scipy.org/ipython/ipython/browser/ipython/trunk/IPython/Extensions/ipy_traits_completer.py
Hide deprecated methods from tab completion
I would like to control which methods appear when a user uses tab-completion on a custom object in ipython - in particular, I want to hide functions that I have deprecated. I still want these methods to be callable, but I don't want users to see them and start using them if they are inspecting the object. Is this something that is possible?
[ "Partial answer for you. I'll post the example code and then explain why its only a partial answer.\nCode:\nclass hidden(object): # or whatever its parent class is\n def __init__(self):\n self.value = 4\n def show(self):\n return self.value\n def change(self,n):\n self.value = n\n def __getattr__(self, attrname):\n # put the dep'd method/attribute names here\n deprecateds = ['dep_show','dep_change']\n if attrname in deprecateds:\n print(\"These aren't the methods you're looking for.\")\n def dep_change(n):\n self.value = n\n def dep_show():\n return self.value\n return eval(attrname)\n else:\n raise AttributeError, attrname\n\nSo now the caveat: they're not methods (note the lack of self as the first variable). If you need your users (or your code) to be able to call im_class, im_func, or im_self on any of your deprecated methods, then this hack won't work. Also, i'm pretty sure there's going to be a performance hit because you're defining each dep'd function inside __getattr__. This won't affect your other attribute lookups (had I put them in __getattribute__, that would be a different matter), but it will slow down access to those deprecated methods. This can be (largely, but not entirely) negated by putting each function definition inside its own if block, instead of doing a list-membership check, but, depending on how big your function is, that could be really annoying to maintain. \nUPDATE: \n1) If you want to make the deprecated functions methods (and you do), just use\nimport types\nreturn types.MethodType(eval(attrname), self)\n\ninstead of\nreturn eval(attrname)\nin the above snippet, and add self as the first argument to the function defs. It turns them into instancemethods (so you can use im_class, im_func, and im_self to your heart's content). \n2) If the __getattr__ hook didn't thrill you, there's another option (that I know of) (albiet, with its own caveats, and we'll get to those): Put the deprecated functions definitions inside __init__, and hide them with a custom __dir__. Here's what the above code would look like done this way:\nclass hidden(object):\n def __init__(self):\n self.value = 4\n from types import MethodType\n def dep_show(self):\n return self.value\n self.__setattr__('dep_show', MethodType(dep_show, self))\n def dep_change(self, n):\n self.value = n\n self.__setattr__('dep_change', MethodType(dep_change, self))\n def show(self):\n return self.value\n def change(self, n):\n self.value = n\n def __dir__(self):\n heritage = dir(super(self.__class__, self)) # inherited attributes\n hide = ['dep_show', 'dep_change']\n show = [k for k in self.__class__.__dict__.keys() + self.__dict__.keys() if not k in heritage + private]\n return sorted(heritage + show)\n\nThe advantage here is that you're not defining the functions anew every lookup, which nets you speed. The disadvantage here is that because you're not defining functions anew each lookup, they have to 'persist' (if you will). So, while the custom __dir__ method hides your deprecateds from dir(hiddenObj) and, therefore, IPython's tab-completion, they still exist in the instance's __dict__ attribute, where users can discover them.\n", "Seems like there is a special magic method for the introcpection which is called by dir(): __dir__(). Isn't it what you are lookin for?\n", "The DeprecationWarning isn't emitted until the method is called, so you'd have to have a separate attribute on the class that stores the names of deprecated methods, then check that before suggesting a completion.\nAlternatively, you could walk the AST for the method looking for DeprecationWarning, but that will fail if either the class is defined in C, or if the method may emit a DeprecationWarning based on the type or value of the arguments.\n", "About the completion mechanism in IPython, it is documented here:\nhttp://ipython.scipy.org/doc/manual/html/api/generated/IPython.core.completer.html#ipcompleter\nBut a really interesting example for you is the traits completer, that does precisely what you want to do: it hides some methods (based on their names) from the autocompletion.\nHere is the code:\nhttp://projects.scipy.org/ipython/ipython/browser/ipython/trunk/IPython/Extensions/ipy_traits_completer.py\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0002531479_ipython_python.txt
Q: Python: Get items at depth? (set library?) I have a nested list something like this: PLACES = ( ('CA', 'Canada', ( ('AB', 'Alberta'), ('BC', 'British Columbia' ( ('van', 'Vancouver'), ), ... )), ('US', 'United States', ( ('AL', 'Alabama'), ('AK', 'Alaska'), ... I need to retrieve some data out of it. If depth is 0 I need to retrieve all the countries (and their codes), if depth == 1, I need to retrieve all the states/provinces, if depth == 2 I need to retrieve all the cities... and so forth. Is there some set library for doing stuff like this? Or can someone point me in the right direction? I started coding up a solution only to realize it wouldn't work for levels deeper than 1 because you have to go in and out of each list... Also notice that not all items have a 3rd part (i.e., we're pretending Alberta doesn't have any cities, so retrieving items at depth 2 would just return ('van','Vancouver') in this limited scenario). I didn't realize this before, but I also needed the parent value. So, I modified interjay's solution: def depth_gen(seq, depth, par=None): if depth==0: for x in seq: yield par, x[0], x[1] return for x in seq: if len(x)==3: par = x[0] for y in depth_gen(x[2], depth-1, par): yield y Which I'm using to generate some HTML: <label for="id-pickup_address-province">Province</label> <select id="id-pickup_address-province" rel="pickup_address-country" name="pickup_address-province"> <option rel="CA" value="AB">Alberta</option> <option rel="CA" value="BC">British Columbia</option> <option rel="CA" value="MB">Manitoba</option> ... <option rel="US" value="WV">West Virginia</option> <option rel="US" value="WI">Wisconsin</option> <option rel="US" value="WY">Wyoming</option> </select> <label for="id-pickup_address-country">Country</label> <select id="id-pickup_address-country" name="pickup_address-country"> <option value="CA">Canada</option> <option value="US">United States</option> </select> And then I should be able to easily filter the list with jQuery based on which country is selected... A: Here is a solution which will work for any depth: def depthGenerator(seq, depth): if depth==0: for x in seq: yield x[:2] #strip subsequences return for x in seq: if len(x)==3: #has subsequence? for y in depthGenerator(x[2], depth-1): yield y Example: >>> list(depthGenerator(PLACES, 1)) [('AB', 'Alberta'), ('BC', 'British Columbia'), ('AL', 'Alabama'), ('AK', 'Alaska')] A: This is what I see: for (county, countryName, stateTuple) in MyTuple: for (state, stateName, CountyTuple) in stateTuple: ... and so on, which is a repeating pattern. def extract( myTuple, level ): if level: return ( item[2] for item in myTuple if len(item) == 3) else: return ( (item[0], item[1]) for item in myTuple ) Then call extract as many times as you need for your "depth". A: Suggestion, don't use nested lists. Create some kind of real structure of classes that gives you more information and organization. It will make it easier to think about, easier to code and easier for other people to read.
Python: Get items at depth? (set library?)
I have a nested list something like this: PLACES = ( ('CA', 'Canada', ( ('AB', 'Alberta'), ('BC', 'British Columbia' ( ('van', 'Vancouver'), ), ... )), ('US', 'United States', ( ('AL', 'Alabama'), ('AK', 'Alaska'), ... I need to retrieve some data out of it. If depth is 0 I need to retrieve all the countries (and their codes), if depth == 1, I need to retrieve all the states/provinces, if depth == 2 I need to retrieve all the cities... and so forth. Is there some set library for doing stuff like this? Or can someone point me in the right direction? I started coding up a solution only to realize it wouldn't work for levels deeper than 1 because you have to go in and out of each list... Also notice that not all items have a 3rd part (i.e., we're pretending Alberta doesn't have any cities, so retrieving items at depth 2 would just return ('van','Vancouver') in this limited scenario). I didn't realize this before, but I also needed the parent value. So, I modified interjay's solution: def depth_gen(seq, depth, par=None): if depth==0: for x in seq: yield par, x[0], x[1] return for x in seq: if len(x)==3: par = x[0] for y in depth_gen(x[2], depth-1, par): yield y Which I'm using to generate some HTML: <label for="id-pickup_address-province">Province</label> <select id="id-pickup_address-province" rel="pickup_address-country" name="pickup_address-province"> <option rel="CA" value="AB">Alberta</option> <option rel="CA" value="BC">British Columbia</option> <option rel="CA" value="MB">Manitoba</option> ... <option rel="US" value="WV">West Virginia</option> <option rel="US" value="WI">Wisconsin</option> <option rel="US" value="WY">Wyoming</option> </select> <label for="id-pickup_address-country">Country</label> <select id="id-pickup_address-country" name="pickup_address-country"> <option value="CA">Canada</option> <option value="US">United States</option> </select> And then I should be able to easily filter the list with jQuery based on which country is selected...
[ "Here is a solution which will work for any depth:\ndef depthGenerator(seq, depth):\n if depth==0:\n for x in seq:\n yield x[:2] #strip subsequences\n return\n\n for x in seq:\n if len(x)==3: #has subsequence?\n for y in depthGenerator(x[2], depth-1):\n yield y\n\nExample:\n>>> list(depthGenerator(PLACES, 1))\n[('AB', 'Alberta'), ('BC', 'British Columbia'), ('AL', 'Alabama'), ('AK', 'Alaska')]\n\n", "This is what I see:\nfor (county, countryName, stateTuple) in MyTuple:\n for (state, stateName, CountyTuple) in stateTuple:\n ...\n\nand so on, which is a repeating pattern.\ndef extract( myTuple, level ):\n if level:\n return ( item[2] for item in myTuple if len(item) == 3)\n else:\n return ( (item[0], item[1]) for item in myTuple )\n\nThen call extract as many times as you need for your \"depth\".\n", "Suggestion, don't use nested lists. Create some kind of real structure of classes that gives you more information and organization. It will make it easier to think about, easier to code and easier for other people to read.\n" ]
[ 5, 1, 1 ]
[]
[]
[ "algorithm", "list", "python", "set" ]
stackoverflow_0002610588_algorithm_list_python_set.txt
Q: A better python property decorator I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing. (Seems psyco and this decorator dont play nice). I think it would be best to change it. def Property(function): """Allow readable properties""" keys = 'fget', 'fset', 'fdel' func_locals = {'doc':function.__doc__} def probeFunc(frame, event, arg): if event == 'return': locals = frame.f_locals func_locals.update(dict((k,locals.get(k)) for k in keys)) sys.settrace(None) return probeFunc sys.settrace(probeFunc) function() return property(**func_locals) Used like so: class A(object): @Property def prop(): def fget(self): return self.__prop def fset(self, value): self.__prop = value ... ect The errors I get say the problems are because of sys.settrace. (Perhaps this is abuse of settrace ?) My question: Is the same decorator achievable without sys.settrace. If not I'm in for some heavy rewrites. A: The same thing? No. You can't do what that decorator does without magic like sys.settrace. (It technically doesn't have to be sys.settrace, but using something else -- like bytecode rewriting -- wouldn't be an improvement.) You can make it a lot simpler by doing, for example: def Property(f): fget, fset, fdel = f() fdoc = f.__doc__ return property(fget, fset, fdel, fdoc) class Foo(object): @Property def myprop(): "Property docstring" def fget(self): return 'fget' def fset(self, x): pass def fdel(self): pass return fget, fset, fdel In Python 2.6 and later you can use a slightly different decorator, though: def Property(cls): fget = cls.__dict__.get('fget') fset = cls.__dict__.get('fset') fdel = cls.__dict__.get('fdel') fdoc = cls.__doc__ return property(fget, fset, fdel, fdoc) And you would use it like so: class Foo(object): @Property class myprop(object): "Property docstring" def fget(self): return 'fget' def fset(self, x): pass def fdel(self): pass However, a more idiomatic way of doing this in Python 2.6 and later is like so: class Foo(object): @property def myprop(self): "Property docstring" return 'fget' @myprop.setter def myprop(self, x): pass @myprop.deleter def myprop(self): pass A: It might be possible; it appears that this abuse of settrace is being used to catch the decorated function just before it returns for the purpose of pilfering it's local variables... Unfortunately, the main approaches I can think of at the moment involve hacking the bytecode :-(. However, you could replace it with one that requires every so-decorated function to call another special function rather than simply returning, or you could modify it to call sys.gettrace rather than throwing out whatever trace function might be active, and restore the same trace function afterward.
A better python property decorator
I've inherited some python code that contains a rather cryptic decorator. This decorator sets properties in classes all over the project. The problem is that this I have traced my debugging problems to this decorator. Seems it "fubars" all debuggers I've tried and trying to speed up the code with psyco breaks everthing. (Seems psyco and this decorator dont play nice). I think it would be best to change it. def Property(function): """Allow readable properties""" keys = 'fget', 'fset', 'fdel' func_locals = {'doc':function.__doc__} def probeFunc(frame, event, arg): if event == 'return': locals = frame.f_locals func_locals.update(dict((k,locals.get(k)) for k in keys)) sys.settrace(None) return probeFunc sys.settrace(probeFunc) function() return property(**func_locals) Used like so: class A(object): @Property def prop(): def fget(self): return self.__prop def fset(self, value): self.__prop = value ... ect The errors I get say the problems are because of sys.settrace. (Perhaps this is abuse of settrace ?) My question: Is the same decorator achievable without sys.settrace. If not I'm in for some heavy rewrites.
[ "The same thing? No. You can't do what that decorator does without magic like sys.settrace. (It technically doesn't have to be sys.settrace, but using something else -- like bytecode rewriting -- wouldn't be an improvement.) You can make it a lot simpler by doing, for example:\ndef Property(f): \n fget, fset, fdel = f()\n fdoc = f.__doc__\n return property(fget, fset, fdel, fdoc)\n\nclass Foo(object):\n @Property\n def myprop():\n \"Property docstring\"\n def fget(self): \n return 'fget' \n def fset(self, x):\n pass\n def fdel(self):\n pass\n return fget, fset, fdel\n\nIn Python 2.6 and later you can use a slightly different decorator, though:\ndef Property(cls):\n fget = cls.__dict__.get('fget')\n fset = cls.__dict__.get('fset')\n fdel = cls.__dict__.get('fdel')\n fdoc = cls.__doc__\n return property(fget, fset, fdel, fdoc)\n\nAnd you would use it like so:\nclass Foo(object):\n @Property\n class myprop(object):\n \"Property docstring\"\n def fget(self):\n return 'fget'\n def fset(self, x):\n pass\n def fdel(self):\n pass\n\nHowever, a more idiomatic way of doing this in Python 2.6 and later is like so:\nclass Foo(object):\n @property\n def myprop(self):\n \"Property docstring\"\n return 'fget'\n @myprop.setter\n def myprop(self, x):\n pass\n @myprop.deleter\n def myprop(self):\n pass\n\n", "It might be possible; it appears that this abuse of settrace is being used to catch the decorated function just before it returns for the purpose of pilfering it's local variables...\nUnfortunately, the main approaches I can think of at the moment involve hacking the bytecode :-(.\nHowever, you could replace it with one that requires every so-decorated function to call another special function rather than simply returning, or you could modify it to call sys.gettrace rather than throwing out whatever trace function might be active, and restore the same trace function afterward.\n" ]
[ 8, 2 ]
[]
[]
[ "debugging", "decorator", "properties", "python" ]
stackoverflow_0002610621_debugging_decorator_properties_python.txt
Q: How to compare 2 lists and merge them in Python/MySQL? I want to merge data. Following are my MySQL tables. I want to use Python to traverse though a list of both Lists (one with dupe = 'x' and other with null dupes). This is sample data. Actual data is humongous. For instance : a b c d e f key dupe -------------------- 1 d c f k l 1 x 2 g h j 1 3 i h u u 2 4 u r t 2 x From the above sample table, the desired output is : a b c d e f key dupe -------------------- 2 g c h k j 1 3 i r h u u 2 What I have so far : import string, os, sys import MySQLdb from EncryptedFile import EncryptedFile enc = EncryptedFile( os.getenv("HOME") + '/.py-encrypted-file') user = enc.getValue("user") pw = enc.getValue("pw") db = MySQLdb.connect(host="127.0.0.1", user=user, passwd=pw,db=user) cursor = db.cursor() cursor2 = db.cursor() cursor.execute("select * from delThisTable where dupe is null") cursor2.execute("select * from delThisTable where dupe is not null") result = cursor.fetchall() result2 = cursor2.fetchall() for each record for each field perform the comparison and perform the necessary updates ### How do I compare the record with same key value and update the original row null field value with the non-null value from the duplicate? Please fill this void... cursor.close() cursor2.close() db.close() Thanks guys! A: OK, let's have some fun... mysql> create table so (a int, b char, c char, d char, e char, f char, `key` int, dupe char); Query OK, 0 rows affected (0.05 sec) mysql> insert into so values (1, 'd', 'c', 'f', 'k', 'l', 1, 'x'), (2, 'g', null, 'h', null, 'j', 1, null), (3, 'i', null, 'h', 'u', 'u', 2, null), (4, 'u', 'r', null, null, 't', 2, 'x'); Query OK, 4 rows affected (0.00 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select * from so order by a; +------+------+------+------+------+------+------+------+ | a | b | c | d | e | f | key | dupe | +------+------+------+------+------+------+------+------+ | 1 | d | c | f | k | l | 1 | x | | 2 | g | NULL | h | NULL | j | 1 | NULL | | 3 | i | NULL | h | u | u | 2 | NULL | | 4 | u | r | NULL | NULL | t | 2 | x | +------+------+------+------+------+------+------+------+ 4 rows in set (0.00 sec) Python 2.6.5 (r265:79063, Mar 26 2010, 22:43:05) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>> db = MySQLdb.connect(host="127.0.0.1", db="test") >>> c = db.cursor() >>> c.execute("SELECT a, b, c, d, e, f, `key`, dupe FROM so") 4L >>> rows = c.fetchall() >>> rows ((1L, 'd', 'c', 'f', 'k', 'l', 1L, 'x'), (4L, 'u', 'r', None, None, 't', 2L, 'x'), (2L, 'g', None, 'h', None, 'j', 1L, None), (3L, 'i', None, 'h', 'u', 'u', 2L, None)) >>> data = dict() >>> for row in rows: ... key, isDupe = row[-2], row[-1] ... if key not in data: ... data[key] = list(row[:-1]) ... else: ... for i in range(len(row)-1): ... if data[key][i] is None or (not isDupe and row[i] is not None): ... data[key][i] = row[i] ... >>> data {1L: [2L, 'g', 'c', 'h', 'k', 'j', 1L], 2L: [3L, 'i', 'r', 'h', 'u', 'u', 2L]}
How to compare 2 lists and merge them in Python/MySQL?
I want to merge data. Following are my MySQL tables. I want to use Python to traverse though a list of both Lists (one with dupe = 'x' and other with null dupes). This is sample data. Actual data is humongous. For instance : a b c d e f key dupe -------------------- 1 d c f k l 1 x 2 g h j 1 3 i h u u 2 4 u r t 2 x From the above sample table, the desired output is : a b c d e f key dupe -------------------- 2 g c h k j 1 3 i r h u u 2 What I have so far : import string, os, sys import MySQLdb from EncryptedFile import EncryptedFile enc = EncryptedFile( os.getenv("HOME") + '/.py-encrypted-file') user = enc.getValue("user") pw = enc.getValue("pw") db = MySQLdb.connect(host="127.0.0.1", user=user, passwd=pw,db=user) cursor = db.cursor() cursor2 = db.cursor() cursor.execute("select * from delThisTable where dupe is null") cursor2.execute("select * from delThisTable where dupe is not null") result = cursor.fetchall() result2 = cursor2.fetchall() for each record for each field perform the comparison and perform the necessary updates ### How do I compare the record with same key value and update the original row null field value with the non-null value from the duplicate? Please fill this void... cursor.close() cursor2.close() db.close() Thanks guys!
[ "OK, let's have some fun...\nmysql> create table so (a int, b char, c char, d char, e char, f char, `key` int, dupe char);\nQuery OK, 0 rows affected (0.05 sec)\n\nmysql> insert into so values (1, 'd', 'c', 'f', 'k', 'l', 1, 'x'), (2, 'g', null, 'h', null, 'j', 1, null), (3, 'i', null, 'h', 'u', 'u', 2, null), (4, 'u', 'r', null, null, 't', 2, 'x');\nQuery OK, 4 rows affected (0.00 sec)\nRecords: 4 Duplicates: 0 Warnings: 0\n\nmysql> select * from so order by a;\n+------+------+------+------+------+------+------+------+\n| a | b | c | d | e | f | key | dupe |\n+------+------+------+------+------+------+------+------+\n| 1 | d | c | f | k | l | 1 | x |\n| 2 | g | NULL | h | NULL | j | 1 | NULL |\n| 3 | i | NULL | h | u | u | 2 | NULL |\n| 4 | u | r | NULL | NULL | t | 2 | x |\n+------+------+------+------+------+------+------+------+\n4 rows in set (0.00 sec)\n\n\nPython 2.6.5 (r265:79063, Mar 26 2010, 22:43:05) \n[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import MySQLdb\n>>> db = MySQLdb.connect(host=\"127.0.0.1\", db=\"test\")\n>>> c = db.cursor()\n>>> c.execute(\"SELECT a, b, c, d, e, f, `key`, dupe FROM so\")\n4L\n>>> rows = c.fetchall()\n>>> rows\n((1L, 'd', 'c', 'f', 'k', 'l', 1L, 'x'), (4L, 'u', 'r', None, None, 't', 2L, 'x'), (2L, 'g', None, 'h', None, 'j', 1L, None), (3L, 'i', None, 'h', 'u', 'u', 2L, None))\n>>> data = dict()\n>>> for row in rows:\n... key, isDupe = row[-2], row[-1]\n... if key not in data:\n... data[key] = list(row[:-1])\n... else:\n... for i in range(len(row)-1):\n... if data[key][i] is None or (not isDupe and row[i] is not None):\n... data[key][i] = row[i]\n... \n>>> data\n{1L: [2L, 'g', 'c', 'h', 'k', 'j', 1L], 2L: [3L, 'i', 'r', 'h', 'u', 'u', 2L]}\n\n" ]
[ 2 ]
[]
[]
[ "duplicate_data", "duplicates", "merge", "mysql", "python" ]
stackoverflow_0002610443_duplicate_data_duplicates_merge_mysql_python.txt
Q: Django project models.py versus app models.py I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck. I took a database that I use (a copy of course) and generated the conceptual schema as a django model using inspectdb. I did this at the project level, and presumed then I could write apps using subschemas in the applications for that project. But generalizing the tutorial, they define the model in the application's model.py. If I did that, I would be repeating the model (or part of it) that's already at the project level, which seems like a mistake and a maintenance issue. So how, in Django style, do I use the project schema (or parts of it) without redefining it in the application's models.py? Thanks in advance. A: There shouldn't be any reason to have "project level models" (or "project level views" for that matter). You just need to split the functionality into separate apps. Let's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generating timetables, and yet another one for an internal message board, etc.. Every app defines its own models (there are no "project level models"), but apps can import each others models (so message board posts can have a ForeignKey field pointing at student from the "students" app). See also James Bennett's "writing reusable Django applications" presentation from DjangoCon 2008. A: A model should only be defined once in a Django project The model needs to exist in an app under the project You can access other app's models by importing them If you need to "add on" to an existing model it can be inherited from (see: multi table inheritance). This is fairly simple but if you're just starting out you may want to leave that for later. A: Django models can only reside in applications, not in project itself. By default manage.py inspectdb outputs content of the models.py file and it's up to you to put it in the right place. In your case it would be easier to put whole thing in one app and later split it in the places where it would make sense. I'm not sure what's the state with the current version, but before presence of models module in package was indication that this is django application and can be put in INSTALLED_APPS list.
Django project models.py versus app models.py
I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck. I took a database that I use (a copy of course) and generated the conceptual schema as a django model using inspectdb. I did this at the project level, and presumed then I could write apps using subschemas in the applications for that project. But generalizing the tutorial, they define the model in the application's model.py. If I did that, I would be repeating the model (or part of it) that's already at the project level, which seems like a mistake and a maintenance issue. So how, in Django style, do I use the project schema (or parts of it) without redefining it in the application's models.py? Thanks in advance.
[ "There shouldn't be any reason to have \"project level models\" (or \"project level views\" for that matter). You just need to split the functionality into separate apps.\nLet's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generating timetables, and yet another one for an internal message board, etc.. Every app defines its own models (there are no \"project level models\"), but apps can import each others models (so message board posts can have a ForeignKey field pointing at student from the \"students\" app).\nSee also James Bennett's \"writing reusable Django applications\" presentation from DjangoCon 2008.\n", "\nA model should only be defined once in a Django project\nThe model needs to exist in an app under the project\nYou can access other app's models by importing them\nIf you need to \"add on\" to an existing model it can be inherited from (see: multi table inheritance). This is fairly simple but if you're just starting out you may want to leave that for later.\n\n", "Django models can only reside in applications, not in project itself. By default manage.py inspectdb outputs content of the models.py file and it's up to you to put it in the right place.\nIn your case it would be easier to put whole thing in one app and later split it in the places where it would make sense.\nI'm not sure what's the state with the current version, but before presence of models module in package was indication that this is django application and can be put in INSTALLED_APPS list.\n" ]
[ 27, 9, 6 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002610727_django_django_models_python.txt
Q: Can zlib.crc32 or zlib.adler32 be safely used to mask primary keys in URLs? In Django Design Patterns, the author recommends using zlib.crc32 to mask primary keys in URLs. After some quick testing, I noticed that crc32 produces negative integers about half the time, which seems undesirable for use in a URL. zlib.adler32 does not appear to produce negatives, but is described as "weaker" than CRC. Is this method (either CRC or Adler-32) safe for usage in a URL as an alternate to a primary key? (i.e. is it collision-safe?) Is the "weaker" Adler-32 a satisfactory alternative for this task? How the heck do you reverse this?! That is, how do you determine the original primary key from the checksum? A: You can interpret the 32 bit CRC value as an unsigned integer. A: Upon further investigation, this seems like a really bad idea: In [11]: s = set([zlib.crc32(str(x)) for x in xrange(20000000)]) In [12]: len(s) Out[12]: 19989760 In [13]: 20000000 - len(s) Out[13]: 10240 That's 10,240 collisions in 20,000,000 primary keys. A: The problem is not hashing the value. The problem is mapping the hash back to the key. Even if there are collisions you could always increment until you hit an unused hash. The reason hashes are used for e.g. authentication is because there's already a key (e.g the username) that can be used to find the appropriate record. At that point it becomes just a matter of comparing the given hash against the stored hash. If you're using the hash to mask the key instead then it will be trickier than just comparing it. Turning the hash itself into the key will solve this though.
Can zlib.crc32 or zlib.adler32 be safely used to mask primary keys in URLs?
In Django Design Patterns, the author recommends using zlib.crc32 to mask primary keys in URLs. After some quick testing, I noticed that crc32 produces negative integers about half the time, which seems undesirable for use in a URL. zlib.adler32 does not appear to produce negatives, but is described as "weaker" than CRC. Is this method (either CRC or Adler-32) safe for usage in a URL as an alternate to a primary key? (i.e. is it collision-safe?) Is the "weaker" Adler-32 a satisfactory alternative for this task? How the heck do you reverse this?! That is, how do you determine the original primary key from the checksum?
[ "You can interpret the 32 bit CRC value as an unsigned integer.\n", "Upon further investigation, this seems like a really bad idea:\nIn [11]: s = set([zlib.crc32(str(x)) for x in xrange(20000000)])\nIn [12]: len(s)\nOut[12]: 19989760\nIn [13]: 20000000 - len(s)\nOut[13]: 10240\n\nThat's 10,240 collisions in 20,000,000 primary keys.\n", "The problem is not hashing the value. The problem is mapping the hash back to the key. Even if there are collisions you could always increment until you hit an unused hash.\nThe reason hashes are used for e.g. authentication is because there's already a key (e.g the username) that can be used to find the appropriate record. At that point it becomes just a matter of comparing the given hash against the stored hash. If you're using the hash to mask the key instead then it will be trickier than just comparing it. Turning the hash itself into the key will solve this though.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "crc", "primary_key", "python", "url", "zlib" ]
stackoverflow_0002610677_crc_primary_key_python_url_zlib.txt
Q: Python-daemon doesn't kill its kids When using python-daemon, I'm creating subprocesses likeso: import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with daemon.DaemonContext(): for i in xrange(3): Worker(q) while True: # let the Workers do their thing q.put(_something_we_wait_for()) When I kill the parent daemonic process (i.e. not a Worker) with a Ctrl-C or SIGTERM, etc., the children don't die. How does one kill the kids? My first thought is to use atexit to kill all the workers, likeso: with daemon.DaemonContext(): workers = list() for i in xrange(3): workers.append(Worker(q)) @atexit.register def kill_the_children(): for w in workers: w.terminate() while True: # let the Workers do their thing q.put(_something_we_wait_for()) However, the children of daemons are tricky things to handle, and I'd be obliged for thoughts and input on how this ought to be done. Thank you. A: Your options are a bit limited. If doing self.daemon = True in the constructor for the Worker class does not solve your problem and trying to catch signals in the Parent (ie, SIGTERM, SIGINT) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the children commit suicide when the parent dies. The first step is to give the constructor to Worker the PID of the parent process (you can do this with os.getpid()). Then, instead of just doing self.queue.get() in the worker loop, do something like this: waiting = True while waiting: # see if Parent is at home if os.getppid() != self.parentPID: # woe is me! My Parent has died! sys.exit() # or whatever you want to do to quit the Worker process try: # I picked the timeout randomly; use what works data = self.queue.get(block=False, timeout=0.1) waiting = False except queue.Queue.Empty: continue # try again # now do stuff with data The solution above checks to see if the parent PID is different than what it originally was (that is, if the child process was adopted by init or lauchd because the parent died) - see reference. However, if that doesn't work for some reason you can replace it with the following function (adapted from here): def parentIsAlive(self): try: # try to call Parent os.kill(self.parentPID, 0) except OSError: # *beeep* oh no! The phone's disconnected! return False else: # *ring* Hi mom! return True Now, when the Parent dies (for whatever reason), the child Workers will spontaneously drop like flies - just as you wanted, you daemon! :-D A: You should store the parent pid when the child is first created (let's say in self.myppid) and when self.myppid is diferent from getppid() means that the parent died. To avoid checking if the parent has changed over and over again, you can use PR_SET_PDEATHSIG that is described in the signals documentation. 5.8 The Linux "parent death" signal For each process there is a variable pdeath_signal, that is initialized to 0 after fork() or clone(). It gives the signal that the process should get when its parent dies. In this case, you want your process to die, you can just set it to a SIGHUP, like this: prctl(PR_SET_PDEATHSIG, SIGHUP); A: Atexit won't do the trick -- it only gets run on successful non-signal termination -- see the note near the top of the docs. You need to set up signal handling via one of two means. The easier-sounding option: set the daemon flag on your worker processes, per http://docs.python.org/library/multiprocessing.html#process-and-exceptions Somewhat harder-sounding option: PEP-3143 seems to imply there is a built-in way to hook program cleanup needs in python-daemon.
Python-daemon doesn't kill its kids
When using python-daemon, I'm creating subprocesses likeso: import multiprocessing class Worker(multiprocessing.Process): def __init__(self, queue): self.queue = queue # we wait for things from this in Worker.run() ... q = multiprocessing.Queue() with daemon.DaemonContext(): for i in xrange(3): Worker(q) while True: # let the Workers do their thing q.put(_something_we_wait_for()) When I kill the parent daemonic process (i.e. not a Worker) with a Ctrl-C or SIGTERM, etc., the children don't die. How does one kill the kids? My first thought is to use atexit to kill all the workers, likeso: with daemon.DaemonContext(): workers = list() for i in xrange(3): workers.append(Worker(q)) @atexit.register def kill_the_children(): for w in workers: w.terminate() while True: # let the Workers do their thing q.put(_something_we_wait_for()) However, the children of daemons are tricky things to handle, and I'd be obliged for thoughts and input on how this ought to be done. Thank you.
[ "Your options are a bit limited. If doing self.daemon = True in the constructor for the Worker class does not solve your problem and trying to catch signals in the Parent (ie, SIGTERM, SIGINT) doesn't work, you may have to try the opposite solution - instead of having the parent kill the children, you can have the children commit suicide when the parent dies.\nThe first step is to give the constructor to Worker the PID of the parent process (you can do this with os.getpid()). Then, instead of just doing self.queue.get() in the worker loop, do something like this:\nwaiting = True\nwhile waiting:\n # see if Parent is at home\n if os.getppid() != self.parentPID:\n # woe is me! My Parent has died!\n sys.exit() # or whatever you want to do to quit the Worker process\n try:\n # I picked the timeout randomly; use what works\n data = self.queue.get(block=False, timeout=0.1)\n waiting = False\n except queue.Queue.Empty:\n continue # try again\n# now do stuff with data\n\nThe solution above checks to see if the parent PID is different than what it originally was (that is, if the child process was adopted by init or lauchd because the parent died) - see reference. However, if that doesn't work for some reason you can replace it with the following function (adapted from here):\ndef parentIsAlive(self):\n try:\n # try to call Parent\n os.kill(self.parentPID, 0)\n except OSError:\n # *beeep* oh no! The phone's disconnected!\n return False\n else:\n # *ring* Hi mom!\n return True\n\nNow, when the Parent dies (for whatever reason), the child Workers will spontaneously drop like flies - just as you wanted, you daemon! :-D\n", "You should store the parent pid when the child is first created (let's say in self.myppid) and when self.myppid is diferent from getppid() means that the parent died.\nTo avoid checking if the parent has changed over and over again, you can use PR_SET_PDEATHSIG that is described in the signals documentation.\n\n5.8 The Linux \"parent death\" signal\nFor each process there is a variable pdeath_signal, that is\ninitialized to 0 after fork() or clone(). It gives the signal that the\nprocess should get when its parent dies.\n\nIn this case, you want your process to die, you can just set it to a SIGHUP, like this:\nprctl(PR_SET_PDEATHSIG, SIGHUP);\n\n", "Atexit won't do the trick -- it only gets run on successful non-signal termination -- see the note near the top of the docs. You need to set up signal handling via one of two means.\nThe easier-sounding option: set the daemon flag on your worker processes, per http://docs.python.org/library/multiprocessing.html#process-and-exceptions\nSomewhat harder-sounding option: PEP-3143 seems to imply there is a built-in way to hook program cleanup needs in python-daemon.\n" ]
[ 32, 4, 2 ]
[]
[]
[ "children", "daemon", "multiprocessing", "python", "zombie_process" ]
stackoverflow_0002542610_children_daemon_multiprocessing_python_zombie_process.txt
Q: Making all variables accessible to namespace Say I have a simple function: def myfunc(): a = 4.2 b = 5.5 ... many similar variables ... I use this function one time only and I am wondering what is the easiest way to make all the variables inside the function accessible to my main name-space. Do I have to declare global for each item? or any other suggested methods? Thanks. A: Best way, in my biased opinion, is to wrap the dictionary into a nice object where the "variables" are accessed as attributes -- the pattern I named Bunch when I introduced it many years ago, and a great example of the last item in the Zen of Python (if you don't know what that is, import this at an interpreter interactive prompt). To wit...: class Bunch(object): def __init__(self, d=None): if d is not None: self.__dict__.update(d) def myfunc(): a = 4.2 b = 5.5 ... return Bunch(locals()) x = myfunc() print x.a, x.b Using qualified names like x.a and x.b, rather than barenames such as a and b, is the crucial idea here: qualified names let you separate namespaces and treat them right, while barenames would make one big soup of everything and violate the Zen of Python;-). And of course there's no need to use an unwrapped dict and unsightly x['a'], x['b'] accesses!-) A: If what you want is separation of your constants then put them in another module: consts.py: foo = 42 bar = 'quux' main.py: import consts print consts.foo print consts.bar[::-1] A: I can't think of any good reason for doing this, but if you REALLY want to for some strange reason: def myfunc(): x = 5.6 y = 7.3 # many other variables globals().update( locals() ) This works because the globals function returns a dictionary of the global variables in your module's namespace, which you can dynamically update with the dictionary of all local variables returned by the locals function. This is very dangerous because it will clobber everything in your global namespace, so if you already had an x or y variable, then they'll get overwritten. And as I said, I really can't think of a good reason to ever do this, so definitely think twice before resorting to this kind of trickery! A: It sounds like what you want to do isn't natural because it isn't something you should generally do much. Perhaps what you really want is to make a class and set all these things on an instance of it. class MyState(object): def __init__(self): self.a = 4.2 self.b = 5.5 ... many similar variables ... Storing state on an instance of a class you create is usually very strongly preferred to mutating global state. This method also does not require any magic.
Making all variables accessible to namespace
Say I have a simple function: def myfunc(): a = 4.2 b = 5.5 ... many similar variables ... I use this function one time only and I am wondering what is the easiest way to make all the variables inside the function accessible to my main name-space. Do I have to declare global for each item? or any other suggested methods? Thanks.
[ "Best way, in my biased opinion, is to wrap the dictionary into a nice object where the \"variables\" are accessed as attributes -- the pattern I named Bunch when I introduced it many years ago, and a great example of the last item in the Zen of Python (if you don't know what that is, import this at an interpreter interactive prompt). To wit...:\nclass Bunch(object):\n def __init__(self, d=None):\n if d is not None: self.__dict__.update(d)\n\ndef myfunc():\n a = 4.2\n b = 5.5\n ...\n return Bunch(locals())\n\nx = myfunc()\n\nprint x.a, x.b\n\nUsing qualified names like x.a and x.b, rather than barenames such as a and b, is the crucial idea here: qualified names let you separate namespaces and treat them right, while barenames would make one big soup of everything and violate the Zen of Python;-). And of course there's no need to use an unwrapped dict and unsightly x['a'], x['b'] accesses!-)\n", "If what you want is separation of your constants then put them in another module:\nconsts.py:\nfoo = 42\nbar = 'quux'\n\nmain.py:\nimport consts\n\nprint consts.foo\nprint consts.bar[::-1]\n\n", "I can't think of any good reason for doing this, but if you REALLY want to for some strange reason:\ndef myfunc():\n x = 5.6\n y = 7.3\n # many other variables\n globals().update( locals() )\n\nThis works because the globals function returns a dictionary of the global variables in your module's namespace, which you can dynamically update with the dictionary of all local variables returned by the locals function.\nThis is very dangerous because it will clobber everything in your global namespace, so if you already had an x or y variable, then they'll get overwritten. And as I said, I really can't think of a good reason to ever do this, so definitely think twice before resorting to this kind of trickery!\n", "It sounds like what you want to do isn't natural because it isn't something you should generally do much.\nPerhaps what you really want is to make a class and set all these things on an instance of it. \nclass MyState(object):\n def __init__(self):\n self.a = 4.2\n self.b = 5.5\n ... many similar variables ...\n\nStoring state on an instance of a class you create is usually very strongly preferred to mutating global state. This method also does not require any magic.\n" ]
[ 8, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002610931_python.txt
Q: Installing Python Script, Maintaining Reference to Python 2.6 I am trying to distribute my Python program. The program relies on version 2.6. I went through the distribution documentation: http://docs.python.org/distutils/index.html and what I have figured out so far is that I basically need to write a setup.py script. Something like: setup(name='Distutils', version='1.0', description='Python Distribution Utilities', author='My Name', author_email='My Email', url='some URL', package_dir={'': 'src'}, packages=[''], ) I would like to ensure that my program uses 2.6 interpreter library when user install it on their box. What would be the best approach to ensure that my program uses 2.6 ? Shall I distribute python 2.6 library along with my program ? Is there any alternative approach ? A: One option is to specify the specific version of the Python interpreter using the hash bang: #! /usr/bin/env python2.6 Another option is to check sys.version_info, for example: if (sys.version_info[0] != 2) or (sys.version_info[1]<6): if sys.version_info[0] > 2: print("Version 2.6+, and not 3.0+ needed.") sys.exit(1) else: print "Version 2.6+, needed. Please upgrade Python." sys.exit(1) The hash bang is probably the best option, as it actually ensures that the script will be interpreted by "python2.6" instead of some other interpreter; however, there are some disadvantages: This will only work on UNIX-like systems that use the hash bang. This will won't work if Python2.7 is installed, but not Python 2.6. As a workaround, what you can do is create a "launcher" Python script that checks for "python2.6"... "python2.9", which is the last possible version of the 2.6+ line before Python 3.0+. This launcher script can then invoke your main program using whichever python interpreter it finds in the search process. You will have to make your launcher script in a way that uses elements common to most Python versions. Borrowing from test if executable exists in Python: def which(program): import os def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def first_which(progs): for prog in progs: progloc = which(prog) if progloc != None: return progloc return None def main(): interpreter=first_which(["python2.6","python2.7","python2.8","python2.9"]) # Invoke your program using "interpreter" # You will need to use os.popen or subprocess, # depending on the version of Python which which # this launcher script was invoked... My own opinion is that the method above is more complicated than necessary, and I would just go with the hash bang... or I would write out the hash bang to the Python file at deployment time, using a language other than Python (for which the version wouldn't be an issue... otherwise, it becomes a recursive problem). I would also strongly urge you NOT to include a copy of Python in your software distribution. This will make your download much larger, and it will annoy users who already have a valid installation of Python available. Instead, you should simply direct users to download and install the appropriate version if it isn't available. A: Check sys.hexversion and make sure that it's greater than or equal to 0x02060000.
Installing Python Script, Maintaining Reference to Python 2.6
I am trying to distribute my Python program. The program relies on version 2.6. I went through the distribution documentation: http://docs.python.org/distutils/index.html and what I have figured out so far is that I basically need to write a setup.py script. Something like: setup(name='Distutils', version='1.0', description='Python Distribution Utilities', author='My Name', author_email='My Email', url='some URL', package_dir={'': 'src'}, packages=[''], ) I would like to ensure that my program uses 2.6 interpreter library when user install it on their box. What would be the best approach to ensure that my program uses 2.6 ? Shall I distribute python 2.6 library along with my program ? Is there any alternative approach ?
[ "One option is to specify the specific version of the Python interpreter using the hash bang:\n\n#! /usr/bin/env python2.6\n\nAnother option is to check sys.version_info, for example:\n\nif (sys.version_info[0] != 2) or (sys.version_info[1]<6):\n if sys.version_info[0] > 2:\n print(\"Version 2.6+, and not 3.0+ needed.\")\n sys.exit(1)\n else:\n print \"Version 2.6+, needed. Please upgrade Python.\"\n sys.exit(1)\n\nThe hash bang is probably the best option, as it actually ensures that the script will be interpreted by \"python2.6\" instead of some other interpreter; however, there are some disadvantages:\n\nThis will only work on UNIX-like systems that use the hash bang.\nThis will won't work if Python2.7 is installed, but not Python 2.6.\n\nAs a workaround, what you can do is create a \"launcher\" Python script that checks for \"python2.6\"... \"python2.9\", which is the last possible version of the 2.6+ line before Python 3.0+. This launcher script can then invoke your main program using whichever python interpreter it finds in the search process. You will have to make your launcher script in a way that uses elements common to most Python versions.\nBorrowing from test if executable exists in Python:\n\ndef which(program):\n import os\n def is_exe(fpath):\n return os.path.exists(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\ndef first_which(progs):\n for prog in progs:\n progloc = which(prog)\n if progloc != None:\n return progloc\n return None\n\ndef main():\n interpreter=first_which([\"python2.6\",\"python2.7\",\"python2.8\",\"python2.9\"])\n # Invoke your program using \"interpreter\"\n # You will need to use os.popen or subprocess,\n # depending on the version of Python which which\n # this launcher script was invoked...\n\nMy own opinion is that the method above is more complicated than necessary, and I would just go with the hash bang... or I would write out the hash bang to the Python file at deployment time, using a language other than Python (for which the version wouldn't be an issue... otherwise, it becomes a recursive problem).\nI would also strongly urge you NOT to include a copy of Python in your software distribution. This will make your download much larger, and it will annoy users who already have a valid installation of Python available. Instead, you should simply direct users to download and install the appropriate version if it isn't available.\n", "Check sys.hexversion and make sure that it's greater than or equal to 0x02060000.\n" ]
[ 1, 0 ]
[]
[]
[ "distribution", "programming_languages", "python" ]
stackoverflow_0002611430_distribution_programming_languages_python.txt
Q: Any tips on moving from ActionScript 3 to Python? I've been developing stuff using ActionScript since AS2,and when AS3 was released i had a bit of a hard time to understand its concepts. Then i realized i had to learn some OOP. I started studying OOP and now i feel i need to take a step further, that's why i chose Python. Are there any tips/advices/hints or whatever like that to help me on this move? Thank you in advance. --edit-- In other words, what are the differences and similarities between the languages? A: I can tell you that I started to understand ActionScript much better after reading Learning Python and Python Tutorial in the meantime
Any tips on moving from ActionScript 3 to Python?
I've been developing stuff using ActionScript since AS2,and when AS3 was released i had a bit of a hard time to understand its concepts. Then i realized i had to learn some OOP. I started studying OOP and now i feel i need to take a step further, that's why i chose Python. Are there any tips/advices/hints or whatever like that to help me on this move? Thank you in advance. --edit-- In other words, what are the differences and similarities between the languages?
[ "I can tell you that I started to understand ActionScript much better after reading Learning Python and Python Tutorial in the meantime\n" ]
[ 0 ]
[]
[]
[ "actionscript", "migration", "oop", "python" ]
stackoverflow_0002611045_actionscript_migration_oop_python.txt
Q: Deploying Pylons with uWSGI We're trying to move our intranet to Pylons. My boss is trying to set up Pylons to use uWSGI behind Apache so he can set up multiple, independent applications. However, he's having a difficult time getting it set up, with some apparent code problems in the C source code for uWSGI. Does anyone have any suggestions for how to deploy Pylons applications that might help us out? Thanks, Doug A: Here is how I did it: http://tonylandis.com/python/deployment-howt-pylons-nginx-and-uwsgi/ A: You can directly use paste for deploying pylons on uWSGI: http://projects.unbit.it/uwsgi/wiki/UsePaste A: The Pylons documentation contains very detailed instructions about deployment. Is there anything specific that isn't working properly?
Deploying Pylons with uWSGI
We're trying to move our intranet to Pylons. My boss is trying to set up Pylons to use uWSGI behind Apache so he can set up multiple, independent applications. However, he's having a difficult time getting it set up, with some apparent code problems in the C source code for uWSGI. Does anyone have any suggestions for how to deploy Pylons applications that might help us out? Thanks, Doug
[ "Here is how I did it:\nhttp://tonylandis.com/python/deployment-howt-pylons-nginx-and-uwsgi/\n", "You can directly use paste for deploying pylons on uWSGI: \nhttp://projects.unbit.it/uwsgi/wiki/UsePaste\n", "The Pylons documentation contains very detailed instructions about deployment. \nIs there anything specific that isn't working properly?\n" ]
[ 6, 3, 0 ]
[]
[]
[ "apache", "deployment", "pylons", "python", "uwsgi" ]
stackoverflow_0002217679_apache_deployment_pylons_python_uwsgi.txt
Q: Loading Files in AppEngine I've got a tiny bit of code to display a file in app.yaml - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) in main.py ... class ShowImage(webapp.RequestHandler): def get(self): rootpath = os.path.dirname(__file__) file = rootpath + "/static/tracker.gif"; fh=open(file, 'r') self.response.out.write(fh.read()) fh.close ... I can see the files gone up by going to my *.appspot.com/tracker.gif (as per the app.yaml) But using *.appspot.com/showimage returns Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 510, in __call__ handler.get(*groups) File "/base/data/home/apps/APPNAME/2.341131266814384624/main.py", line 170, in get fh=open(file, 'r') IOError: [Errno 2] No such file or directory: '/base/data/home/apps/APPNAME/2.341131266814384624/static/tracker.gif' A: Removed - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) from app.yaml apparently you cant serve content from folders you daftly marked as static As from Deployment of static directory contents to google app engine A: To spell out what Chris M. is referring to: When deploying your application, any files matching an "upload" property for a "static_files" handler end up in a totally different place from your code and related files. As far as your code is concerned, they have been removed from the path you expect them to be at.
Loading Files in AppEngine
I've got a tiny bit of code to display a file in app.yaml - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png|jpg)) in main.py ... class ShowImage(webapp.RequestHandler): def get(self): rootpath = os.path.dirname(__file__) file = rootpath + "/static/tracker.gif"; fh=open(file, 'r') self.response.out.write(fh.read()) fh.close ... I can see the files gone up by going to my *.appspot.com/tracker.gif (as per the app.yaml) But using *.appspot.com/showimage returns Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 510, in __call__ handler.get(*groups) File "/base/data/home/apps/APPNAME/2.341131266814384624/main.py", line 170, in get fh=open(file, 'r') IOError: [Errno 2] No such file or directory: '/base/data/home/apps/APPNAME/2.341131266814384624/static/tracker.gif'
[ "Removed \n- url: /(.*\\.(gif|png|jpg))\n static_files: static/\\1\n upload: static/(.*\\.(gif|png|jpg))\n\nfrom app.yaml apparently you cant serve content from folders you daftly marked as static\nAs from Deployment of static directory contents to google app engine\n", "To spell out what Chris M. is referring to:\nWhen deploying your application, any files matching an \"upload\" property for a \"static_files\" handler end up in a totally different place from your code and related files. As far as your code is concerned, they have been removed from the path you expect them to be at.\n" ]
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002607063_google_app_engine_python.txt
Q: How to use the _Qt python module? There is a python module called "_Qt". PyQt is not what I want. I was wondering if there was any documentation for the _Qt module installed with python as a standard module. I have a mac. A: That's QuickTime, nothing to do with Qt. In your question it's not really clear if you intended to use Qt or QuickTime.
How to use the _Qt python module?
There is a python module called "_Qt". PyQt is not what I want. I was wondering if there was any documentation for the _Qt module installed with python as a standard module. I have a mac.
[ "That's QuickTime, nothing to do with Qt.\nIn your question it's not really clear if you intended to use Qt or QuickTime.\n" ]
[ 0 ]
[]
[]
[ "module", "python", "qt" ]
stackoverflow_0002611593_module_python_qt.txt
Q: How to rotate the text of a wx.StaticText? I want to write a Static Text with an upside down ^ How can I do it? A: There are a couple of approaches. 1) If you actually want to do the rotation, you can do it by drawing the text to a wx.GraphicsContext and then rotation it there, write this to a bitmap, and display that. 2) It might be easier to find the right unicode symbol. Having spent way too much of my time lately looking at unicode symbols, I can suggest 02C7, 032C, 2228, 2304, 1D5B, 1D65. Note, though, that not all of these will be present in all fonts. As far as I know, wx.StaticText doesn't rotate text. A: You can either find the right unicode symbol or just use "v"
How to rotate the text of a wx.StaticText?
I want to write a Static Text with an upside down ^ How can I do it?
[ "There are a couple of approaches.\n1) If you actually want to do the rotation, you can do it by drawing the text to a wx.GraphicsContext and then rotation it there, write this to a bitmap, and display that.\n2) It might be easier to find the right unicode symbol. Having spent way too much of my time lately looking at unicode symbols, I can suggest 02C7, 032C, 2228, 2304, 1D5B, 1D65. Note, though, that not all of these will be present in all fonts.\nAs far as I know, wx.StaticText doesn't rotate text.\n", "You can either find the right unicode symbol or just use \"v\"\n" ]
[ 3, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002610494_python_wxpython.txt
Q: Python Comet Server I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python. Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own? A: Orbited seems as a nice solution. Haven't tried it though. Update: things have changed in the last 2.5 years. We now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication. socket.io along with tornadio (socket.io 0.6) and tornadio2 (socket.io 0.7+) sock.js along with SockJS-tornado A: I recommend you should use StreamHub Comet Server - its used by a lot of people - personally I use it with a couple of Django sites I run. You will need to write a tiny bit of Java to handle the streaming - I did this using Jython. The front-end code is some real simple Javascript a la: StreamHub hub = new StreamHub(); hub.connect("http://myserver.com/"); hub.subscribe("newsfeed", function(sTopic, oData) { alert("new news item: " + oData.Title); }); The documentation is pretty good - I had similar problems as you trying to get started with the sparse docs of Cometd et al. For a start I'd read Getting Started With Comet and StreamHub, download and see how some of the examples work and reference the API docs if you need to: Javascript API JSDoc Streaming from Java Javadoc A: Here is a full-featured example of combining Django, Orbited,and Twisted to create a real-time (Comet) app: http://github.com/clemesha/hotdot using Python. A: I've done tons of APIs using twisted for stuff like that, most of which are available on my github account. Most are client-side, but slosh is a server I wrote to do a realtime cheap pubsub sort of thing. It scales somewhat horizontally for reads by allowing for simple stream replication. Writes are a little different when you stick to plain HTTP, but I've pushed a decent amount through it for a demo. Otherwise, you have full-on BOSH which most XMPP servers support and will allow you to decouple the message distribution from the web frontend. A: I haven't done it, but this guy has and writes a good article about it, with Django examples and pointers (which I haven't checked) to other frameworks. A: the orbited and redis solutions are nice, but not longer relevant when you have something like the PubSubHubbub that google released. This makes it very easy to be the publisher or the subscriber to a given feed. http://code.google.com/p/pubsubhubbub/ A: Here's an example that does long-polling with gevent and Django. It uses greenlet - stack switching functionality from Stackless packaged as a CPython extension.
Python Comet Server
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python. Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?
[ "Orbited seems as a nice solution. Haven't tried it though.\n\nUpdate: things have changed in the last 2.5 years.\nWe now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication.\n\nsocket.io along with tornadio (socket.io 0.6) and tornadio2 (socket.io 0.7+)\nsock.js along with SockJS-tornado\n\n", "I recommend you should use StreamHub Comet Server - its used by a lot of people - personally I use it with a couple of Django sites I run. You will need to write a tiny bit of Java to handle the streaming - I did this using Jython. The front-end code is some real simple Javascript a la:\nStreamHub hub = new StreamHub();\nhub.connect(\"http://myserver.com/\");\nhub.subscribe(\"newsfeed\", function(sTopic, oData) { alert(\"new news item: \" + oData.Title); });\n\nThe documentation is pretty good - I had similar problems as you trying to get started with the sparse docs of Cometd et al. For a start I'd read Getting Started With Comet and StreamHub, download and see how some of the examples work and reference the API docs if you need to:\n\nJavascript API JSDoc \nStreaming from Java Javadoc\n\n", "Here is a full-featured example of combining Django, Orbited,and Twisted to create a real-time (Comet) app: http://github.com/clemesha/hotdot using Python.\n", "I've done tons of APIs using twisted for stuff like that, most of which are available on my github account.\nMost are client-side, but slosh is a server I wrote to do a realtime cheap pubsub sort of thing. It scales somewhat horizontally for reads by allowing for simple stream replication. Writes are a little different when you stick to plain HTTP, but I've pushed a decent amount through it for a demo.\nOtherwise, you have full-on BOSH which most XMPP servers support and will allow you to decouple the message distribution from the web frontend.\n", "I haven't done it, but this guy has and writes a good article about it, with Django examples and pointers (which I haven't checked) to other frameworks.\n", "the orbited and redis solutions are nice, but not longer relevant when you have something like the PubSubHubbub that google released. This makes it very easy to be the publisher or the subscriber to a given feed. http://code.google.com/p/pubsubhubbub/\n", "Here's an example that does long-polling with gevent and Django.\nIt uses greenlet - stack switching functionality from Stackless packaged as a CPython extension.\n" ]
[ 13, 9, 6, 4, 2, 1, 1 ]
[]
[]
[ "cometd", "python", "python_stackless" ]
stackoverflow_0000960969_cometd_python_python_stackless.txt
Q: Create thumbnail images for jpegs with python As the title says i am looking for a way convert a huge number of images into thumbnails of different sizes , How do i go about doing this in python A: See: http://www.pythonware.com/products/pil/index.htm import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for", infile
Create thumbnail images for jpegs with python
As the title says i am looking for a way convert a huge number of images into thumbnails of different sizes , How do i go about doing this in python
[ "See: http://www.pythonware.com/products/pil/index.htm\nimport os, sys\nimport Image\n\nsize = 128, 128\n\nfor infile in sys.argv[1:]:\n outfile = os.path.splitext(infile)[0] + \".thumbnail\"\n if infile != outfile:\n try:\n im = Image.open(infile)\n im.thumbnail(size)\n im.save(outfile, \"JPEG\")\n except IOError:\n print \"cannot create thumbnail for\", infile\n\n" ]
[ 22 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0002612436_image_processing_python.txt
Q: How to create make .so files from code written in C or C++ that are usable from Python Looking at Python modules and at code in the "lib-dnyload" directory in the Python framework, I noticed whenever code is creating some kind of GUI or graphic it imports a non-Python file with a .so extension. And there are tons .so files in "lib-dnyload". From googling things I found that these files are called shared objects and are written in C or C++. I have a Mac and I use GCC. How do I make shared object files that are accessible via Python? Mainly just how to make shared objects with GCC using Mac OS X. A: Official python documentation starts with simple example. It's good enough for start. A: In my opinion the easiest way is to use Cython. Cython will generate some C code for you, compile it to make a ".so" library that you can load from python. This is easy and painless. I suggest you to follow the tutorial and you should have a so library pretty soon. If you want to know all the details behind C extensions of python, you should dive in the Python documentation about C extensions. A: The standard way to build and install C extension modules with Python is to use the features of Distutils which is included in the standard Python library. Generally that means including the C file(s) in your project directory and creating a configuration file, normally called setup.py, to identify the C source files. By running a properly-configured setup.py file under Python, Distutils will take care of compiling and linking the C source files by using your system's C compiler and linker. (On OS X, you'll need to have installed Apple's free Xcode Developer Tools which installs versions of gcc.) Wading through all the Distutils documentation to figure out what to do can be overwhelming right now. Here's a simple tutorial that should be enough to get you started. Why use a Distutils setup.py rather than just calling gcc yourself? Several reasons: Since C extensions normally run within the context of the Python interpreter itself, it is important that extensions be compiled and linked in a manner compatible with the C code in the interpreter. Distutils tries to take the guesswork out of this by supplying the right options for the Python you are executing under. This can be particularly important on OS X where Pythons come in various flavors including some with various combinations of multi-architecture executables (i.e. -arch i386, -arch ppc, -arch x86_64, -arch ppc64) and with support for multiple OS X versions (i.e. the current python.org OS X installers are compatible with OS X 10.4 through 10.6). Distutils allows you to package up and distribute combinations of pure Python and C extension modules in a machine and operating system independent way. In many cases, if the C code is written to avoid operating system dependent system calls and the like, your C extensions can be built and installed on most current Python platforms without modification and without you having to know which C compiler to use or options to set. You'll find that nearly all modern Python third-party packages with C code work this way so it's good to get in the habit of using Distutils for this from the start. As you'll see in the tutorial, it's very easy to setup a setup.py file for many cases. A: You can write python extensions in many ways, including Cython, SWIG, boost.python ... You can also write a shared library and use the "ctypes" library to access it. A: There are different ways to do this: Use the Python.h header in your C code. This produces the fastest code. Use wrappers around the Python headers like SWIG. The code may be a bit slower but you need no or minimal change in the C/C++ source code. In most of case you just need to write a SWIG interface files and the shared objects are integrated with Python/PHP/Java etc. It is the easiest way to start to wrapp your C/C++ code. If you are more familiar with Python language and want to avoid writing SWIG interface files in C/C++ style than Cython is the best wrapper for you.
How to create make .so files from code written in C or C++ that are usable from Python
Looking at Python modules and at code in the "lib-dnyload" directory in the Python framework, I noticed whenever code is creating some kind of GUI or graphic it imports a non-Python file with a .so extension. And there are tons .so files in "lib-dnyload". From googling things I found that these files are called shared objects and are written in C or C++. I have a Mac and I use GCC. How do I make shared object files that are accessible via Python? Mainly just how to make shared objects with GCC using Mac OS X.
[ "Official python documentation starts with simple example. It's good enough for start.\n", "In my opinion the easiest way is to use Cython. Cython will generate some C code for you, compile it to make a \".so\" library that you can load from python. This is easy and painless. I suggest you to follow the tutorial and you should have a so library pretty soon.\nIf you want to know all the details behind C extensions of python, you should dive in the Python documentation about C extensions.\n", "The standard way to build and install C extension modules with Python is to use the features of Distutils which is included in the standard Python library. Generally that means including the C file(s) in your project directory and creating a configuration file, normally called setup.py, to identify the C source files. By running a properly-configured setup.py file under Python, Distutils will take care of compiling and linking the C source files by using your system's C compiler and linker. (On OS X, you'll need to have installed Apple's free Xcode Developer Tools which installs versions of gcc.) Wading through all the Distutils documentation to figure out what to do can be overwhelming right now. Here's a simple tutorial that should be enough to get you started.\nWhy use a Distutils setup.py rather than just calling gcc yourself? Several reasons:\n\nSince C extensions normally run within the context of the Python interpreter itself, it is important that extensions be compiled and linked in a manner compatible with the C code in the interpreter. Distutils tries to take the guesswork out of this by supplying the right options for the Python you are executing under. This can be particularly important on OS X where Pythons come in various flavors including some with various combinations of multi-architecture executables (i.e. -arch i386, -arch ppc, -arch x86_64, -arch ppc64) and with support for multiple OS X versions (i.e. the current python.org OS X installers are compatible with OS X 10.4 through 10.6).\nDistutils allows you to package up and distribute combinations of pure Python and C extension modules in a machine and operating system independent way. In many cases, if the C code is written to avoid operating system dependent system calls and the like, your C extensions can be built and installed on most current Python platforms without modification and without you having to know which C compiler to use or options to set.\nYou'll find that nearly all modern Python third-party packages with C code work this way so it's good to get in the habit of using Distutils for this from the start.\nAs you'll see in the tutorial, it's very easy to setup a setup.py file for many cases.\n\n", "You can write python extensions in many ways, including Cython, SWIG, boost.python ...\nYou can also write a shared library and use the \"ctypes\" library to access it.\n", "There are different ways to do this:\n\nUse the Python.h header in your C code. This produces the fastest code.\nUse wrappers around the Python headers like SWIG. The code may be a bit slower but you need no or minimal change in the C/C++ source code. In most of case you just need to write a SWIG interface files and the shared objects are integrated with Python/PHP/Java etc. It is the easiest way to start to wrapp your C/C++ code.\nIf you are more familiar with Python language and want to avoid writing SWIG interface files in C/C++ style than Cython is the best wrapper for you.\n\n" ]
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "distutils", "gcc", "macos", "python", "shared_objects" ]
stackoverflow_0002610421_distutils_gcc_macos_python_shared_objects.txt
Q: Including a pyd directly in a setup.py file I have a complex build process to generate a couple of python extension modules (.pyd). I want to include these in my setup.py for use with distutils. The distutils page talks in length about how to add extension modules from source, but I'd want to simply package these precompiled .pyd. What is the best practice to do this? Eventually, I'd also like to freeze everything in an executable with py2exe. Will I be able to do this if I directly specify the .pyd? A: You could add your extension name to 'includes' options={ 'py2exe':{'includes':['yourextensionname_without_pyd']} } Here is the list of options from py2exe site
Including a pyd directly in a setup.py file
I have a complex build process to generate a couple of python extension modules (.pyd). I want to include these in my setup.py for use with distutils. The distutils page talks in length about how to add extension modules from source, but I'd want to simply package these precompiled .pyd. What is the best practice to do this? Eventually, I'd also like to freeze everything in an executable with py2exe. Will I be able to do this if I directly specify the .pyd?
[ "You could add your extension name to 'includes' \noptions={\n 'py2exe':{'includes':['yourextensionname_without_pyd']}\n}\n\nHere is the list of options from py2exe site\n" ]
[ 1 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0002612518_distutils_python.txt
Q: python lists error A=s.append(s[i]+A+B) A=s.append(s[i]+A+B) TypeError: unsupported operand type(s) for +: 'long' and 'str' What does this error mean ? A and B are strings and s is a list A: s may be a list, but the element - s[i] - is not - it's a long, as indicated by the error. In addition, append() operates on the list directly - it returns None, so you're actually setting A to be None - probably not what you wanted! There are two things you can do to help avoid this type of error in the future. Don't use one-letter variable names. Use descriptive, one to three-word length names that describe what the variable has in it (and/or what it's supposed to be used for). When you do have a problem, try putting it in a try/except block where you put the error name after except and print out the offending variables: try: s.append(s[i]+A+B) except TypeError: print "Failed to add", s[i], ",", A, ",", "and", B raise Don't forget the raise at the end there - that way you don't just ignore the issue and start getting really strange errors. A: If A and B are strings, then s[i] must be a 'long'. A: s[i] is likely a long. You can't add a long to a string. Try: A=s.append(str(s[i])+A+B)
python lists error
A=s.append(s[i]+A+B) A=s.append(s[i]+A+B) TypeError: unsupported operand type(s) for +: 'long' and 'str' What does this error mean ? A and B are strings and s is a list
[ "s may be a list, but the element - s[i] - is not - it's a long, as indicated by the error.\nIn addition, append() operates on the list directly - it returns None, so you're actually setting A to be None - probably not what you wanted!\nThere are two things you can do to help avoid this type of error in the future.\n\nDon't use one-letter variable names. Use descriptive, one to three-word length names that describe what the variable has in it (and/or what it's supposed to be used for).\nWhen you do have a problem, try putting it in a try/except block where you put the error name after except and print out the offending variables:\n\n\n\n\ntry:\n s.append(s[i]+A+B)\nexcept TypeError:\n print \"Failed to add\", s[i], \",\", A, \",\", \"and\", B\n raise\n\nDon't forget the raise at the end there - that way you don't just ignore the issue and start getting really strange errors.\n", "If A and B are strings, then s[i] must be a 'long'.\n", "s[i] is likely a long. You can't add a long to a string.\nTry:\n\nA=s.append(str(s[i])+A+B)\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612507_python.txt
Q: indexing error in list in python B=l.append((l[i]+A+B)) l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ? A: List index out of range means that i is greater than len(l) - 1 (since Python, and many other programming languages, use indexing that starts at 0 instead of 1, the last item in the list has index len(l) - 1, not just len(l). Try debugging like so: try: B = l.append((l[i] + A + B)) except IndexError: print "Appending from index", i, "to list l of length:", len(l) raise This will tell you the value of i and the length of l when the append fails so you can search for the problem. Is this in a loop? It may help to show us the code of the loop. It could be that, even though you're increasing the length of l by appending to it, you're increasing i even faster, so that it eventually gets to be bigger than len(l) - 1. A: There are many problems in your code: 1) the append method does not return anything, so it does not make sense to write B = l.append(...) 2) The double parenthesis are confusing, the code you wrote is exactly equivalent to B.append(l[i]+A+B) 3) Finally, obviously, the index i must be a valid index for the list l, otherwise you will get an IndexError exception. A: Variable i is larger or equal to the size of the l array.
indexing error in list in python
B=l.append((l[i]+A+B)) l is a list here and i am trying to append into it more value for it to act as an array . But its still giving me error like list index out of range . How to get rid of it ?
[ "List index out of range means that i is greater than len(l) - 1 (since Python, and many other programming languages, use indexing that starts at 0 instead of 1, the last item in the list has index len(l) - 1, not just len(l).\nTry debugging like so:\ntry:\n B = l.append((l[i] + A + B))\nexcept IndexError:\n print \"Appending from index\", i, \"to list l of length:\", len(l)\n raise\n\nThis will tell you the value of i and the length of l when the append fails so you can search for the problem.\nIs this in a loop? It may help to show us the code of the loop. It could be that, even though you're increasing the length of l by appending to it, you're increasing i even faster, so that it eventually gets to be bigger than len(l) - 1.\n", "There are many problems in your code:\n1) the append method does not return anything, so it does not make sense to write B = l.append(...)\n2) The double parenthesis are confusing, the code you wrote is exactly equivalent to B.append(l[i]+A+B)\n3) Finally, obviously, the index i must be a valid index for the list l, otherwise you will get an IndexError exception.\n", "Variable i is larger or equal to the size of the l array.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612461_python.txt
Q: How do you construct an array suitable for numpy sorting? I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods: import numpy x=numpy.asarray([5,4,3]) y=numpy.asarray([33,44,55]) dtype=[('alpha',float), ('beta',float)] values=numpy.array([(x),(y)]) values=numpy.rollaxis(values,1) #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') print "Try 1:\n", values values=numpy.empty((len(x),2)) for n in range (len(x)): values[n][0]=y[n] values[n][1]=x[n] print "Try 2:\n", values #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') ### values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])] print "Try 3:\n", values values = numpy.array(values, dtype=dtype) a=numpy.array(values,dtype=dtype) q=numpy.sort(a,order='alpha') print "Result:\n",q I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly? *** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again? A: I think what you want is the zip function. If you have x = [1,2,3] y = [4,5,6] then zip(x,y) == [(1,4),(2,5),(3,6)] So your array could be constructed using a = numpy.array(zip(x,y), dtype=dtype) A: for your bonus question -- zip actually unzips too: In [1]: a = range(10) In [2]: b = range(10, 20) In [3]: c = zip(a, b) In [4]: c Out[4]: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)] In [5]: d, e = zip(*c) In [6]: d, e Out[6]: ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)) A: Simon suggested argsort as an alternative approach; I'd recommend it as the way to go. No messy merging, zipping, or unzipping: just access by index. idx = numpy.argsort(x) ans = [ (x[idx[i]],y[idx[i]]) for i in idx] A: zip() might be inefficient for large arrays. numpy.dstack() could be used instead of zip: ndx = numpy.argsort(x) values = numpy.dstack((x[ndx], y[ndx])) A: I think you just need to specify the axis that you are sorting on when you have made your final ndarray. Alternatively argsort one of the original arrays and you'll have an index array that you can use to look up in both x and y, which might mean you don't need values at all. (scipy.org seems to be unreachable right now or I would post you a link to some docs) Given that your description doesn't quite match your code snippet it's hard to say with certainty, but I think you have over-complicated the creation of your numpy array. A: I couldn't get a working solution using Numpy's sort function, but here's something else that works: import numpy x = [5,4,3] y = [33,44,55] r = numpy.asarray([(x[i],y[i]) for i in numpy.lexsort([x])]) lexsort returns the permutation of the array indices which puts the rows in sorted order. If you wanted your results sorted on multiple keys, e.g. by x and then by y, use numpy.lexsort([x,y]) instead.
How do you construct an array suitable for numpy sorting?
I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods: import numpy x=numpy.asarray([5,4,3]) y=numpy.asarray([33,44,55]) dtype=[('alpha',float), ('beta',float)] values=numpy.array([(x),(y)]) values=numpy.rollaxis(values,1) #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') print "Try 1:\n", values values=numpy.empty((len(x),2)) for n in range (len(x)): values[n][0]=y[n] values[n][1]=x[n] print "Try 2:\n", values #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') ### values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])] print "Try 3:\n", values values = numpy.array(values, dtype=dtype) a=numpy.array(values,dtype=dtype) q=numpy.sort(a,order='alpha') print "Result:\n",q I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly? *** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?
[ "I think what you want is the zip function. If you have \nx = [1,2,3]\ny = [4,5,6]\n\nthen zip(x,y) == [(1,4),(2,5),(3,6)]\nSo your array could be constructed using\na = numpy.array(zip(x,y), dtype=dtype)\n\n", "for your bonus question -- zip actually unzips too:\nIn [1]: a = range(10)\nIn [2]: b = range(10, 20)\nIn [3]: c = zip(a, b)\nIn [4]: c\nOut[4]: \n[(0, 10),\n (1, 11),\n (2, 12),\n (3, 13),\n (4, 14),\n (5, 15),\n (6, 16),\n (7, 17),\n (8, 18),\n (9, 19)]\nIn [5]: d, e = zip(*c)\nIn [6]: d, e\nOut[6]: ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19))\n\n", "Simon suggested argsort as an alternative approach; I'd recommend it as the way to go. No messy merging, zipping, or unzipping: just access by index.\nidx = numpy.argsort(x)\nans = [ (x[idx[i]],y[idx[i]]) for i in idx]\n\n", "zip() might be inefficient for large arrays. numpy.dstack() could be used instead of zip:\nndx = numpy.argsort(x)\nvalues = numpy.dstack((x[ndx], y[ndx]))\n\n", "I think you just need to specify the axis that you are sorting on when you have made your final ndarray. Alternatively argsort one of the original arrays and you'll have an index array that you can use to look up in both x and y, which might mean you don't need values at all.\n(scipy.org seems to be unreachable right now or I would post you a link to some docs)\nGiven that your description doesn't quite match your code snippet it's hard to say with certainty, but I think you have over-complicated the creation of your numpy array.\n", "I couldn't get a working solution using Numpy's sort function, but here's something else that works:\nimport numpy\nx = [5,4,3]\ny = [33,44,55]\nr = numpy.asarray([(x[i],y[i]) for i in numpy.lexsort([x])])\n\nlexsort returns the permutation of the array indices which puts the rows in sorted order. If you wanted your results sorted on multiple keys, e.g. by x and then by y, use numpy.lexsort([x,y]) instead.\n" ]
[ 6, 3, 3, 3, 2, 1 ]
[]
[]
[ "algorithm", "arrays", "numpy", "python" ]
stackoverflow_0000560283_algorithm_arrays_numpy_python.txt
Q: struct.error: unpack requires a string argument of length 4 Python says I need 4 bytes for a format code of "BH": struct.error: unpack requires a string argument of length 4 Here is the code, I am putting in 3 bytes as I think is needed: major, minor = struct.unpack("BH", self.fp.read(3)) "B" Unsigned char (1 byte) + "H" Unsigned short (2 bytes) = 3 bytes (!?) struct.calcsize("BH") says 4 bytes. EDIT: The file is ~800 MB and this is in the first few bytes of the file so I'm fairly certain there's data left to be read. A: The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider: struct { 11 char a; 012345678901 short b; ------------ char c; axbbcxxxdddd int d; }; This structure will occupy 12 bytes of memory (x being pad bytes). Python works similarly (see the struct documentation): >>> import struct >>> struct.pack('BHBL',1,2,3,4) '\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00' >>> struct.calcsize('BHBL') 12 Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding: >>> struct.calcsize('=BHBL') 8 >>> struct.pack('=BHBL',1,2,3,4) '\x01\x02\x00\x03\x04\x00\x00\x00' Beware of letting struct handle padding. In C, these structures: struct A { struct B { short a; int a; char b; char b; }; }; are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end: >>> struct.pack('LB',1,2) '\x01\x00\x00\x00\x02' >>> struct.pack('LBLB',1,2,3,4) '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04' A: By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char. To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding: >>> struct.calcsize('=BH') 3 The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.
struct.error: unpack requires a string argument of length 4
Python says I need 4 bytes for a format code of "BH": struct.error: unpack requires a string argument of length 4 Here is the code, I am putting in 3 bytes as I think is needed: major, minor = struct.unpack("BH", self.fp.read(3)) "B" Unsigned char (1 byte) + "H" Unsigned short (2 bytes) = 3 bytes (!?) struct.calcsize("BH") says 4 bytes. EDIT: The file is ~800 MB and this is in the first few bytes of the file so I'm fairly certain there's data left to be read.
[ "The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add \"pad bytes\" to make structure members fall on natural boundaries. Consider:\nstruct { 11\n char a; 012345678901\n short b; ------------\n char c; axbbcxxxdddd\n int d;\n};\n\nThis structure will occupy 12 bytes of memory (x being pad bytes).\nPython works similarly (see the struct documentation):\n>>> import struct\n>>> struct.pack('BHBL',1,2,3,4)\n'\\x01\\x00\\x02\\x00\\x03\\x00\\x00\\x00\\x04\\x00\\x00\\x00'\n>>> struct.calcsize('BHBL')\n12\n\nCompilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:\n>>> struct.calcsize('=BHBL')\n8\n>>> struct.pack('=BHBL',1,2,3,4)\n'\\x01\\x02\\x00\\x03\\x04\\x00\\x00\\x00'\n\nBeware of letting struct handle padding. In C, these structures:\nstruct A { struct B {\n short a; int a;\n char b; char b;\n}; };\n\nare typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:\n>>> struct.pack('LB',1,2)\n'\\x01\\x00\\x00\\x00\\x02'\n>>> struct.pack('LBLB',1,2,3,4)\n'\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x04'\n\n", "By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.\nTo disable this, use: struct.unpack(\"=BH\", data). This will use standard alignment, which doesn't add padding:\n>>> struct.calcsize('=BH')\n3\n\nThe = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.\n" ]
[ 28, 8 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0002611858_python_struct.txt
Q: error in python d not defined. I am learning python and have this error . I can figure out where\what the error is in the code. File "<string>", line 1, in <module>. Name = "" Desc = "" Gender = "" Race = "" # Prompt user for user-defined information Name = input('What is your Name? ') Desc = input('Describe yourself: ') When i run the program it outputs What is your Name? (i input d ) this gives the error Traceback (most recent call last): File "/python/chargen.py", line 19, in <module> Name = input('What is your Name? ') File "<string>", line 1, in <module> NameError: name 'd' is not defined This is an example code from Python 3 for Absolute Beginners. A: In Python 2.x, input() expects something which is a Python expression, which means that if you type d it interprets that as a variable named d. If you typed "d", then it would be fine. What you probably actually want for 2.x is raw_input(), which returns the entered value as a raw string instead of evaluating it. Since you're getting this behavior, it looks like you're using a 2.x version of the Python interpreter - instead, I'd go to www.python.org and download a Python 3.x interpreter so that it will match up with the book you're using. A: You're probably using Python 2.x, where input will eval the user input. Only in Python 3.x input() returns the raw user input. You can check the version of Python by running python in console, e.g. this is Python 2.6: ~$ python Python 2.6.5 (r265:79063, Apr 5 2010, 00:18:33) [GCC 4.2.1 (Apple Inc. build 5659)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> You can run a specific version of Python (e.g. 3.1) by python3.1: ~$ python3.1 Python 3.1.1 (r311:74480, Jan 25 2010, 15:23:53) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> A: In Python 3.0 and above, which the book you are using teaches, input() does what raw_input() did in Python 2, so in that case the code would be correct; however, it appears that you are using an older version of Python (2.6?). I would recommend going to the Python website and downloading the latest version of Python 3 instead, so you have an easier time following the book. The immediate problem, given that you are using Python 2, is that you're using input(), which evaluates whatever you give it. What you want to do is get the raw string that the user input: Name = raw_input("What is your Name? ") There are lots of little differences between Python 3.x and 2.x, so definitely go get the latest Python 3 if you want to keep using Python 3 for Absolute Beginners.
error in python d not defined.
I am learning python and have this error . I can figure out where\what the error is in the code. File "<string>", line 1, in <module>. Name = "" Desc = "" Gender = "" Race = "" # Prompt user for user-defined information Name = input('What is your Name? ') Desc = input('Describe yourself: ') When i run the program it outputs What is your Name? (i input d ) this gives the error Traceback (most recent call last): File "/python/chargen.py", line 19, in <module> Name = input('What is your Name? ') File "<string>", line 1, in <module> NameError: name 'd' is not defined This is an example code from Python 3 for Absolute Beginners.
[ "In Python 2.x, input() expects something which is a Python expression, which means that if you type d it interprets that as a variable named d. If you typed \"d\", then it would be fine.\nWhat you probably actually want for 2.x is raw_input(), which returns the entered value as a raw string instead of evaluating it.\nSince you're getting this behavior, it looks like you're using a 2.x version of the Python interpreter - instead, I'd go to www.python.org and download a Python 3.x interpreter so that it will match up with the book you're using.\n", "You're probably using Python 2.x, where input will eval the user input. Only in Python 3.x input() returns the raw user input.\nYou can check the version of Python by running python in console, e.g. this is Python 2.6:\n~$ python\nPython 2.6.5 (r265:79063, Apr 5 2010, 00:18:33) \n[GCC 4.2.1 (Apple Inc. build 5659)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> \n\nYou can run a specific version of Python (e.g. 3.1) by python3.1:\n~$ python3.1\nPython 3.1.1 (r311:74480, Jan 25 2010, 15:23:53) \n[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> \n\n", "In Python 3.0 and above, which the book you are using teaches, input() does what raw_input() did in Python 2, so in that case the code would be correct; however, it appears that you are using an older version of Python (2.6?).\nI would recommend going to the Python website and downloading the latest version of Python 3 instead, so you have an easier time following the book.\n\nThe immediate problem, given that you are using Python 2, is that you're using input(), which evaluates whatever you give it. What you want to do is get the raw string that the user input:\nName = raw_input(\"What is your Name? \")\n\nThere are lots of little differences between Python 3.x and 2.x, so definitely go get the latest Python 3 if you want to keep using Python 3 for Absolute Beginners.\n" ]
[ 21, 4, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002612948_python_python_3.x.txt
Q: What Can A 'TreeDict' (Or Treemap) Be Used For In Practice? I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java. I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc. Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it. A: I've seen several answers pointing to the "walk in ordered sequence" feature, which is indeed important, but none highlighting the other big feature, which is "find first entry with a key >= this". This has many uses even when there's no real need to "walk" from there. For example (this came up in a recent SO answer), say you want to generate pseudo-random values with given relative frequencies -- i.e, you're given, say, a dict d: {'wolf': 42, 'sheep': 15, 'dog': 23, 'goat': 15, 'cat': 5} and need a way to generate 'wolf' with a probability of 42 out of 100 (since 100 is the total of the relative frequencies given), 'sheep' 15 out of 100, and so on; and the number of distinct values can be quite large, as can the relative frequencies. Then, store the given values (in whatever order) as the values in a tree map, with the corresponding keys being the "total cumulative frequency" up to that point. I.e.: def preprocess(d): tot = 0 for v in d: tot += d[v] treemap.insert(key=tot, value=v) return tot, treemap Now, generating a value can be pretty fast (O(log(len(d)))), as follows: def generate(tot, treemap, r=random): n = r.randrange(tot) return treemap.firstGTkey(n).value where firstGTKey is a method that returns the first entry (with .key and .value attributes, in this hypothetical example) with a key > the given argument. I've used this approach with large files stored as B-Trees, for example (using e.g. bsddb.bt_open and the set_location method). A: The reason for keeping the elements in sorted order is for faster retrieval. Say I wanted all of the values in the dictionary in a sorted range. This is much faster with a TreeDict then with the regular hashmap. It basically allows you to keep everything in the dictionary in sorted order. I know in the application I'm currently working on uses a class like this to basically query the data structure. A: It's useful when you need to go through a Dictionary in order of the keys; which comes up on occasion. I've actually found its infinitely more common in certain programming contests then anything else (think ACM, etc). The most useful feature of a TreeMap is when you want to quickly find the min or max key; using a sorted dictionary this is often a single method call; and algorithmically can be done in O(log(n)) time, as opposed to iterating over each key looking for a min/max if the collection is unsorted. Basically, a much friendlier interface. One of the more common times I run into it is when objects are identified by a specific name, and you want to print out the objects ordered according to the name; say a mapping from directory name to number of files in a directory. One other place I've used it is in an excel spreadsheet wrapper; mapping from row number to row object. This lets you quickly find the last row index, without looping through each row. Also, it's useful when you can easily define a comparison relation on keys, but not necessarily a hashing function, as needed for HashMaps. The best (though weak) example I can think of is case insensitive string keys. A: I often use Dict<DateTime, someClassOrValue> when working with industrial process data-- Valve open/close, machinery start/stop, etc. Having the keys sorted is especially useful when I need to compare time intervals between start/stop or open/close events in a decent amount of time. However, since I've been able to use linq in C# I've found that it's often easier to just work with IEnumerables and use the IQueryable extension methods to get the information I need. A: Almost all "GROUP BY" reporting requires a sorted dictionary. summary = sortedDefaultDict() for row in somePileOfData: summary[row.group_by] += row.balance for k in sorted(summary.keys()): print k, summary[k] This is done so often in data warehousing applications, that it's difficult to express how central this is. If the sorted function call does no work, it saves a ton of time in the long run. A: Have you seen that: http://code.activestate.com/recipes/576998/ ? zuo A: They can make various algorithms easier to implement.
What Can A 'TreeDict' (Or Treemap) Be Used For In Practice?
I'm developing a 'TreeDict' class in Python. This is a basically a dict that allows you to retrieve its key-value pairs in sorted order, just like the Treemap collection class in Java. I've implemented some functionality based on the way unique indexes in relational databases can be used, e.g. functions to let you retrieve values corresponding to a range of keys, keys greater than, less than or equal to a particular value in sorted order, strings or tuples that have a specific prefix in sorted order, etc. Unfortunately, I can't think of any real life problem that will require a class like this. I suspect that the reason we don't have sorted dicts in Python is that in practice they aren't required often enough to be worth it, but I want to be proved wrong. Can you think of any specific applications of a 'TreeDict'? Any real life problem that would be best solved by this data structure? I just want to know for sure whether this is worth it.
[ "I've seen several answers pointing to the \"walk in ordered sequence\" feature, which is indeed important, but none highlighting the other big feature, which is \"find first entry with a key >= this\". This has many uses even when there's no real need to \"walk\" from there.\nFor example (this came up in a recent SO answer), say you want to generate pseudo-random values with given relative frequencies -- i.e, you're given, say, a dict d:\n{'wolf': 42, 'sheep': 15, 'dog': 23, 'goat': 15, 'cat': 5}\n\nand need a way to generate 'wolf' with a probability of 42 out of 100 (since 100 is the total of the relative frequencies given), 'sheep' 15 out of 100, and so on; and the number of distinct values can be quite large, as can the relative frequencies.\nThen, store the given values (in whatever order) as the values in a tree map, with the corresponding keys being the \"total cumulative frequency\" up to that point. I.e.:\ndef preprocess(d):\n tot = 0\n for v in d:\n tot += d[v]\n treemap.insert(key=tot, value=v)\n return tot, treemap\n\nNow, generating a value can be pretty fast (O(log(len(d)))), as follows:\ndef generate(tot, treemap, r=random):\n n = r.randrange(tot)\n return treemap.firstGTkey(n).value\n\nwhere firstGTKey is a method that returns the first entry (with .key and .value attributes, in this hypothetical example) with a key > the given argument. I've used this approach with large files stored as B-Trees, for example (using e.g. bsddb.bt_open and the set_location method).\n", "The reason for keeping the elements in sorted order is for faster retrieval. Say I wanted all of the values in the dictionary in a sorted range. This is much faster with a TreeDict then with the regular hashmap. It basically allows you to keep everything in the dictionary in sorted order. I know in the application I'm currently working on uses a class like this to basically query the data structure.\n", "It's useful when you need to go through a Dictionary in order of the keys; which comes up on occasion. I've actually found its infinitely more common in certain programming contests then anything else (think ACM, etc).\nThe most useful feature of a TreeMap is when you want to quickly find the min or max key; using a sorted dictionary this is often a single method call; and algorithmically can be done in O(log(n)) time, as opposed to iterating over each key looking for a min/max if the collection is unsorted. Basically, a much friendlier interface.\nOne of the more common times I run into it is when objects are identified by a specific name, and you want to print out the objects ordered according to the name; say a mapping from directory name to number of files in a directory.\nOne other place I've used it is in an excel spreadsheet wrapper; mapping from row number to row object. This lets you quickly find the last row index, without looping through each row.\nAlso, it's useful when you can easily define a comparison relation on keys, but not necessarily a hashing function, as needed for HashMaps. The best (though weak) example I can think of is case insensitive string keys.\n", "I often use Dict<DateTime, someClassOrValue> when working with industrial process data--\nValve open/close, machinery start/stop, etc.\nHaving the keys sorted is especially useful when I need to compare time intervals between start/stop or open/close events in a decent amount of time.\nHowever, since I've been able to use linq in C# I've found that it's often easier to just work with IEnumerables and use the IQueryable extension methods to get the information I need.\n", "Almost all \"GROUP BY\" reporting requires a sorted dictionary.\nsummary = sortedDefaultDict()\nfor row in somePileOfData:\n summary[row.group_by] += row.balance\nfor k in sorted(summary.keys()):\n print k, summary[k]\n\nThis is done so often in data warehousing applications, that it's difficult to express how central this is.\nIf the sorted function call does no work, it saves a ton of time in the long run.\n", "Have you seen that: http://code.activestate.com/recipes/576998/ ?\nzuo\n", "They can make various algorithms easier to implement.\n" ]
[ 6, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "collections", "dictionary", "python", "treemap", "uses" ]
stackoverflow_0001014247_collections_dictionary_python_treemap_uses.txt
Q: Python: Is there a way to reflectivly list all attributes of a class Given a class such as class MyClass: text = "hello" number = 123 Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the class I am to get it's attributes for are generate using SWIG (so they are hidden in .so :) ). So I am really looking for something equivalant to Java's [Class.getDeclardFields][1] Any help would be appreciated, otherwise I'll have to solve this problem with SWIG + JAVA instead of SWIG + Python. A: I usually just use dir(MyClass). Works on instantiated objects too. edit: I should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically. Also it may not work on linked libraries. A: >>> import cmath >>> dir(cmath) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> cmath.atan <built-in function atan> is dirable and open("/usr/lib/python2.6/lib-dynload/cmath.so", O_RDONLY) = 4 read(4, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0@\17\0\0004\0\0\0"..., 512) = 512 fstat64(4, {st_mode=S_IFREG|0644, st_size=32176, ...}) = 0 mmap2(NULL, 43824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x268000 mmap2(0x26f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x6) = 0x26f000 mmap2(0x271000, 6960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x271000 close(4) is dynamically loaded
Python: Is there a way to reflectivly list all attributes of a class
Given a class such as class MyClass: text = "hello" number = 123 Is there a way in python to inspect MyClass an determine that it has the two attributes text and number. I can not use something like inspect.getSource(object) because the class I am to get it's attributes for are generate using SWIG (so they are hidden in .so :) ). So I am really looking for something equivalant to Java's [Class.getDeclardFields][1] Any help would be appreciated, otherwise I'll have to solve this problem with SWIG + JAVA instead of SWIG + Python.
[ "I usually just use dir(MyClass). Works on instantiated objects too.\nedit:\nI should mention this is a shorthand function I use for figuring out if my objects are getting created correctly. You might want to look more carefully into the reflection API's if you're doing this programmatically. \nAlso it may not work on linked libraries.\n", ">>> import cmath\n>>> dir(cmath)\n['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']\n>>> cmath.atan\n<built-in function atan>\n\nis dirable and\nopen(\"/usr/lib/python2.6/lib-dynload/cmath.so\", O_RDONLY) = 4\nread(4, \"\\177ELF\\1\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0\\3\\0\\1\\0\\0\\0@\\17\\0\\0004\\0\\0\\0\"..., 512) = 512\nfstat64(4, {st_mode=S_IFREG|0644, st_size=32176, ...}) = 0\nmmap2(NULL, 43824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 4, 0) = 0x268000\nmmap2(0x26f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 4, 0x6) = 0x26f000\nmmap2(0x271000, 6960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x271000\nclose(4)\n\nis dynamically loaded\n" ]
[ 8, 0 ]
[ "Please write actual, executable code snippets; don't expect people answering your question to first fix your code.\nclass MyClass(object):\n text = \"hello\"\n number = 123\n\nfor a in dir(MyClass):\n print a\n\n" ]
[ -1 ]
[ "python", "reflection", "swig" ]
stackoverflow_0002612257_python_reflection_swig.txt
Q: SQLAlchemy unsupported type error - and table design issues? back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('preferences', Integer), Column('allocated_rank', Integer), Column('allocated_project', Integer) ) metadata.create_all(engine) mapper(Student, students_table) Fairly simple, and for the most part I've been enjoying the ability to query almost any bit of information I want provided I avoid the error cases below. The class it is mapped from is: class Student(object): def __init__(self, sid, name): self.sid = sid self.name = name self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.sid, self.name) Explanation: preferences is basically a set of all the projects the student would prefer to be assigned. When the allocation algorithm kicks in, a student's allocated_project emerges from this preference set. Now if I try to do this: for student in students.itervalues(): session.add(student) session.commit() It throws two errors, one for the allocated_project column (seen below) and a similar error for the preferences column: sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 4 - probably unsupported type. u'INSERT INTO studs (sid, name, allocated_rank, allocated_project) VALUES (?, ?, ?, ?, ?, ?, ?)' [1101, 'Muffett,M.', 1, 888 Human-spider relationships (Supervisor id: 123)] If I go back into my code I find that, when I'm copying the preferences from the given text files, it actually refers to the Project class which is mapped to a dictionary, using the unique project id's (pid) as keys. Thus, as I iterate through each student via their rank and to the preferences set, it adds not a project id, but the reference to the project id from the projects dictionary. students[sid].preferences[int(rank)].add(projects[int(pid)]) Now this is very useful to me since I can find out all I want to about a student's preferred projects without having to run another check to pull up information about the project id. The form you see in the error has the object print information passed as: return "%s %s (Supervisor id: %s)" %(self.proj_id, self.proj_name, self.proj_sup) My questions are: I'm trying to store an object in a database field aren't I? Would the correct way then, be copying the project information (project id, name, etc) into its own table, referenced by the unique project id? That way I can just have the project id field for one of the student tables just be an integer id and when I need more information, just join the tables? So and so forth for other tables? If the above makes sense, then how does one maintain the relationship with a column of information in one table which is a key index on another table? Does this boil down into a database design problem? Are there any other elegant ways of accomplishing this? Apologies if this is a very long-winded question. It's rather crucial for me to solve this, so I've tried to explain as much as I can, whilst attempting to show that I'm trying (key word here sadly) to understand what could be going wrong. A: Do you expect that SQLAlchemy magically convert your object and collection of objects to integer value? It's impossible. SQLAlchemy can store related objects in separate tables or serialized, but it doesn't have telepathic algorithms to read your mind. So you have to describe your choice explicitly. Answers to your questions: Yes, adding to session and then committing will store your object[s] to database. Yes, storing related objects in separate table is quite common idiom. SQLAlchemy handles quite nicely so you don't need to specify joins explicitly in most cases. There is good chapter in SQLAlchemy tutorial on this topic. Storing related objects in separate table causes no database design problems. It's idiom used in most case. Using separate table is the best way for most cases. But there is also an PickleType column type which uses BLOB to store serialized object.
SQLAlchemy unsupported type error - and table design issues?
back again with some more SQLAlchemy shenanigans. Let me step through this. My table is now set up as so: engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() students_table = Table('studs', metadata, Column('sid', Integer, primary_key=True), Column('name', String), Column('preferences', Integer), Column('allocated_rank', Integer), Column('allocated_project', Integer) ) metadata.create_all(engine) mapper(Student, students_table) Fairly simple, and for the most part I've been enjoying the ability to query almost any bit of information I want provided I avoid the error cases below. The class it is mapped from is: class Student(object): def __init__(self, sid, name): self.sid = sid self.name = name self.preferences = collections.defaultdict(set) self.allocated_project = None self.allocated_rank = 0 def __repr__(self): return str(self) def __str__(self): return "%s %s" %(self.sid, self.name) Explanation: preferences is basically a set of all the projects the student would prefer to be assigned. When the allocation algorithm kicks in, a student's allocated_project emerges from this preference set. Now if I try to do this: for student in students.itervalues(): session.add(student) session.commit() It throws two errors, one for the allocated_project column (seen below) and a similar error for the preferences column: sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 4 - probably unsupported type. u'INSERT INTO studs (sid, name, allocated_rank, allocated_project) VALUES (?, ?, ?, ?, ?, ?, ?)' [1101, 'Muffett,M.', 1, 888 Human-spider relationships (Supervisor id: 123)] If I go back into my code I find that, when I'm copying the preferences from the given text files, it actually refers to the Project class which is mapped to a dictionary, using the unique project id's (pid) as keys. Thus, as I iterate through each student via their rank and to the preferences set, it adds not a project id, but the reference to the project id from the projects dictionary. students[sid].preferences[int(rank)].add(projects[int(pid)]) Now this is very useful to me since I can find out all I want to about a student's preferred projects without having to run another check to pull up information about the project id. The form you see in the error has the object print information passed as: return "%s %s (Supervisor id: %s)" %(self.proj_id, self.proj_name, self.proj_sup) My questions are: I'm trying to store an object in a database field aren't I? Would the correct way then, be copying the project information (project id, name, etc) into its own table, referenced by the unique project id? That way I can just have the project id field for one of the student tables just be an integer id and when I need more information, just join the tables? So and so forth for other tables? If the above makes sense, then how does one maintain the relationship with a column of information in one table which is a key index on another table? Does this boil down into a database design problem? Are there any other elegant ways of accomplishing this? Apologies if this is a very long-winded question. It's rather crucial for me to solve this, so I've tried to explain as much as I can, whilst attempting to show that I'm trying (key word here sadly) to understand what could be going wrong.
[ "Do you expect that SQLAlchemy magically convert your object and collection of objects to integer value? It's impossible. SQLAlchemy can store related objects in separate tables or serialized, but it doesn't have telepathic algorithms to read your mind. So you have to describe your choice explicitly.\nAnswers to your questions:\n\nYes, adding to session and then committing will store your object[s] to database.\nYes, storing related objects in separate table is quite common idiom. SQLAlchemy handles quite nicely so you don't need to specify joins explicitly in most cases.\nThere is good chapter in SQLAlchemy tutorial on this topic.\nStoring related objects in separate table causes no database design problems. It's idiom used in most case.\nUsing separate table is the best way for most cases. But there is also an PickleType column type which uses BLOB to store serialized object.\n\n" ]
[ 4 ]
[]
[]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0002609719_database_design_python_sqlalchemy.txt
Q: beautifulsoup and mechanize to get ajax call result hi im building a scraper using python 2.5 and beautifulsoup but im stuble upon a problem ... part of the web page is generating after user click on some button, whitch start an ajax request by calling specific javacsript function using proper parameters is there a way to simulate user interaction and get this result? i come across a mechanize module but it seems to me that this is mostly used to work with forms ... i would appreciate any links or some code samples thanks A: ok so i have figured it out ... it was quite simple after i realised that i could use combination of urllib, ulrlib2 and beautifulsoup import urllib, urllib2 from BeautifulSoup import BeautifulSoup as bs_parse data = urllib.urlencode(values) req = urllib2.Request(url, data) res = urllib2.urlopen(req) page = bs_parse(res.read()) A: No, you can't do that easily. AFAIK your options are, easiest first: Read the AJAX javascript code yourself, as a human programmer, understand it, and then write python code to simulate the AJAX calls by hand. You can also use some capture software to capture requests/responses made live and try to reproduce them with code; Use selenium or some other browser automation tool to fetch the page on a real web browser; Use some python javascript runner like spidermonkey or pyv8 to run the javascript code, and hook it to your copy of the HTML dom;
beautifulsoup and mechanize to get ajax call result
hi im building a scraper using python 2.5 and beautifulsoup but im stuble upon a problem ... part of the web page is generating after user click on some button, whitch start an ajax request by calling specific javacsript function using proper parameters is there a way to simulate user interaction and get this result? i come across a mechanize module but it seems to me that this is mostly used to work with forms ... i would appreciate any links or some code samples thanks
[ "ok so i have figured it out ... it was quite simple after i realised that i could use combination of urllib, ulrlib2 and beautifulsoup\nimport urllib, urllib2\nfrom BeautifulSoup import BeautifulSoup as bs_parse\n\ndata = urllib.urlencode(values)\nreq = urllib2.Request(url, data)\nres = urllib2.urlopen(req)\npage = bs_parse(res.read())\n\n", "No, you can't do that easily. AFAIK your options are, easiest first:\n\nRead the AJAX javascript code yourself, as a human programmer, understand it, and then write python code to simulate the AJAX calls by hand. You can also use some capture software to capture requests/responses made live and try to reproduce them with code;\nUse selenium or some other browser automation tool to fetch the page on a real web browser;\nUse some python javascript runner like spidermonkey or pyv8 to run the javascript code, and hook it to your copy of the HTML dom;\n\n" ]
[ 6, 3 ]
[]
[]
[ "ajax", "beautifulsoup", "mechanize", "python", "scraper" ]
stackoverflow_0002610112_ajax_beautifulsoup_mechanize_python_scraper.txt
Q: How hard is it to modify the Django Models? I am doing geolocation, and Django does not have a PointField. So, I am forced to writing in RAW SQL. GeoDjango, the Django library, does not support the following query for MYSQL databases (can someone verify that for me?) cursor.execute("SELECT id FROM l_tag WHERE\ (GLength(LineStringFromWKB(LineString(asbinary(utm),asbinary(PointFromWKB(point(%s, %s)))))) < %s + accuracy + %s)\ I don't nkow why GeoDjango library cannot do this in MYSQL database. I hate writing RAW SQL for calculating distances between two points. Is there a way I can create my own library for Django that can handle this? If so, how hard is it? A: Why don't you just extend a class that's already there? Just curious and wish I could help you specifically. A: GeoDjango does have a PointField. It looks like you're trying to do a dwithin field lookup, which does not work on MySQL (as of April 2010), but does in Postgres: class Tag(Model): point = PointField() Tag.objects.filter(point__dwithin=(point,D(mi=4))) Careful with this kind of query, as it requires a table scan. If you can tolerate selecting all points within a rectangular region, you could use the bounding box contained query: Tag.objects.filter(point__contained=geom) where geom is a polygon.
How hard is it to modify the Django Models?
I am doing geolocation, and Django does not have a PointField. So, I am forced to writing in RAW SQL. GeoDjango, the Django library, does not support the following query for MYSQL databases (can someone verify that for me?) cursor.execute("SELECT id FROM l_tag WHERE\ (GLength(LineStringFromWKB(LineString(asbinary(utm),asbinary(PointFromWKB(point(%s, %s)))))) < %s + accuracy + %s)\ I don't nkow why GeoDjango library cannot do this in MYSQL database. I hate writing RAW SQL for calculating distances between two points. Is there a way I can create my own library for Django that can handle this? If so, how hard is it?
[ "Why don't you just extend a class that's already there? Just curious and wish I could help you specifically.\n", "GeoDjango does have a PointField. \nIt looks like you're trying to do a dwithin field lookup, which does not work on MySQL (as of April 2010), but does in Postgres:\nclass Tag(Model):\n point = PointField()\nTag.objects.filter(point__dwithin=(point,D(mi=4)))\nCareful with this kind of query, as it requires a table scan. If you can tolerate selecting all points within a rectangular region, you could use the bounding box contained query:\nTag.objects.filter(point__contained=geom) \nwhere geom is a polygon.\n" ]
[ 0, 0 ]
[]
[]
[ "database", "django", "geodjango", "mysql", "python" ]
stackoverflow_0002548791_database_django_geodjango_mysql_python.txt
Q: Eclipse PyDev doesn't shut down interpreter when you click the little red button Seems that even after unchecking the option in the PyDev/Debug preferenecs pane to launch in the background, once it's launched I have to go to task manager to kill the python process. A: This often happens when you're using something like cherrypy/django and the process restarts after you've changed a python file while it's running. When this happens, I think the process is different but still using the same output console and thus won't be killed when you press the red button. I'm not sure there's a way of fixing it, except for disabling auto-restarting in the web framework etc. A: As far as I can tell when working with Django you need to add runserver --noreload to your program argument in Run > Run... menu
Eclipse PyDev doesn't shut down interpreter when you click the little red button
Seems that even after unchecking the option in the PyDev/Debug preferenecs pane to launch in the background, once it's launched I have to go to task manager to kill the python process.
[ "This often happens when you're using something like cherrypy/django and the process restarts after you've changed a python file while it's running. When this happens, I think the process is different but still using the same output console and thus won't be killed when you press the red button. \nI'm not sure there's a way of fixing it, except for disabling auto-restarting in the web framework etc.\n", "As far as I can tell when working with Django you need to add runserver --noreload to your program argument in Run > Run... menu\n" ]
[ 1, 1 ]
[]
[]
[ "eclipse", "eclipse_plugin", "pydev", "python" ]
stackoverflow_0002613672_eclipse_eclipse_plugin_pydev_python.txt
Q: ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN? I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not. It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python command-line tools for management. the items in question are mostly books and artist prints, some of which are self-published. What is nice about using ISBNs as primary keys is that in on top of relational integrity, you get lots of handy utilities for validating ISBNs, automatically looking up missing or additional information on the book items, etcetera, many of which I've taken advantage. some such tools are off-the-shelf (PyISBN, PyAWS etc) and some are hand-rolled -- I tried to keep all of these parts nice and decoupled, but you know how things can get. I couldn't find anything online about 'private ISBNs' or 'self-assigned ISBNs' but that's the sort of thing I was interested in doing. I doubt that's what I'll settle on, since there is already an apparent run on ISBN numbers. should I retool everything for EAN numbers, or migrate off ISBNs as primary keys in general? if anyone has any experience with working with these systems, I'd love to hear about it, your advice is most welcome. A: I don't know postgres but normally ISBM would be a unique index key but not the primary. It's better to have an integer as primary/foreign key. That way you only need to add a new field EAN/ISSN as nullable. A: I agree with the_lotus, not least because ISBN is a poor choice for primary key Data wise, it may not be unique enough. If clustered, it's quite wide and non-numeric Example A: If you're using ISBN-10s, then you definitely should migrate to something else, as those are already deprecated. You can easily take ISBN-10s and turn them into ISBN-13s (see wikipedia), which I think are EAN-compatible (again, see wikipedia), but as the_lotus suggests, it's probably better to have some sort of auto-incrementing integer with no external meaning as the primary key and then index on the EAN/ISBN/etc. A: A simple solution (although arguably whether good) would be to use (isbn,title) or (isbn,author) which should pretty much guarantee uniqueness. Ideology is great but practicality also serves a purpose.
ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN?
I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not. It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python command-line tools for management. the items in question are mostly books and artist prints, some of which are self-published. What is nice about using ISBNs as primary keys is that in on top of relational integrity, you get lots of handy utilities for validating ISBNs, automatically looking up missing or additional information on the book items, etcetera, many of which I've taken advantage. some such tools are off-the-shelf (PyISBN, PyAWS etc) and some are hand-rolled -- I tried to keep all of these parts nice and decoupled, but you know how things can get. I couldn't find anything online about 'private ISBNs' or 'self-assigned ISBNs' but that's the sort of thing I was interested in doing. I doubt that's what I'll settle on, since there is already an apparent run on ISBN numbers. should I retool everything for EAN numbers, or migrate off ISBNs as primary keys in general? if anyone has any experience with working with these systems, I'd love to hear about it, your advice is most welcome.
[ "I don't know postgres but normally ISBM would be a unique index key but not the primary. It's better to have an integer as primary/foreign key. That way you only need to add a new field EAN/ISSN as nullable.\n", "I agree with the_lotus, not least because ISBN is a poor choice for primary key\nData wise, it may not be unique enough. If clustered, it's quite wide and non-numeric\nExample\n", "If you're using ISBN-10s, then you definitely should migrate to something else, as those are already deprecated. You can easily take ISBN-10s and turn them into ISBN-13s (see wikipedia), which I think are EAN-compatible (again, see wikipedia), but as the_lotus suggests, it's probably better to have some sort of auto-incrementing integer with no external meaning as the primary key and then index on the EAN/ISBN/etc.\n", "A simple solution (although arguably whether good) would be to use (isbn,title) or (isbn,author) which should pretty much guarantee uniqueness. Ideology is great but practicality also serves a purpose.\n" ]
[ 3, 3, 2, 2 ]
[]
[]
[ "django", "isbn", "postgresql", "python" ]
stackoverflow_0002610000_django_isbn_postgresql_python.txt
Q: beautifulsoup: find the n-th element's sibling I have a complex html DOM tree of the following nature: <table> ... <tr> <td> ... </td> <td> <table> <tr> <td> <!-- inner most table --> <table> ... </table> <h2>This is hell!</h2> <td> </tr> </table> </td> </tr> </table> I have some logic to find out the inner most table. But after having found it, I need to get the next sibling element (h2). Is there anyway you can do this? A: If tag is the innermost table, then tag.findNextSibling('h2') will be <h2>This is hell!</h2> To literally get the next sibling, you could use tag.nextSibling, which in this case, is u'\n'. If you want the next sibling that is not a NavigableString (such as u'\n'), then you could use tag.findNextSibling(text=None) If you want the second sibling (no matter what it is), you could use tag.nextSibling.nextSibling (but note that if tag does not have a next sibling, then tag.nextSibling will be None, and tag.nextSibling.nextSibling will raise an AttributeError.) A: Every tag object has a nextSibling attribute that's exactly what you're looking for -- the next sibling (or None for a tag that's the last child of its parent tag, of course).
beautifulsoup: find the n-th element's sibling
I have a complex html DOM tree of the following nature: <table> ... <tr> <td> ... </td> <td> <table> <tr> <td> <!-- inner most table --> <table> ... </table> <h2>This is hell!</h2> <td> </tr> </table> </td> </tr> </table> I have some logic to find out the inner most table. But after having found it, I need to get the next sibling element (h2). Is there anyway you can do this?
[ "If tag is the innermost table, then\ntag.findNextSibling('h2')\n\nwill be\n<h2>This is hell!</h2>\n\nTo literally get the next sibling, you could use tag.nextSibling,\nwhich in this case, is u'\\n'. \nIf you want the next sibling that is not a NavigableString (such as u'\\n'), then you could use\ntag.findNextSibling(text=None)\n\nIf you want the second sibling (no matter what it is), you could use\ntag.nextSibling.nextSibling\n\n(but note that if tag does not have a next sibling, then tag.nextSibling will be None, and tag.nextSibling.nextSibling will raise an AttributeError.)\n", "Every tag object has a nextSibling attribute that's exactly what you're looking for -- the next sibling (or None for a tag that's the last child of its parent tag, of course).\n" ]
[ 10, 1 ]
[]
[]
[ "beautifulsoup", "find", "python", "siblings" ]
stackoverflow_0002613527_beautifulsoup_find_python_siblings.txt
Q: Added tagging to existing model, now how does its admin work? I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it. class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass I thought that was all I needed so I went through my old database of blog posts (this is a newly ported blog) and copied the tags in. It worked and I could display tags and filter by tag. However, I just wrote a new BlogPost and realise there's no tag field there. Reading the documentation (coincidentally, dry enough to be used as an antiperspirant), I found the TagField. Thinking this would just be a manager-style layer over the existing tagging register, I added it. It complained about there not being a Tag column. I'd rather not denormalise on tags just to satisfy create an interface for inputting them. Is there a TagManager class that I can just set on the model? tags = TagManager() # or somesuch A: Did you try using TagField() in the model instead of registering the model? from tagging.fields import TagField class BlogPost(models.Model): # ... tags = TagField() A: Like istruble said (sorry I can't comment above): Did you try using TagField() in the model instead of registering the model? from tagging.fields import TagField class BlogPost(models.Model): # ... tags = TagField() But after that, you have to change your database table. I would recommend to make a backup of your database. Then run manage.py reset APPNAME check out how the table has changed. Restore the backup and try to alter the table, so that it looks like the new one. In this way you wont lose your data ;) And remember, syncdb will not work since the table exist allready.
Added tagging to existing model, now how does its admin work?
I wanted to add a StackOverflow-style tag input to a blog model of mine. This is a model that has a lot of data already in it. class BlogPost(models.Model): # my blog fields try: tagging.register(BlogPost) except tagging.AlreadyRegistered: pass I thought that was all I needed so I went through my old database of blog posts (this is a newly ported blog) and copied the tags in. It worked and I could display tags and filter by tag. However, I just wrote a new BlogPost and realise there's no tag field there. Reading the documentation (coincidentally, dry enough to be used as an antiperspirant), I found the TagField. Thinking this would just be a manager-style layer over the existing tagging register, I added it. It complained about there not being a Tag column. I'd rather not denormalise on tags just to satisfy create an interface for inputting them. Is there a TagManager class that I can just set on the model? tags = TagManager() # or somesuch
[ "Did you try using TagField() in the model instead of registering the model?\nfrom tagging.fields import TagField\n\nclass BlogPost(models.Model):\n # ...\n tags = TagField()\n\n", "Like istruble said (sorry I can't comment above):\nDid you try using TagField() in the model instead of registering the model?\nfrom tagging.fields import TagField\n\nclass BlogPost(models.Model):\n # ...\n tags = TagField()\n\nBut after that, you have to change your database table. I would recommend to make a backup of your database. Then run manage.py reset APPNAME check out how the table has changed. Restore the backup and try to alter the table, so that it looks like the new one. In this way you wont lose your data ;)\nAnd remember, syncdb will not work since the table exist allready.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "django_tagging", "python" ]
stackoverflow_0002560240_django_django_admin_django_tagging_python.txt
Q: Python 2.5 module allowing implementation of javascript under windows hi im looking for some modules for python 2.5 whitch allows to run and executes javascript ... any ideas? A: pyv8 definitely supports Windows, but I'm not sure that it supports Python 2.5 out of the box (the pre-built binary packages definitely require Python 2.6; I think that you can build from sources with 2.5, but you might need to tweak said sources for the purpose, and I think you will also need a suitable C compiler, compatible with the one used to build your 2.5 [[mingw may help, perhaps with more tweaks]]). If you could upgrade your Python to 2.6 that would simplify things a lot... what's keeping you blocked to 2.5? A: python-spidermonkey This Python module allows for the implementation of Javascript? classes, objects and functions in Python, as well as the evaluation and calling of Javascript scripts and functions. It borrows heavily from Claes Jacobssen's Javascript Perl module, which in turn is based on Mozilla's PerlConnect Perl binding.
Python 2.5 module allowing implementation of javascript under windows
hi im looking for some modules for python 2.5 whitch allows to run and executes javascript ... any ideas?
[ "pyv8 definitely supports Windows, but I'm not sure that it supports Python 2.5 out of the box (the pre-built binary packages definitely require Python 2.6; I think that you can build from sources with 2.5, but you might need to tweak said sources for the purpose, and I think you will also need a suitable C compiler, compatible with the one used to build your 2.5 [[mingw may help, perhaps with more tweaks]]).\nIf you could upgrade your Python to 2.6 that would simplify things a lot... what's keeping you blocked to 2.5?\n", "python-spidermonkey\n\nThis Python module allows for the implementation of Javascript?\n classes, objects and functions in Python, as well as the evaluation\n and calling of Javascript scripts and functions. It borrows heavily\n from Claes Jacobssen's Javascript Perl module, which in turn is based\n on Mozilla's PerlConnect Perl binding.\n\n" ]
[ 1, 0 ]
[]
[]
[ "javascript", "python", "windows" ]
stackoverflow_0002613100_javascript_python_windows.txt
Q: Pylons custom authorizer with Authkit? How do i setup authkit for more authorizers? I want to give certain users admin rights, but only for their own page. A: http://pylonsbook.com/en/1.1/authentication-and-authorization.html#authkit What do you mean by 'admin rights, but only for their own page'? You mean that user could, for example view other user profiles and edit his own profile? In this case you should check what information should be shown to user and what actions (s)he could perform by yourself.
Pylons custom authorizer with Authkit?
How do i setup authkit for more authorizers? I want to give certain users admin rights, but only for their own page.
[ "http://pylonsbook.com/en/1.1/authentication-and-authorization.html#authkit\nWhat do you mean by 'admin rights, but only for their own page'? You mean that user could, for example view other user profiles and edit his own profile?\nIn this case you should check what information should be shown to user and what actions (s)he could perform by yourself.\n" ]
[ 1 ]
[]
[]
[ "authentication", "authkit", "pylons", "python" ]
stackoverflow_0002611325_authentication_authkit_pylons_python.txt
Q: How to enter decimal/binary numbers when creating byte objects in python? I'm using python 3.1.1. I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. Hexadecimal and octal numbers can be entered using an escape of \x for hexadecimal numbers and just a \ for octal numbers. However, there's no escape sequences for decimal or binary numbers. Is there any way to enter them into byte objects? A: You can use the built-in bytes constructor to turn a sequence of integers into a byte string: >>> bytes((7,8,9,10,11)) b'\x07\x08\t\n\x0b' >>> bytes(range(7,12)) b'\x07\x08\t\n\x0b' >>> bytes((0b1,0b0,0b1)) b'\x01\x00\x01' A: You could use binary literals for integers >>> b = bytearray(b'abc') >>> b[0] = 0b1001 # `9` decimal (TAB) >>> b bytearray(b'\tbc')
How to enter decimal/binary numbers when creating byte objects in python?
I'm using python 3.1.1. I know that I can create byte objects using the byte literal in the form of b'...'. In these byte objects, each byte can be represented as a character(in ascii code if I'm not wrong) or as a hexadecimal/octal number. Hexadecimal and octal numbers can be entered using an escape of \x for hexadecimal numbers and just a \ for octal numbers. However, there's no escape sequences for decimal or binary numbers. Is there any way to enter them into byte objects?
[ "You can use the built-in bytes constructor to turn a sequence of integers into a byte string:\n>>> bytes((7,8,9,10,11))\nb'\\x07\\x08\\t\\n\\x0b'\n>>> bytes(range(7,12))\nb'\\x07\\x08\\t\\n\\x0b'\n>>> bytes((0b1,0b0,0b1))\nb'\\x01\\x00\\x01'\n\n", "You could use binary literals for integers\n>>> b = bytearray(b'abc')\n>>> b[0] = 0b1001 # `9` decimal (TAB)\n>>> b\nbytearray(b'\\tbc')\n\n" ]
[ 4, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002614406_python_python_3.x.txt
Q: Problem with Classes in Python Ok guys, I'm really new at python (and programming itself) so sorry for my ignorance, but I really needed to ask this. So im doing a wxPython project where I added several tabs for a notebook (each tab of the notebook = a class) and there is one tab where I added a checkbox (in a tab, lets call it for example Tab1), and what I want is that when someone checks it, a button that exists in other tab (class called for example tab2) gets hidden where previously it was being shown. Well I see that it isn't hard to accomplish this, but my problem is the classes (tab1 and tab2, in this example). I've been trying to figure it out by searching but I guess im not searching hard enough because I just can't get it right. If they were in the same class I wouldn't have a problem, but as they are in different classes, im having a huge struggle with this. Hope someone can help me, and sorry for my ignorance once again. EDIT: Sorry guys wasn't being shown/hidden, but rather being enabled/disabled. class Tab2(wx.Panel): def __init__(self, parent): ..... self.jaddbutton = wx.Button(self,-1, label ="Button", size = (160,24)) self.jaddbutton.Bind(wx.EVT_BUTTON, self.jaddbuttonclick, self.jaddbutton) def jaddbuttonclick(self, event): .... class Tab1(wx.Panel): def __init__(self, parent): self.jdcheck = wx.CheckBox(self, -1, 'Disable') self.jdcheck.Bind(wx.EVT_CHECKBOX, self.checkoptions, self.jdcheck) def checkoptions(self,event): checkboxval = self.jdcheck.GetValue() if checkboxval == False: self.jaddbutton.Disable() # This is what I want to do but it is on the other class else: self.jaddbutton.Enable() # Same as above class TextFrame(wx.Frame): def __init__(self): p = wx.Panel(self) self.nb = wx.Notebook(p, size = (750, 332)) #Tabs tab1 = Tab1(self.nb) tab2 = Tab2(self.nb) self.nb.AddPage(tab1, "ssomething") self.nb.AddPage(tab2, "somethingr") A: This sounds more like a wxpython question than a classes question. Normally, in python, tab1 would need a handle to tab2 in order to hide the button in tab2. Or it would need a handle to some shared resource, like a parent class or shared model class, that would allow tab1 to affect settings in tab2 (like the hiding of a button). PyQt provides an event system to allow communication between classes which may not necessarily contain handles to each other. What is the common "accepted" way to communicate in wxpython? Here is a fairly abstract example of the shared parent solution. class Parent(object): def create_tabs(): self.tab1 = Tab1(self) self.tab2 = Tab2(self) def hide_tab2_button(): self.tab2.hide_button() class Tab1(object): def __init__(self, parent): self.parent = parent def on_checkbox_checked(self): self.parent.hide_tab2_button() class Tab2(object): def __init__(self, parent): self.parent = parent def hide_button(self): self.button.hide() # Or whatever the wxpython command is to hide a button. A: In the tabs' __init__, save the parent reference (the notebook): class Tab1(wx.Panel): def __init__(self, parent): self.parent = parent ...etc, etc... Then, self.parent.GetPage(x) lets you access the x-th page (i.e., tab) of the notebook from any other page (tab). So instead of self.jaddbutton.Disable() etc, you'd be using, e.g.: othertab = self.parent.GetPage(1) othertab.jaddbutton.Disable() and so forth.
Problem with Classes in Python
Ok guys, I'm really new at python (and programming itself) so sorry for my ignorance, but I really needed to ask this. So im doing a wxPython project where I added several tabs for a notebook (each tab of the notebook = a class) and there is one tab where I added a checkbox (in a tab, lets call it for example Tab1), and what I want is that when someone checks it, a button that exists in other tab (class called for example tab2) gets hidden where previously it was being shown. Well I see that it isn't hard to accomplish this, but my problem is the classes (tab1 and tab2, in this example). I've been trying to figure it out by searching but I guess im not searching hard enough because I just can't get it right. If they were in the same class I wouldn't have a problem, but as they are in different classes, im having a huge struggle with this. Hope someone can help me, and sorry for my ignorance once again. EDIT: Sorry guys wasn't being shown/hidden, but rather being enabled/disabled. class Tab2(wx.Panel): def __init__(self, parent): ..... self.jaddbutton = wx.Button(self,-1, label ="Button", size = (160,24)) self.jaddbutton.Bind(wx.EVT_BUTTON, self.jaddbuttonclick, self.jaddbutton) def jaddbuttonclick(self, event): .... class Tab1(wx.Panel): def __init__(self, parent): self.jdcheck = wx.CheckBox(self, -1, 'Disable') self.jdcheck.Bind(wx.EVT_CHECKBOX, self.checkoptions, self.jdcheck) def checkoptions(self,event): checkboxval = self.jdcheck.GetValue() if checkboxval == False: self.jaddbutton.Disable() # This is what I want to do but it is on the other class else: self.jaddbutton.Enable() # Same as above class TextFrame(wx.Frame): def __init__(self): p = wx.Panel(self) self.nb = wx.Notebook(p, size = (750, 332)) #Tabs tab1 = Tab1(self.nb) tab2 = Tab2(self.nb) self.nb.AddPage(tab1, "ssomething") self.nb.AddPage(tab2, "somethingr")
[ "This sounds more like a wxpython question than a classes question. Normally, in python, tab1 would need a handle to tab2 in order to hide the button in tab2. Or it would need a handle to some shared resource, like a parent class or shared model class, that would allow tab1 to affect settings in tab2 (like the hiding of a button). PyQt provides an event system to allow communication between classes which may not necessarily contain handles to each other. What is the common \"accepted\" way to communicate in wxpython?\nHere is a fairly abstract example of the shared parent solution.\nclass Parent(object):\n\n def create_tabs():\n self.tab1 = Tab1(self)\n self.tab2 = Tab2(self)\n\n def hide_tab2_button():\n self.tab2.hide_button()\n\n\nclass Tab1(object):\n def __init__(self, parent):\n self.parent = parent\n\n def on_checkbox_checked(self):\n self.parent.hide_tab2_button()\n\n\nclass Tab2(object):\n def __init__(self, parent):\n self.parent = parent\n\n def hide_button(self):\n self.button.hide() # Or whatever the wxpython command is to hide a button.\n\n", "In the tabs' __init__, save the parent reference (the notebook):\nclass Tab1(wx.Panel):\n def __init__(self, parent):\n self.parent = parent\n ...etc, etc...\n\nThen, self.parent.GetPage(x) lets you access the x-th page (i.e., tab) of the notebook from any other page (tab). So instead of self.jaddbutton.Disable() etc, you'd be using, e.g.:\nothertab = self.parent.GetPage(1)\nothertab.jaddbutton.Disable()\n\nand so forth.\n" ]
[ 6, 5 ]
[]
[]
[ "class", "python", "wxpython" ]
stackoverflow_0002614225_class_python_wxpython.txt
Q: how to create a string which can be used as an array in python? i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array. A: That's how Python strings already work: >>> a = "abcd" >>> a[0] 'a' >>> a[2] 'c' But keep in mind that this is read only access. A: You can convert a string to a list of characters by using list, and to go the other way use join: >>> s = 'Hello, world!' >>> l = list(s) >>> l[7] = 'f' >>> ''.join(l) 'Hello, forld!' A: I am a bit surprised that no one seems to have written a popular "MutableString" wrapper class for Python. I would think that you'd want to have it store the string as a list, returning it via ''.join() and implement a suite of methods including those for strings (startswith, endswith, isalpha and all its ilk and so one) and those for lists. For simple operations just operating on the list and using ''.join() as necessary is fine. However, for something something like: 'foobar'.replace('oba', 'amca') when you're working with a list representation gets to be ugly. (that=list(''.join(that).replace(something, it)) ... or something like that). The constant marshaling between list and string representations is visually distracting.
how to create a string which can be used as an array in python?
i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array.
[ "That's how Python strings already work:\n>>> a = \"abcd\"\n>>> a[0]\n'a'\n>>> a[2]\n'c'\n\nBut keep in mind that this is read only access.\n", "You can convert a string to a list of characters by using list, and to go the other way use join:\n>>> s = 'Hello, world!'\n>>> l = list(s)\n>>> l[7] = 'f'\n>>> ''.join(l)\n'Hello, forld!'\n\n", "I am a bit surprised that no one seems to have written a popular \"MutableString\" wrapper class for Python. I would think that you'd want to have it store the string as a list, returning it via ''.join() and implement a suite of methods including those for strings (startswith, endswith, isalpha and all its ilk and so one) and those for lists.\nFor simple operations just operating on the list and using ''.join() as necessary is fine. However, for something something like: 'foobar'.replace('oba', 'amca') when you're working with a list representation gets to be ugly. (that=list(''.join(that).replace(something, it)) ... or something like that). The constant marshaling between list and string representations is visually distracting.\n" ]
[ 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002612583_python.txt
Q: Python script, runs well, but not perfectly, debugging help What it does (sort of)... or is meant to, the script reads from a csv file that contains information on sound files and create a play list exactly 60 minutes long. An example csv, contains: their title, duration (in seconds), minium total time to be played (in minutes) An example is: Soundfoo,120,10 Soundbar,30,6 Sounddev,60,20 Soundrandom,15,8 The script works out the minimum instances of plays, take 'Soundfoo' for example, the length of each sample is 120 seconds and the minimum time to be played is 10 minutes, so basic maths 10*60/120 gives the number of instances the song is to be played, in this case 5. It is meant to take minimum number of instances and spread out equally from each other; so there will never be a period where for example Soundbar is played twice in a row. Then if the minium instances of each song has been used, and there is still time with in the 60 min, how is it possible to tell it to go back and fill the time by selecting each sound and including it till the 60 min is filled while remaining sparsely populated. Heres the issue(s)! The script fails to calculate the actual time require to play all the sounds in a file and the total time of the playlist, the thing is tho it doesn't get it wrong all the time maybe 3/5 times, even if I run it on the same csv file it will give me different answers. Here is the file I shall run the script on e for sake of ease to see the issue: Sound1,60,10 Sound2,60,10 Sound3,60,10 Sound4,60,10 Sound5,60,10 Sound6,60,10 I'll do it three times and post the results: 1 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 62 Total playtime in minutes: 62.0 2 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 71 Total playtime in minutes: 71.0 3 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 60 Total playtime in minutes: 60.0 Relevant Code: pastebin.com/demkBXk6 And finally... in context: http://pastebin.com/demkBXk6 If you made it down to here, thanks for staying and reading, kudos. A: I ran your code several times and I got always the same result indicated below. I can not replicate your problem. edit: sorry, yes now I see the problem. The problem is in the first while loop I would take away everything in this loop. The code is too convoluted and thus a call for bug. It can be done simpler and more clear: If what you want is to randomly shuffle the list of required_playlist you only need to do random.shuffle(required_playlist) this will shuffle the list in place. To fill the actual_plays dictionary then you can use a defaultdict from collections import defaultdict actual_plays = defaultdict(int) for song in required_playlist: actual_plays[song] += 1 This obviously can be done before or after shuffling. In this step there is no way you could obtain different numbers of repetitions than the minimum you define. cheers joaquin A: I'm guessing it has something to do with your use of the random library throughout the script. Try to break your program up into functions that contain discrete bits of logic and are named to reflect what they do.
Python script, runs well, but not perfectly, debugging help
What it does (sort of)... or is meant to, the script reads from a csv file that contains information on sound files and create a play list exactly 60 minutes long. An example csv, contains: their title, duration (in seconds), minium total time to be played (in minutes) An example is: Soundfoo,120,10 Soundbar,30,6 Sounddev,60,20 Soundrandom,15,8 The script works out the minimum instances of plays, take 'Soundfoo' for example, the length of each sample is 120 seconds and the minimum time to be played is 10 minutes, so basic maths 10*60/120 gives the number of instances the song is to be played, in this case 5. It is meant to take minimum number of instances and spread out equally from each other; so there will never be a period where for example Soundbar is played twice in a row. Then if the minium instances of each song has been used, and there is still time with in the 60 min, how is it possible to tell it to go back and fill the time by selecting each sound and including it till the 60 min is filled while remaining sparsely populated. Heres the issue(s)! The script fails to calculate the actual time require to play all the sounds in a file and the total time of the playlist, the thing is tho it doesn't get it wrong all the time maybe 3/5 times, even if I run it on the same csv file it will give me different answers. Here is the file I shall run the script on e for sake of ease to see the issue: Sound1,60,10 Sound2,60,10 Sound3,60,10 Sound4,60,10 Sound5,60,10 Sound6,60,10 I'll do it three times and post the results: 1 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 62 Total playtime in minutes: 62.0 2 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 71 Total playtime in minutes: 71.0 3 Required playtime in minutes: 60 Actual time in minutes to play all required ads: 60 Total playtime in minutes: 60.0 Relevant Code: pastebin.com/demkBXk6 And finally... in context: http://pastebin.com/demkBXk6 If you made it down to here, thanks for staying and reading, kudos.
[ "I ran your code several times and I got always the same result indicated below. I can not replicate your problem. \nedit: sorry, yes now I see the problem.\nThe problem is in the first while loop\nI would take away everything in this loop. The code is too convoluted and thus a call for bug. It can be done simpler and more clear:\nIf what you want is to randomly shuffle the list of required_playlist you only need to do\nrandom.shuffle(required_playlist)\n\nthis will shuffle the list in place.\nTo fill the actual_plays dictionary then you can use a defaultdict\nfrom collections import defaultdict\nactual_plays = defaultdict(int)\nfor song in required_playlist: actual_plays[song] += 1\n\nThis obviously can be done before or after shuffling. In this step there is no way you could obtain different numbers of repetitions than the minimum you define.\ncheers\njoaquin\n", "I'm guessing it has something to do with your use of the random library throughout the script. Try to break your program up into functions that contain discrete bits of logic and are named to reflect what they do. \n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002610543_python.txt
Q: Python (windows) will open files from command line, but not from a script launched from eclipse I'm pretty new to writing python for windows (linux is no problem), and am having problems getting python to recognize files when running scripts, though it behaves fine in the command line What am I doing wrong here? def verifyFile(x): # return os.path.isfile(x) This will return true (with a valid file, of course) when called from the python command line, but when I run the script from eclipse, or launch it from windows, it ALWAYS returns false. Any thoughts on why this is? I've tried passing pathnames like this: D:\Documents and Settings\BDE\Desktop\cdburn.jpg and like this: D:/Documents and Settings/BDE/Desktop/cdburn.jpg I've changed sys,argv[0] to '' I've tried this: def verifyFile(x): # try: f = open(x, 'r') f.close() return True except: return False and am getting no love! Any help would be appreciated. Thanks Blake A: There is not really enough information here to debug your issue, but I have a suspicion. Try adding the line print sys.argv to the start of your code, and see what the actual arguments that are being passed in to your program. I have a feeling that you will find the the filename D:\Documents and Settings\BDE\Desktop\cdburn.jpg is being split into 3 separate arguments, D:\Documents, and, Settings\BDE\Desktop\cdburn.jpg. If so, you need to quote any filename that has spaces in it.
Python (windows) will open files from command line, but not from a script launched from eclipse
I'm pretty new to writing python for windows (linux is no problem), and am having problems getting python to recognize files when running scripts, though it behaves fine in the command line What am I doing wrong here? def verifyFile(x): # return os.path.isfile(x) This will return true (with a valid file, of course) when called from the python command line, but when I run the script from eclipse, or launch it from windows, it ALWAYS returns false. Any thoughts on why this is? I've tried passing pathnames like this: D:\Documents and Settings\BDE\Desktop\cdburn.jpg and like this: D:/Documents and Settings/BDE/Desktop/cdburn.jpg I've changed sys,argv[0] to '' I've tried this: def verifyFile(x): # try: f = open(x, 'r') f.close() return True except: return False and am getting no love! Any help would be appreciated. Thanks Blake
[ "There is not really enough information here to debug your issue, but I have a suspicion.\nTry adding the line \nprint sys.argv\n\nto the start of your code, and see what the actual arguments that are being passed in to your program. I have a feeling that you will find the the filename D:\\Documents and Settings\\BDE\\Desktop\\cdburn.jpg is being split into 3 separate arguments, D:\\Documents, and, Settings\\BDE\\Desktop\\cdburn.jpg. If so, you need to quote any filename that has spaces in it.\n" ]
[ 1 ]
[]
[]
[ "file", "python", "windows" ]
stackoverflow_0002614749_file_python_windows.txt
Q: Copy string - Python Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text. Basically I want to copy a string so I can for example, lets say, paste(ctrl+v). Sorry for such a trivial question, haha. A: For Windows, you use win32clipboard. You will need pywin32. For GTK (at least on GNU/Linux), you can use pygtk. EDIT: Since you mentioned (a bit late) you're using wxPython, they actually have a module for this too, wx.Clipboard. A: This depends a lot on the OS. On Linux, due to X's bizarre selection model, the easiest way is to use popen('xsel -pi'), and write the text to that pipe. For example: (I think) def select_xsel(text): import subprocess xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE) xsel_proc.communicate(some_text) As pointed out in the comments, on a Mac, you can use the /usr/bin/pbcopy command, like this: xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) If you want to support different OSes, you could combine different solutions with os.name to determine which method to use: import os, subprocess def select_text(text): if os.name == "posix": # try Mac first try: xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) except: # try Linux version xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE) elif os.name == "nt": # Windows... A: For Windows, you can do this and it's much easier than creating a new subprocess etc... A: For a multi-platform solution you will need to use a cross-platform framework like wxPython or PyQt - they both have support for reading and writing to the system clipboard in a platform independent way.
Copy string - Python
Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text. Basically I want to copy a string so I can for example, lets say, paste(ctrl+v). Sorry for such a trivial question, haha.
[ "For Windows, you use win32clipboard. You will need pywin32.\nFor GTK (at least on GNU/Linux), you can use pygtk.\nEDIT: Since you mentioned (a bit late) you're using wxPython, they actually have a module for this too, wx.Clipboard.\n", "This depends a lot on the OS. On Linux, due to X's bizarre selection model, the easiest way is to use popen('xsel -pi'), and write the text to that pipe.\nFor example: (I think)\ndef select_xsel(text):\n import subprocess\n xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)\n xsel_proc.communicate(some_text)\n\nAs pointed out in the comments, on a Mac, you can use the /usr/bin/pbcopy command, like this:\nxsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)\n\nIf you want to support different OSes, you could combine different solutions with os.name to determine which method to use:\nimport os, subprocess\ndef select_text(text):\n if os.name == \"posix\":\n # try Mac first\n try:\n xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)\n except:\n # try Linux version\n xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)\n elif os.name == \"nt\":\n # Windows...\n\n", "For Windows, you can do this and it's much easier than creating a new subprocess etc...\n", "For a multi-platform solution you will need to use a cross-platform framework like wxPython or PyQt - they both have support for reading and writing to the system clipboard in a platform independent way.\n" ]
[ 4, 2, 2, 2 ]
[]
[]
[ "clipboard", "copy", "python", "string" ]
stackoverflow_0002614975_clipboard_copy_python_string.txt
Q: Multi-Threaded data insertion in MySQL using python I am working on a project involving insertion a lot of data in to the database. I am wondering if anybody knows how to fill 2 or 3 tables in the database at the same time.An example or psueodecode would be helpful. Thanks A: If you have a lot of data to insert into the database all at once, then you probably are interested in bulk loading data. The ideal tool for that is the bulk loader that likely comes with your database -- Oracle, Microsoft SQL Server, Sybase SQL Server, and MySQL (to name the ones that come to mind) all have bulk loaders. For example, Microsoft has the bulk insert statement and the bcp program to perform this task. I recommend you look into that rather than rigging up some tool in python, with or without threads.
Multi-Threaded data insertion in MySQL using python
I am working on a project involving insertion a lot of data in to the database. I am wondering if anybody knows how to fill 2 or 3 tables in the database at the same time.An example or psueodecode would be helpful. Thanks
[ "If you have a lot of data to insert into the database all at once, then you probably are interested in bulk loading data. The ideal tool for that is the bulk loader that likely comes with your database -- Oracle, Microsoft SQL Server, Sybase SQL Server, and MySQL (to name the ones that come to mind) all have bulk loaders. For example, Microsoft has the bulk insert statement and the bcp program to perform this task. I recommend you look into that rather than rigging up some tool in python, with or without threads.\n" ]
[ 3 ]
[]
[]
[ "database", "multithreading", "mysql", "python" ]
stackoverflow_0002613105_database_multithreading_mysql_python.txt
Q: Decoding tcp packets using python I am trying to decode data received over a tcp connection. The packets are small, no more than 100 bytes. However when there is a lot of them I receive some of the the packets joined together. Is there a way to prevent this. I am using python I have tried to separate the packets, my source is below. The packets start with STX byte and end with ETX bytes, the byte following the STX is the packet length, (packet lengths less than 5 are invalid) the checksum is the last bytes before the ETX def decode(data): while True: start = data.find(STX) if start == -1: #no stx in message pkt = '' data = '' break #stx found , next byte is the length pktlen = ord(data[1]) #check message ends in ETX (pktken -1) or checksum invalid if pktlen < 5 or data[pktlen-1] != ETX or checksum_valid(data[start:pktlen]) == False: print "Invalid Pkt" data = data[start+1:] continue else: pkt = data[start:pktlen] data = data[pktlen:] break return data , pkt I use it like this #process reports try: data = sock.recv(256) except: continue else: while data: data, pkt = decode(data) if pkt: process(pkt) Also if there are multiple packets in the data stream, is it best to return the packets as a collection of lists or just return the first packet I am not that familiar with python, only C, is this method OK. Any advice would be most appreciated. Thanks in advance Thanks A: I would create a class that is responsible for decoding the packets from a stream, like this: class PacketDecoder(object): STX = ... ETX = ... def __init__(self): self._stream = '' def feed(self, buffer): self._stream += buffer def decode(self): ''' Yields packets from the current stream. ''' while len(self._stream) > 2: end = self._stream.find(self.ETX) if end == -1: break packet_len = ord(self._stream[1]) packet = self._stream[:end] if packet_len >= 5 and check_sum_valid(packet): yield packet self._stream = self._stream[end+1:] And then use like this: decoder = PacketDecoder() while True: data = sock.recv(256) if not data: # handle lost connection... decoder.feed(data) for packet in decoder.decode(): process(packet) A: TCP provides a data stream, not individual packets, at the interface level. If you want discrete packets, you can use UDP (and handle lost or out of order packets on your own), or put some data separator inline. It sounds like you are doing that already, with STX/ETX as your separators. However, as you note, you get multiple messages in one data chunk from your TCP stack. Note that unless you are doing some other processing, data in the code you show does not necessarily contain an integral number of messages. That is, it is likely that the last STX will not have a matching ETX. The ETX will be in the next data chunk without an STX. You should probably read individual messages from the TCP data stream and return them as they occur. A: Try scapy, a powerful interactive packet manipulation program. A: Where does the data come from ? Instead of trying to decode it by hand, why not use the excellent Impacket package: http://oss.coresecurity.com/projects/impacket.html A: Nice and simple... :) The trick is in the file object. f=sock.makefile() while True: STX = f.read(1) pktlen = f.read(1) wholePacket = STX + pktlen + f.read(ord(pktlen)-2) doSomethingWithPacket(wholePacket) And that's it! (There is also no need to check checksums when using TCP.) And here is a more "robust"(?) version (it uses STX and checksum): f=sock.makefile() while True: while f.read(1)!=STX: continue pktlen = f.read(1) wholePacket = STX + pktlen + f.read(ord(pktlen)-2) if checksum_valid(wholePacket): doSomethingWithPacket(wholePacket)
Decoding tcp packets using python
I am trying to decode data received over a tcp connection. The packets are small, no more than 100 bytes. However when there is a lot of them I receive some of the the packets joined together. Is there a way to prevent this. I am using python I have tried to separate the packets, my source is below. The packets start with STX byte and end with ETX bytes, the byte following the STX is the packet length, (packet lengths less than 5 are invalid) the checksum is the last bytes before the ETX def decode(data): while True: start = data.find(STX) if start == -1: #no stx in message pkt = '' data = '' break #stx found , next byte is the length pktlen = ord(data[1]) #check message ends in ETX (pktken -1) or checksum invalid if pktlen < 5 or data[pktlen-1] != ETX or checksum_valid(data[start:pktlen]) == False: print "Invalid Pkt" data = data[start+1:] continue else: pkt = data[start:pktlen] data = data[pktlen:] break return data , pkt I use it like this #process reports try: data = sock.recv(256) except: continue else: while data: data, pkt = decode(data) if pkt: process(pkt) Also if there are multiple packets in the data stream, is it best to return the packets as a collection of lists or just return the first packet I am not that familiar with python, only C, is this method OK. Any advice would be most appreciated. Thanks in advance Thanks
[ "I would create a class that is responsible for decoding the packets from a stream, like this:\nclass PacketDecoder(object):\n\n STX = ...\n ETX = ...\n\n def __init__(self):\n self._stream = ''\n\n def feed(self, buffer):\n self._stream += buffer\n\n def decode(self):\n '''\n Yields packets from the current stream.\n '''\n while len(self._stream) > 2:\n end = self._stream.find(self.ETX)\n if end == -1:\n break\n\n packet_len = ord(self._stream[1])\n packet = self._stream[:end]\n if packet_len >= 5 and check_sum_valid(packet):\n yield packet\n self._stream = self._stream[end+1:]\n\nAnd then use like this:\ndecoder = PacketDecoder()\nwhile True:\n data = sock.recv(256) \n if not data:\n # handle lost connection... \n decoder.feed(data)\n for packet in decoder.decode():\n process(packet)\n\n", "TCP provides a data stream, not individual packets, at the interface level. If you want discrete packets, you can use UDP (and handle lost or out of order packets on your own), or put some data separator inline. It sounds like you are doing that already, with STX/ETX as your separators. However, as you note, you get multiple messages in one data chunk from your TCP stack.\nNote that unless you are doing some other processing, data in the code you show does not necessarily contain an integral number of messages. That is, it is likely that the last STX will not have a matching ETX. The ETX will be in the next data chunk without an STX.\nYou should probably read individual messages from the TCP data stream and return them as they occur.\n", "Try scapy, a powerful interactive packet manipulation program.\n", "Where does the data come from ? Instead of trying to decode it by hand, why not use the excellent Impacket package:\nhttp://oss.coresecurity.com/projects/impacket.html\n", "Nice and simple... :)\nThe trick is in the file object.\nf=sock.makefile()\nwhile True:\n STX = f.read(1)\n pktlen = f.read(1)\n wholePacket = STX + pktlen + f.read(ord(pktlen)-2)\n doSomethingWithPacket(wholePacket)\n\nAnd that's it! (There is also no need to check checksums when using TCP.)\nAnd here is a more \"robust\"(?) version (it uses STX and checksum):\nf=sock.makefile()\nwhile True:\n while f.read(1)!=STX:\n continue\n pktlen = f.read(1)\n wholePacket = STX + pktlen + f.read(ord(pktlen)-2)\n if checksum_valid(wholePacket):\n doSomethingWithPacket(wholePacket)\n\n" ]
[ 5, 4, 3, 0, 0 ]
[]
[]
[ "decoding", "packets", "python", "string", "tcp" ]
stackoverflow_0002184181_decoding_packets_python_string_tcp.txt
Q: Python NameError when attempting to use a user-defined class I'm getting a weird instance of a NameError when attempting to use a class I wrote. In a directory, I have the following file structure: dir/ ReutersParser.py test.py reut-xxx.sgm Where my custom class is defined in ReutersParser.py and I have a test script defined in test.py. The ReutersParser looks something like this: from sgmllib import SGMLParser class ReutersParser(SGMLParser): def __init__(self, verbose=0): SGMLParser.__init__(self, verbose) ... rest of parser if __name__ == '__main__': f = open('reut2-short.sgm') s = f.read() p = ReutersParser() p.parse(s) It's a parser to deal with SGML files of Reuters articles. The test works perfectly. Anyway, I'm going to use it in test.py, which looks like this: from ReutersParser import ReutersParser def main(): parser = ReutersParser() if __name__ == '__main__': main() When it gets to that parser line, I'm getting this error: Traceback (most recent call last): File "D:\Projects\Reuters\test.py", line 34, in <module> main() File "D:\Projects\Reuters\test.py", line 19, in main parser = ReutersParser() File "D:\Projects\Reuters\ReutersParser.py", line 38, in __init__ SGMLParser.__init__(self, verbose) NameError: global name 'sgmllib' is not defined For some reason, when I try to use my ReutersParser in test.py, it throws an error that says it cannot find sgmllib, which is a built-in module. I'm at my wits' end trying to figure out why the import won't work. What's causing this NameError? I've tried importing sgmllib in my test.py and that works, so I don't understand why it can't find it when trying to run the constructor for my ReutersParser. A: Your problem is not your code, but what you run it in. If you read the error and the code it displays closely: File "D:\Projects\Reuters\ReutersParser.py", line 38, in __init__ SGMLParser.__init__(self, verbose) NameError: global name 'sgmllib' is not defined you'll notice there's no reference to 'sgmllib' on the line that Python thinks produced this error. That means one of two things: either the error didn't originate there (and Python is quite confused), or the code that's being displayed is not the code that is being executed. The latter is quite common when you, for example, run your code in an IDE that doesn't restart the Python interpreter between code executions. It will execute your old code, but when displaying the traceback will show the new code. I'm guessing you did sgmllib.SGMLParser.__init__(self, verbose) on that line at some point in the past. The reason it was fixed by renaming the class is probably that you did something -- like editing the code -- that caused the IDE to either restart the interpreter, properly clean it up or (by accident) reloaded the right module the right way for it to see the new code. Since you name your module after your class (which is bad style, by the way) I assume you renamed your module when you renamed your class, and so your IDE picked up the new code this time. Until the next time the same thing happens, of course.
Python NameError when attempting to use a user-defined class
I'm getting a weird instance of a NameError when attempting to use a class I wrote. In a directory, I have the following file structure: dir/ ReutersParser.py test.py reut-xxx.sgm Where my custom class is defined in ReutersParser.py and I have a test script defined in test.py. The ReutersParser looks something like this: from sgmllib import SGMLParser class ReutersParser(SGMLParser): def __init__(self, verbose=0): SGMLParser.__init__(self, verbose) ... rest of parser if __name__ == '__main__': f = open('reut2-short.sgm') s = f.read() p = ReutersParser() p.parse(s) It's a parser to deal with SGML files of Reuters articles. The test works perfectly. Anyway, I'm going to use it in test.py, which looks like this: from ReutersParser import ReutersParser def main(): parser = ReutersParser() if __name__ == '__main__': main() When it gets to that parser line, I'm getting this error: Traceback (most recent call last): File "D:\Projects\Reuters\test.py", line 34, in <module> main() File "D:\Projects\Reuters\test.py", line 19, in main parser = ReutersParser() File "D:\Projects\Reuters\ReutersParser.py", line 38, in __init__ SGMLParser.__init__(self, verbose) NameError: global name 'sgmllib' is not defined For some reason, when I try to use my ReutersParser in test.py, it throws an error that says it cannot find sgmllib, which is a built-in module. I'm at my wits' end trying to figure out why the import won't work. What's causing this NameError? I've tried importing sgmllib in my test.py and that works, so I don't understand why it can't find it when trying to run the constructor for my ReutersParser.
[ "Your problem is not your code, but what you run it in. If you read the error and the code it displays closely:\n File \"D:\\Projects\\Reuters\\ReutersParser.py\", line 38, in __init__\n SGMLParser.__init__(self, verbose)\nNameError: global name 'sgmllib' is not defined\n\nyou'll notice there's no reference to 'sgmllib' on the line that Python thinks produced this error. That means one of two things: either the error didn't originate there (and Python is quite confused), or the code that's being displayed is not the code that is being executed. The latter is quite common when you, for example, run your code in an IDE that doesn't restart the Python interpreter between code executions. It will execute your old code, but when displaying the traceback will show the new code. I'm guessing you did sgmllib.SGMLParser.__init__(self, verbose) on that line at some point in the past.\nThe reason it was fixed by renaming the class is probably that you did something -- like editing the code -- that caused the IDE to either restart the interpreter, properly clean it up or (by accident) reloaded the right module the right way for it to see the new code. Since you name your module after your class (which is bad style, by the way) I assume you renamed your module when you renamed your class, and so your IDE picked up the new code this time. Until the next time the same thing happens, of course.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002615059_python.txt
Q: Scrapy domain_name for spider From the Scrapy tutorial: domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders. Does this mean that domain_name must be a valid domain name, like domain_name = 'example.com' Or can I name domain_name = 'ex1' The problem is I had a spider that worked with domain name domain_name = 'whitecase.com' Now I created a new spider as an instance of CrawlSpider and named it domain_name = 'wc2' but I am getting the error "could not find spider for domain "wc2"" A: To answer my own question: domain_name = 'wc2' works. A: As you have found out yourself, domain_name shouldn't be real. It's used when calling the spider to crawl.
Scrapy domain_name for spider
From the Scrapy tutorial: domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders. Does this mean that domain_name must be a valid domain name, like domain_name = 'example.com' Or can I name domain_name = 'ex1' The problem is I had a spider that worked with domain name domain_name = 'whitecase.com' Now I created a new spider as an instance of CrawlSpider and named it domain_name = 'wc2' but I am getting the error "could not find spider for domain "wc2""
[ "To answer my own question:\n\ndomain_name = 'wc2'\n\nworks.\n", "As you have found out yourself, domain_name shouldn't be real. It's used when calling the spider to crawl.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0001804694_python_scrapy.txt
Q: Simple pygtk and threads example please Can someone give me a simple example involving threads in this manner, please. Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that? class fun: wTree = None def __init__( self ): self.wTree = gtk.glade.XML( "ui.glade" ) dic = { "on_buttonOne" : self.one, "on_buttonTwo" : self.two, } self.wTree.signal_autoconnect( dic ) gtk.main() def sone(self, widget): time.sleep(1) print "1" time.sleep(1) print "2" time.sleep(1) print "3" def stwo(self, widget): time.sleep(1) print "4" time.sleep(1) print "5" time.sleep(1) print "6" do=fun() Pretty please, help me. A: Use Python Threads: http://docs.python.org/library/threading.html Something like: class SoneThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.start() # invoke the run method def run(self): time.sleep(1) print "1" time.sleep(1) print "2" time.sleep(1) print "3" Now in sone just call SoneThread(), that should work. Also you need to call gtk.gdk.threads_init() in order to make python threads work with your GTK+ application. See: http://library.gnome.org/devel/pygtk/stable/gdk-functions.html#function-gdk--threads-init A: When using gtk, it will run a main loop, and you schedule everything you want to do as events to the gtk loop. You don't need threads to do anything. Here's a complete, full, ready-to-run example that uses glib.timeout_add to do what you want. Note that clicking on both buttons (or multiple times on a button) doesn't freeze the gui and everything happens "at the same time"... import gtk import glib def yieldsleep(func): def start(*args, **kwds): iterable = func(*args, **kwds) def step(*args, **kwds): try: time = next(iterable) glib.timeout_add_seconds(time, step) except StopIteration: pass glib.idle_add(step) return start class Fun(object): def __init__(self): window = gtk.Window() vbox = gtk.VBox() btnone = gtk.Button('one') btnone.connect('clicked', self.click_one) btnone.show() vbox.pack_start(btnone) btntwo = gtk.Button('two') btntwo.connect('clicked', self.click_two) btntwo.show() vbox.pack_start(btntwo) vbox.show() window.add(vbox) window.show() @yieldsleep def click_one(self, widget, data=None): yield 1 #time.sleep(1) print '1' yield 1 #time.sleep(1) print '2' yield 1 #time.sleep(1) print '3' @yieldsleep def click_two(self, widget, data=None): yield 1 #time.sleep(1) print '4' yield 1 #time.sleep(1) print '5' yield 1 #time.sleep(1) print '6' do = Fun() gtk.main()
Simple pygtk and threads example please
Can someone give me a simple example involving threads in this manner, please. Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that? class fun: wTree = None def __init__( self ): self.wTree = gtk.glade.XML( "ui.glade" ) dic = { "on_buttonOne" : self.one, "on_buttonTwo" : self.two, } self.wTree.signal_autoconnect( dic ) gtk.main() def sone(self, widget): time.sleep(1) print "1" time.sleep(1) print "2" time.sleep(1) print "3" def stwo(self, widget): time.sleep(1) print "4" time.sleep(1) print "5" time.sleep(1) print "6" do=fun() Pretty please, help me.
[ "Use Python Threads: http://docs.python.org/library/threading.html\nSomething like:\nclass SoneThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.start() # invoke the run method\n\n def run(self):\n time.sleep(1)\n print \"1\"\n time.sleep(1)\n print \"2\"\n time.sleep(1)\n print \"3\"\n\nNow in sone just call SoneThread(), that should work.\nAlso you need to call gtk.gdk.threads_init() in order to make python threads work with your GTK+ application.\nSee: http://library.gnome.org/devel/pygtk/stable/gdk-functions.html#function-gdk--threads-init\n", "When using gtk, it will run a main loop, and you schedule everything you want to do as events to the gtk loop. You don't need threads to do anything.\nHere's a complete, full, ready-to-run example that uses glib.timeout_add to do what you want.\nNote that clicking on both buttons (or multiple times on a button) doesn't freeze the gui and everything happens \"at the same time\"...\nimport gtk\nimport glib\n\ndef yieldsleep(func):\n def start(*args, **kwds):\n iterable = func(*args, **kwds)\n def step(*args, **kwds):\n try:\n time = next(iterable)\n glib.timeout_add_seconds(time, step)\n except StopIteration:\n pass\n glib.idle_add(step)\n return start\n\nclass Fun(object):\n def __init__(self):\n window = gtk.Window()\n\n vbox = gtk.VBox()\n\n btnone = gtk.Button('one')\n btnone.connect('clicked', self.click_one)\n btnone.show()\n vbox.pack_start(btnone)\n\n btntwo = gtk.Button('two')\n btntwo.connect('clicked', self.click_two)\n btntwo.show()\n vbox.pack_start(btntwo)\n\n vbox.show()\n window.add(vbox)\n window.show()\n\n @yieldsleep\n def click_one(self, widget, data=None):\n yield 1 #time.sleep(1)\n print '1'\n yield 1 #time.sleep(1)\n print '2'\n yield 1 #time.sleep(1)\n print '3'\n\n @yieldsleep\n def click_two(self, widget, data=None):\n yield 1 #time.sleep(1)\n print '4'\n yield 1 #time.sleep(1)\n print '5'\n yield 1 #time.sleep(1)\n print '6'\n\ndo = Fun()\ngtk.main()\n\n" ]
[ 4, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002615124_pygtk_python.txt
Q: how to transfer a python object between two requests? i want to process a python dict object in batches between two requests. i was wondering what's the best way to do it. i want to do that because my dict is big and i couldn't do the whole processing in 30s. thanks A: You can serialize your object (perhaps with pickle, though there may be more efficient and specific ways if your object's nature is well-constrained) and save the serialized byte string to the datastore and to memcache (I don't recommend using just memcache, because it just might occasionally happen that the cache is "flushed" between the two requests -- in that case, you definitely want to be able to fetch your serialized byte string from the datastore!). memcache will to the pickling for you, if you pass the original object -- but, since you need the serialized string anyway to put it in the datastore, I think it's better to do your own explicit serialization. Once you memcache.add a string, the fact that the latter gets pickled (and later unpickled on retrieval) is not a big deal -- the overhead of time and space is really quite modest. There are limits to this approach -- you can't memcache more than 1MB per key, for example, so if your object's truly huge you need to split up the serialized bytestring onto multiple keys (and for more than a few such megabyte-slices, things get very unwieldy). Also, of course, the first and the second request must "agree" on a key to use for the serialized data's storage and retrieval -- i.e. there must be a simple way to get that key without confusion (for example, it might be based on the name of the current user).
how to transfer a python object between two requests?
i want to process a python dict object in batches between two requests. i was wondering what's the best way to do it. i want to do that because my dict is big and i couldn't do the whole processing in 30s. thanks
[ "You can serialize your object (perhaps with pickle, though there may be more efficient and specific ways if your object's nature is well-constrained) and save the serialized byte string to the datastore and to memcache (I don't recommend using just memcache, because it just might occasionally happen that the cache is \"flushed\" between the two requests -- in that case, you definitely want to be able to fetch your serialized byte string from the datastore!).\nmemcache will to the pickling for you, if you pass the original object -- but, since you need the serialized string anyway to put it in the datastore, I think it's better to do your own explicit serialization. Once you memcache.add a string, the fact that the latter gets pickled (and later unpickled on retrieval) is not a big deal -- the overhead of time and space is really quite modest.\nThere are limits to this approach -- you can't memcache more than 1MB per key, for example, so if your object's truly huge you need to split up the serialized bytestring onto multiple keys (and for more than a few such megabyte-slices, things get very unwieldy).\nAlso, of course, the first and the second request must \"agree\" on a key to use for the serialized data's storage and retrieval -- i.e. there must be a simple way to get that key without confusion (for example, it might be based on the name of the current user).\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002615050_google_app_engine_python.txt
Q: Rationale behind Python's preferred for syntax What is the rationale behind the advocated use of the for i in xrange(...)-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File idiomatic.py: #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 for x in xrange(N): for y in xrange(M): pass File cstyle.py: #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 while x < N: while y < M: y += 1 x += 1 Profiling results were as follows: bash-3.1$ time python cstyle.py real 0m0.109s user 0m0.015s sys 0m0.000s bash-3.1$ time python idiomatic.py real 0m4.492s user 0m0.000s sys 0m0.031s I can understand why the Pythonic version is slower -- I imagine it has a lot to do with calling xrange N times, perhaps this could be eliminated if there was a way to rewind a generator. However, with this deal of difference in execution time, why would one prefer to use the Pythonic version? Edit: I conducted the tests again using the code Mr. Martelli provided, and the results were indeed better now: I thought I'd enumerate the conclusions from the thread here: 1) Lots of code at the module scope is a bad idea, even if the code is enclosed in an if __name__ == "__main__": block. 2) *Curiously enough, modifying the code that belonged to thebadone to my incorrect version (letting y grow without resetting) produced little difference in performance, even for larger values of M and N. A: Here's the proper comparison, e.g. in loop.py: M = 10000 N = 10000 def thegoodone(): for x in xrange(N): for y in xrange(M): pass def thebadone(): x = 0 while x < N: y = 0 while y < M: y += 1 x += 1 All substantial code should always be in functions -- putting a hundred million loops at a module's top level shows reckless disregard for performance and makes a mockery of any attempts at measuring said performance. Once you've done that, you see: $ python -mtimeit -s'import loop' 'loop.thegoodone()' 10 loops, best of 3: 3.45 sec per loop $ python -mtimeit -s'import loop' 'loop.thebadone()' 10 loops, best of 3: 10.6 sec per loop So, properly measured, the bad way that you advocate is about 3 times slower than the good way which Python promotes. I hope this makes you reconsider your erroneous advocacy. A: You forgot to reset y to 0 after the inner loop. #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 while x < N: while y < M: y += 1 x += 1 y = 0 ed: 20.63s after fix vs. 6.97s using xrange A: good for iterating over data structures The for i in ... syntax is great for iterating over data structures. In a lower-level language, you would generally be iterating over an array indexed by an int, but with the python syntax you can eliminate the indexing step. A: this is not a direct answer to the question, but i want to open the dialog a bit more on xrange(). two things: A. there is something wrong with one of the OP statements that no one has corrected yet (yes, in addition to the bug in the code of not resetting y): "I imagine it has a lot to do with calling xrange N times...." unlike traditional counting for loops, Python's is more like a shell's foreach... looping over an iterable. therefore, xrange() is called exactly once, not "N times." B. xrange() is the name of this function in Python 2. it replaces and is renamed to range() in Python 3, so keep this in mind when porting. if you didn't know already, xrange() returns an iterator(-like object) while range() returns lists. since the latter is more inefficient, it has been deprecated in favor of xrange() which is more memory-friendly. the workaround in Python 3, for all those who need to have a list is list(range(N)). A: I've repeated the test from @Alex Martelli's answer. The idiomatic for loop is 5 times faster than the while loop: python -mtimeit -s'from while_vs_for import while_loop as loop' 'loop(10000)' 10 loops, best of 3: 9.6 sec per loop python -mtimeit -s'from while_vs_for import for_loop as loop' 'loop(10000)' 10 loops, best of 3: 1.83 sec per loop while_vs_for.py: def while_loop(N): x = 0 while x < N: y = 0 while y < N: pass y += 1 x += 1 def for_loop(N): for x in xrange(N): for y in xrange(N): pass At module level: $ time -p python for.py real 4.38 user 4.37 sys 0.01 $ time -p python while.py real 14.28 user 14.28 sys 0.01
Rationale behind Python's preferred for syntax
What is the rationale behind the advocated use of the for i in xrange(...)-style looping constructs in Python? For simple integer looping, the difference in overheads is substantial. I conducted a simple test using two pieces of code: File idiomatic.py: #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 for x in xrange(N): for y in xrange(M): pass File cstyle.py: #!/usr/bin/env python M = 10000 N = 10000 if __name__ == "__main__": x, y = 0, 0 while x < N: while y < M: y += 1 x += 1 Profiling results were as follows: bash-3.1$ time python cstyle.py real 0m0.109s user 0m0.015s sys 0m0.000s bash-3.1$ time python idiomatic.py real 0m4.492s user 0m0.000s sys 0m0.031s I can understand why the Pythonic version is slower -- I imagine it has a lot to do with calling xrange N times, perhaps this could be eliminated if there was a way to rewind a generator. However, with this deal of difference in execution time, why would one prefer to use the Pythonic version? Edit: I conducted the tests again using the code Mr. Martelli provided, and the results were indeed better now: I thought I'd enumerate the conclusions from the thread here: 1) Lots of code at the module scope is a bad idea, even if the code is enclosed in an if __name__ == "__main__": block. 2) *Curiously enough, modifying the code that belonged to thebadone to my incorrect version (letting y grow without resetting) produced little difference in performance, even for larger values of M and N.
[ "Here's the proper comparison, e.g. in loop.py:\nM = 10000\nN = 10000\n\ndef thegoodone():\n for x in xrange(N):\n for y in xrange(M):\n pass\n\ndef thebadone():\n x = 0\n while x < N:\n y = 0\n while y < M:\n y += 1\n x += 1\n\nAll substantial code should always be in functions -- putting a hundred million loops at a module's top level shows reckless disregard for performance and makes a mockery of any attempts at measuring said performance.\nOnce you've done that, you see:\n$ python -mtimeit -s'import loop' 'loop.thegoodone()'\n10 loops, best of 3: 3.45 sec per loop\n$ python -mtimeit -s'import loop' 'loop.thebadone()'\n10 loops, best of 3: 10.6 sec per loop\n\nSo, properly measured, the bad way that you advocate is about 3 times slower than the good way which Python promotes. I hope this makes you reconsider your erroneous advocacy.\n", "You forgot to reset y to 0 after the inner loop.\n#!/usr/bin/env python\nM = 10000\nN = 10000\n\nif __name__ == \"__main__\":\n x, y = 0, 0\n while x < N:\n while y < M:\n y += 1\n x += 1\n y = 0\n\ned: 20.63s after fix vs. 6.97s using xrange\n", "good for iterating over data structures\nThe for i in ... syntax is great for iterating over data structures. In a lower-level language, you would generally be iterating over an array indexed by an int, but with the python syntax you can eliminate the indexing step.\n", "this is not a direct answer to the question, but i want to open the dialog a bit more on xrange(). two things:\nA. there is something wrong with one of the OP statements that no one has corrected yet (yes, in addition to the bug in the code of not resetting y):\n\"I imagine it has a lot to do with calling xrange N times....\"\nunlike traditional counting for loops, Python's is more like a shell's foreach... looping over an iterable. therefore, xrange() is called exactly once, not \"N times.\"\nB. xrange() is the name of this function in Python 2. it replaces and is renamed to range() in Python 3, so keep this in mind when porting. if you didn't know already, xrange() returns an iterator(-like object) while range() returns lists. since the latter is more inefficient, it has been deprecated in favor of xrange() which is more memory-friendly. the workaround in Python 3, for all those who need to have a list is list(range(N)).\n", "I've repeated the test from @Alex Martelli's answer. The idiomatic for loop is 5 times faster than the while loop:\npython -mtimeit -s'from while_vs_for import while_loop as loop' 'loop(10000)'\n10 loops, best of 3: 9.6 sec per loop\npython -mtimeit -s'from while_vs_for import for_loop as loop' 'loop(10000)'\n10 loops, best of 3: 1.83 sec per loop\n\nwhile_vs_for.py:\ndef while_loop(N):\n x = 0\n while x < N:\n y = 0\n while y < N:\n pass\n y += 1\n x += 1\n\ndef for_loop(N):\n for x in xrange(N):\n for y in xrange(N):\n pass\n\nAt module level:\n$ time -p python for.py\nreal 4.38\nuser 4.37\nsys 0.01\n$ time -p python while.py\nreal 14.28\nuser 14.28\nsys 0.01\n\n" ]
[ 22, 11, 3, 1, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0002611867_performance_python.txt
Q: (Python) Why do I always have to type absolute paths in file functions? For instance, if I have: C:\42\main.py and C:\42\info.txt and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt". Is it supposed to be like that? If not, how can I fix it? A: You can specify paths relative to where your script is. I do it all the time when writing unittests. Every python file has a special attribute -- __file__ -- that stores the path to that file. py_file= os.path.abspath(__file__) # path to main.py py_dir = os.path.dirname(py_file) # path to the parent dir of main.py txt_file = os.path.join(py_dir, 'info.txt') # path to info.txt A: It is supposed to be like that. Relative paths are relative to the process's current working directory, not the directory that your script resides in. A: Rather than hardcoding it, you can find the script's path using sys.path[0], and either chdir to it or use it directly in the filename: os.path.join(sys.path[0], 'info.txt')
(Python) Why do I always have to type absolute paths in file functions?
For instance, if I have: C:\42\main.py and C:\42\info.txt and I want to read info.txt from main.py, I have to input "C:\42\info.txt" instad of just "info.txt". Is it supposed to be like that? If not, how can I fix it?
[ "You can specify paths relative to where your script is. I do it all the time when writing unittests.\nEvery python file has a special attribute -- __file__ -- that stores the path to that file. \npy_file= os.path.abspath(__file__) # path to main.py\npy_dir = os.path.dirname(py_file) # path to the parent dir of main.py\ntxt_file = os.path.join(py_dir, 'info.txt') # path to info.txt\n\n", "It is supposed to be like that. Relative paths are relative to the process's current working directory, not the directory that your script resides in.\n", "Rather than hardcoding it, you can find the script's path using sys.path[0], and either chdir to it or use it directly in the filename:\nos.path.join(sys.path[0], 'info.txt')\n\n" ]
[ 10, 5, 1 ]
[]
[]
[ "absolute_path", "python" ]
stackoverflow_0002615526_absolute_path_python.txt
Q: Why can't I download a whole image file with urllib2.urlopen() When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wireless, and I often get broken downloads on larger files in firefox, but my browser has no problem getting a 200k image file. I'm new to python, and programming in general, so I'm wondering what nuance I'm missing. import urllib2 xkcdpic=urllib2.urlopen("http://imgs.xkcd.com/comics/literally.png") xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png","w") while 1: chunk=xkcdpic.read(4028) if chunk: print chunk xkcdpicfile.write(chunk) else: break A: To write a binary file on Windows you need to explicitly open it as binary, i.e.: xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png", "wb") note the extra b in the options: "wb", not just "w"! I would also recommend losing the print chunk which may send arbitrary binary sequences to the console and possibly caused undesired side effects. If you're keen to see the hex bytes whizz by meaninglessly, maybe print repr(chunk), if you insist. But I'd find something more meaningful to show, e.g. len(chunk) and maybe the total number of bytes so far.
Why can't I download a whole image file with urllib2.urlopen()
When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wireless, and I often get broken downloads on larger files in firefox, but my browser has no problem getting a 200k image file. I'm new to python, and programming in general, so I'm wondering what nuance I'm missing. import urllib2 xkcdpic=urllib2.urlopen("http://imgs.xkcd.com/comics/literally.png") xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png","w") while 1: chunk=xkcdpic.read(4028) if chunk: print chunk xkcdpicfile.write(chunk) else: break
[ "To write a binary file on Windows you need to explicitly open it as binary, i.e.:\nxkcdpicfile=open(\"C:\\\\Documents and Settings\\\\John Gann\\\\Desktop\\\\xkcd.png\",\n \"wb\")\n\nnote the extra b in the options: \"wb\", not just \"w\"!\nI would also recommend losing the print chunk which may send arbitrary binary sequences to the console and possibly caused undesired side effects. If you're keen to see the hex bytes whizz by meaninglessly, maybe print repr(chunk), if you insist. But I'd find something more meaningful to show, e.g. len(chunk) and maybe the total number of bytes so far.\n" ]
[ 10 ]
[]
[]
[ "download", "image", "python" ]
stackoverflow_0002615593_download_image_python.txt
Q: Help calling def from class Noob question... class msgbox: def __init__(self, lbl_msg = '', dlg_title = ''): self.wTree = gtk.glade.XML('msgbox.glade') self.wTree.get_widget('dialog1').set_title(dlg_title) self.wTree.get_widget('label1').set_text(lbl_msg) self.wTree.signal_autoconnect( {'on_okbutton1_clicked':self.done} ) def done(self,w): self.wTree.get_widget('dialog1').destroy() class Fun(object): wTree = None def __init__(self): self.wTree = gtk.glade.XML( "main.glade" ) self.wTree.signal_autoconnect( {'on_buttonOne' : self.one,} ) gtk.main() @yieldsleep def one(self, widget, data=None): self.msg = msgbox('Please wait...','') yield 500 self.msg = msgbox().done() # <----------------??? self.msg = msgbox('Done!','') With this i get an error: messageBox().done() TypeError: done() takes exactly 2 arguments (1 given) How can i make the dialog box with "please wait" to close before the second dialog box with "done" appears?? Thank you. A: It looks like you want self.msg.done() to close the existing "Please wait..." message box. msgbox().done() creates a new message box, then calls done on this new instance. As for the extra parameter, you aren't using it, so remove it from the definition of done: def done(self): self.wTree.get_widget('dialog1').destroy() Off Topic Class msgbox should inherit from object so you get a new-style class. Define a destructor on msgbox and you don't need to explicitly call msgbox.done, which you might forget to do. class Msgbox(object): ... def __del__(self): self.wTree.get_widget('dialog1').destroy() class Fun(object): ... @yieldsleep def one(self, widget, data=None): self.msg = Msgbox('Please wait...','') yield 500 # actually, you probably need to delete the old self.msg # so it gets destroyed before the new message box is created del self.msg self.msg = Msgbox('Done!','') A: You've chosen to define the done method like this: def done(self,w): so it does need two arguments -- the msgbox instance you're calling it on, and a second mysterious w argument which it then never uses. When you call done, you don't pass that mysterious and totally useless argument. So why not change the def to: def done(self): getting rid of the mysterious, useless w which you're currently requiring but not supplying?
Help calling def from class
Noob question... class msgbox: def __init__(self, lbl_msg = '', dlg_title = ''): self.wTree = gtk.glade.XML('msgbox.glade') self.wTree.get_widget('dialog1').set_title(dlg_title) self.wTree.get_widget('label1').set_text(lbl_msg) self.wTree.signal_autoconnect( {'on_okbutton1_clicked':self.done} ) def done(self,w): self.wTree.get_widget('dialog1').destroy() class Fun(object): wTree = None def __init__(self): self.wTree = gtk.glade.XML( "main.glade" ) self.wTree.signal_autoconnect( {'on_buttonOne' : self.one,} ) gtk.main() @yieldsleep def one(self, widget, data=None): self.msg = msgbox('Please wait...','') yield 500 self.msg = msgbox().done() # <----------------??? self.msg = msgbox('Done!','') With this i get an error: messageBox().done() TypeError: done() takes exactly 2 arguments (1 given) How can i make the dialog box with "please wait" to close before the second dialog box with "done" appears?? Thank you.
[ "It looks like you want\nself.msg.done()\n\nto close the existing \"Please wait...\" message box. msgbox().done() creates a new message box, then calls done on this new instance.\nAs for the extra parameter, you aren't using it, so remove it from the definition of done:\ndef done(self):\n self.wTree.get_widget('dialog1').destroy()\n\nOff Topic\nClass msgbox should inherit from object so you get a new-style class.\nDefine a destructor on msgbox and you don't need to explicitly call msgbox.done, which you might forget to do.\nclass Msgbox(object):\n ...\n def __del__(self):\n self.wTree.get_widget('dialog1').destroy()\n\nclass Fun(object):\n ...\n @yieldsleep\n def one(self, widget, data=None):\n self.msg = Msgbox('Please wait...','')\n yield 500\n # actually, you probably need to delete the old self.msg\n # so it gets destroyed before the new message box is created\n del self.msg\n self.msg = Msgbox('Done!','')\n\n", "You've chosen to define the done method like this:\ndef done(self,w):\n\nso it does need two arguments -- the msgbox instance you're calling it on, and a second mysterious w argument which it then never uses. When you call done, you don't pass that mysterious and totally useless argument. So why not change the def to:\ndef done(self):\n\ngetting rid of the mysterious, useless w which you're currently requiring but not supplying?\n" ]
[ 1, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002615610_pygtk_python.txt
Q: Trace/BPT trap when running feedparser inside a Thread object I am trying to run a Thread to parse a list of links using the universal feed parser, but when I start the thread I get a Trace/BPT trap. Here's the code I am using: class parseRssFiles(Thread): def __init__ (self,rssLinks): Thread.__init__(self) self.rssLinks = rssLinks def run(self): self.rssContents = [ feedparser.parse(link) for link in rssLinks] Is there any other way to do this? Link to the report generated by Mac OS X 10.6.2: http://simaom.com/trace.txt Thanks A: Without a working test case, it is hard to know for sure but I suspect you are running into the problem documented in Python tracker issue 7144, namely, trying to initialize the CoreFoundation framework on other than the main thread. That problem is fixed in Python 2.6.5 which you could install from python.org or MacPorts. An untested workaround for the Apple-supplied Python 2.6.1 in 10.6 may be to execute something innocuous in the main thread that will cause CoreFoundation to be initialized before starting any secondary threads. Something like this in the main thread might do it: import locale locale.getdefautlocale()
Trace/BPT trap when running feedparser inside a Thread object
I am trying to run a Thread to parse a list of links using the universal feed parser, but when I start the thread I get a Trace/BPT trap. Here's the code I am using: class parseRssFiles(Thread): def __init__ (self,rssLinks): Thread.__init__(self) self.rssLinks = rssLinks def run(self): self.rssContents = [ feedparser.parse(link) for link in rssLinks] Is there any other way to do this? Link to the report generated by Mac OS X 10.6.2: http://simaom.com/trace.txt Thanks
[ "Without a working test case, it is hard to know for sure but I suspect you are running into the problem documented in Python tracker issue 7144, namely, trying to initialize the CoreFoundation framework on other than the main thread. That problem is fixed in Python 2.6.5 which you could install from python.org or MacPorts. An untested workaround for the Apple-supplied Python 2.6.1 in 10.6 may be to execute something innocuous in the main thread that will cause CoreFoundation to be initialized before starting any secondary threads. Something like this in the main thread might do it:\nimport locale\nlocale.getdefautlocale()\n\n" ]
[ 1 ]
[]
[]
[ "feedparser", "multithreading", "python" ]
stackoverflow_0002614910_feedparser_multithreading_python.txt
Q: Storing Data from both POST variables and GET parameters I want my python script to simultaneously accept POST variables and query string variables from the web address. The script has code : form = cgi.FieldStorage() print form However, this only captures the post variables and no query variables from the web address. Is there a way to do this? Thanks, Ali A: cgi.parse_qsl (in any Python 2.*; urlparse.parse_qsl in 2.6 or better) take a query string and return a list of name, value pairs. Use os.environ['QUERY_STRING'] to get the query string part of the URL your CGI script was reached at (everything after the ? in the URL, if any).
Storing Data from both POST variables and GET parameters
I want my python script to simultaneously accept POST variables and query string variables from the web address. The script has code : form = cgi.FieldStorage() print form However, this only captures the post variables and no query variables from the web address. Is there a way to do this? Thanks, Ali
[ "cgi.parse_qsl (in any Python 2.*; urlparse.parse_qsl in 2.6 or better) take a query string and return a list of name, value pairs. Use os.environ['QUERY_STRING'] to get the query string part of the URL your CGI script was reached at (everything after the ? in the URL, if any).\n" ]
[ 1 ]
[]
[]
[ "cgi", "forms", "get", "post", "python" ]
stackoverflow_0002616001_cgi_forms_get_post_python.txt
Q: How to create Fibonacci Sequence in Java I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this: a = 0 b = 1 while b < 10: print b a, b = b, b+a The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought: public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. A: I'd do it this way: public class FibonacciAlgorithm { private int a = 0; private int b = 1; public FibonacciAlgorithm() { } public int increment() { int temp = b; b = a + b; a = temp; return value; } public int getValue() { return b; } } This keeps it as close to your original Java code as possible. [Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.] A: The line a, b = b, b+a Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning. t1 = b t2 = b+a a = t1 b = t2 A: You need to store the value of either a or b in a temporary variable first; public Integer increment() { int temp = a; a = b; b = temp + b; return value; } A: Java integers can only store the first 46 Fibonacci numbers, use a lookup table. A: I'll just translate your earlier code: public void fibb(int max) { int a = 0; int b = 1; while (a < max) { System.out.println(a); int temp = a + b; a = b; b = temp; } } A: Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid: public int Fibb(int index) { if (index < 2) return 1; else return Fibb(index-1)+Fibb(index-2); }; Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover. A: The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this: Make a list out of 'b' and 'a + b' Make another list out of references to 'a' and 'b' Assign all the elements from the second list to the first one (It might actually be a tuple, I'm not exactly fluent in Python.) So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java. In general, a statement in Python like var1, var2, ...varN = expression1, expression2, ...expressionN is going to translate in Java to temp1 = expression1; temp2 = expression2; ... tempN = expressionN; var1 = temp1; var2 = temp2; ... varN = tempN; This way all the expressions resolve to values before the assignments happen, and none of the assignments have side effects on the expressions. If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible. A: There was a recursive solution posted above, but this solution is tail recursive so it grows linearly. public class Fibonacci { public long fibonacci(int number) { return fib(0,1,number); } private long fib(long result, long next, int n) { if (n == 0) return result; else return fib(next, result+next, n-1); } } A: i'll do this fib = 100; for(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) { System.out.print(a + ","); }
How to create Fibonacci Sequence in Java
I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this: a = 0 b = 1 while b < 10: print b a, b = b, b+a The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought: public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me.
[ "I'd do it this way:\npublic class FibonacciAlgorithm {\n\n private int a = 0;\n\n private int b = 1;\n\n public FibonacciAlgorithm() {\n\n }\n\n public int increment() {\n int temp = b;\n b = a + b;\n a = temp;\n return value;\n }\n\n public int getValue() {\n return b;\n }\n}\n\nThis keeps it as close to your original Java code as possible.\n[Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.]\n", "The line\na, b = b, b+a\n\nDoesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.\nt1 = b\nt2 = b+a\na = t1\nb = t2\n\n", "You need to store the value of either a or b in a temporary variable first;\n public Integer increment() \n { \n int temp = a;\n a = b;\n b = temp + b;\n return value;\n }\n\n", "Java integers can only store the first 46 Fibonacci numbers, use a lookup table.\n", "I'll just translate your earlier code:\npublic void fibb(int max) {\n int a = 0;\n int b = 1;\n while (a < max) {\n System.out.println(a);\n int temp = a + b;\n a = b;\n b = temp;\n }\n}\n\n", "Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:\npublic int Fibb(int index) {\nif (index < 2)\n return 1;\nelse\n return Fibb(index-1)+Fibb(index-2);\n};\n\nGiven the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover.\n", "The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:\nMake a list out of 'b' and 'a + b'\nMake another list out of references to 'a' and 'b'\nAssign all the elements from the second list to the first one\n\n(It might actually be a tuple, I'm not exactly fluent in Python.)\nSo the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.\nIn general, a statement in Python like\nvar1, var2, ...varN = expression1, expression2, ...expressionN\n\nis going to translate in Java to\ntemp1 = expression1;\ntemp2 = expression2;\n...\ntempN = expressionN;\nvar1 = temp1;\nvar2 = temp2;\n...\nvarN = tempN;\n\nThis way all the expressions resolve to values before the assignments happen, and none of the assignments have side effects on the expressions.\nIf I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible.\n", "There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.\npublic class Fibonacci {\n public long fibonacci(int number) {\n return fib(0,1,number);\n }\n\n private long fib(long result, long next, int n) {\n if (n == 0)\n return result;\n else\n return fib(next, result+next, n-1);\n }\n}\n\n", "i'll do this\nfib = 100;\nfor(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) {\n System.out.print(a + \",\");\n}\n\n" ]
[ 7, 4, 2, 1, 0, 0, 0, 0, 0 ]
[ "public Integer increment() {\n a = b;\n b = a + b;\n return value;\n }\nIs certainly wrong. I think switching the first two lines should do the trick\n" ]
[ -1 ]
[ "java", "python" ]
stackoverflow_0001045151_java_python.txt
Q: Python: what package contains the installation metadata? e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"? A: You want the sys module: >>> print sys.executable /usr/bin/python >>> print sys.path ['', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode'] A: distutils.sysconfig is the module that "provides access to Python’s low-level configuration information". The get_python_lib function, in particular, gives "the directory for either the general or platform-dependent library installation", depending on its arguments. However, sys.executable is not exposed by said sysconfig module -- it's only in the sys module.
Python: what package contains the installation metadata?
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
[ "You want the sys module:\n>>> print sys.executable\n/usr/bin/python\n>>> print sys.path\n['', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',\n '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', \n'/Library/Python/2.6/site-packages', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', \n'/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']\n\n", "distutils.sysconfig is the module that \"provides access to Python’s low-level configuration information\". The get_python_lib function, in particular, gives \"the directory for either the general or platform-dependent library installation\", depending on its arguments.\nHowever, sys.executable is not exposed by said sysconfig module -- it's only in the sys module.\n" ]
[ 1, 1 ]
[]
[]
[ "installation", "metadata", "python" ]
stackoverflow_0002616190_installation_metadata_python.txt
Q: Real-time data on webpage with jQuery I would like a webpage that constantly updates a graph with new data as it arrives. Regularly, all the data you have is passed to the page at the beginning of the request. However, I need the page to be able to update itself with fresh information every few seconds to redraw the graph. Background The webpage will be similar to this http://www.panic.com/blog/2010/03/the-panic-status-board/. The data coming in will temperature values to be graphed measured by an Arduino and saved to the Django database (this part is already complete). Update It sounds as though the solution is to use the jQuery.ajax() function ( http://api.jquery.com/jQuery.ajax/) with a function as the .complete callback that will schedule another request several seconds later to a URL that will return the data in JSON format. How can that method be scheduled? With the .delay() function? A: So the page must perform periodic jQuery.ajax calls with a url parameter set to a server's URL where the latest up-to-data information (possibly just as an incremental delta from the last instant for which the client has info -- the client can send that instant as a query parameter in the Ajax call) is served, ideally in JSON form. The callback at the completion of the async request can schedule the next ajax calls for a few seconds in the future, and then repaint the graph. The fact that, server-side, you're using Django, doesn't seem all that crucial -- the server just needs to format a bunch of data as JSON and send it back, after all. A: If the data is composed by on-the-fly graphics, you can just serve them (in gif, png or any other graphic format) through Django and reload each individually or even reload all the page at once. It depends on the load and performance requirements, but you can start simply reloading all the page and then, if necessary, use AJAX to reload just each specific part (it's very easy to achieve with jQuery or prototype using updates). If you expect a lot of data, then you should change to generate the graphic on the client, using just JSON incremental data.
Real-time data on webpage with jQuery
I would like a webpage that constantly updates a graph with new data as it arrives. Regularly, all the data you have is passed to the page at the beginning of the request. However, I need the page to be able to update itself with fresh information every few seconds to redraw the graph. Background The webpage will be similar to this http://www.panic.com/blog/2010/03/the-panic-status-board/. The data coming in will temperature values to be graphed measured by an Arduino and saved to the Django database (this part is already complete). Update It sounds as though the solution is to use the jQuery.ajax() function ( http://api.jquery.com/jQuery.ajax/) with a function as the .complete callback that will schedule another request several seconds later to a URL that will return the data in JSON format. How can that method be scheduled? With the .delay() function?
[ "So the page must perform periodic jQuery.ajax calls with a url parameter set to a server's URL where the latest up-to-data information (possibly just as an incremental delta from the last instant for which the client has info -- the client can send that instant as a query parameter in the Ajax call) is served, ideally in JSON form. The callback at the completion of the async request can schedule the next ajax calls for a few seconds in the future, and then repaint the graph.\nThe fact that, server-side, you're using Django, doesn't seem all that crucial -- the server just needs to format a bunch of data as JSON and send it back, after all.\n", "If the data is composed by on-the-fly graphics, you can just serve them (in gif, png or any other graphic format) through Django and reload each individually or even reload all the page at once.\nIt depends on the load and performance requirements, but you can start simply reloading all the page and then, if necessary, use AJAX to reload just each specific part (it's very easy to achieve with jQuery or prototype using updates). If you expect a lot of data, then you should change to generate the graphic on the client, using just JSON incremental data.\n" ]
[ 6, 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0002615719_django_jquery_python.txt
Q: Python: eliminating stack traces into library code? When I get a runtime exception from the standard library, it's almost always a problem in my code and not in the library code. Is there a way to truncate the exception stack trace so that it doesn't show the guts of the library package? For example, I would like to get this: Traceback (most recent call last): File "./lmd3-mkhead.py", line 71, in <module> main() File "./lmd3-mkhead.py", line 66, in main create() File "./lmd3-mkhead.py", line 41, in create headver1[depotFile]=rev TypeError: Data values must be of type string or None. and not this: Traceback (most recent call last): File "./lmd3-mkhead.py", line 71, in <module> main() File "./lmd3-mkhead.py", line 66, in main create() File "./lmd3-mkhead.py", line 41, in create headver1[depotFile]=rev File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/__init__.py", line 276, in __setitem__ _DeadlockWrap(wrapF) # self.db[key] = value File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/dbutils.py", line 68, in DeadlockWrap return function(*_args, **_kwargs) File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/__init__.py", line 275, in wrapF self.db[key] = value TypeError: Data values must be of type string or None. update: added an answer with the code, thanks to the pointer from Alex. A: The traceback module in Python's standard library lets you emit error tracebacks in a way that accords to your liking, while an exception is propagating. You can use this power either in the except leg of a try/except statement, or in a function you've installed as sys.excepthook, which gets called if and when an exception propagates all the way; quoting the docs: In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook. Here's a simple, artificial example: >>> import sys >>> import traceback >>> def f(n): ... if n<=0: raise ZeroDivisionError ... f(n-1) ... >>> def excepthook(type, value, tb): ... traceback.print_exception(type, value, tb, 3) ... >>> sys.excepthook = excepthook >>> f(8) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in f File "<stdin>", line 3, in f ZeroDivisionError as you see, without needing a try/except, you can easily limit the traceback to (for example) the first three levels -- even though we know by design that there were 9 nested levels when the exception was raised. You want something more sophisticated than a simple limit on levels, so you'll need to call traceback.format_exception, which gives you a list of lines rather than printing it, then "prune" from that list the lines that are about modules you never want to see in your tracebacks, and finally emit the remaining lines (typically to sys.stderr, but, whatever!-). A: Thanks to the pointer from Alex, here's teh codez: def trimmedexceptions(type, value, tb, pylibdir=None, lev=None): """trim system packages from the exception printout""" if pylibdir is None: import traceback, distutils.sysconfig pylibdir = distutils.sysconfig.get_python_lib(1,1) nlev = trimmedexceptions(type, value, tb, pylibdir, 0) traceback.print_exception(type, value, tb, nlev) else: fn = tb.tb_frame.f_code.co_filename if tb.tb_next is None or fn.startswith(pylibdir): return lev else: return trimmedexceptions(type, value, tb.tb_next, pylibdir, lev+1) import sys sys.excepthook=trimmedexceptions # --- test code --- def f1(): f2() def f2(): f3() def f3(): import xmlrpclib proxy = xmlrpclib.ServerProxy('http://nosuchserver') proxy.f() f1() Which yields this stack trace: Traceback (most recent call last): File "./tsttraceback.py", line 47, in <module> f1() File "./tsttraceback.py", line 40, in f1 def f1(): f2() File "./tsttraceback.py", line 41, in f2 def f2(): f3() File "./tsttraceback.py", line 45, in f3 proxy.f() gaierror: [Errno -2] Name or service not known A: The Traceback library is probably what you want. Here's one example that might help: import traceback try: your_main() except: lines = traceback.format_exc() print lines[:lines.find('File "/usr')] (This obviously won't work if there's an exception outside the library, and might not exactly fit your needs, but it's one way of using the traceback library) A: Put an unqualified try...except at the top of your code (ie: in your "main") or set sys.excepthook. You can then format the stack trace however you'd like.
Python: eliminating stack traces into library code?
When I get a runtime exception from the standard library, it's almost always a problem in my code and not in the library code. Is there a way to truncate the exception stack trace so that it doesn't show the guts of the library package? For example, I would like to get this: Traceback (most recent call last): File "./lmd3-mkhead.py", line 71, in <module> main() File "./lmd3-mkhead.py", line 66, in main create() File "./lmd3-mkhead.py", line 41, in create headver1[depotFile]=rev TypeError: Data values must be of type string or None. and not this: Traceback (most recent call last): File "./lmd3-mkhead.py", line 71, in <module> main() File "./lmd3-mkhead.py", line 66, in main create() File "./lmd3-mkhead.py", line 41, in create headver1[depotFile]=rev File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/__init__.py", line 276, in __setitem__ _DeadlockWrap(wrapF) # self.db[key] = value File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/dbutils.py", line 68, in DeadlockWrap return function(*_args, **_kwargs) File "/usr/anim/modsquad/oses/fc11/lib/python2.6/bsddb/__init__.py", line 275, in wrapF self.db[key] = value TypeError: Data values must be of type string or None. update: added an answer with the code, thanks to the pointer from Alex.
[ "The traceback module in Python's standard library lets you emit error tracebacks in a way that accords to your liking, while an exception is propagating. You can use this power either in the except leg of a try/except statement, or in a function you've installed as sys.excepthook, which gets called if and when an exception propagates all the way; quoting the docs:\n\nIn an interactive session this happens\n just before control is returned to the\n prompt; in a Python program this\n happens just before the program exits.\n The handling of such top-level\n exceptions can be customized by\n assigning another three-argument\n function to sys.excepthook.\n\nHere's a simple, artificial example:\n>>> import sys\n>>> import traceback\n>>> def f(n):\n... if n<=0: raise ZeroDivisionError\n... f(n-1)\n... \n>>> def excepthook(type, value, tb):\n... traceback.print_exception(type, value, tb, 3)\n... \n>>> sys.excepthook = excepthook\n>>> f(8)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 3, in f\n File \"<stdin>\", line 3, in f\nZeroDivisionError\n\nas you see, without needing a try/except, you can easily limit the traceback to (for example) the first three levels -- even though we know by design that there were 9 nested levels when the exception was raised.\nYou want something more sophisticated than a simple limit on levels, so you'll need to call traceback.format_exception, which gives you a list of lines rather than printing it, then \"prune\" from that list the lines that are about modules you never want to see in your tracebacks, and finally emit the remaining lines (typically to sys.stderr, but, whatever!-).\n", "Thanks to the pointer from Alex, here's teh codez:\ndef trimmedexceptions(type, value, tb, pylibdir=None, lev=None):\n \"\"\"trim system packages from the exception printout\"\"\"\n if pylibdir is None:\n import traceback, distutils.sysconfig\n pylibdir = distutils.sysconfig.get_python_lib(1,1)\n nlev = trimmedexceptions(type, value, tb, pylibdir, 0)\n traceback.print_exception(type, value, tb, nlev)\n else:\n fn = tb.tb_frame.f_code.co_filename\n if tb.tb_next is None or fn.startswith(pylibdir):\n return lev\n else:\n return trimmedexceptions(type, value, tb.tb_next, pylibdir, lev+1)\n\nimport sys\nsys.excepthook=trimmedexceptions\n\n# --- test code ---\n\ndef f1(): f2()\ndef f2(): f3()\ndef f3():\n import xmlrpclib\n proxy = xmlrpclib.ServerProxy('http://nosuchserver')\n proxy.f()\n\nf1()\n\nWhich yields this stack trace:\nTraceback (most recent call last):\n File \"./tsttraceback.py\", line 47, in <module>\n f1()\n File \"./tsttraceback.py\", line 40, in f1\n def f1(): f2()\n File \"./tsttraceback.py\", line 41, in f2\n def f2(): f3()\n File \"./tsttraceback.py\", line 45, in f3\n proxy.f()\ngaierror: [Errno -2] Name or service not known\n\n", "The Traceback library is probably what you want. Here's one example that might help:\nimport traceback\n\ntry:\n your_main()\nexcept:\n lines = traceback.format_exc()\n print lines[:lines.find('File \"/usr')]\n\n(This obviously won't work if there's an exception outside the library, and might not exactly fit your needs, but it's one way of using the traceback library)\n", "Put an unqualified try...except at the top of your code (ie: in your \"main\") or set sys.excepthook. You can then format the stack trace however you'd like.\n" ]
[ 11, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002615414_python.txt
Q: How to simulate tuples and sets in C#? I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages? A: .NET 3.5 has HashSet. .NET 4.0 will have a Tuple class. As noted in the article, earlier version of .NET do contain KeyValuePair< TKey, TValue > which is similar to a Tuple< T1, T2 >, with the main difference being that KeyValuePair requires that TKey is unique. A: For Sets, HashSets (a .NET 3.5 feature) do the trick quite well. A partial answer, for tuples: .NET 4.0 provides [some] support for tuples. Earlier versions of C# can use the anonymous type (I think introduced in .Net 2.0, 3.0 for sure, with all the LINQ stuff). Neither of these approaches are as convenient as with Python; the main handicap comes from the fact that C# is statically typed. However the C# 4.0 Tuple class has factory-like static methods which make the creation of tuples easier (up to 8-tuple, i.e. tuples with 8 members). For example one can have var customer1 = Tuple.Create("John", "Smith", 14, 5.33, "202-123-444"); Using anonymous type can be done as follow. The main drawback of this approach is that one needs to explicitly name the elements of the "tuple" (although this naming can be implicitly "projected" if the values used for initialization are "projected" from another object. customer1 = new Customer { Name = "John", Surname = "Smith", NumberOfVisits = 14, CurrentBalance = 5.33, PhoneNr = "202-123-444" }; A: If you're working with a .NET Framework earlier than already mentioned, Wintellect Power Collections might prove of some interest - it has Pair and Triple for 2- and 3-tuples, and collections such as Set, Bag, and Ordered flavours of both. Of course, there's nothing stopping you from implementing 4.0's Tuple yourself. (By the way, there's nothing particularly 'dynamic' about data structures like these in and of themselves)
How to simulate tuples and sets in C#?
I want to use some features of python like as Tuples and Sets in c#. should I implement them? or there are already implemented? could anybody knows a library of dynamic data structures for .net languages?
[ ".NET 3.5 has HashSet.\n.NET 4.0 will have a Tuple class. As noted in the article, earlier version of .NET do contain KeyValuePair< TKey, TValue > which is similar to a Tuple< T1, T2 >, with the main difference being that KeyValuePair requires that TKey is unique. \n", "For Sets, HashSets (a .NET 3.5 feature) do the trick quite well.\nA partial answer, for tuples:\n\n.NET 4.0 provides [some] support for tuples.\nEarlier versions of C# can use the anonymous type (I think introduced in .Net 2.0, 3.0 for sure, with all the LINQ stuff).\n\nNeither of these approaches are as convenient as with Python; the main handicap comes from the fact that C# is statically typed. However the C# 4.0 Tuple class has factory-like static methods which make the creation of tuples easier (up to 8-tuple, i.e. tuples with 8 members). For example one can have\n\n var customer1 = Tuple.Create(\"John\", \"Smith\", 14, 5.33, \"202-123-444\");\n\nUsing anonymous type can be done as follow. The main drawback of this approach is that one needs to explicitly name the elements of the \"tuple\" (although this naming can be implicitly \"projected\" if the values used for initialization are \"projected\" from another object.\n\n customer1 = new Customer {\n Name = \"John\",\n Surname = \"Smith\",\n NumberOfVisits = 14,\n CurrentBalance = 5.33,\n PhoneNr = \"202-123-444\"\n };\n\n", "If you're working with a .NET Framework earlier than already mentioned, Wintellect Power Collections might prove of some interest - it has Pair and Triple for 2- and 3-tuples, and collections such as Set, Bag, and Ordered flavours of both.\nOf course, there's nothing stopping you from implementing 4.0's Tuple yourself.\n(By the way, there's nothing particularly 'dynamic' about data structures like these in and of themselves)\n" ]
[ 14, 3, 1 ]
[]
[]
[ "c#", "data_structures", "python", "set", "tuples" ]
stackoverflow_0002616255_c#_data_structures_python_set_tuples.txt
Q: Is it possible to detect when the system is recording a sound and then perform some action on Python? I began learning Python a few days ago, and i was wondering about a practical use for a program. Then i came up with the following: if my brother is in his room recording himself playing guitar, a led plugged to the usb and wired so it's outside his door lights up, and then i'll know he's recording and i'll take care not to make any noises. The main questions are: How Python can detect any recording going on in the system? How would i interface with the usb so i can actually turn the led on? A: to interact with USB, you can read this related question. to detect recording, you will have to tell us on which operating system your program is intented to run (but i am not sure it is possible to detect that another application is recording)
Is it possible to detect when the system is recording a sound and then perform some action on Python?
I began learning Python a few days ago, and i was wondering about a practical use for a program. Then i came up with the following: if my brother is in his room recording himself playing guitar, a led plugged to the usb and wired so it's outside his door lights up, and then i'll know he's recording and i'll take care not to make any noises. The main questions are: How Python can detect any recording going on in the system? How would i interface with the usb so i can actually turn the led on?
[ "to interact with USB, you can read this related question.\nto detect recording, you will have to tell us on which operating system your program is intented to run (but i am not sure it is possible to detect that another application is recording)\n" ]
[ 0 ]
[]
[]
[ "audio_recording", "detection", "led", "python", "usb" ]
stackoverflow_0002616252_audio_recording_detection_led_python_usb.txt
Q: How can I learn to set up a build process? What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for his project. If this is too abstract to make any sense, I would add that I use Python and do web programming with Django. Thanks in advance. A: I like a couple of Pragmatic Programmers' books on this subject, Ship it! and Release it!. Together, they teach a lot of real-world, pragmatic stuff about such things as build systems and how to design well-deployable programs. A: If you're doing this in Java, you can check out Maven. There are a host of tutorials for it: Maven in Five Minutes The Maven Tutorial: A practical guide for Maven 2 users Maven: The definitive Guide (book) All of this falls under the category of Software-Development Principles, Software-Design Philosophy, Software-Configuration Management, and Build and Release Management: Best practices for build and release management High-level best practices in Software-Configuration Management Software-Configuration Management Best Principles It's a moderately-involved field. After years of programming, I'm still learning and understanding new things about build-management and software-configuration management. A: I think that the process you are referring to is called continuous integration. One of the popular tools for that is Hudson (see Hudson with django). Make sure to also check out the django-continuous-integration project. A: For Python projects you should use setuptools. Setuptools has all the stuff to pack things up into .eggs, compile C modules, run unit tests, etc... If you've ever done "python setup.py [build|install|test]" then you've used setuptools. A: While this is certainly not a complete answer to your question, I would like to recommend very highly the learning of the tool 'make'. I find myself using it on a VERY regular basis, for a wide variety of tasks, including (but by no means limited to) building, testing, and deploying software.
How can I learn to set up a build process?
What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for his project. If this is too abstract to make any sense, I would add that I use Python and do web programming with Django. Thanks in advance.
[ "I like a couple of Pragmatic Programmers' books on this subject, Ship it! and Release it!. Together, they teach a lot of real-world, pragmatic stuff about such things as build systems and how to design well-deployable programs.\n", "If you're doing this in Java, you can check out Maven. There are a host of tutorials for it:\n\nMaven in Five Minutes\nThe Maven Tutorial: A practical guide for Maven 2 users\nMaven: The definitive Guide (book)\n\nAll of this falls under the category of Software-Development Principles, Software-Design Philosophy, Software-Configuration Management, and Build and Release Management:\n\nBest practices for build and release management\nHigh-level best practices in Software-Configuration Management\nSoftware-Configuration Management Best Principles\n\nIt's a moderately-involved field. After years of programming, I'm still learning and understanding new things about build-management and software-configuration management.\n", "I think that the process you are referring to is called continuous integration.\nOne of the popular tools for that is Hudson (see Hudson with django). Make sure to also check out the django-continuous-integration project.\n", "For Python projects you should use setuptools. Setuptools has all the stuff to pack things up into .eggs, compile C modules, run unit tests, etc... If you've ever done \"python setup.py [build|install|test]\" then you've used setuptools.\n", "While this is certainly not a complete answer to your question, I would like to recommend very highly the learning of the tool 'make'. I find myself using it on a VERY regular basis, for a wide variety of tasks, including (but by no means limited to) building, testing, and deploying software.\n" ]
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "ci_server", "python" ]
stackoverflow_0002615923_ci_server_python.txt
Q: Unknown reason for code executing the way it does in python I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: import time def newGameStep2(): print ' ****************************************** ' print '\nStep2\t\t\t\tCharacter Name' print '\nChoose a name for your character. This cannot\n be changed during the game. Note that there\n are limitations upon the name.' print '\nLimitations:\n\tYou cannot use:\n\tCommander\n\tLieutenant\n\tMajor\n\t\tas these are reserved.\n All unusual capitalisations will be removed.\n There is a two-word-limit on names.' newStep2Choice = raw_input('>>>') newStep2Choice = newStep2Choice.lower() if 'commander' in newStep2Choice or 'lieutenant' in newStep2Choice or 'major' in newStep2Choice: print 'You cannot use the terms \'commander\', \'lieutenant\' or \'major\' in the name. They are reserved.\n' print time.sleep(2) newGameStep2() else: newStep2Choice = newStep2Choice.split(' ') newStep2Choice = [newStep2Choice[0].capitalize(), newStep2Choice[1].capitalize()] newStep2Choice = ' ' .join(newStep2Choice) return newStep2Choice myVar = newGameStep2() print myVar When I was testing, I inputted 'major a', and when it asked me to input another name, i inputted 'a b'. However, when it returned the output of the function, it returns 'major a'. I went through this with a debugger, yet I still can't seem to find where the problem occurred. Thanks for any help, Jasper A: Your recursive call to newGameStep2() isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and return newStep2Choice returns the first read value. You need to change the recursive call to: return newGameStep2()
Unknown reason for code executing the way it does in python
I am a beginner programmer, using python on Mac. I created a function as a part of a game which receives the player's input for the main character's name. The code is: import time def newGameStep2(): print ' ****************************************** ' print '\nStep2\t\t\t\tCharacter Name' print '\nChoose a name for your character. This cannot\n be changed during the game. Note that there\n are limitations upon the name.' print '\nLimitations:\n\tYou cannot use:\n\tCommander\n\tLieutenant\n\tMajor\n\t\tas these are reserved.\n All unusual capitalisations will be removed.\n There is a two-word-limit on names.' newStep2Choice = raw_input('>>>') newStep2Choice = newStep2Choice.lower() if 'commander' in newStep2Choice or 'lieutenant' in newStep2Choice or 'major' in newStep2Choice: print 'You cannot use the terms \'commander\', \'lieutenant\' or \'major\' in the name. They are reserved.\n' print time.sleep(2) newGameStep2() else: newStep2Choice = newStep2Choice.split(' ') newStep2Choice = [newStep2Choice[0].capitalize(), newStep2Choice[1].capitalize()] newStep2Choice = ' ' .join(newStep2Choice) return newStep2Choice myVar = newGameStep2() print myVar When I was testing, I inputted 'major a', and when it asked me to input another name, i inputted 'a b'. However, when it returned the output of the function, it returns 'major a'. I went through this with a debugger, yet I still can't seem to find where the problem occurred. Thanks for any help, Jasper
[ "Your recursive call to newGameStep2() isn't returning, so when the second call finishes, control flow continues in the first call after the if/else block, and return newStep2Choice returns the first read value. You need to change the recursive call to:\nreturn newGameStep2()\n\n" ]
[ 8 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002616468_macos_python.txt
Q: Pythonic reading from config files I have a python class which reads a config file using ConfigParser: Config file: [geography] Xmin=6.6 Xmax=18.6 Ymin=36.6 YMax=47.1 Python code: class Slicer: def __init__(self, config_file_name): config = ConfigParser.ConfigParser() config.read(config_file_name) # Rad the lines from the file self.x_min = config.getfloat('geography', 'xmin') self.x_max = config.getfloat('geography', 'xmax') self.y_min = config.getfloat('geography', 'ymin') self.y_max = config.getfloat('geography', 'ymax') I feel that the last four lines are repetitive, and should somehow be compressed to one Pythonic line that would create a self.item variable for each item in the section. Any ideas? Adam UPDATE: Following your answers, I've modified my code to: for item in config.items('geography'): setattr(self, '_'+item[0], float(item[1])) Now, print self.__dict__ >>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001, '_ymin': 36.600000000000001, '_xmin': 6.5999999999999996} A: I usually try to avoid external interactions in a constructor - makes it hard to test the code. Better pass a config parser instance or a fp-like object instead of a filename. A: for line in ['x_min', 'x_max', 'y_min', 'y_max']: setattr(self, line, config.getfloat('geography', line.replace('_', ''))) A: How about something like: for key in ['xmin','xmax','ymin','ymax']: self.__dict__[key] = config.getfloat('geography',key); Note that the above will assign it to self.xmin instead of self.x_min... however, if you are fine with that naming, then this should work... otherwise, mapping between names would be more code than the original.
Pythonic reading from config files
I have a python class which reads a config file using ConfigParser: Config file: [geography] Xmin=6.6 Xmax=18.6 Ymin=36.6 YMax=47.1 Python code: class Slicer: def __init__(self, config_file_name): config = ConfigParser.ConfigParser() config.read(config_file_name) # Rad the lines from the file self.x_min = config.getfloat('geography', 'xmin') self.x_max = config.getfloat('geography', 'xmax') self.y_min = config.getfloat('geography', 'ymin') self.y_max = config.getfloat('geography', 'ymax') I feel that the last four lines are repetitive, and should somehow be compressed to one Pythonic line that would create a self.item variable for each item in the section. Any ideas? Adam UPDATE: Following your answers, I've modified my code to: for item in config.items('geography'): setattr(self, '_'+item[0], float(item[1])) Now, print self.__dict__ >>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001, '_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}
[ "I usually try to avoid external interactions in a constructor - makes it hard to test the code. Better pass a config parser instance or a fp-like object instead of a filename.\n", "for line in ['x_min', 'x_max', 'y_min', 'y_max']:\n\n setattr(self, line, config.getfloat('geography', line.replace('_', '')))\n\n", "How about something like:\n\nfor key in ['xmin','xmax','ymin','ymax']:\n self.__dict__[key] = config.getfloat('geography',key);\n\nNote that the above will assign it to self.xmin instead of self.x_min... however, if you are fine with that naming, then this should work... otherwise, mapping between names would be more code than the original.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "coding_style", "configparser", "dry", "python" ]
stackoverflow_0002616574_coding_style_configparser_dry_python.txt
Q: Port C's fread(&struct,....) to Python Hey, I'm really struggling with this one. I'am trying to port a small piece of someone else's code to Python and this is what I have: typedef struct { uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH]; uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH]; uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH]; } __attribute__((__packed__)) frame_t; frame_t frame; while (! feof(stdin)) { fread(&frame, 1, sizeof(frame), stdin); // DO SOME STUFF } Later I need to access the data like so: frame.Y[x][y] So I made a Class 'frame' in Python and inserted the corresponding variables(frame.Y, frame.Cb, frame.Cr). I have tried to sequentially map the data from Y[0][0] to Cr[MAX][MAX], even printed out the C struct in action but didn't manage to wrap my head around the method used to put the data in there. I've been struggling overnight with this and have to get back to the army tonight, so any immediate help is very welcome and appreciated. Thanks A: You have to use struct python standard module. From its documentation (emphasys added): This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources. Note: as the data you are reading in the end is of a uniform format, you could also use the array module and then "restructure" the data in Python, but I think the best way to go is by using struct.
Port C's fread(&struct,....) to Python
Hey, I'm really struggling with this one. I'am trying to port a small piece of someone else's code to Python and this is what I have: typedef struct { uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH]; uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH]; uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH]; } __attribute__((__packed__)) frame_t; frame_t frame; while (! feof(stdin)) { fread(&frame, 1, sizeof(frame), stdin); // DO SOME STUFF } Later I need to access the data like so: frame.Y[x][y] So I made a Class 'frame' in Python and inserted the corresponding variables(frame.Y, frame.Cb, frame.Cr). I have tried to sequentially map the data from Y[0][0] to Cr[MAX][MAX], even printed out the C struct in action but didn't manage to wrap my head around the method used to put the data in there. I've been struggling overnight with this and have to get back to the army tonight, so any immediate help is very welcome and appreciated. Thanks
[ "You have to use struct python standard module.\nFrom its documentation (emphasys added):\n\nThis module performs conversions\n between Python values and C structs\n represented as Python strings. It uses\n format strings (explained below) as\n compact descriptions of the lay-out of\n the C structs and the intended\n conversion to/from Python values. This\n can be used in handling binary data\n stored in files or from network\n connections, among other sources.\n\nNote: as the data you are reading in the end is of a uniform format, you could also use the array module and then \"restructure\" the data in Python, but I think the best way to go is by using struct.\n" ]
[ 6 ]
[]
[]
[ "c", "porting", "python", "struct" ]
stackoverflow_0002616680_c_porting_python_struct.txt
Q: Retrieving information with Python's urllib from a page that is done via __doPostBack()? I'm trying to parse a page that has different sections that are loaded with a Javascript __doPostBack() function. An example of a link is: javascript:__doPostBack('ctl00$cphMain$ucOemSchPicker$dlSch$ctl03$btnSch','') As soon as this is clicked, the browser doesn't fetch a new URL but a section of webpage is updated to reflect new information. What would I pass into a urllib function to complete the operation? A: javascript:__doPostBack('... (Urgh. That's a sad and nasty approach.) A simple general-purpose approach for finding URLs whose logic is buried in JavaScript is to run the page normally, with a network debugger on (eg. Firebug's ‘Net’ tab, or Fiddler). By monitoring the request made when you click, you can see what URL and what POST request body parameters are to be passed. You'll need to use the data argument of urlopen to send POST request bodies.
Retrieving information with Python's urllib from a page that is done via __doPostBack()?
I'm trying to parse a page that has different sections that are loaded with a Javascript __doPostBack() function. An example of a link is: javascript:__doPostBack('ctl00$cphMain$ucOemSchPicker$dlSch$ctl03$btnSch','') As soon as this is clicked, the browser doesn't fetch a new URL but a section of webpage is updated to reflect new information. What would I pass into a urllib function to complete the operation?
[ "javascript:__doPostBack('...\n\n(Urgh. That's a sad and nasty approach.)\nA simple general-purpose approach for finding URLs whose logic is buried in JavaScript is to run the page normally, with a network debugger on (eg. Firebug's ‘Net’ tab, or Fiddler). By monitoring the request made when you click, you can see what URL and what POST request body parameters are to be passed.\nYou'll need to use the data argument of urlopen to send POST request bodies.\n" ]
[ 1 ]
[]
[]
[ "asp.net", "javascript", "parsing", "python", "urllib" ]
stackoverflow_0002616783_asp.net_javascript_parsing_python_urllib.txt
Q: fade out in Image module Python I want to take a BMP or JPG and duplicate it so the new image will darker (or brighrt) what function can I use? Ariel A: You can use ImageEnhance module of PIL: import Image import ImageEnhance image = Image.open(r'c:\temp\20090809210.jpg') enhancer = ImageEnhance.Brightness(image) brighter_image = enhancer.enhance(2) darker_image = enhancer.enhance(0.5) Look at PIL and ImageEnhance documentation for more details. Note: I think ImageEnhancer documentation is a bit too terse, and you may need some experimenting within the interactive prompt to get it right. A: If you want to do it the hard way i.e. code up a pixel by pixel intensity change. Here is how: 1) Convert from RGB to HSI 2) Increase or decrease the Intensity component 3) Conver back from HSI to RGB True fade out i.e. alpha channel is not present in the JPG or BMP formats [ RGBA format image in PIL] . You get black to white using the the intensity technique. If you want to use alpha use png or tiff instead.
fade out in Image module Python
I want to take a BMP or JPG and duplicate it so the new image will darker (or brighrt) what function can I use? Ariel
[ "You can use ImageEnhance module of PIL:\nimport Image\nimport ImageEnhance\n\nimage = Image.open(r'c:\\temp\\20090809210.jpg')\nenhancer = ImageEnhance.Brightness(image)\nbrighter_image = enhancer.enhance(2)\ndarker_image = enhancer.enhance(0.5)\n\nLook at PIL and ImageEnhance documentation for more details.\nNote: I think ImageEnhancer documentation is a bit too terse, and you may need some experimenting within the interactive prompt to get it right.\n", "If you want to do it the hard way i.e. code up a pixel by pixel intensity change. Here is how:\n1) Convert from RGB to HSI\n2) Increase or decrease the Intensity component\n3) Conver back from HSI to RGB\nTrue fade out i.e. alpha channel is not present in the JPG or BMP formats [ RGBA format image in PIL] . You get black to white using the the intensity technique. If you want to use alpha use png or tiff instead.\n" ]
[ 7, 1 ]
[]
[]
[ "fadeout", "image", "python" ]
stackoverflow_0002616645_fadeout_image_python.txt