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: Django m2m queries, distinct Users for a m2m relationship of a Model I have a model Model with a m2m field : user = .. fk user ... watchers = models.ManyToManyField(User, related_name="boardShot_watchers", null=True) How do i select all distinct Users involved in this watchers relationship for all my entries of type Model ? I dont think there is an ORM way to access to intermediary M2M table. Greg A: Not in your current model. If you want to have explicit access to the joining table, you need to make it part of the Django object model. The docs explain how to do this: http://www.djangoproject.com/documentation/models/m2m_intermediary/ The admin and other django.contrib* components can be configured to treat most fields the same as if they were just model.ManyToMany's. But it will take a little config.
Django m2m queries, distinct Users for a m2m relationship of a Model
I have a model Model with a m2m field : user = .. fk user ... watchers = models.ManyToManyField(User, related_name="boardShot_watchers", null=True) How do i select all distinct Users involved in this watchers relationship for all my entries of type Model ? I dont think there is an ORM way to access to intermediary M2M table. Greg
[ "Not in your current model. If you want to have explicit access to the joining table, you need to make it part of the Django object model. The docs explain how to do this:\nhttp://www.djangoproject.com/documentation/models/m2m_intermediary/\nThe admin and other django.contrib* components can be configured to treat most fields the same as if they were just model.ManyToMany's. But it will take a little config. \n" ]
[ 2 ]
[]
[]
[ "django", "m2m", "orm", "python" ]
stackoverflow_0000807470_django_m2m_orm_python.txt
Q: How to query filter in django without multiple occurrences I have 2 models: ParentModel: 'just' sits there ChildModel: has a foreign key to ParentModel ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()) gives multiple occurrences of ParentModel. How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occurrences... A: You almost got it right... ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct() A: You might want to avoid using childmodel__in=ChildModel.objects.all() if the number of ChildModel objects is large. This will generate SQL with all ChildModel id's enumerated in a list, possibly creating a huge SQL query. If you can use Django 1.1 with aggregation support, you could do something like: ParentModel.objects.annotate(num_children=Count('child')).filter(num_children__gte=1) which should generate better SQL.
How to query filter in django without multiple occurrences
I have 2 models: ParentModel: 'just' sits there ChildModel: has a foreign key to ParentModel ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()) gives multiple occurrences of ParentModel. How do I query all ParentModels that have at least one ChildModel that's referring to it? And without multiple occurrences...
[ "You almost got it right...\nParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct()\n\n", "You might want to avoid using childmodel__in=ChildModel.objects.all() if the number of ChildModel objects is large. This will generate SQL with all ChildModel id's enumerated in a list, possibly creating a huge SQL query.\nIf you can use Django 1.1 with aggregation support, you could do something like:\nParentModel.objects.annotate(num_children=Count('child')).filter(num_children__gte=1)\n\nwhich should generate better SQL.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000796971_django_python.txt
Q: Python embedding with threads -- avoiding deadlocks? Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks? The problem is this: To call into Python, I need to hold the GIL. Typically, I do this by getting the main thread state when I first create the interpreter, and then using PyEval_RestoreThread() to take the GIL and swap in the thread state before I call into Python. When called from Python, I may need to access some protected resources that are protected by a separate critical section in my host. This means that Python will hold the GIL (potentially from some other thread than I initially called into), and then attempt to acquire my protection lock. When calling into Python, I may need to hold the same locks, because I may be iterating over some collection of objects, for example. The problem is that even if I hold the GIL when I call into Python, Python may give it up, give it to another thread, and then have that thread call into my host, expecting to take the host locks. Meanwhile, the host may take the host locks, and the GIL lock, and call into Python. Deadlock ensues. The problem here is that Python relinquishes the GIL to another thread while I've called into it. That's what it's expected to do, but it makes it impossible to sequence locking -- even if I first take GIL, then take my own lock, then call Python, Python will call into my system from another thread, expecting to take my own lock (because it un-sequenced the GIL by releasing it). I can't really make the rest of my system use the GIL for all possible locks in the system -- and that wouldn't even work right, because Python may still release it to another thread. I can't really guarantee that my host doesn't hold any locks when entering Python, either, because I'm not in control of all the code in the host. So, is it just the case that this can't be done? A: "When calling into Python, I may need to hold the same locks, because I may be iterating over some collection of objects, for example." This often indicates that a single process with multiple threads isn't appropriate. Perhaps this is a situation where multiple processes -- each with a specific object from the collection -- makes more sense. Independent process -- each with their own pool of threads -- may be easier to manage. A: The code that is called by python should release the GIL before taking any of your locks. That way I believe it can't get into the dead-lock.
Python embedding with threads -- avoiding deadlocks?
Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks? The problem is this: To call into Python, I need to hold the GIL. Typically, I do this by getting the main thread state when I first create the interpreter, and then using PyEval_RestoreThread() to take the GIL and swap in the thread state before I call into Python. When called from Python, I may need to access some protected resources that are protected by a separate critical section in my host. This means that Python will hold the GIL (potentially from some other thread than I initially called into), and then attempt to acquire my protection lock. When calling into Python, I may need to hold the same locks, because I may be iterating over some collection of objects, for example. The problem is that even if I hold the GIL when I call into Python, Python may give it up, give it to another thread, and then have that thread call into my host, expecting to take the host locks. Meanwhile, the host may take the host locks, and the GIL lock, and call into Python. Deadlock ensues. The problem here is that Python relinquishes the GIL to another thread while I've called into it. That's what it's expected to do, but it makes it impossible to sequence locking -- even if I first take GIL, then take my own lock, then call Python, Python will call into my system from another thread, expecting to take my own lock (because it un-sequenced the GIL by releasing it). I can't really make the rest of my system use the GIL for all possible locks in the system -- and that wouldn't even work right, because Python may still release it to another thread. I can't really guarantee that my host doesn't hold any locks when entering Python, either, because I'm not in control of all the code in the host. So, is it just the case that this can't be done?
[ "\"When calling into Python, I may need to hold the same locks, because I may be iterating over some collection of objects, for example.\"\nThis often indicates that a single process with multiple threads isn't appropriate. Perhaps this is a situation where multiple processes -- each with a specific object from the collection -- makes more sense.\nIndependent process -- each with their own pool of threads -- may be easier to manage.\n", "The code that is called by python should release the GIL before taking any of your locks.\nThat way I believe it can't get into the dead-lock.\n" ]
[ 2, 2 ]
[ "There was recently some discussion of a similar issue on the pyopenssl list. I'm afraid if I try to explain this I'm going to get it wrong, so instead I'll refer you to the problem in question.\n" ]
[ -1 ]
[ "deadlock", "embedding", "multithreading", "python" ]
stackoverflow_0000803566_deadlock_embedding_multithreading_python.txt
Q: Printing XML into HTML with python I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on the widget, it strips out all the tags. How can I pretty print XML in an HTML document? A: cgi.escape can help you. It will convert the characters '&', '<' and '>' in the string to HTML-safe sequences. That is enough to prevent interpretation of xml tags. >>> cgi.escape('<tag>') '&lt;tag&gt; A: A cdata section might help. http://reference.sitepoint.com/javascript/CDATASection http://en.wikipedia.org/wiki/CDATA
Printing XML into HTML with python
I have a TextEdit widget in PyQt that I use to print out a log in HTML. I use HTML so I can separate entries into color categories (red for error, yellow for debug, blue for message, etc), but this creates a problem. Most of the debug messages are XML. When I use appendHtml on the widget, it strips out all the tags. How can I pretty print XML in an HTML document?
[ "cgi.escape can help you. It will convert the characters '&', '<' and '>' in the string to HTML-safe sequences. That is enough to prevent interpretation of xml tags.\n>>> cgi.escape('<tag>')\n'&lt;tag&gt;\n\n", "A cdata section might help.\nhttp://reference.sitepoint.com/javascript/CDATASection\nhttp://en.wikipedia.org/wiki/CDATA\n" ]
[ 4, 0 ]
[]
[]
[ "html", "python", "xml" ]
stackoverflow_0000808529_html_python_xml.txt
Q: SQLAlchemy - Mapper configuration and declarative base I am writing a multimedia archive database backend and I want to use joined table inheritance. I am using Python with SQLAlchemy with the declarative extension. The table holding the media record is as follows: _Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) storage_id = Column(String(M_STORAGE_ID), ForeignKey('storages.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) type = Column(String(M_RECORD_TYPE)) name = Column(String(M_RECORD_NAME)) The column type is a discriminator. Now I want to define the child class AudioRecord from the Record class, but I don't how to setup the polymorphic mapper using the declarative syntax. I am looking for an equivalent for the following code (from SQLAlchemy documentation): mapper(Record, records, polymorphic_on=records.c.type, polymorphic_identity='record') mapper(AudioRecord, audiorecords, inherits=Record, polymorphic_identity='audio_record') How can I pass the polymorphic_on, polymorphic_identity and inherits keywords to the mapper created by the declarative extension? Thank you Jan A: I finally found the answer in the manual. http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#joined-table-inheritance
SQLAlchemy - Mapper configuration and declarative base
I am writing a multimedia archive database backend and I want to use joined table inheritance. I am using Python with SQLAlchemy with the declarative extension. The table holding the media record is as follows: _Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) storage_id = Column(String(M_STORAGE_ID), ForeignKey('storages.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) type = Column(String(M_RECORD_TYPE)) name = Column(String(M_RECORD_NAME)) The column type is a discriminator. Now I want to define the child class AudioRecord from the Record class, but I don't how to setup the polymorphic mapper using the declarative syntax. I am looking for an equivalent for the following code (from SQLAlchemy documentation): mapper(Record, records, polymorphic_on=records.c.type, polymorphic_identity='record') mapper(AudioRecord, audiorecords, inherits=Record, polymorphic_identity='audio_record') How can I pass the polymorphic_on, polymorphic_identity and inherits keywords to the mapper created by the declarative extension? Thank you Jan
[ "I finally found the answer in the manual.\nhttp://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#joined-table-inheritance\n" ]
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000792588_python_sqlalchemy.txt
Q: Parsing files with Python What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three? A: It depends on the grammar. You can use pyparsing instead of implementing your own parser. It is very easy to use. A: You should offer more information about your aims ... What kind of file What structure? Tab separated? XML - like? What kind of encoding? Whats the target structure? Do you need to reparse the file in a regular time period (like an interpreter)? A: how complex the syntax is? are you inventing a new one or not? for a complex language, consider bison bindings like lex + pybison. if you can decide what syntax to use, try YAML. A: It does not depend on your programming language (python) if your parser will have one, two, three or n passes. It depends on the grammar of the syntax you are trying to parse. If the syntax is complex enough I would recommend LEX/YACC combo as Francis said.
Parsing files with Python
What type of Python objects should I use to parse files with a specific syntax? Also what sort of loop should be followed to make it through the file. Should one pass be sufficient? Two, three?
[ "It depends on the grammar. You can use pyparsing instead of implementing your own parser. It is very easy to use. \n", "You should offer more information about your aims ...\n\nWhat kind of file\nWhat structure? Tab separated? XML - like?\nWhat kind of encoding?\nWhats the target structure?\nDo you need to reparse the file in a regular time period (like an interpreter)?\n\n", "how complex the syntax is? are you inventing a new one or not?\nfor a complex language, consider bison bindings like lex + pybison.\nif you can decide what syntax to use, try YAML.\n", "It does not depend on your programming language (python) if your parser will have one, two, three or n passes. It depends on the grammar of the syntax you are trying to parse.\nIf the syntax is complex enough I would recommend LEX/YACC combo as Francis said.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "object", "parsing", "python" ]
stackoverflow_0000808621_object_parsing_python.txt
Q: Python - Threading and a While True Loop I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached). Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 < time.clock(): if 15 < time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break A: Are your threads appending to self.output here, with your main task consuming them? If so, this is a tailor-made job for Queue.Queue. Your code should become something like: import Queue # Initialise queue as: queue = Queue.Queue() Finished = object() # Unique marker the producer will put in the queue when finished # Consumer: try: while True: next_item = self.queue.get(timeout=15) if next_item is Finished: break yield next_item except Queue.Empty: print "Timeout exceeded" Your producer threads add items to the queue with queue.put(item) [Edit] The original code has a race issue when checking self.done (for example multiple items may be appended to the queue before the flag is set, causing the code to bail out at the first one). Updated with a suggestion from ΤΖΩΤΖΙΟΥ - the producer thread should instead append a special token (Finished) to the queue to indicate it is complete. Note: If you have multiple producer threads, you'll need a more general approach to detecting when they're all finished. You could accomplish this with the same strategy - each thread a Finished marker and the consumer terminates when it sees num_threads markers. A: Use a semaphore; have the working thread release it when it's finished, and block your appending thread until the worker is finished with the semaphore. ie. in the worker, do something like self.done = threading.Semaphore() at the beginning of work, and self.done.release() when finished. In the code you noted above, instead of the busy loop, simply do self.done.acquire(); when the worker thread is finished, control will return. Edit: I'm afraid I don't address your needed timeout value, though; this issue describes the need for a semaphore timeout in the standard library. A: Use time.sleep(seconds) to create a brief pause after each iteration of the while loop to relinquish the cpu. You will have to set the time you sleep during each iteration based on how important it is that you catch the job quickly after it's complete. Example: time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 < time.clock(): if 15 < time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break time.sleep(0.01) # sleep for 10 milliseconds A: You have to use a synchronization primitive here. Look here: http://docs.python.org/library/threading.html. Event objects seem very simple and should solve your problem. You can also use a condition object or a semaphore. I don't post an example because I've never used Event objects, and the alternatives are probably less simple. Edit: I'm not really sure I understood your problem. If a thread can wait until some condition is statisfied, use synchronization. Otherwise the sleep() solution that someone posted will about taking too much CPU time. A: use mutex module or event/semaphore
Python - Threading and a While True Loop
I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached). Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. time.clock() while True: if len(self.output): yield self.output.pop(0) elif self.done or 15 < time.clock(): if 15 < time.clock(): yield "Maximum Execution Time Exceeded %s seconds" % time.clock() break
[ "Are your threads appending to self.output here, with your main task consuming them? If so, this is a tailor-made job for Queue.Queue. Your code should become something like:\nimport Queue\n\n# Initialise queue as:\nqueue = Queue.Queue()\nFinished = object() # Unique marker the producer will put in the queue when finished\n\n# Consumer:\ntry:\n while True:\n next_item = self.queue.get(timeout=15)\n if next_item is Finished: break\n yield next_item\n\nexcept Queue.Empty:\n print \"Timeout exceeded\"\n\nYour producer threads add items to the queue with queue.put(item)\n[Edit] The original code has a race issue when checking self.done (for example multiple items may be appended to the queue before the flag is set, causing the code to bail out at the first one). Updated with a suggestion from ΤΖΩΤΖΙΟΥ - the producer thread should instead append a special token (Finished) to the queue to indicate it is complete.\nNote: If you have multiple producer threads, you'll need a more general approach to detecting when they're all finished. You could accomplish this with the same strategy - each thread a Finished marker and the consumer terminates when it sees num_threads markers.\n", "Use a semaphore; have the working thread release it when it's finished, and block your appending thread until the worker is finished with the semaphore.\nie. in the worker, do something like self.done = threading.Semaphore() at the beginning of work, and self.done.release() when finished. In the code you noted above, instead of the busy loop, simply do self.done.acquire(); when the worker thread is finished, control will return.\nEdit: I'm afraid I don't address your needed timeout value, though; this issue describes the need for a semaphore timeout in the standard library.\n", "Use time.sleep(seconds) to create a brief pause after each iteration of the while loop to relinquish the cpu. You will have to set the time you sleep during each iteration based on how important it is that you catch the job quickly after it's complete.\nExample:\ntime.clock()\nwhile True:\n\n if len(self.output):\n yield self.output.pop(0)\n\n elif self.done or 15 < time.clock():\n if 15 < time.clock():\n yield \"Maximum Execution Time Exceeded %s seconds\" % time.clock()\n break\n\n time.sleep(0.01) # sleep for 10 milliseconds\n\n", "You have to use a synchronization primitive here. Look here: http://docs.python.org/library/threading.html.\nEvent objects seem very simple and should solve your problem. You can also use a condition object or a semaphore.\nI don't post an example because I've never used Event objects, and the alternatives are probably less simple.\n\nEdit: I'm not really sure I understood your problem. If a thread can wait until some condition is statisfied, use synchronization. Otherwise the sleep() solution that someone posted will about taking too much CPU time.\n", "use mutex module or event/semaphore\n" ]
[ 11, 1, 0, 0, 0 ]
[]
[]
[ "loops", "multithreading", "python" ]
stackoverflow_0000808746_loops_multithreading_python.txt
Q: Make python enter password when running a csh script I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: import commands commands.getoutput('server stop') A: Have a look at the pexpect module. It is designed to deal with interactive programs, which seems to be your case. Oh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D A: Use subprocess. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE.. from subprocess import Popen, PIPE proc = Popen(['server', 'stop'], stdin=PIPE) proc.communicate('password') You would do better do avoid the password and try a scheme like sudo and sudoers. Pexpect, mentioned elsewhere, is not part of the standard library. A: import pexpect child = pexpect.spawn('server stop') child.expect_exact('Password:') child.sendline('password') print "Stopping the servers..." index = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60) child.expect(pexpect.EOF) Did the trick! Pexpect rules! A: Add input= in proc.communicate() make it run, for guys who like to use standard lib. from subprocess import Popen, PIPE proc = Popen(['server', 'stop'], stdin=PIPE) proc.communicate(input='password') A: Should be able to pass it as a parameter. something like: commands.getoutput('server stop -p password') A: This seems to work better: import popen2 (stdout, stdin) = popen2.popen2('server stop') stdin.write("password") But it's not 100% yet. Even though "password" is the correct password I'm still getting su: Sorry back from the csh script when it's trying to su to root. A: To avoid having to answer the Password question in the python script I'm just going to run the script as root. This question is still unanswered but I guess I'll just do it this way for now.
Make python enter password when running a csh script
I'm writing a python script that executes a csh script in Solaris 10. The csh script prompts the user for the root password (which I know) but I'm not sure how to make the python script answer the prompt with the password. Is this possible? Here is what I'm using to execute the csh script: import commands commands.getoutput('server stop')
[ "Have a look at the pexpect module. It is designed to deal with interactive programs, which seems to be your case.\nOh, and remember that hard-encoding root's password in a shell or python script is potentially a security hole :D\n", "Use subprocess. Call Popen() to create your process and use communicate() to send it text. Sorry, forgot to include the PIPE..\nfrom subprocess import Popen, PIPE\n\nproc = Popen(['server', 'stop'], stdin=PIPE)\n\nproc.communicate('password')\n\nYou would do better do avoid the password and try a scheme like sudo and sudoers. Pexpect, mentioned elsewhere, is not part of the standard library.\n", "import pexpect\nchild = pexpect.spawn('server stop')\nchild.expect_exact('Password:')\n\nchild.sendline('password')\n\nprint \"Stopping the servers...\"\n\nindex = child.expect_exact(['Server processes successfully stopped.', 'Server is not running...'], 60)\nchild.expect(pexpect.EOF)\n\nDid the trick! Pexpect rules!\n", "Add input= in proc.communicate() make it run, for guys who like to use standard lib.\nfrom subprocess import Popen, PIPE\nproc = Popen(['server', 'stop'], stdin=PIPE)\nproc.communicate(input='password')\n\n", "Should be able to pass it as a parameter. something like:\ncommands.getoutput('server stop -p password')\n\n", "This seems to work better:\nimport popen2\n\n(stdout, stdin) = popen2.popen2('server stop')\n\nstdin.write(\"password\")\n\nBut it's not 100% yet. Even though \"password\" is the correct password I'm still getting su: Sorry back from the csh script when it's trying to su to root.\n", "To avoid having to answer the Password question in the python script I'm just going to run the script as root. This question is still unanswered but I guess I'll just do it this way for now.\n" ]
[ 8, 5, 1, 1, 0, 0, 0 ]
[]
[]
[ "csh", "passwords", "python", "root", "scripting" ]
stackoverflow_0000230845_csh_passwords_python_root_scripting.txt
Q: Python regex for finding contents of MediaWiki markup links If I have some xml containing things like the following mediawiki markup: " ...collected in the 12th century, of which [[Alexander the Great]] was the hero, and in which he was represented, somewhat like the British [[King Arthur|Arthur]]" what would be the appropriate arguments to something like: re.findall([[__?__]], article_entry) I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: [[Alexander of Paris|poet named Alexander]] A: Here is an example import re pattern = re.compile(r"\[\[([\w \|]+)\]\]") text = "blah blah [[Alexander of Paris|poet named Alexander]] bldfkas" results = pattern.findall(text) output = [] for link in results: output.append(link.split("|")[0]) # outputs ['Alexander of Paris'] Version 2, puts more into the regex, but as a result, changes the output: import re pattern = re.compile(r"\[\[([\w ]+)(\|[\w ]+)?\]\]") text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]" results = pattern.findall(text) # outputs [('a', '|b'), ('c', '|d'), ('efg', '')] print [link[0] for link in results] # outputs ['a', 'c', 'efg'] Version 3, if you only want the link without the title. pattern = re.compile(r"\[\[([\w ]+)(?:\|[\w ]+)?\]\]") text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]" results = pattern.findall(text) # outputs ['a', 'c', 'efg'] A: RegExp: \w+( \w+)+(?=]]) input [[Alexander of Paris|poet named Alexander]] output poet named Alexander input [[Alexander of Paris]] output Alexander of Paris A: import re pattern = re.compile(r"\[\[([\w ]+)(?:\||\]\])") text = "of which [[Alexander the Great]] was somewhat like [[King Arthur|Arthur]]" results = pattern.findall(text) print results Would give the output ["Alexander the Great", "King Arthur"] A: If you are trying to get all the links from a page, of course it is much easier to use the MediaWiki API if at all possible, e.g. http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=Stack_Overflow_(website). Note that both these methods miss links embedded in templates.
Python regex for finding contents of MediaWiki markup links
If I have some xml containing things like the following mediawiki markup: " ...collected in the 12th century, of which [[Alexander the Great]] was the hero, and in which he was represented, somewhat like the British [[King Arthur|Arthur]]" what would be the appropriate arguments to something like: re.findall([[__?__]], article_entry) I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: [[Alexander of Paris|poet named Alexander]]
[ "Here is an example\nimport re\n\npattern = re.compile(r\"\\[\\[([\\w \\|]+)\\]\\]\")\ntext = \"blah blah [[Alexander of Paris|poet named Alexander]] bldfkas\"\nresults = pattern.findall(text)\n\noutput = []\nfor link in results:\n output.append(link.split(\"|\")[0])\n\n# outputs ['Alexander of Paris']\n\nVersion 2, puts more into the regex, but as a result, changes the output:\nimport re\n\npattern = re.compile(r\"\\[\\[([\\w ]+)(\\|[\\w ]+)?\\]\\]\")\ntext = \"[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]\"\nresults = pattern.findall(text)\n\n# outputs [('a', '|b'), ('c', '|d'), ('efg', '')]\n\nprint [link[0] for link in results]\n\n# outputs ['a', 'c', 'efg']\n\nVersion 3, if you only want the link without the title.\npattern = re.compile(r\"\\[\\[([\\w ]+)(?:\\|[\\w ]+)?\\]\\]\")\ntext = \"[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]\"\nresults = pattern.findall(text)\n\n# outputs ['a', 'c', 'efg']\n\n", "RegExp: \\w+( \\w+)+(?=]])\ninput\n[[Alexander of Paris|poet named Alexander]]\noutput\npoet named Alexander\ninput\n[[Alexander of Paris]]\noutput\nAlexander of Paris\n", "import re\npattern = re.compile(r\"\\[\\[([\\w ]+)(?:\\||\\]\\])\")\ntext = \"of which [[Alexander the Great]] was somewhat like [[King Arthur|Arthur]]\"\nresults = pattern.findall(text)\nprint results\n\nWould give the output\n[\"Alexander the Great\", \"King Arthur\"]\n\n", "If you are trying to get all the links from a page, of course it is much easier to use the MediaWiki API if at all possible, e.g. http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=Stack_Overflow_(website).\nNote that both these methods miss links embedded in templates.\n" ]
[ 5, 1, 1, 1 ]
[]
[]
[ "mediawiki", "python", "regex" ]
stackoverflow_0000809837_mediawiki_python_regex.txt
Q: how to manually assign imagefield in Django I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file... A: See the django docs for django.core.files.File Where fd is an open file object: model_instance.image_field.save('filename.jpeg', fd.read(), True)
how to manually assign imagefield in Django
I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...
[ "See the django docs for django.core.files.File\nWhere fd is an open file object:\nmodel_instance.image_field.save('filename.jpeg', fd.read(), True)\n\n" ]
[ 20 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000811167_django_django_models_python.txt
Q: reading a stream made by urllib2 never recovers when connection got interrupted While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever. I thought that the read function will timeout and eventually raise an exception but this does not seam to be the case when the connection got interrupted during a read function call. Here is the code that will cause the problem: import urllib2 while True: try: stream = urllib2.urlopen('http://www.google.de/images/nav_logo4.png') while stream.read(): pass print "Done" except: print "Error" (If you try out the script you probably need to interrupt the connection several times before you will reach the state from which the script never recovers) I watched the script via Winpdb and made a screenshot of the state from which the script does never recover (even if the network got available again). Winpdb http://img10.imageshack.us/img10/6716/urllib2.jpg Is there a way to create a python script that will continue to work reliable even if the network connection got interrupted? (I would prefer to avoid doing this inside an extra thread.) A: Try something like: import socket socket.setdefaulttimeout(5.0) ... try: ... except socket.timeout: (it timed out, retry) A: Good question, I would be really interested in finding an answer. The only workaround I could think of is using the signal trick explained in python docs. In your case it will be more like: import signal import urllib2 def read(url): stream = urllib2.urlopen(url) return stream.read() def handler(signum, frame): raise IOError("The page is taking too long to read") # Set the signal handler and a 5-second alarm signal.signal(signal.SIGALRM, handler) signal.alarm(5) # This read() may hang indefinitely try: output = read('http://www.google.de/images/nav_logo4.png') except IOError: # try to read again or print an error pass signal.alarm(0) # Disable the alarm
reading a stream made by urllib2 never recovers when connection got interrupted
While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever. I thought that the read function will timeout and eventually raise an exception but this does not seam to be the case when the connection got interrupted during a read function call. Here is the code that will cause the problem: import urllib2 while True: try: stream = urllib2.urlopen('http://www.google.de/images/nav_logo4.png') while stream.read(): pass print "Done" except: print "Error" (If you try out the script you probably need to interrupt the connection several times before you will reach the state from which the script never recovers) I watched the script via Winpdb and made a screenshot of the state from which the script does never recover (even if the network got available again). Winpdb http://img10.imageshack.us/img10/6716/urllib2.jpg Is there a way to create a python script that will continue to work reliable even if the network connection got interrupted? (I would prefer to avoid doing this inside an extra thread.)
[ "Try something like:\nimport socket\nsocket.setdefaulttimeout(5.0)\n ...\ntry:\n ...\nexcept socket.timeout:\n (it timed out, retry)\n\n", "Good question, I would be really interested in finding an answer. The only workaround I could think of is using the signal trick explained in python docs.\nIn your case it will be more like:\nimport signal\nimport urllib2\n\ndef read(url):\n stream = urllib2.urlopen(url)\n return stream.read()\n\ndef handler(signum, frame):\n raise IOError(\"The page is taking too long to read\")\n\n# Set the signal handler and a 5-second alarm\nsignal.signal(signal.SIGALRM, handler)\nsignal.alarm(5)\n\n# This read() may hang indefinitely\ntry:\n output = read('http://www.google.de/images/nav_logo4.png')\nexcept IOError:\n # try to read again or print an error\n pass\n\nsignal.alarm(0) # Disable the alarm\n\n" ]
[ 7, 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0000811446_python_urllib2.txt
Q: Is it possible to write a great PHP app which uses Unicode? My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points. Is there a PHP tool out there that can help me get Unicode working well in PHP? Or should I take the opportunity to look into alternatives such as Python? A: PHP can handle unicode fine once you make sure to encode and decode on entry and exit. If you are storing in a database, ensure that the language encodings and charset mappings match up between the html pages, web server, your editor, and the database. If the whole application uses UTF-8 everywhere, decoding is not necessary. The only time you need to decode is when you are outputting data in another charset that isn't on the web. When outputting html, you can use htmlentities($var, ENT_QUOTES, 'UTF-8'); to get the correct output. The standard function will destroy the string in most cases. Same goes for mail functions too. http://developer.loftdigital.com/blog/php-utf-8-cheatsheet is a very good resource for working in UTF-8 A: One of the Major feature of PHP 6 will be tightly integrated with UNICODE support. Implementing UTF-8 in PHP 5. Since PHP strings are byte-oriented, the only practical encoding scheme for Unicode text is UTF-8. Tricks are [Got it from PHp Architect Magazine]: Present HTML pages in UTF-8 Convert PHP scripts to UTF-8 Convert the site content, back-end databases and the like to UTF-8 Ensure that no PHP functions corrupt the UTF-8 text Check out http://www.gravitonic.com/talks/ PHP UTF 8 Cheat Sheet A: PHP is mostly unaware of chrasets and treats strings as bytestreams. That's not much of a problem really, but you'll have to do a bit of work your self. The general rule of thumb is that you should use the same charset everywhere. If you use UTF-8 everywhere, then you're 99% there. Just make sure that you don't mix charsets, because then it gets really complicated. The only thing that won't work correct with UTF-8, is string manipulation, which needs to operate on a character level. Eg. strlen, substr etc. You should use UTF-8-aware versions in place of those. The multibyte-string extension gives you just that. For a checklist of places where you need to make sure the charset is set correct, look at: http://developer.loftdigital.com/blog/php-utf-8-cheatsheet For more information, look at: http://www.phpwact.org/php/i18n/utf-8
Is it possible to write a great PHP app which uses Unicode?
My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points. Is there a PHP tool out there that can help me get Unicode working well in PHP? Or should I take the opportunity to look into alternatives such as Python?
[ "PHP can handle unicode fine once you make sure to encode and decode on entry and exit. If you are storing in a database, ensure that the language encodings and charset mappings match up between the html pages, web server, your editor, and the database.\nIf the whole application uses UTF-8 everywhere, decoding is not necessary. The only time you need to decode is when you are outputting data in another charset that isn't on the web. When outputting html, you can use \nhtmlentities($var, ENT_QUOTES, 'UTF-8');\n\nto get the correct output. The standard function will destroy the string in most cases. Same goes for mail functions too.\nhttp://developer.loftdigital.com/blog/php-utf-8-cheatsheet is a very good resource for working in UTF-8\n", "One of the Major feature of PHP 6 will be tightly integrated with UNICODE support.\nImplementing UTF-8 in PHP 5.\nSince PHP strings are byte-oriented, the only practical encoding scheme for Unicode text is UTF-8. Tricks are [Got it from PHp Architect Magazine]:\n\nPresent HTML pages in UTF-8\nConvert PHP scripts to UTF-8\nConvert the site content, back-end databases and the like to UTF-8\nEnsure that no PHP functions corrupt the UTF-8 text\n\n\nCheck out http://www.gravitonic.com/talks/ PHP UTF 8 Cheat Sheet\n\n", "PHP is mostly unaware of chrasets and treats strings as bytestreams. That's not much of a problem really, but you'll have to do a bit of work your self.\nThe general rule of thumb is that you should use the same charset everywhere. If you use UTF-8 everywhere, then you're 99% there. Just make sure that you don't mix charsets, because then it gets really complicated. The only thing that won't work correct with UTF-8, is string manipulation, which needs to operate on a character level. Eg. strlen, substr etc. You should use UTF-8-aware versions in place of those. The multibyte-string extension gives you just that.\nFor a checklist of places where you need to make sure the charset is set correct, look at:\nhttp://developer.loftdigital.com/blog/php-utf-8-cheatsheet\nFor more information, look at:\nhttp://www.phpwact.org/php/i18n/utf-8\n" ]
[ 4, 1, 0 ]
[]
[]
[ "php", "python", "unicode", "web_applications" ]
stackoverflow_0000811306_php_python_unicode_web_applications.txt
Q: string encodings in python In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example, time.strftime( "%b" ) will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings? A: Strings don't store any encoding information, you just have to specify one when you convert to/from unicode or print to an output device : import locale lang, encoding = locale.getdefaultlocale() mystring = u"blabla" print mystring.encode(encoding) UTF-8 is not unicode, it's an encoding of unicode into single byte strings. The best practice is to work with unicode everywhere on the python side, store your strings with an unicode reversible encoding such as UTF-8, and convert to fancy locales only for user output. A: charset encoding detection is very complex. however, what's your real purpose for this? if you just want to value to be in unicode, simply write unicode(time.strftime("%b")) and it should work for all the cases you've mentioned above: mac os: unicode(unicode) -> unicode win/eng: unicode(ascii) -> unicode win/noneng: unicode(some_cp) -> will be converted by local cp -> unicode A: If you have a reasonably long string in an unknown encoding, you can try to guess the encoding, e.g. with the Universal Encoding Detector at https://github.com/dcramer/chardet -- not foolproof of course, but sometimes it guesses right;-). But that won't help much with very short strings.
string encodings in python
In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example, time.strftime( "%b" ) will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings?
[ "Strings don't store any encoding information, you just have to specify one when you convert to/from unicode or print to an output device :\nimport locale\nlang, encoding = locale.getdefaultlocale()\nmystring = u\"blabla\"\nprint mystring.encode(encoding)\n\nUTF-8 is not unicode, it's an encoding of unicode into single byte strings.\nThe best practice is to work with unicode everywhere on the python side, store your strings with an unicode reversible encoding such as UTF-8, and convert to fancy locales only for user output.\n", "charset encoding detection is very complex.\nhowever, what's your real purpose for this?\nif you just want to value to be in unicode, simply write\nunicode(time.strftime(\"%b\"))\n\nand it should work for all the cases you've mentioned above:\n\nmac os: unicode(unicode) -> unicode\nwin/eng: unicode(ascii) -> unicode\nwin/noneng: unicode(some_cp) -> will be converted by local cp -> unicode\n\n", "If you have a reasonably long string in an unknown encoding, you can try to guess the encoding, e.g. with the Universal Encoding Detector at https://github.com/dcramer/chardet -- not foolproof of course, but sometimes it guesses right;-). But that won't help much with very short strings.\n" ]
[ 5, 1, 1 ]
[]
[]
[ "codepages", "python", "unicode" ]
stackoverflow_0000810794_codepages_python_unicode.txt
Q: Python Timeout script to kill thread active for more than X seconds I have been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread. The only decent example I have found is Timeout on a function call and that one is not without its flaws.. Anyone know of a better way to do this? A: See my answer to python: how to send packets in multi thread and then the thread kill itself - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want. There is also similar Python recipe at activestate. A: I know this might not be what you want, but have you considered the signal approach? Timeout on a function call http://docs.python.org/library/signal.html#example You can set an alarm signal at the beginning of the thread execution, and then stop the thread in the signal handler.
Python Timeout script to kill thread active for more than X seconds
I have been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread. The only decent example I have found is Timeout on a function call and that one is not without its flaws.. Anyone know of a better way to do this?
[ "See my answer to python: how to send packets in multi thread and then the thread kill itself - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want.\nThere is also similar Python recipe at activestate.\n", "I know this might not be what you want, but have you considered the signal approach?\nTimeout on a function call\nhttp://docs.python.org/library/signal.html#example\nYou can set an alarm signal at the beginning of the thread execution, and then stop the thread in the signal handler.\n" ]
[ 2, 0 ]
[]
[]
[ "multithreading", "python", "timeout" ]
stackoverflow_0000811692_multithreading_python_timeout.txt
Q: What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach virtualenv uses. For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004. We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again. We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, Supervisor doesn't even work correctly with Python 2.6. Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules. Many Thanks! -Michael A: I wouldn't abandon 2.6 just because of deprecation warnings; those will disappear over time. (You can use the -W ignore option to the Python interpreter to prevent them from being printed out, at least) But if modules you need to use actually don't work with Python 2.6, that would be a legitimate reason to stay with 2.5. Python 2.5 is in wide use now and probably will be for a long time to come (consider how long 2.3 has lasted!), so even if you go with 2.5, you won't be forced to upgrade for a while. I use Python 2.5 for all my development work, but only because it's the version that happens to be available in Gentoo (Linux)'s package repository. When the Gentoo maintainers declare Python 2.6 "stable"*, I'll switch to that. Of course, this reasoning wouldn't necessarily apply to you. * Python 2.6 actually is stable, the reason it's not declared as such in Gentoo is that Gentoo relies on other programs which themselves depend on Python and are not yet upgraded to work with 2.6. Again, this reasoning probably doesn't apply to you. A: My company is standardized in 2.5. Like you we can't make the switch to 3.0 for a million reasons, but I very much wish we could move up to 2.6. Doing coding day to day I'll be looking through the documentation and I'll find exactly the module or function that I want, but then it'll have the little annotation: New in Version 2.6 I would say go with the newest version, and if you have depreciation warnings pop up (there will probably be very few) then just go in a find a better way to do it. Overall your code will be better with 2.6. A: To me the most important to stick with python 2.5+ is because it officially supports ctypes, which changed many plugin systems. Although you can find ctypes to work with 2.3/2.4, they are not officially bundled. So my suggestion would be 2.5. A: We're sticking with 2.5.2 for now. Our tech stack centers on Django (but we have a dozen other bits and bobs.) So we stay close to what they do. We had to go back to docutils to 0.4 so it would work with epydoc 3.0.1. So far, this hasn't been a big issue, but it may -- at some point -- cause us to rethink our use of epydoc. The 2.6 upgrade is part of our development plan. We have budget, but not fixed schedule right now. The 3.0 upgrade, similarly, is something I remind folks of. We have to budget for it. We won't do it this year unless Django leaps to 3.0. We might do it next year. A: I think the best solution is to give up the hope on total uniformity, although having a common environment is something to strive for. You will always will be confronted with version problems, for example when upgrading to the next best interpreter version. So instead of dealing with it on a per issue base you could solve this problem by taking a good look on your release management. Instead of releasing source, go for platform depending binaries (besides the source distribution). So what you do is that you define a number of supported CPU's, for example: x86-32, x86-64, sparc Then which operating systems: Linux, Windows, Solaris, FreeBSD For each OS you support a number of their major versions. Next step is that you provide binaries for all of them. Yes indeed this will require quite some infrastructure investment and setting up of automatic building from your repositories (you do have them?). The advantages is that your users only have 'one' thing to install and you can easily switch versions or even mixing versions. Actually you can even use different programming languages with this approach without affecting your release management too much.
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)?
In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach virtualenv uses. For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004. We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again. We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, Supervisor doesn't even work correctly with Python 2.6. Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules. Many Thanks! -Michael
[ "I wouldn't abandon 2.6 just because of deprecation warnings; those will disappear over time. (You can use the -W ignore option to the Python interpreter to prevent them from being printed out, at least) But if modules you need to use actually don't work with Python 2.6, that would be a legitimate reason to stay with 2.5. Python 2.5 is in wide use now and probably will be for a long time to come (consider how long 2.3 has lasted!), so even if you go with 2.5, you won't be forced to upgrade for a while.\nI use Python 2.5 for all my development work, but only because it's the version that happens to be available in Gentoo (Linux)'s package repository. When the Gentoo maintainers declare Python 2.6 \"stable\"*, I'll switch to that. Of course, this reasoning wouldn't necessarily apply to you.\n* Python 2.6 actually is stable, the reason it's not declared as such in Gentoo is that Gentoo relies on other programs which themselves depend on Python and are not yet upgraded to work with 2.6. Again, this reasoning probably doesn't apply to you.\n", "My company is standardized in 2.5. Like you we can't make the switch to 3.0 for a million reasons, but I very much wish we could move up to 2.6. \nDoing coding day to day I'll be looking through the documentation and I'll find exactly the module or function that I want, but then it'll have the little annotation: New in Version 2.6\nI would say go with the newest version, and if you have depreciation warnings pop up (there will probably be very few) then just go in a find a better way to do it. Overall your code will be better with 2.6.\n", "To me the most important to stick with python 2.5+ is because it officially supports ctypes, which changed many plugin systems.\nAlthough you can find ctypes to work with 2.3/2.4, they are not officially bundled.\nSo my suggestion would be 2.5.\n", "We're sticking with 2.5.2 for now. Our tech stack centers on Django (but we have a dozen other bits and bobs.) So we stay close to what they do.\nWe had to go back to docutils to 0.4 so it would work with epydoc 3.0.1. So far, this hasn't been a big issue, but it may -- at some point -- cause us to rethink our use of epydoc.\nThe 2.6 upgrade is part of our development plan. We have budget, but not fixed schedule right now.\nThe 3.0 upgrade, similarly, is something I remind folks of. We have to budget for it. We won't do it this year unless Django leaps to 3.0. We might do it next year.\n", "I think the best solution is to give up the hope on total uniformity, although having a common environment is something to strive for. You will always will be confronted with version problems, for example when upgrading to the next best interpreter version.\nSo instead of dealing with it on a per issue base you could solve this problem by taking a good look on your release management.\nInstead of releasing source, go for platform depending binaries (besides the source distribution).\nSo what you do is that you define a number of supported CPU's, for example:\nx86-32, x86-64, sparc\nThen which operating systems:\nLinux, Windows, Solaris, FreeBSD\nFor each OS you support a number of their major versions.\nNext step is that you provide binaries for all of them.\nYes indeed this will require quite some infrastructure investment and setting up of automatic building from your repositories (you do have them?).\nThe advantages is that your users only have 'one' thing to install and you can easily switch versions or even mixing versions. Actually you can even use different programming languages with this approach without affecting your release management too much.\n" ]
[ 5, 4, 2, 2, 1 ]
[]
[]
[ "production", "python", "standards", "supervisord" ]
stackoverflow_0000812085_production_python_standards_supervisord.txt
Q: python- is beautifulsoup misreporting my html? I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1. I'm trying to scrape http://utahcritseries.com/RawResults.aspx, using: from BeautifulSoup import BeautifulSoup import urllib2 base_url = "http://www.utahcritseries.com/RawResults.aspx" data=urllib2.urlopen(base_url) soup=BeautifulSoup(data) i = 0 table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents') #table=soup.table print "begin table" for row in table.findAll('tr')[1:10]: i=i + 1 col = row.findAll('td') date = col[0].string event = col[1].a.string confirmed = col[2].string print '%s - %s' % (date, event) print "end table" print "%s rows processed" % i On my windows machine,I get the correct result, which is a list of dates and event names. On my mac, I don't. instead, I get 3/2/2002 - Rocky Mtn Raceway Criterium None - Rocky Mtn Raceway Criterium 3/23/2002 - Rocky Mtn Raceway Criterium None - Rocky Mtn Raceway Criterium 4/2/2002 - Rocky Mtn Raceway Criterium None - Saltair Time Trial 4/9/2002 - Rocky Mtn Raceway Criterium None - DMV Criterium 4/16/2002 - Rocky Mtn Raceway Criterium What I'm noticing is that when I print row on my windows machine, the tr data looks exactly the same as the source html. Note the style tag on the second table row. Here's the first two rows: <tr> <td> 3/2/2002 </td> <td> <a href="Event.aspx?id=226"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=226"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> <tr style="color:#333333;background-color:#EFEFEF;"> <td> 3/16/2002 </td> <td> <a href="Event.aspx?id=227"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=227"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> On my mac when I print the first two rows, the style information is removed from the tr tag and it's moved into each td field. I don't understand why this is happening. I'm getting None for every other date value, because BeautifulSoup is putting a font tag around every other date. Here's the mac's output: <tr> <td> 3/2/2002 </td> <td> <a href="Event.aspx?id=226"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=226"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> <tr bgcolor="#EFEFEF"> <td> <font color="#333333"> 3/16/2002 </font> </td> <td> <font color="#333333"> <a href="Event.aspx?id=227"> Rocky Mtn Raceway Criterium </a> </font> </td> <td> <font color="#333333"> Confirmed </font> </td> <td> <font color="#333333"> <a href="Event.aspx?id=227"> Points </a> </font> </td> <td> <font color="#333333"> <a disabled="disabled"> Results </a> </font> </td> </tr> My script is displaying the correct result under windows-what do I need to do in order to get my Mac to work correctly? A: There are documented problems with version 3.1 of BeautifulSoup. You might want to double check that is the version you in fact are using, and if so downgrade. A: I suspect the problem is in the urlib2 request, not BeautifulSoup: It might help if you show us the same section of the raw data as returned by this command on both machines: urllib2.urlopen(base_url) This page looks like it might help: http://bytes.com/groups/python/635923-building-browser-like-get-request The simplest solution is probably just to detect which environment the script is running in and change the parsing logic accordingly. >>> import os >>> os.uname() ('Darwin', 'skom.local', '9.6.0', 'Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386', 'i386') Or get microsoft to use web standards :) Also, didn't you use mechanize to fetch the pages? If so, the problem may be there.
python- is beautifulsoup misreporting my html?
I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1. I'm trying to scrape http://utahcritseries.com/RawResults.aspx, using: from BeautifulSoup import BeautifulSoup import urllib2 base_url = "http://www.utahcritseries.com/RawResults.aspx" data=urllib2.urlopen(base_url) soup=BeautifulSoup(data) i = 0 table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents') #table=soup.table print "begin table" for row in table.findAll('tr')[1:10]: i=i + 1 col = row.findAll('td') date = col[0].string event = col[1].a.string confirmed = col[2].string print '%s - %s' % (date, event) print "end table" print "%s rows processed" % i On my windows machine,I get the correct result, which is a list of dates and event names. On my mac, I don't. instead, I get 3/2/2002 - Rocky Mtn Raceway Criterium None - Rocky Mtn Raceway Criterium 3/23/2002 - Rocky Mtn Raceway Criterium None - Rocky Mtn Raceway Criterium 4/2/2002 - Rocky Mtn Raceway Criterium None - Saltair Time Trial 4/9/2002 - Rocky Mtn Raceway Criterium None - DMV Criterium 4/16/2002 - Rocky Mtn Raceway Criterium What I'm noticing is that when I print row on my windows machine, the tr data looks exactly the same as the source html. Note the style tag on the second table row. Here's the first two rows: <tr> <td> 3/2/2002 </td> <td> <a href="Event.aspx?id=226"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=226"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> <tr style="color:#333333;background-color:#EFEFEF;"> <td> 3/16/2002 </td> <td> <a href="Event.aspx?id=227"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=227"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> On my mac when I print the first two rows, the style information is removed from the tr tag and it's moved into each td field. I don't understand why this is happening. I'm getting None for every other date value, because BeautifulSoup is putting a font tag around every other date. Here's the mac's output: <tr> <td> 3/2/2002 </td> <td> <a href="Event.aspx?id=226"> Rocky Mtn Raceway Criterium </a> </td> <td> Confirmed </td> <td> <a href="Event.aspx?id=226"> Points </a> </td> <td> <a disabled="disabled"> Results </a> </td> </tr> <tr bgcolor="#EFEFEF"> <td> <font color="#333333"> 3/16/2002 </font> </td> <td> <font color="#333333"> <a href="Event.aspx?id=227"> Rocky Mtn Raceway Criterium </a> </font> </td> <td> <font color="#333333"> Confirmed </font> </td> <td> <font color="#333333"> <a href="Event.aspx?id=227"> Points </a> </font> </td> <td> <font color="#333333"> <a disabled="disabled"> Results </a> </font> </td> </tr> My script is displaying the correct result under windows-what do I need to do in order to get my Mac to work correctly?
[ "There are documented problems with version 3.1 of BeautifulSoup.\nYou might want to double check that is the version you in fact are using, and if so downgrade.\n", "I suspect the problem is in the urlib2 request, not BeautifulSoup:\nIt might help if you show us the same section of the raw data as returned by this command on both machines:\nurllib2.urlopen(base_url)\n\nThis page looks like it might help:\nhttp://bytes.com/groups/python/635923-building-browser-like-get-request\nThe simplest solution is probably just to detect which environment the script is running in and change the parsing logic accordingly. \n>>> import os\n>>> os.uname() \n('Darwin', 'skom.local', '9.6.0', 'Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386', 'i386')\n\nOr get microsoft to use web standards :)\nAlso, didn't you use mechanize to fetch the pages? If so, the problem may be there. \n" ]
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "configuration", "macos", "python", "screen_scraping" ]
stackoverflow_0000810173_beautifulsoup_configuration_macos_python_screen_scraping.txt
Q: Python decorating functions before call I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible? A: With: decorator(original_function)() Without: original_function() A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some documentation might help clarify things. A: def original_function(): pass decorated_function= decorator(original_function) if use_decorated: decorated_function() else: original_function() Decorate only once, and afterwards choose which version to call. A: Here is the recipe I came up with for the problem. I also needed to keep the signatures the same so I used the decorator module but you could re-jig to avoid that. Basically, the trick was to add an attribute to the function. The 'original' function is unbound so you need to pass in a 'self' as the first parameter so I added some extra code to check for that too. # http://www.phyast.pitt.edu/~micheles/python/decorator-2.0.1.zip from decorator import decorator, update_wrapper class mustbe : pass def wrapper ( interface_ ) : print "inside hhh" def call ( func, self, *args, **kwargs ) : print "decorated" print "calling %s.%s with args %s, %s" % (self, func.__name__, args, kwargs) return interface_ ( self, *args, **kwargs ) def original ( instance , *args, **kwargs ) : if not isinstance ( instance, mustbe ) : raise TypeError, "Only use this decorator on children of mustbe" return interface_ ( instance, *args, **kwargs ) call = decorator ( call, interface_ ) call.original = update_wrapper ( original, call ) return call class CCC ( mustbe ): var = "class var" @wrapper def foo ( self, param ) : """foo""" print self.var, param class SSS ( CCC ) : @wrapper ( hidden_=True ) def bar ( self, a, b, c ) : print a, b, c if __name__ == "__main__" : from inspect import getargspec print ">>> i=CCC()" i=CCC() print ">>> i.var = 'parrot'" i.var = 'parrot' print ">>> i.foo.__doc__" print i.foo.__doc__ print ">>> getargspec(i.foo)" print getargspec(i.foo) print ">>> i.foo(99)" i.foo(99) print ">>> i.foo.original.__doc__" print i.foo.original.__doc__ print ">>> getargspec(i.foo.original)" print getargspec(i.foo.original) print ">>> i.foo.original(i,42)" i.foo.original(i,42) print ">>> j=SSS()" j=SSS() print ">>> j.bar(1,2,3)" j.bar(1,2,3)
Python decorating functions before call
I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?
[ "With:\ndecorator(original_function)()\n\nWithout:\noriginal_function()\n\nA decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some documentation might help clarify things.\n", "def original_function():\n pass\n\ndecorated_function= decorator(original_function)\n\nif use_decorated:\n decorated_function()\nelse:\n original_function()\n\nDecorate only once, and afterwards choose which version to call.\n", "Here is the recipe I came up with for the problem. I also needed to keep the signatures the same so I used the decorator module but you could re-jig to avoid that. Basically, the trick was to add an attribute to the function. The 'original' function is unbound so you need to pass in a 'self' as the first parameter so I added some extra code to check for that too.\n# http://www.phyast.pitt.edu/~micheles/python/decorator-2.0.1.zip\nfrom decorator import decorator, update_wrapper\n\nclass mustbe : pass\n\ndef wrapper ( interface_ ) :\n print \"inside hhh\"\n def call ( func, self, *args, **kwargs ) :\n print \"decorated\"\n print \"calling %s.%s with args %s, %s\" % (self, func.__name__, args, kwargs)\n return interface_ ( self, *args, **kwargs )\n def original ( instance , *args, **kwargs ) :\n if not isinstance ( instance, mustbe ) :\n raise TypeError, \"Only use this decorator on children of mustbe\"\n return interface_ ( instance, *args, **kwargs )\n call = decorator ( call, interface_ )\n call.original = update_wrapper ( original, call )\n return call\n\nclass CCC ( mustbe ):\n var = \"class var\"\n @wrapper\n def foo ( self, param ) :\n \"\"\"foo\"\"\"\n print self.var, param\n\nclass SSS ( CCC ) :\n @wrapper ( hidden_=True )\n def bar ( self, a, b, c ) :\n print a, b, c\n\nif __name__ == \"__main__\" :\n from inspect import getargspec\n\n print \">>> i=CCC()\"\n i=CCC()\n\n print \">>> i.var = 'parrot'\"\n i.var = 'parrot'\n\n print \">>> i.foo.__doc__\"\n print i.foo.__doc__\n\n print \">>> getargspec(i.foo)\"\n print getargspec(i.foo)\n\n print \">>> i.foo(99)\"\n i.foo(99)\n\n print \">>> i.foo.original.__doc__\"\n print i.foo.original.__doc__\n\n print \">>> getargspec(i.foo.original)\"\n print getargspec(i.foo.original)\n\n print \">>> i.foo.original(i,42)\"\n i.foo.original(i,42)\n\n print \">>> j=SSS()\"\n j=SSS()\n\n print \">>> j.bar(1,2,3)\"\n j.bar(1,2,3)\n\n" ]
[ 26, 2, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000282393_decorator_python.txt
Q: Thread Finished Event in Python I have a PyQt program, in this program I start a new thread for drawing a complicated image. I want to know when the thread has finished so I can print the image on the form. The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread. I could do it using one thread but the program halts. I used to do it in C# using a BackgroundWorker which had an event for finishing. Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit? A: In the samples with PyQt-Py2.6-gpl-4.4.4-2.exe, there's the Mandelbrot app. In my install, the source is in C:\Python26\Lib\site-packages\PyQt4\examples\threads\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. Looks like what you want. A: I had a similar issue with one of my projects, and used signals to tell my main GUI thread when to display results from the worker and update a progress bar. Note that there are several examples to connect objects and signals in the PyQt reference guide. Not all of which apply to python (took me a while to realize this). Here are the examples you want to look at for connecting a python signal to a python function. QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction) a.emit(QtCore.SIGNAL("pySig"), "Hello", "World") Also, don't forget to add __pyqtSignals__ = ( "PySig", ) to your worker class. Here's a stripped down version of what I did: class MyGui(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.worker = None def makeWorker(self): #create new thread self.worker = Worker(work_to_do) #connect thread to GUI function QtCore.QObject.connect(self.worker, QtCore.SIGNAL('progressUpdated'), self.updateWorkerProgress) QtCore.QObject.connect(self.worker, QtCore.SIGNAL('resultsReady'), self.updateResults) #start thread self.worker.start() def updateResults(self): results = self.worker.results #display results in the GUI def updateWorkerProgress(self, msg) progress = self.worker.progress #update progress bar and display msg in status bar class Worker(QtCore.QThread): __pyqtSignals__ = ( "resultsReady", "progressUpdated" ) def __init__(self, work_queue): self.progress = 0 self.results = [] self.work_queue = work_queue QtCore.QThread.__init__(self, None) def run(self): #do whatever work num_work_items = len(self.work_queue) for i, work_item in enumerate(self.work_queue): new_progress = int((float(i)/num_work_items)*100) #emit signal only if progress has changed if self.progress != new_progress: self.progress = new_progress self.emit(QtCore.SIGNAL("progressUpdated"), 'Working...') #process work item and update results result = processWorkItem(work_item) self.results.append(result) self.emit(QtCore.SIGNAL("resultsReady")) A: I believe that your drawing thread can send an event to the main thread using QApplication.postEvent. You just need to pick some object as the receiver of the event. More info A: Expanding on Jeff's answer: the Qt documentation on thread support states that it's possible to make event handlers (slots in Qt parlance) execute in the thread that "owns" an object. So in your case, you'd define a slot printImage(QImage) on the form, and a doneDrawing(QImage) signal on whatever is creating the image, and just connect them using a queued or auto connection.
Thread Finished Event in Python
I have a PyQt program, in this program I start a new thread for drawing a complicated image. I want to know when the thread has finished so I can print the image on the form. The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread. I could do it using one thread but the program halts. I used to do it in C# using a BackgroundWorker which had an event for finishing. Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?
[ "In the samples with PyQt-Py2.6-gpl-4.4.4-2.exe, there's the Mandelbrot app. In my install, the source is in C:\\Python26\\Lib\\site-packages\\PyQt4\\examples\\threads\\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. Looks like what you want.\n", "I had a similar issue with one of my projects, and used signals to tell my main GUI thread when to display results from the worker and update a progress bar.\nNote that there are several examples to connect objects and signals in the PyQt reference guide. Not all of which apply to python (took me a while to realize this).\nHere are the examples you want to look at for connecting a python signal to a python function.\nQtCore.QObject.connect(a, QtCore.SIGNAL(\"PySig\"), pyFunction)\na.emit(QtCore.SIGNAL(\"pySig\"), \"Hello\", \"World\")\n\nAlso, don't forget to add __pyqtSignals__ = ( \"PySig\", ) to your worker class.\nHere's a stripped down version of what I did:\nclass MyGui(QtGui.QMainWindow):\n\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n self.worker = None\n\n def makeWorker(self):\n #create new thread\n self.worker = Worker(work_to_do)\n #connect thread to GUI function\n QtCore.QObject.connect(self.worker, QtCore.SIGNAL('progressUpdated'), self.updateWorkerProgress)\n QtCore.QObject.connect(self.worker, QtCore.SIGNAL('resultsReady'), self.updateResults)\n #start thread\n self.worker.start()\n\n def updateResults(self):\n results = self.worker.results\n #display results in the GUI\n\n def updateWorkerProgress(self, msg)\n progress = self.worker.progress\n #update progress bar and display msg in status bar\n\n\nclass Worker(QtCore.QThread):\n\n __pyqtSignals__ = ( \"resultsReady\", \n \"progressUpdated\" )\n\n def __init__(self, work_queue):\n self.progress = 0 \n self.results = []\n self.work_queue = work_queue\n QtCore.QThread.__init__(self, None)\n\n def run(self):\n #do whatever work\n num_work_items = len(self.work_queue)\n for i, work_item in enumerate(self.work_queue):\n new_progress = int((float(i)/num_work_items)*100)\n #emit signal only if progress has changed\n if self.progress != new_progress:\n self.progress = new_progress\n self.emit(QtCore.SIGNAL(\"progressUpdated\"), 'Working...')\n #process work item and update results\n result = processWorkItem(work_item)\n self.results.append(result)\n self.emit(QtCore.SIGNAL(\"resultsReady\"))\n\n", "I believe that your drawing thread can send an event to the main thread using QApplication.postEvent. You just need to pick some object as the receiver of the event. More info\n", "Expanding on Jeff's answer: the Qt documentation on thread support states that it's possible to make event handlers (slots in Qt parlance) execute in the thread that \"owns\" an object.\nSo in your case, you'd define a slot printImage(QImage) on the form, and a doneDrawing(QImage) signal on whatever is creating the image, and just connect them using a queued or auto connection.\n" ]
[ 3, 2, 0, 0 ]
[]
[]
[ "delegates", "multithreading", "python" ]
stackoverflow_0000812870_delegates_multithreading_python.txt
Q: Ruby String Translation I want to find the successor of each element in my encoded string. For example K->M A->C etc. string.each_char do |ch| dummy_string<< ch.succ.succ end However this method translates y->aa. Is there a method in Ruby that is like maketrans() in Python? A: You seem to be looking for String#tr. Use like this: some_string.tr('a-zA-Z', 'c-zabC-ZAB') A: def successor(s) s.tr('a-zA-Z','c-zabC-ZAB') end successor("Chris Doggett") #"Ejtku Fqiigvv" A: I don't know of one offhand, but I think the Ruby way would probably involve passing a block to a regexp function. Here's a dumb one that only works for upper-case letters: "ABCYZ".gsub(/\w/) { |a| a=="Z" ? "A" : a.succ } => "BCDZA" Edit: meh, never mind, listen to Pesto, he sounds smart.
Ruby String Translation
I want to find the successor of each element in my encoded string. For example K->M A->C etc. string.each_char do |ch| dummy_string<< ch.succ.succ end However this method translates y->aa. Is there a method in Ruby that is like maketrans() in Python?
[ "You seem to be looking for String#tr. Use like this: some_string.tr('a-zA-Z', 'c-zabC-ZAB')\n", "def successor(s)\n s.tr('a-zA-Z','c-zabC-ZAB')\nend\n\nsuccessor(\"Chris Doggett\") #\"Ejtku Fqiigvv\"\n\n", "I don't know of one offhand, but I think the Ruby way would probably involve passing a block to a regexp function. Here's a dumb one that only works for upper-case letters:\n\"ABCYZ\".gsub(/\\w/) { |a| a==\"Z\" ? \"A\" : a.succ }\n=> \"BCDZA\"\n\nEdit: meh, never mind, listen to Pesto, he sounds smart.\n" ]
[ 8, 1, 0 ]
[]
[]
[ "python", "ruby", "string" ]
stackoverflow_0000813147_python_ruby_string.txt
Q: Why does python logging package not support printing variable length args? When I first learned Python, I got used to doing this: print "text", lineNumber, "some dictionary", my_dict When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this: def error(*args): print ERR_PREFIX, for _x in args: print _x, print "\r\n", error("text", lineNumber, "some dictionary", my_dict) Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this: error("text %d some dictionary %s" % (lineNumber, my_dict)) Or, I could do something really silly like this: error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict)))) The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier? As a follow-up question, can you think of a way to override the Logger class to perform this? A: I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect. That out of the way, the following code will make the logging module behave as you desire. import logging import types class ExtendedLogRecord(logging.LogRecord): def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ if not hasattr(types, "UnicodeType"): #if no unicode support... msg = str(self.msg) else: try: msg = str(self.msg) except UnicodeError: msg = self.msg #Defer encoding till later if self.args: msg +=' '+' '.join(map(str,self.args)) return msg #Patch the logging default logging class logging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args) some_dict={'foo':14,'bar':15} logging.error('text',15,'some dictionary',some_dict) Output: ERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15} A: Patching the logging package (as one answer recommended) is actually a bad idea, because it means that other code (that you didn't write, e.g. stuff in the standard library) that calls logging.error() would no longer work correctly. Instead, you can change your existing error() function to call logging.error() instead or print: def error(*args): logging.error('%s', ' '.join(map(str, args))) (If there might be unicode objects you'd have to be a bit more careful, but you get the idea.) A: Your claim about logging is not completely true. log= logging.getLogger( "some.logger" ) log.info( "%s %d", "test", value ) log.error("text %d some dictionary %s", lineNumber, my_dict) You don't need to explicitly use the string formatting operator, % Edit You can leverage your original "error" function. def error( *args ): log.error( " ".join( map( str, args ) ) ) Which will probably make the transition less complex. You can also do this. class MyErrorMessageHandler( object ): def __init__( self, logger ): self.log= logger def __call__( self, *args ): self.log.error( " ".join( map( str, args ) ) ) error= MyErrorMessageHandler( logging.getLogger("some.name") ) Which might be palatable, also. A: Well, printing and logging are two very different things. It stands to reason that as such their usages could potentially be quite different as well. A: It's relatively easy to add a method to a class dynamically. Why not just add your method to Logging.
Why does python logging package not support printing variable length args?
When I first learned Python, I got used to doing this: print "text", lineNumber, "some dictionary", my_dict When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this: def error(*args): print ERR_PREFIX, for _x in args: print _x, print "\r\n", error("text", lineNumber, "some dictionary", my_dict) Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this: error("text %d some dictionary %s" % (lineNumber, my_dict)) Or, I could do something really silly like this: error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict)))) The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier? As a follow-up question, can you think of a way to override the Logger class to perform this?
[ "I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect. \nThat out of the way, the following code will make the logging module behave as you desire.\nimport logging\nimport types\n\nclass ExtendedLogRecord(logging.LogRecord):\n\n def getMessage(self):\n \"\"\"\n Return the message for this LogRecord.\n\n Return the message for this LogRecord after merging any user-supplied\n arguments with the message.\n \"\"\"\n if not hasattr(types, \"UnicodeType\"): #if no unicode support...\n msg = str(self.msg)\n else:\n try:\n msg = str(self.msg)\n except UnicodeError:\n msg = self.msg #Defer encoding till later\n if self.args:\n msg +=' '+' '.join(map(str,self.args))\n return msg\n\n#Patch the logging default logging class\nlogging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args)\n\nsome_dict={'foo':14,'bar':15}\nlogging.error('text',15,'some dictionary',some_dict)\n\nOutput:\nERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15}\n\n", "Patching the logging package (as one answer recommended) is actually a bad idea, because it means that other code (that you didn't write, e.g. stuff in the standard library) that calls logging.error() would no longer work correctly.\nInstead, you can change your existing error() function to call logging.error() instead or print:\ndef error(*args):\n logging.error('%s', ' '.join(map(str, args)))\n\n(If there might be unicode objects you'd have to be a bit more careful, but you get the idea.)\n", "Your claim about logging is not completely true.\nlog= logging.getLogger( \"some.logger\" )\nlog.info( \"%s %d\", \"test\", value )\nlog.error(\"text %d some dictionary %s\", lineNumber, my_dict) \n\nYou don't need to explicitly use the string formatting operator, %\n\nEdit\nYou can leverage your original \"error\" function.\ndef error( *args ):\n log.error( \" \".join( map( str, args ) ) )\n\nWhich will probably make the transition less complex.\nYou can also do this.\nclass MyErrorMessageHandler( object ):\n def __init__( self, logger ):\n self.log= logger\n def __call__( self, *args ):\n self.log.error( \" \".join( map( str, args ) ) )\nerror= MyErrorMessageHandler( logging.getLogger(\"some.name\") )\n\nWhich might be palatable, also.\n", "Well, printing and logging are two very different things. It stands to reason that as such their usages could potentially be quite different as well.\n", "It's relatively easy to add a method to a class dynamically. Why not just add your method to Logging.\n" ]
[ 7, 2, 1, 0, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0000812422_logging_python.txt
Q: I want to make a temporary answerphone which records MP3s An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. I want to make a temporary system (with as little as possible programming) which will: Allow me to establish a public telephone number (preferably in the UK) Allow members of the public to call in and receive a short pre-recorded message Leave a message of their own after the beep. At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks. I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry). Thanks! A: I use twilio, very easy, very fun. A: Skype has a voicemail feature which sounds perfect for this and I suppose you would need a SkypeIn number as well A: You may want to check out asterisk. I don't think it will become any easier than using an existing system. Maybe you can find someone in the asterisk community to help set up such a system. A: Take a look at Sipgate.co.uk, they provide a free UK dial in number and free incoming calls. Not so relavant for you but they also have a python api. They are a SIP provider and there are many libraries (e.g. http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial ) for sip in python - so you could set up a python application to login to your sipgate account, pick up and incoming calls and dump the sound to a wav/mp3 whatever.
I want to make a temporary answerphone which records MP3s
An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. I want to make a temporary system (with as little as possible programming) which will: Allow me to establish a public telephone number (preferably in the UK) Allow members of the public to call in and receive a short pre-recorded message Leave a message of their own after the beep. At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks. I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry). Thanks!
[ "I use twilio, very easy, very fun.\n", "Skype has a voicemail feature which sounds perfect for this and I suppose you would need a SkypeIn number as well\n", "You may want to check out asterisk. I don't think it will become any easier than using an existing system.\nMaybe you can find someone in the asterisk community to help set up such a system.\n", "Take a look at Sipgate.co.uk, they provide a free UK dial in number and free incoming calls. Not so relavant for you but they also have a python api.\nThey are a SIP provider and there are many libraries (e.g. http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial ) for sip in python - so you could set up a python application to login to your sipgate account, pick up and incoming calls and dump the sound to a wav/mp3 whatever. \n" ]
[ 5, 2, 1, 1 ]
[]
[]
[ "python", "voip" ]
stackoverflow_0000813114_python_voip.txt
Q: Is there a way to check whether function output is assigned to a variable in Python? In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just check_status() I would like to see something like: Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on However, I would also like it to pass the output as a list if I call it in the context of a variable assignment: not_robot_stat = check_status() print not_robot_stat >>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary? A: New Solution This is a new that solution detects when the result of the function is used for assignment by examining its own bytecode. There is no bytecode writing done, and it should even be compatible with future versions of Python because it uses the opcode module for definitions. import inspect, dis, opcode def check_status(): try: frame = inspect.currentframe().f_back next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])] if next_opcode == "POP_TOP": # or next_opcode == "RETURN_VALUE": # include the above line in the if statement if you consider "return check_status()" to be assignment print "I was not assigned" print "Pretty printer status check 0.02v" print "NOTE: This is so totally not written for giant robots" return finally: del frame # do normal routine info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} return info # no assignment def test1(): check_status() # assignment def test2(): a = check_status() # could be assignment (check above for options) def test3(): return check_status() # assignment def test4(): a = [] a.append(check_status()) return a Solution 1 This is the old solution that detects whenever you are calling the function while debugging under python -i or PDB. import inspect def check_status(): frame = inspect.currentframe() try: if frame.f_back.f_code.co_name == "<module>" and frame.f_back.f_code.co_filename == "<stdin>": print "Pretty printer status check 0.02v" print "NOTE: This is so totally not written for giant robots" finally: del frame # do regular stuff return {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} def test(): check_status() >>> check_status() Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} >>> a=check_status() Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots >>> a {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} test() >>> A: However, I would also like it to pass the output as a list You mean "return the output as a dictionary" - be careful ;-) One thing you could do is use the ability of the Python interpreter to automatically convert to a string the result of any expression. To do this, create a custom subclass of dict that, when asked to convert itself to a string, performs whatever pretty formatting you want. For instance, class PrettyDict(dict): def __str__(self): return '''Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... %s Time to ion canon charge is %dm %ds Booster rocket in %s state (other stuff) ''' % (self.conf_op and 'ok' or 'OMGPANIC!!!', self.t_canoncharge / 60, self.t_canoncharge % 60, BOOSTER_STATES[self.booster_charge], ... ) Of course you could probably come up with a prettier way to write the code, but the basic idea is that the __str__ method creates the pretty-printed string that represents the state of the object and returns it. Then, if you return a PrettyDict from your check_status() function, when you type >>> check_status() you would see Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on The only catch is that >>> not_robot_stat = check_status() >>> print not_robot_stat would give you the same thing, because the same conversion to string takes place as part of the print function. But for using this in some real application, I doubt that that would matter. If you really wanted to see the return value as a pure dict, you could do >>> print repr(not_robot_stat) instead, and it should show you {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} The point is that, as other posters have said, there is no way for a function in Python to know what's going to be done with it's return value (EDIT: okay, maybe there would be some weird bytecode-hacking way, but don't do that) - but you can work around it in the cases that matter. A: There's no use case for this. Python assigns all interactive results to a special variable named _. You can do the following interactively. Works great. No funny business. >>> check_status() {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} >>> pprint.pprint( _ ) {'beer_temp': 2, 'beer_type': 31007, 'catchphrase_suggestion': 1023, 'cond_op': 1, 'fuel_est': 32557154, 'range_est_sigma': 0.023, 'stage_booster': 5, 't_canoncharge': 1342, 'virtual_on': 'hell yes'} A: There is no way for a function to know how its return value is being used. Well, as you mention, egregious bytecode hacks might be able to do it, but it would be really complicated and probably fragile. Go the simpler explicit route. A: Even if there is a way to do this, it's a bad idea. Imagine trying to debug something that behaves differently depending on the context it's called from. Now try to imagine that it's six months from now and this is buried in part of some system that's too big to keep in your head all at once. Keep it simple. Explicit is better than implicit. Just make a pretty-print function (or use the pprint module) and call that on the result. In an interactive Pythn session you can use _ to get the value of the last expression. A: There is no way to do this, at least not with the normal syntax procedures, because the function call and the assignment are completely independent operations, which have no awareness of each other. The simplest workaround I can see for this is to pass a flag as an arg to your check_status function, and deal with it accordingly. def check_status(return_dict=False) : if return_dict : # Return stuff here. # Pretty Print stuff here. And then... check_status() # Pretty print not_robot_stat = check_status(True) # Get the dict. EDIT: I assumed you'd be pretty printing more often than you'd assign. If that's not the case, interchange the default value and the value you pass in. A: The only way to do what you want is indeed "to play with the bytecode" -- there is no other way to recover that info. A much better way, of course, is to provide two separate functions: one to get the status as a dict, the other to call the first one and format it. Alternatively (but not an excellent architecture) you could have a single function that takes an optional parameter to behave in these two utterly different ways -- this is not excellent because a function should have ONE function, i.e. basically do ONE thing, not two different ones such as these.
Is there a way to check whether function output is assigned to a variable in Python?
In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just check_status() I would like to see something like: Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on However, I would also like it to pass the output as a list if I call it in the context of a variable assignment: not_robot_stat = check_status() print not_robot_stat >>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?
[ "New Solution\nThis is a new that solution detects when the result of the function is used for assignment by examining its own bytecode. There is no bytecode writing done, and it should even be compatible with future versions of Python because it uses the opcode module for definitions.\nimport inspect, dis, opcode\n\ndef check_status():\n\n try:\n frame = inspect.currentframe().f_back\n next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])]\n if next_opcode == \"POP_TOP\": \n # or next_opcode == \"RETURN_VALUE\":\n # include the above line in the if statement if you consider \"return check_status()\" to be assignment\n print \"I was not assigned\"\n print \"Pretty printer status check 0.02v\"\n print \"NOTE: This is so totally not written for giant robots\"\n return\n finally:\n del frame \n\n # do normal routine\n\n info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}\n\n return info\n\n# no assignment \ndef test1():\n check_status()\n\n# assignment\ndef test2():\n a = check_status()\n\n# could be assignment (check above for options)\ndef test3():\n return check_status()\n\n# assignment\ndef test4():\n a = []\n a.append(check_status())\n return a\n\nSolution 1\nThis is the old solution that detects whenever you are calling the function while debugging under python -i or PDB.\nimport inspect\n\ndef check_status():\n frame = inspect.currentframe()\n try:\n if frame.f_back.f_code.co_name == \"<module>\" and frame.f_back.f_code.co_filename == \"<stdin>\":\n print \"Pretty printer status check 0.02v\"\n print \"NOTE: This is so totally not written for giant robots\"\n finally:\n del frame\n\n # do regular stuff \n return {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}\n\ndef test():\n check_status()\n\n\n>>> check_status()\nPretty printer status check 0.02v\nNOTE: This is so totally not written for giant robots\n{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}\n\n>>> a=check_status()\nPretty printer status check 0.02v\nNOTE: This is so totally not written for giant robots\n\n>>> a\n{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}\n\ntest()\n>>>\n\n", "\nHowever, I would also like it to pass the output as a list\n\nYou mean \"return the output as a dictionary\" - be careful ;-)\nOne thing you could do is use the ability of the Python interpreter to automatically convert to a string the result of any expression. To do this, create a custom subclass of dict that, when asked to convert itself to a string, performs whatever pretty formatting you want. For instance,\nclass PrettyDict(dict):\n def __str__(self):\n return '''Pretty printer status check 0.02v\nNOTE: This is so totally not written for giant robots\n=================================\nSystem operational: ... %s\nTime to ion canon charge is %dm %ds\nBooster rocket in %s state\n (other stuff)\n''' % (self.conf_op and 'ok' or 'OMGPANIC!!!',\n self.t_canoncharge / 60, self.t_canoncharge % 60, \n BOOSTER_STATES[self.booster_charge],\n ... )\n\nOf course you could probably come up with a prettier way to write the code, but the basic idea is that the __str__ method creates the pretty-printed string that represents the state of the object and returns it. Then, if you return a PrettyDict from your check_status() function, when you type\n>>> check_status()\n\nyou would see\nPretty printer status check 0.02v\nNOTE: This is so totally not written for giant robots\n=================================\nSystem operational: ... ok\nTime to ion canon charge is 9m 21s\nBooster rocket in AFTERBURNER state\nRange check is optimal\nRocket fuel is 10h 19m 40s to depletion\nBeer served is type WICKSE LAGER, chill optimal\nSuggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO\nVirtual ... on\nThe only catch is that\n>>> not_robot_stat = check_status()\n>>> print not_robot_stat\n\nwould give you the same thing, because the same conversion to string takes place as part of the print function. But for using this in some real application, I doubt that that would matter. If you really wanted to see the return value as a pure dict, you could do\n>>> print repr(not_robot_stat)\n\ninstead, and it should show you\n{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}\nThe point is that, as other posters have said, there is no way for a function in Python to know what's going to be done with it's return value (EDIT: okay, maybe there would be some weird bytecode-hacking way, but don't do that) - but you can work around it in the cases that matter.\n", "There's no use case for this. Python assigns all interactive results to a special variable named _. \nYou can do the following interactively. Works great. No funny business.\n>>> check_status()\n{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}\n\n>>> pprint.pprint( _ )\n{'beer_temp': 2,\n 'beer_type': 31007,\n 'catchphrase_suggestion': 1023,\n 'cond_op': 1,\n 'fuel_est': 32557154,\n 'range_est_sigma': 0.023,\n 'stage_booster': 5,\n 't_canoncharge': 1342,\n 'virtual_on': 'hell yes'}\n\n", "There is no way for a function to know how its return value is being used.\nWell, as you mention, egregious bytecode hacks might be able to do it, but it would be really complicated and probably fragile. Go the simpler explicit route.\n", "Even if there is a way to do this, it's a bad idea. Imagine trying to debug something that behaves differently depending on the context it's called from. Now try to imagine that it's six months from now and this is buried in part of some system that's too big to keep in your head all at once.\nKeep it simple. Explicit is better than implicit. Just make a pretty-print function (or use the pprint module) and call that on the result. In an interactive Pythn session you can use _ to get the value of the last expression.\n", "There is no way to do this, at least not with the normal syntax procedures, because the function call and the assignment are completely independent operations, which have no awareness of each other.\nThe simplest workaround I can see for this is to pass a flag as an arg to your check_status function, and deal with it accordingly.\ndef check_status(return_dict=False) :\n if return_dict :\n # Return stuff here.\n # Pretty Print stuff here.\n\nAnd then...\ncheck_status() # Pretty print\nnot_robot_stat = check_status(True) # Get the dict.\n\nEDIT: I assumed you'd be pretty printing more often than you'd assign. If that's not the case, interchange the default value and the value you pass in.\n", "The only way to do what you want is indeed \"to play with the bytecode\" -- there is no other way to recover that info. A much better way, of course, is to provide two separate functions: one to get the status as a dict, the other to call the first one and format it. \nAlternatively (but not an excellent architecture) you could have a single function that takes an optional parameter to behave in these two utterly different ways -- this is not excellent because a function should have ONE function, i.e. basically do ONE thing, not two different ones such as these.\n" ]
[ 5, 4, 3, 2, 2, 0, 0 ]
[]
[]
[ "bytecode", "functional_programming", "python" ]
stackoverflow_0000813882_bytecode_functional_programming_python.txt
Q: How can I create a locked-down python environment? I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution. After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used. My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. A: "reasonably safe" defined arbitrarily as "safer than Excel and VBA". You can't win that fight. Because the fight is over the wrong thing. Anyone can use any EXE or DLL. You need to define "locked down" differently -- in a way that you can succeed. You need to define "locked down" as "cannot change the .PY files" or "we can audit all changes to the .PY files". If you shift the playing field to something you can control, you stand a small chance of winning. Get the regulations -- don't trust anyone else to interpret them for you. Be absolutely sure what the regulations require -- don't listen to someone else's interpretation. A: Sadly, Python is not very safe in this way, and this is quite well known. Its dynamic nature combined with the very thin layer over standard OS functionality makes it hard to lock things down. Usually the best option is to ensure the user running the app has limited rights, but I expect that is not practical. Another is to run it in a virtual machine where potential damage is at least limited to that environment. Failing that, someone with knowledge of Python's C API could build you a bespoke .dll that explicitly limits the scope of that particular Python interpreter, vetting imports and file writes etc., but that would require quite a thorough inspection of what functionality you need and don't need and some equally thorough testing after the fact. A: One idea is to run IronPython inside an AppDomain on .NET. See David W.'s comment here. Also, there is a module you can import to restrict the interpreter from writing files. It's called safelite. You can use that, and point out that even the inventor of Python was unable to break the security of that module! (More than twice.) I know that writing files is not the only security you're worried about. But what you are being asked to do is stupid, so hopefully the person asking you will see "safe Python" and be satisfied. A: Follow the geordi way. Each suspect program is run in its own jailed account. Monitor system calls from the process (I know how to do this in Windows, but it is beyond the scope of this question) and kill the process if needed. A: I agree that you should examine the regulations to see what they actually require. If you really do need a "locked down" Python DLL, here's a way that might do it. It will probably take a while and won't be easy to get right. BTW, since this is theoretical, I'm waving my hands over work that varies from massive to trivial :-). The idea is to modify Python.DLL so it only imports .py modules that have been signed by your private key. It verifies this by using the public key and a code signature stashed in a variable you add to each .py that you trust via a coding signing tool. Thus you have: Build a private build from the Python source. In your build, change the import statement to check for a code signature on every module when imported. Create a code signing tool that signs all the modules you use and assert are safe (aka trusted code). Something like __code_signature__ = "ABD03402340"; but cryptographically secure in each module's __init__.py file. Create a private/public key pair for signing the code and guard the private key. You probably don't want to sign any of the modules with exec() or eval() type capabilities. .NET's code signing model might be helpful here if you can use IronPython. I'm not sure its a great idea to pursue, but in the end you would be able to assert that your build of the Python.DLL would only run the code that you have signed with your private key.
How can I create a locked-down python environment?
I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution. After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used. My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe.
[ "\"reasonably safe\" defined arbitrarily as \"safer than Excel and VBA\".\nYou can't win that fight. Because the fight is over the wrong thing. Anyone can use any EXE or DLL.\nYou need to define \"locked down\" differently -- in a way that you can succeed.\nYou need to define \"locked down\" as \"cannot change the .PY files\" or \"we can audit all changes to the .PY files\". If you shift the playing field to something you can control, you stand a small chance of winning.\nGet the regulations -- don't trust anyone else to interpret them for you.\nBe absolutely sure what the regulations require -- don't listen to someone else's interpretation. \n", "Sadly, Python is not very safe in this way, and this is quite well known. Its dynamic nature combined with the very thin layer over standard OS functionality makes it hard to lock things down. Usually the best option is to ensure the user running the app has limited rights, but I expect that is not practical. Another is to run it in a virtual machine where potential damage is at least limited to that environment.\nFailing that, someone with knowledge of Python's C API could build you a bespoke .dll that explicitly limits the scope of that particular Python interpreter, vetting imports and file writes etc., but that would require quite a thorough inspection of what functionality you need and don't need and some equally thorough testing after the fact.\n", "One idea is to run IronPython inside an AppDomain on .NET. See David W.'s comment here.\nAlso, there is a module you can import to restrict the interpreter from writing files. It's called safelite. \nYou can use that, and point out that even the inventor of Python was unable to break the security of that module! (More than twice.) \nI know that writing files is not the only security you're worried about. But what you are being asked to do is stupid, so hopefully the person asking you will see \"safe Python\" and be satisfied. \n", "Follow the geordi way. \nEach suspect program is run in its own jailed account. Monitor system calls from the process (I know how to do this in Windows, but it is beyond the scope of this question) and kill the process if needed. \n", "I agree that you should examine the regulations to see what they actually require. If you really do need a \"locked down\" Python DLL, here's a way that might do it. It will probably take a while and won't be easy to get right. BTW, since this is theoretical, I'm waving my hands over work that varies from massive to trivial :-).\nThe idea is to modify Python.DLL so it only imports .py modules that have been signed by your private key. It verifies this by using the public key and a code signature stashed in a variable you add to each .py that you trust via a coding signing tool.\nThus you have:\n\nBuild a private build from the Python source.\nIn your build, change the import statement to check for a code signature on every module when imported. \nCreate a code signing tool that signs all the modules you use and assert are safe (aka trusted code). Something like __code_signature__ = \"ABD03402340\"; but cryptographically secure in each module's __init__.py file.\nCreate a private/public key pair for signing the code and guard the private key.\nYou probably don't want to sign any of the modules with exec() or eval() type capabilities.\n\n.NET's code signing model might be helpful here if you can use IronPython.\nI'm not sure its a great idea to pursue, but in the end you would be able to assert that your build of the Python.DLL would only run the code that you have signed with your private key.\n" ]
[ 9, 3, 3, 1, 0 ]
[]
[]
[ "excel", "python", "security", "windows" ]
stackoverflow_0000811670_excel_python_security_windows.txt
Q: PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL? The debug configuration of my app is built against: PYTHON25_D.DLL MSVCR80D.DLL We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD. When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and dependencies: MYSCRIPT.PYD PYTHON25.DLL MSVCR71.DLL KERNEL32.DLL What I want is the debug version, built against the same C runtime library my app uses (MSVCR80D.DLL). How can I convert MYSCRIPT.PY into: MYSCRIPT_D.PYD <-- debug version of .PYD end with "_D" PYTHON25_D.DLL <-- debug version of Python MSVCR80D.DLL <-- ver 8.0, Debug KERNEL32.DLL How can this be done? A: it won't work, beacuse MSVCR80D is a side by side runtime You will need to either tell user to directly install MS runtime or manually also copy the manifest files. Also the MSVCR71.DLL is not selected for you. It's for Python, so you may still need to keep it. A: Note that the MS debug dlls are nondistributable - you must not give them avay. However, py2exe will collect the debug versions of all dlls correctly if you run a debug version of Python, and a debug compiled version of py2exe.
PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL?
The debug configuration of my app is built against: PYTHON25_D.DLL MSVCR80D.DLL We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD. When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and dependencies: MYSCRIPT.PYD PYTHON25.DLL MSVCR71.DLL KERNEL32.DLL What I want is the debug version, built against the same C runtime library my app uses (MSVCR80D.DLL). How can I convert MYSCRIPT.PY into: MYSCRIPT_D.PYD <-- debug version of .PYD end with "_D" PYTHON25_D.DLL <-- debug version of Python MSVCR80D.DLL <-- ver 8.0, Debug KERNEL32.DLL How can this be done?
[ "it won't work, beacuse MSVCR80D is a side by side runtime\nYou will need to either tell user to directly install MS runtime or manually also copy the manifest files.\nAlso the MSVCR71.DLL is not selected for you. It's for Python, so you may still need to keep it.\n", "Note that the MS debug dlls are nondistributable - you must not give them avay. However, py2exe will collect the debug versions of all dlls correctly if you run a debug version of Python, and a debug compiled version of py2exe.\n" ]
[ 0, 0 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0000814078_py2exe_python_windows.txt
Q: distributed/faster python unit tests I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster? A: You can't frequently run all your tests, because they're too slow. This is an inevitable consequence of your project getting bigger, and won't go away. Sure, you may be able to run the tests in parallel and get a nice speedup, but the problem will just come back later, and it'll never be as it was when your project was small. For productivity, you need to be able to code, and run relevant unit tests and get results within a few seconds. If you have a hierarchy of tests, you can do this effectively: run the tests for the module you're working on frequently, the tests for the component you're working on occasionally, and the project-wide tests infrequently (perhaps before you're thinking of checking it in). You may have integration tests, or full system tests which you may run overnight: this strategy is an extension of that idea. All you need to do to set this up is to organize your code and tests to support the hierarchy. A: See py.test, which has the ability to pass unit tests off to a group of machines, or Nose, which (as of trunk, not the currently released version) supports running tests in parallel with the multiprocessing module. A: Profile them to see what really is slow. You may be able to solve this problem with out distribution. If the tests are truly unit tests then I see not many problems with running the tests across multiple execution engines. A: The first part of the solution to this problem is to only run the tests one needs to run. Between commits to a shared branch, one runs only those tests that one's new work interacts with; that should take all of five seconds. If one adopts this model, it becomes vital to make a point of running the entire test suite before committing to a shared resource. The problem of running the full test suite for regression purposes remains, of course, though it's already partially addressed by simply running the full suite less often. To avoid having to wait around while that job runs, one can offload the task of testing to another machine. That quickly turns into a task for a continuous integration system; buildbot seem fairly appropriate to your use case. You should also be able to distribute tests across hosts using buildbot, firing off two jobs with different entry points to the test suite. But I am not convinced that this will gain you much over the first two steps I've mentioned here; it should be reserved for cases when tests take much longer to run than the interval between commits to shared resources. D'A [Caveat lector: My understanding of buildbot is largely theoretical at this point, and it is probably harder than it looks.] A: While coding, only run the tests of the class that You have just changed, not all the tests in the whole project. Still, it is a good practice to run all tests before You commit Your code (but the Continuous Integration server can do it for You).
distributed/faster python unit tests
I have a lot of python unit tests for a project and it's getting to the point where it takes a long time to run them. I don't want to add more because I know they're going to make things slower. How do people solve this problem? Is there any easy way to distribute the test execution over a cluster?
[ "You can't frequently run all your tests, because they're too slow. This is an inevitable consequence of your project getting bigger, and won't go away. Sure, you may be able to run the tests in parallel and get a nice speedup, but the problem will just come back later, and it'll never be as it was when your project was small.\nFor productivity, you need to be able to code, and run relevant unit tests and get results within a few seconds. If you have a hierarchy of tests, you can do this effectively: run the tests for the module you're working on frequently, the tests for the component you're working on occasionally, and the project-wide tests infrequently (perhaps before you're thinking of checking it in). You may have integration tests, or full system tests which you may run overnight: this strategy is an extension of that idea.\nAll you need to do to set this up is to organize your code and tests to support the hierarchy.\n", "See py.test, which has the ability to pass unit tests off to a group of machines, or Nose, which (as of trunk, not the currently released version) supports running tests in parallel with the multiprocessing module.\n", "Profile them to see what really is slow. You may be able to solve this problem with out distribution. If the tests are truly unit tests then I see not many problems with running the tests across multiple execution engines.\n", "The first part of the solution to this problem is to only run the tests one needs to run. Between commits to a shared branch, one runs only those tests that one's new work interacts with; that should take all of five seconds. If one adopts this model, it becomes vital to make a point of running the entire test suite before committing to a shared resource.\nThe problem of running the full test suite for regression purposes remains, of course, though it's already partially addressed by simply running the full suite less often. To avoid having to wait around while that job runs, one can offload the task of testing to another machine. That quickly turns into a task for a continuous integration system; buildbot seem fairly appropriate to your use case.\nYou should also be able to distribute tests across hosts using buildbot, firing off two jobs with different entry points to the test suite. But I am not convinced that this will gain you much over the first two steps I've mentioned here; it should be reserved for cases when tests take much longer to run than the interval between commits to shared resources.\nD'A\n[Caveat lector: My understanding of buildbot is largely theoretical at this point, and it is probably harder than it looks.]\n", "While coding, only run the tests of the class that You have just changed, not all the tests in the whole project.\nStill, it is a good practice to run all tests before You commit Your code (but the Continuous Integration server can do it for You).\n" ]
[ 5, 3, 2, 1, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000809564_python_unit_testing.txt
Q: Amazon S3 permissions Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for me, is there another way to do this? A: There are various ways to control access to the S3 objects: Use the query string auth - but as you noted this does require an expiration date. You could make it far in the future, which has been good enough for most things I have done. Use the S3 ACLS - but this requires the user to have an AWS account and authenticate with AWS to access the S3 object. This is probably not what you are looking for. You proxy the access to the S3 object through your application, which implements your access control logic. This will bring all the bandwidth through your box. You can set up an EC2 instance with your proxy logic - this keeps the bandwidth closer to S3 and can reduce latency in certain situations. The difference between this and #3 could be minimal, but depends your particular situation. A: Have the user hit your server Have the server set up a query-string authentication with a short expiration (minutes, hours?) Have your server redirect to #2 A: You will have to build the whole access logic to S3 in your applications A: I've been dealing with this, too. Don, who wrote the S3 PHP class I'm using, pointed out you can use dirs inside buckets. So you can put your file in a dir with a random string and then redirect to that. mybucket.amazon.net/wef49kfe4j409jf4f4f9jdfd/myfile.zip While not at all secure, you can control access to it by changing permissions or creating and deleting it (keep the original securely in a different bucket) as necessary.
Amazon S3 permissions
Trying to understand S3...How do you limit access to a file you upload to S3? For example, from a web application, each user has files they can upload, but how do you limit access so only that user has access to that file? It seems like the query string authentication requires an expiration date and that won't work for me, is there another way to do this?
[ "There are various ways to control access to the S3 objects:\n\nUse the query string auth - but as you noted this does require an expiration date. You could make it far in the future, which has been good enough for most things I have done.\nUse the S3 ACLS - but this requires the user to have an AWS account and authenticate with AWS to access the S3 object. This is probably not what you are looking for.\nYou proxy the access to the S3 object through your application, which implements your access control logic. This will bring all the bandwidth through your box.\nYou can set up an EC2 instance with your proxy logic - this keeps the bandwidth closer to S3 and can reduce latency in certain situations. The difference between this and #3 could be minimal, but depends your particular situation.\n\n", "\nHave the user hit your server\nHave the server set up a query-string authentication with a short expiration (minutes, hours?)\nHave your server redirect to #2\n\n", "You will have to build the whole access logic to S3 in your applications\n", "I've been dealing with this, too. Don, who wrote the S3 PHP class I'm using, pointed out you can use dirs inside buckets. So you can put your file in a dir with a random string and then redirect to that. mybucket.amazon.net/wef49kfe4j409jf4f4f9jdfd/myfile.zip While not at all secure, you can control access to it by changing permissions or creating and deleting it (keep the original securely in a different bucket) as necessary.\n" ]
[ 14, 8, 1, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "django", "python" ]
stackoverflow_0000765964_amazon_s3_amazon_web_services_django_python.txt
Q: Python regex parsing I have an array of strings in python which each string in the array looking something like this: <r n="Foo Bar" t="5" s="10" l="25"/> I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs. But not really knowing much regex stuff I havent had anything work yet. This is what I have so far. string = '<r n="Foo Bar" t="5" s="10" l="25"/>' print re.split("<r\s+n=(?:\"(^\"]+)\").*?/>", string) What would be the best way to extract the values of n, t, s, and l from that string? A: This will get you most of the way there: >>> print re.findall(r'(\w+)="(.*?)"', string) [('n', 'Foo Bar'), ('t', '5'), ('s', '10'), ('l', '25')] re.split and re.findall are complementary. Every time your thought process begins with "I want each item that looks like X", then you should use re.findall. When it starts with "I want the data between and surrounding each X", use re.split. A: <r n="Foo Bar" t="5" s="10" l="25"/> That source looks like XML, so the "the best way" would be to use an XML parsing module.. If it's not exactly XML, BeautifulSoup (or rather, the BeautifulSoup.BeautifulStoneSoup module) may work best, as it's good at dealing with possibly-invalid XML (or things that "aren't quite XML"): >>> from BeautifulSoup import BeautifulStoneSoup >>> soup = BeautifulStoneSoup("""<r n="Foo Bar" t="5" s="10" l="25"/>""") # grab the "r" element (You could also use soup.findAll("r") if there are multiple >>> soup.find("r") <r n="Foo Bar" t="5" s="10" l="25"></r> # get a specific attribute >>> soup.find("r")['n'] u'Foo Bar' >>> soup.find("r")['t'] u'5' # Get all attributes, or turn them into a regular dictionary >>> soup.find("r").attrs [(u'n', u'Foo Bar'), (u't', u'5'), (u's', u'10'), (u'l', u'25')] >>> dict(soup.find("r").attrs) {u's': u'10', u'l': u'25', u't': u'5', u'n': u'Foo Bar'}
Python regex parsing
I have an array of strings in python which each string in the array looking something like this: <r n="Foo Bar" t="5" s="10" l="25"/> I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs. But not really knowing much regex stuff I havent had anything work yet. This is what I have so far. string = '<r n="Foo Bar" t="5" s="10" l="25"/>' print re.split("<r\s+n=(?:\"(^\"]+)\").*?/>", string) What would be the best way to extract the values of n, t, s, and l from that string?
[ "This will get you most of the way there:\n>>> print re.findall(r'(\\w+)=\"(.*?)\"', string)\n[('n', 'Foo Bar'), ('t', '5'), ('s', '10'), ('l', '25')]\n\nre.split and re.findall are complementary.\nEvery time your thought process begins with \"I want each item that looks like X\", then you should use re.findall. When it starts with \"I want the data between and surrounding each X\", use re.split.\n", "\n<r n=\"Foo Bar\" t=\"5\" s=\"10\" l=\"25\"/>\n\n\nThat source looks like XML, so the \"the best way\" would be to use an XML parsing module.. If it's not exactly XML, BeautifulSoup (or rather, the BeautifulSoup.BeautifulStoneSoup module) may work best, as it's good at dealing with possibly-invalid XML (or things that \"aren't quite XML\"):\n>>> from BeautifulSoup import BeautifulStoneSoup\n>>> soup = BeautifulStoneSoup(\"\"\"<r n=\"Foo Bar\" t=\"5\" s=\"10\" l=\"25\"/>\"\"\")\n\n# grab the \"r\" element (You could also use soup.findAll(\"r\") if there are multiple\n>>> soup.find(\"r\")\n<r n=\"Foo Bar\" t=\"5\" s=\"10\" l=\"25\"></r>\n\n# get a specific attribute\n>>> soup.find(\"r\")['n']\nu'Foo Bar'\n>>> soup.find(\"r\")['t']\nu'5'\n\n# Get all attributes, or turn them into a regular dictionary\n>>> soup.find(\"r\").attrs\n[(u'n', u'Foo Bar'), (u't', u'5'), (u's', u'10'), (u'l', u'25')]\n>>> dict(soup.find(\"r\").attrs)\n{u's': u'10', u'l': u'25', u't': u'5', u'n': u'Foo Bar'}\n\n" ]
[ 7, 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000814786_python_regex.txt
Q: python regular exp. with a unicode char I need a reg exp that will parse something like- "2 * 240pin" where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working: multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$' multiplepat= re.compile(multiple, re.I) print multiplepat.search(u'1 X 240pin').groups() returns multiplepat= re.compile(multiple, re.I) File "C:\Python26\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python26\lib\re.py", line 243, in _compile raise error, v # invalid expression error: nothing to repeat A: multiple= r'^(\d+)\s[xX\*\\u00d7]\s?(\d+)(\w{2,4})$' A: You need to escape the * as it is a quantifier in the context you use it. But you could also use a character class. So try this: ur'^(\d+)\s?[x*\u00d7]\s?(\d+)(\w{2,4})$' A: Use character sets ([]) : [] Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters are not active inside sets. >>> m= u'^(\\d+)\\s?[x*\u00d7]\\s?(\\d+)(\\w{2,4})$' >>> mpat=re.compile(m) >>> mpat.search(u'1 * 240pin').groups() (u'1', u'240', u'pin') >>>
python regular exp. with a unicode char
I need a reg exp that will parse something like- "2 * 240pin" where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working: multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$' multiplepat= re.compile(multiple, re.I) print multiplepat.search(u'1 X 240pin').groups() returns multiplepat= re.compile(multiple, re.I) File "C:\Python26\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python26\lib\re.py", line 243, in _compile raise error, v # invalid expression error: nothing to repeat
[ "multiple= r'^(\\d+)\\s[xX\\*\\\\u00d7]\\s?(\\d+)(\\w{2,4})$'\n\n", "You need to escape the * as it is a quantifier in the context you use it. But you could also use a character class. So try this: \nur'^(\\d+)\\s?[x*\\u00d7]\\s?(\\d+)(\\w{2,4})$'\n\n", "Use character sets ([]) :\n\n[]\nUsed to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. Special characters are not active inside sets.\n\n>>> m= u'^(\\\\d+)\\\\s?[x*\\u00d7]\\\\s?(\\\\d+)(\\\\w{2,4})$'\n>>> mpat=re.compile(m)\n>>> mpat.search(u'1 * 240pin').groups()\n(u'1', u'240', u'pin')\n>>>\n\n" ]
[ 2, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000814933_python_regex.txt
Q: Can I encrypt email and decrypt it back using python default library set? Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python? A: Yes, you can. Read http://www.amk.ca/python/code/crypto.html You'll find an answer there ;) You're question is not concrete enough to say more. You may want to read http://en.wikipedia.org/wiki/Cryptography#Modern_cryptography Cheers, Tuergeist Update: No, you cannot. (with build in functionality due to export restrictions, see http://docs.python.org/library/crypto.html) But you can, if you're implementing you own algorithm (bad idea). So, the BEST solution is, to use the extension recommended by python core developers. See post above. Cheers again. A: A third-party system is your best bet. If you really can't/don't want to use a third-party, maybe something simple would suffice. One of the simpler algorithms is the Tiny Encryption Algorithm (TEA). Here's an example of a Python implementation that you could start with. A: If what you mean is that you want to roll your own encryption system, you could try using the built-in hmac and hashlib modules. (hashlib is new for 2.5, so if you must use an earlier Python, your hash choices are the older md5 and sha modules.) If you are opposed to (or are prevented from) installing a third-party library but are OK with using third-party algorithms or even "lightweight" third-party implementations of algorithms (e.g. published Python source code which resides in a single .py file that you can incorporate or import yourself without using setup.py or any other formal installation), then I highly recommend you do so, because these are likely to be better than what you can come up with on your own. The smallest and user-friendliest of these that I am aware of is known as p3, written by cryptographer Paul Rubin. The original link is no longer active but you can search for it. Googling currently yields a near-exact copy as well as an adaptation for Python 3. You could also try one of several single-module, pure-Python Rijndael (AES) implementations such as this or this. (Again, links are not guaranteed to be permanent so you may have to do some searching.)
Can I encrypt email and decrypt it back using python default library set?
Of course similar questions have been asked in stackoverflow but I don't want to use any third party library like Crypto or something. So I need to generate a ciphertext from a user email and decrypt it back to plaintext. How can I do this in python?
[ "Yes, you can. \nRead http://www.amk.ca/python/code/crypto.html\nYou'll find an answer there ;)\nYou're question is not concrete enough to say more. You may want to read http://en.wikipedia.org/wiki/Cryptography#Modern_cryptography\nCheers,\n Tuergeist\nUpdate: \nNo, you cannot. (with build in functionality due to export restrictions, see http://docs.python.org/library/crypto.html)\nBut you can, if you're implementing you own algorithm (bad idea).\nSo, the BEST solution is, to use the extension recommended by python core developers. See post above.\nCheers again.\n", "A third-party system is your best bet.\nIf you really can't/don't want to use a third-party, maybe something simple would suffice.\nOne of the simpler algorithms is the Tiny Encryption Algorithm (TEA). Here's an example of a Python implementation that you could start with.\n", "If what you mean is that you want to roll your own encryption system, you could try using the built-in hmac and hashlib modules. (hashlib is new for 2.5, so if you must use an earlier Python, your hash choices are the older md5 and sha modules.)\nIf you are opposed to (or are prevented from) installing a third-party library but are OK with using third-party algorithms or even \"lightweight\" third-party implementations of algorithms (e.g. published Python source code which resides in a single .py file that you can incorporate or import yourself without using setup.py or any other formal installation), then I highly recommend you do so, because these are likely to be better than what you can come up with on your own.\nThe smallest and user-friendliest of these that I am aware of is known as p3, written by cryptographer Paul Rubin. The original link is no longer active but you can search for it. Googling currently yields a near-exact copy as well as an adaptation for Python 3.\nYou could also try one of several single-module, pure-Python Rijndael (AES) implementations such as this or this. (Again, links are not guaranteed to be permanent so you may have to do some searching.)\n" ]
[ 4, 4, 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0000806739_encryption_python.txt
Q: What is the best (idiomatic) way to check the type of a Python variable? I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code? if type(x) == type(str()): do_something_with_a_string(x) elif type(x) == type(dict()): do_somethting_with_a_dict(x) else: raise ValueError Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance is preferred over type(x) is). But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series. Let me elaborate on my use case. If a variable is a string, I need to put it in a list. If it's a dict, I need a list of the unique values. Here's what I came up with: def value_list(x): cases = {str: lambda t: [t], dict: lambda t: list(set(t.values()))} try: return cases[type(x)](x) except KeyError: return None If isinstance is preferred, how would you write this value_list() function? A: What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP. def value_list(x): if isinstance(x, dict): return list(set(x.values())) elif isinstance(x, basestring): return [x] else: return None A: type(dict()) says "make a new dict, and then find out what its type is". It's quicker to say just dict. But if you want to just check type, a more idiomatic way is isinstance(x, dict). Note, that isinstance also includes subclasses (thanks Dustin): class D(dict): pass d = D() print("type(d) is dict", type(d) is dict) # -> False print("isinstance (d, dict)", isinstance(d, dict)) # -> True A: built-in types in Python have built in names: >>> s = "hallo" >>> type(s) is str True >>> s = {} >>> type(s) is dict True btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not. A: isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses. For example: >>> class a_dict(dict): ... pass ... >>> type(a_dict()) == type(dict()) False >>> isinstance(a_dict(), dict) True >>> Of course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it. A: I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii. Here is what I will do: In [53]: s='somestring' In [54]: u=u'someunicodestring' In [55]: d={} In [56]: for each in s,u,d: if hasattr(each, 'keys'): print list(set(each.values())) elif hasattr(each, 'lower'): print [each] else: print "error" ....: ....: ['somestring'] [u'someunicodestring'] [] The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do. A: I think it might be preferred to actually do if isinstance(x, str): do_something_with_a_string(x) elif isinstance(x, dict): do_somethting_with_a_dict(x) else: raise ValueError 2 Alternate forms, depending on your code one or the other is probably considered better than that even. One is to not look before you leap try: one, two = tupleOrValue except TypeError: one = tupleOrValue two = None The other approach is from Guido and is a form of function overloading which leaves your code more open ended. http://www.artima.com/weblogs/viewpost.jsp?thread=155514 A: That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict: {type(str()): do_something_with_a_string, type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)() A bit more concise and pythonic wouldn't you say? Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer: {str: do_something_with_a_string, dict: do_something_with_a_dict}.get(type(x), errorhandler)() A: You may want to check out typecheck. http://pypi.python.org/pypi/typecheck Type-checking module for Python This package provides powerful run-time typechecking facilities for Python functions, methods and generators. Without requiring a custom preprocessor or alterations to the language, the typecheck package allows programmers and quality assurance engineers to make precise assertions about the input to, and output from, their code. A: I've been using a different approach: from inspect import getmro if (type([]) in getmro(obj.__class__)): # This is a list, or a subclass of... elif (type{}) in getmro(obj.__class__)): # This one is a dict, or ... I can't remember why I used this instead of isinstance, though...
What is the best (idiomatic) way to check the type of a Python variable?
I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code? if type(x) == type(str()): do_something_with_a_string(x) elif type(x) == type(dict()): do_somethting_with_a_dict(x) else: raise ValueError Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance is preferred over type(x) is). But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series. Let me elaborate on my use case. If a variable is a string, I need to put it in a list. If it's a dict, I need a list of the unique values. Here's what I came up with: def value_list(x): cases = {str: lambda t: [t], dict: lambda t: list(set(t.values()))} try: return cases[type(x)](x) except KeyError: return None If isinstance is preferred, how would you write this value_list() function?
[ "What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP.\ndef value_list(x):\n if isinstance(x, dict):\n return list(set(x.values()))\n elif isinstance(x, basestring):\n return [x]\n else:\n return None\n\n", "type(dict()) says \"make a new dict, and then find out what its type is\". It's quicker to say just dict.\nBut if you want to just check type, a more idiomatic way is isinstance(x, dict).\nNote, that isinstance also includes subclasses (thanks Dustin):\nclass D(dict):\n pass\n\nd = D()\nprint(\"type(d) is dict\", type(d) is dict) # -> False\nprint(\"isinstance (d, dict)\", isinstance(d, dict)) # -> True\n\n", "built-in types in Python have built in names:\n>>> s = \"hallo\"\n>>> type(s) is str\nTrue\n>>> s = {}\n>>> type(s) is dict\nTrue\n\nbtw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.\n", "isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses.\nFor example:\n >>> class a_dict(dict):\n ... pass\n ... \n >>> type(a_dict()) == type(dict())\n False\n >>> isinstance(a_dict(), dict)\n True\n >>> \n\nOf course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it.\n", "I think I will go for the duck typing approach - \"if it walks like a duck, it quacks like a duck, its a duck\". This way you will need not worry about if the string is a unicode or ascii. \nHere is what I will do:\nIn [53]: s='somestring'\n\nIn [54]: u=u'someunicodestring'\n\nIn [55]: d={}\n\nIn [56]: for each in s,u,d:\n if hasattr(each, 'keys'):\n print list(set(each.values()))\n elif hasattr(each, 'lower'):\n print [each]\n else:\n print \"error\"\n ....: \n ....: \n['somestring']\n[u'someunicodestring']\n[]\n\nThe experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.\n", "I think it might be preferred to actually do\nif isinstance(x, str):\n do_something_with_a_string(x)\nelif isinstance(x, dict):\n do_somethting_with_a_dict(x)\nelse:\n raise ValueError\n\n2 Alternate forms, depending on your code one or the other is probably considered better than that even. One is to not look before you leap\ntry:\n one, two = tupleOrValue\nexcept TypeError:\n one = tupleOrValue\n two = None\n\nThe other approach is from Guido and is a form of function overloading which leaves your code more open ended.\nhttp://www.artima.com/weblogs/viewpost.jsp?thread=155514\n", "That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:\n{type(str()): do_something_with_a_string,\n type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()\n\nA bit more concise and pythonic wouldn't you say?\n\nEdit.. Heeding Avisser's advice, the code also works like this, and looks nicer:\n{str: do_something_with_a_string,\n dict: do_something_with_a_dict}.get(type(x), errorhandler)()\n\n", "You may want to check out typecheck.\nhttp://pypi.python.org/pypi/typecheck\nType-checking module for Python\nThis package provides powerful run-time typechecking facilities for Python functions, methods and generators. Without requiring a custom preprocessor or alterations to the language, the typecheck package allows programmers and quality assurance engineers to make precise assertions about the input to, and output from, their code.\n", "I've been using a different approach:\nfrom inspect import getmro\nif (type([]) in getmro(obj.__class__)):\n # This is a list, or a subclass of...\nelif (type{}) in getmro(obj.__class__)):\n # This one is a dict, or ...\n\nI can't remember why I used this instead of isinstance, though...\n" ]
[ 346, 63, 46, 23, 8, 7, 3, 3, 1 ]
[ "*sigh*\nNo, typechecking arguments in python is not necessary. It is never \nnecessary.\nIf your code accepts either a string or a dict object, your design is broken.\nThat comes from the fact that if you don't know already the type of an object\nin your own program, then you're doing something wrong already.\nTypechecking hurts code reuse and reduces performance. Having a function that\nperforms different things depending on the type of the object passed is \nbug-prone and has a behavior harder to understand and maintain.\nYou have the following saner options:\n1) Make a function unique_values that converts dicts in unique lists of values:\ndef unique_values(some_dict):\n return list(set(some_dict.values()))\n\nMake your function assume the argument passed is always a list. That way, if you need to pass a string to the function, you just do:\nmyfunction([some_string])\n\nIf you need to pass it a dict, you do:\nmyfunction(unique_values(some_dict))\n\nThat's your best option, it is clean, easy to understand and maintain. Anyone\nreading the code immediatelly understands what is happening, and you don't have\nto typecheck.\n2) Make two functions, one that accepts lists of strings and one that accepts \ndicts. You can make one call the other internally, in the most convenient \nway (myfunction_dict can create a list of strings and call myfunction_list).\nIn any case, don't typecheck. It is completely unnecessary and has only \ndownsides. Refactor your code instead in a way you don't need to typecheck. \nYou only get benefits in doing so, both in short and long run.\n" ]
[ -2 ]
[ "python", "typechecking", "types" ]
stackoverflow_0000378927_python_typechecking_types.txt
Q: Python imports from crossreferencing packages Currently I'm trying to write my first Python library and I've encountered the following problem: I have the following import in my package myapp.factories: from myapp.models import * And the following in my package myapp.models: from myapp.factories import * I need the models in my factories package but inside one model I also need one of the factories. If I now call the code that needs the factory I get the following error: NameError: global name 'MyModelFactory' is not defined I'm pretty sure it has something to do with the order in which the scripts are loaded but I can't seem to figure out how to get these crossreferences to work. A: "inside one model I also need one of the factories" - just import that factory where you need it: class SomeModel: def some_method(self): from myapp.factories import SomeFactory SomeFactory().do_something()
Python imports from crossreferencing packages
Currently I'm trying to write my first Python library and I've encountered the following problem: I have the following import in my package myapp.factories: from myapp.models import * And the following in my package myapp.models: from myapp.factories import * I need the models in my factories package but inside one model I also need one of the factories. If I now call the code that needs the factory I get the following error: NameError: global name 'MyModelFactory' is not defined I'm pretty sure it has something to do with the order in which the scripts are loaded but I can't seem to figure out how to get these crossreferences to work.
[ "\"inside one model I also need one of the factories\" - just import that factory where you need it:\nclass SomeModel:\n def some_method(self):\n from myapp.factories import SomeFactory\n SomeFactory().do_something()\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000815367_python.txt
Q: C# Web Server: Implementing a Dynamic Language I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following: ASP.NET PHP Python I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement? EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python. A: ASP.NET will surely be the easiest as you can use all the built in classes. Essentially you don't need to build it, you just hook it up to the Web server (I don't know if we can count it as writing ASP.NET though ;) ) You might want to look at Cassini source code A: Have you considered boo? It has a very configurable compiler and there are some good OSS examples out there (for example the brail view engine for Monorail & ASP.NET MVC). A: If you implement a cgi interface, you could use any kind of backend language. If you want to get fancy, you could consider looking into fastcgi. A: Perhaps you should take a look at IronPython. A: Well it would appear you are doing this as a learning experience, after all Microsoft already provides a web server for Windows (IIS). Similary PHP has already been ported to Windows, you could use that port directly. SImilary you could use it as a "reference implimentation" and write your own implimentation of PHP for windows. Either way, it would then permit your web server to host lots of existing applications such as Wordpress etc.
C# Web Server: Implementing a Dynamic Language
I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following: ASP.NET PHP Python I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement? EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.
[ "ASP.NET will surely be the easiest as you can use all the built in classes. Essentially you don't need to build it, you just hook it up to the Web server (I don't know if we can count it as writing ASP.NET though ;) )\nYou might want to look at Cassini source code\n", "Have you considered boo? It has a very configurable compiler and there are some good OSS examples out there (for example the brail view engine for Monorail & ASP.NET MVC).\n", "If you implement a cgi interface, you could use any kind of backend language. If you want to get fancy, you could consider looking into fastcgi.\n", "Perhaps you should take a look at IronPython.\n", "Well it would appear you are doing this as a learning experience, after all Microsoft already provides a web server for Windows (IIS).\nSimilary PHP has already been ported to Windows, you could use that port directly. SImilary you could use it as a \"reference implimentation\" and write your own implimentation of PHP for windows.\nEither way, it would then permit your web server to host lots of existing applications such as Wordpress etc.\n" ]
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "asp.net", "php", "python", "webserver" ]
stackoverflow_0000815446_asp.net_php_python_webserver.txt
Q: How do you remove html tags using Universal Feed Parser? The documentation lists the tags that are allowed/removed by default: http://www.feedparser.org/docs/html-sanitization.html But it doesn't say anything about how you can specify which additional tags you want removed. Is there a way to do this using Universal Feed Parser or do you have to do further processing using your own regex and/or something like Beautiful Soup? A: i took a quick look over the code and i don't think there is a way to overwrite them directly. But you can overwrite feedparser._HTMLSanitizer.acceptable_elements, the list of tags that wont get removed before doing feedparser.parse
How do you remove html tags using Universal Feed Parser?
The documentation lists the tags that are allowed/removed by default: http://www.feedparser.org/docs/html-sanitization.html But it doesn't say anything about how you can specify which additional tags you want removed. Is there a way to do this using Universal Feed Parser or do you have to do further processing using your own regex and/or something like Beautiful Soup?
[ "i took a quick look over the code and i don't think there is a way to overwrite them directly. But you can overwrite feedparser._HTMLSanitizer.acceptable_elements, the list of tags that wont get removed before doing feedparser.parse\n" ]
[ 6 ]
[]
[]
[ "django", "feed", "parsing", "python" ]
stackoverflow_0000815606_django_feed_parsing_python.txt
Q: Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl? UPDATE: I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing? Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question. A: You could use the ''.join method. e.g. # print 'foo', 'bar', 'baz' separated by spaces print 'foo', 'bar', 'baz' # print separated by commas print ', '.join(['foo', 'bar', 'baz']) EDIT: Ok, I misunderstood the purpose of OUTPUT_RECORD_SEPARATOR, so ''.join is not what you want. print 'foo' is equivalent to sys.stdout.write('foo'+'\n'), so you could roll your own print function: def myprint(*args, end='\n'): sys.stdout.write(' '.join(args) + end) Or go one step further with a factory function: def make_printer(end): def myprint(*args, end='\n'): sys.stdout.write(' '.join(args) + end) return myprint # usage: p = make_printer('#') p('foo', 'bar', 'baz') Finally, if you're daring, you could override sys.stdout: sys.old_stdout = sys.stdout class MyWrite(object): def __init__(self, end='\n'): self.end = end def write(self, s): sys.old_stdout.write(s.replace('\n', self.end)) This will cause print statements to produce the alternative line ending. Usage: sys.stdout = MyWrite('!\n') print 'foo' # prints: foo! Note that you may need to override more than just write() – or at least provide redirects for things like MyWrite.flush() to sys.old_stdout.flush(). A: Python 3's print function has sep and end arguments. print('foo', 'bar', 'baz', sep='|', end='#') Note that in Python 3, print is no longer a statement, it is a function. A: If what you want is to have any of \r, \n, or \r\n in the input to be seen as a newline, then you can use “universal newline support” in your ‘open()’ call. In Python 2.6 open(), this needs to be explicitly enabled by adding ‘U’ to the mode string: in_file = open('foo.txt', 'rU') It also depends on this support being available in the Python interpreter; but the docs say this is available by default. In Python 3.0 open(), universal newline behaviour is always available, and is the default behaviour; you can choose a different behaviour with different values for the newline parameter. If you want input to interpret records terminated by something other than a newline, then you don't want ‘readlines’ (which, per the name, reads lines specifically, not records generally) and AFAIK will have to implement your own record-reading code. A: In Python pre-3, you can suppress standard separator appending ',' at end of line: print yourVar, #these 3 lines print without any newline separator print yourVar, print yourVar, if you want to use non-standard separator, suppress normal one and print yours: print yourVar, yourSep, print yourVar, yourSep, print yourVar, yourSep, A: open('file').read().split(your_separator_of_choice) the only difference with readlines() here is that resulting list items won't have separator preserved at the end.
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl? UPDATE: I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing? Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.
[ "You could use the ''.join method. e.g.\n# print 'foo', 'bar', 'baz' separated by spaces\nprint 'foo', 'bar', 'baz'\n# print separated by commas\nprint ', '.join(['foo', 'bar', 'baz'])\n\nEDIT:\nOk, I misunderstood the purpose of OUTPUT_RECORD_SEPARATOR, so ''.join is not what you want.\nprint 'foo' is equivalent to sys.stdout.write('foo'+'\\n'), so you could roll your own print function:\ndef myprint(*args, end='\\n'):\n sys.stdout.write(' '.join(args) + end)\n\nOr go one step further with a factory function:\ndef make_printer(end):\n def myprint(*args, end='\\n'):\n sys.stdout.write(' '.join(args) + end)\n return myprint\n\n# usage:\np = make_printer('#')\np('foo', 'bar', 'baz')\n\nFinally, if you're daring, you could override sys.stdout:\nsys.old_stdout = sys.stdout\nclass MyWrite(object):\n def __init__(self, end='\\n'):\n self.end = end\n def write(self, s):\n sys.old_stdout.write(s.replace('\\n', self.end))\n\nThis will cause print statements to produce the alternative line ending. Usage:\nsys.stdout = MyWrite('!\\n')\nprint 'foo'\n# prints: foo!\n\nNote that you may need to override more than just write() – or at least provide redirects for things like MyWrite.flush() to sys.old_stdout.flush().\n", "Python 3's print function has sep and end arguments.\nprint('foo', 'bar', 'baz', sep='|', end='#')\n\nNote that in Python 3, print is no longer a statement, it is a function.\n", "If what you want is to have any of \\r, \\n, or \\r\\n in the input to be seen as a newline, then you can use “universal newline support” in your ‘open()’ call.\nIn Python 2.6 open(), this needs to be explicitly enabled by adding ‘U’ to the mode string:\nin_file = open('foo.txt', 'rU')\n\nIt also depends on this support being available in the Python interpreter; but the docs say this is available by default.\nIn Python 3.0 open(), universal newline behaviour is always available, and is the default behaviour; you can choose a different behaviour with different values for the newline parameter.\nIf you want input to interpret records terminated by something other than a newline, then you don't want ‘readlines’ (which, per the name, reads lines specifically, not records generally) and AFAIK will have to implement your own record-reading code.\n", "In Python pre-3, you can suppress standard separator appending ',' at end of line:\nprint yourVar, #these 3 lines print without any newline separator\nprint yourVar, \nprint yourVar, \n\nif you want to use non-standard separator, suppress normal one and print yours:\nprint yourVar, yourSep,\nprint yourVar, yourSep,\nprint yourVar, yourSep,\n\n", "open('file').read().split(your_separator_of_choice)\n\nthe only difference with readlines() here is that resulting list items won't have separator preserved at the end.\n" ]
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0000770925_file_io_python.txt
Q: how to get the url of the current page in a GAE template In Google App Engine, is there a tag or other mechanism to get the URL of the current page in a template or is it necessary to pass the url as a variable to the template from the python code? A: It depends how you are populating the templates. If you are using them outside of Django, then you have to populate them with the URL yourself. If you are using them in Django with the default configuration, you would have to populate them with the URL yourself. An alternative that would avoid you having to populate them yourself is to configure the DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST context processor as described on this page and then access the appropriate part of the request object directly (e.g. request.path).
how to get the url of the current page in a GAE template
In Google App Engine, is there a tag or other mechanism to get the URL of the current page in a template or is it necessary to pass the url as a variable to the template from the python code?
[ "It depends how you are populating the templates. If you are using them outside of Django, then you have to populate them with the URL yourself. If you are using them in Django with the default configuration, you would have to populate them with the URL yourself. An alternative that would avoid you having to populate them yourself is to configure the DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST context processor as described on this page and then access the appropriate part of the request object directly (e.g. request.path).\n" ]
[ 3 ]
[]
[]
[ "django_templates", "google_app_engine", "python", "templates", "web_applications" ]
stackoverflow_0000816683_django_templates_google_app_engine_python_templates_web_applications.txt
Q: How to unescape apostrophes and such in Python? I have a string with symbols like this: &#39; That's an apostrophe apparently. I tried saxutils.unescape() without any luck and tried urllib.unquote() How can I decode this? Thanks! A: Check out this question. What you're looking for is "html entity decoding". Typically, you'll find a function named something like "htmldecode" that will do what you want. Both Django and Cheetah provide such functions as does BeautifulSoup. The other answer will work just great if you don't want to use a library and all the entities are numeric. A: Try this: (found it here) from htmlentitydefs import name2codepoint as n2cp import re def decode_htmlentities(string): """ Decode HTML entities–hex, decimal, or named–in a string @see http://snippets.dzone.com/posts/show/4569 >>> u = u'E tu vivrai nel terrore - L&#x27;aldil&#xE0; (1981)' >>> print decode_htmlentities(u).encode('UTF-8') E tu vivrai nel terrore - L'aldilà (1981) >>> print decode_htmlentities("l&#39;eau") l'eau >>> print decode_htmlentities("foo &lt; bar") foo < bar """ def substitute_entity(match): ent = match.group(3) if match.group(1) == "#": # decoding by number if match.group(2) == '': # number is in decimal return unichr(int(ent)) elif match.group(2) == 'x': # number is in hex return unichr(int('0x'+ent, 16)) else: # they were using a name cp = n2cp.get(ent) if cp: return unichr(cp) else: return match.group() entity_re = re.compile(r'&(#?)(x?)(\w+);') return entity_re.subn(substitute_entity, string)[0] A: The most robust solution seems to be this function by Python luminary Fredrik Lundh. It is not the shortest solution, but it handles named entities as well as hex and decimal codes.
How to unescape apostrophes and such in Python?
I have a string with symbols like this: &#39; That's an apostrophe apparently. I tried saxutils.unescape() without any luck and tried urllib.unquote() How can I decode this? Thanks!
[ "Check out this question. What you're looking for is \"html entity decoding\". Typically, you'll find a function named something like \"htmldecode\" that will do what you want. Both Django and Cheetah provide such functions as does BeautifulSoup.\nThe other answer will work just great if you don't want to use a library and all the entities are numeric.\n", "Try this: (found it here)\nfrom htmlentitydefs import name2codepoint as n2cp\nimport re\n\ndef decode_htmlentities(string):\n \"\"\"\n Decode HTML entities–hex, decimal, or named–in a string\n @see http://snippets.dzone.com/posts/show/4569\n\n >>> u = u'E tu vivrai nel terrore - L&#x27;aldil&#xE0; (1981)'\n >>> print decode_htmlentities(u).encode('UTF-8')\n E tu vivrai nel terrore - L'aldilà (1981)\n >>> print decode_htmlentities(\"l&#39;eau\")\n l'eau\n >>> print decode_htmlentities(\"foo &lt; bar\") \n foo < bar\n \"\"\"\n def substitute_entity(match):\n ent = match.group(3)\n if match.group(1) == \"#\":\n # decoding by number\n if match.group(2) == '':\n # number is in decimal\n return unichr(int(ent))\n elif match.group(2) == 'x':\n # number is in hex\n return unichr(int('0x'+ent, 16))\n else:\n # they were using a name\n cp = n2cp.get(ent)\n if cp: return unichr(cp)\n else: return match.group()\n\n entity_re = re.compile(r'&(#?)(x?)(\\w+);')\n return entity_re.subn(substitute_entity, string)[0]\n\n", "The most robust solution seems to be this function by Python luminary Fredrik Lundh. It is not the shortest solution, but it handles named entities as well as hex and decimal codes.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "django", "html", "html_entities", "python" ]
stackoverflow_0000816272_django_html_html_entities_python.txt
Q: Does Python have properties? So something like: vector3.Length that's in fact a function call that calculates the length of the vector, not a variable. A: With new-style classes you can use property(): http://www.python.org/download/releases/2.2.3/descrintro/#property. A: Yes: http://docs.python.org/library/functions.html#property A: If your variable vector3 is a 3-dimensional directed distance of a point from an origin, and you need its length, use something like: import math vector3 = [5, 6, -7] print math.sqrt(vector3[0]**2 + vector3[1]**2 + vector3[2]**2) If you need a solution which works for any number of dimensions, do this: import math vector3 = [5, 6, -7] print math.sqrt(sum(c ** 2 for c in vector3)) You can define your own vector class with the Length property like this: import math class Vector3(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z @property def Length(self): return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) vector3 = Vector3(5, 6, -7) print vector3.Length A: Before the property() decorator came in, the idiom was using a no-parameter method for computed properties. This idiom is still often used in preference to the decorator, though that might be for consistency within a library that started before new-style classes. A: you can override some special methods to change how attributes are accesss, see the python documentation here or here Both these will slow down any attribute access to your class however, so in general using properties is probably best.
Does Python have properties?
So something like: vector3.Length that's in fact a function call that calculates the length of the vector, not a variable.
[ "With new-style classes you can use property(): http://www.python.org/download/releases/2.2.3/descrintro/#property.\n", "Yes: http://docs.python.org/library/functions.html#property\n", "If your variable vector3 is a 3-dimensional directed distance of a point from an origin, and you need its length, use something like:\nimport math\nvector3 = [5, 6, -7]\nprint math.sqrt(vector3[0]**2 + vector3[1]**2 + vector3[2]**2)\n\nIf you need a solution which works for any number of dimensions, do this:\nimport math\nvector3 = [5, 6, -7]\nprint math.sqrt(sum(c ** 2 for c in vector3))\n\nYou can define your own vector class with the Length property like this:\nimport math\nclass Vector3(object):\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n @property\n def Length(self):\n return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)\nvector3 = Vector3(5, 6, -7)\nprint vector3.Length\n\n", "Before the property() decorator came in, the idiom was using a no-parameter method for computed properties. This idiom is still often used in preference to the decorator, though that might be for consistency within a library that started before new-style classes.\n", "you can override some special methods to change how attributes are accesss,\nsee the python documentation here or here \nBoth these will slow down any attribute access to your class however, so in general using properties is probably best.\n" ]
[ 14, 6, 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000813135_python.txt
Q: If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste? Or should I be using a totally different server? A: Nginx with mod_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons. I usually go with the proxy route to a stand-alone Pylons process using the PasteScript#cherrypy WSGI server (as its higher performing than the Paste#http one, though it won't recycle threads if you have leaks...). If you're set on using Apache and its your server (so you can compile and run Apache mod_wsgi), I'd suggest using that setup as its less maintenance to effectively utilize multiple cores. With a proxy setup, you'd have to use the mod_proxy_balancer with multiple paste processes to effectively utilize multiple cores/cpus. If you're deploying to someone else's Apache (shared hosting), mod_proxy is generally the easier solution as its stock in Apache 2.2 and above. Personally, I usually deploy with nginx + proxy to multiple paster processes. A: I've also used mod_fastcgi + flup to great success several times now. There are a couple of recipes floating around for setting this up, but unfortunately it will probably still require some tweaking on your part to get everything working: http://wiki.pylonshq.com/display/pylonscookbook/Production+Deployment+Using+Apache,+FastCGI+and+mod_rewrite
If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste?
Or should I be using a totally different server?
[ "Nginx with mod_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons.\nI usually go with the proxy route to a stand-alone Pylons process using the PasteScript#cherrypy WSGI server (as its higher performing than the Paste#http one, though it won't recycle threads if you have leaks...).\nIf you're set on using Apache and its your server (so you can compile and run Apache mod_wsgi), I'd suggest using that setup as its less maintenance to effectively utilize multiple cores. With a proxy setup, you'd have to use the mod_proxy_balancer with multiple paste processes to effectively utilize multiple cores/cpus.\nIf you're deploying to someone else's Apache (shared hosting), mod_proxy is generally the easier solution as its stock in Apache 2.2 and above.\nPersonally, I usually deploy with nginx + proxy to multiple paster processes.\n", "I've also used mod_fastcgi + flup to great success several times now. There are a couple of recipes floating around for setting this up, but unfortunately it will probably still require some tweaking on your part to get everything working:\nhttp://wiki.pylonshq.com/display/pylonscookbook/Production+Deployment+Using+Apache,+FastCGI+and+mod_rewrite\n" ]
[ 8, 0 ]
[]
[]
[ "apache2", "mod_wsgi", "pylons", "python" ]
stackoverflow_0000813943_apache2_mod_wsgi_pylons_python.txt
Q: Overriding the save method in Django ModelForm I'm having trouble overriding a ModelForm save method. This is the error I'm receiving: Exception Type: TypeError Exception Value: save() got an unexpected keyword argument 'commit' My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields, and to save each of those objects. Helpful nudge in the right direction would be ace. File models.py class CallResultType(models.Model): id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True) callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id') campaign = models.ForeignKey('Campaign', db_column='icampaign_id') callType = models.ForeignKey('CallType', db_column='icall_type_id') agent = models.BooleanField(db_column='bagent', default=True) teamLeader = models.BooleanField(db_column='bTeamLeader', default=True) active = models.BooleanField(db_column='bactive', default=True) File forms.py from django.forms import ModelForm, ModelMultipleChoiceField from callresults.models import * class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, force_insert=False, force_update=False): for cr in self.callResult: for c in self.campain: for ct in self.callType: m = CallResultType(self) # this line is probably wrong m.callResult = cr m.campaign = c m.calltype = ct m.save() class Meta: model = CallResultType File admin.py class CallResultTypeAdmin(admin.ModelAdmin): form = CallResultTypeForm A: In your save you have to have the argument commit. If anything overrides your form, or wants to modify what it's saving, it will do save(commit=False), modify the output, and then save it itself. Also, your ModelForm should return the model it's saving. Usually a ModelForm's save will look something like: def save(self, commit=True): m = super(CallResultTypeForm, self).save(commit=False) # do custom stuff if commit: m.save() return m Read up on the save method. Finally, a lot of this ModelForm won't work just because of the way you are accessing things. Instead of self.callResult, you need to use self.fields['callResult']. UPDATE: In response to your answer: Aside: Why not just use ManyToManyFields in the Model so you don't have to do this? Seems like you're storing redundant data and making more work for yourself (and me :P). from django.db.models import AutoField def copy_model_instance(obj): """ Create a copy of a model instance. M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case) See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/ """ initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()]) return obj.__class__(**initial) class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, commit=True, *args, **kwargs): m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs) results = [] for cr in self.callResult: for c in self.campain: for ct in self.callType: m_new = copy_model_instance(m) m_new.callResult = cr m_new.campaign = c m_new.calltype = ct if commit: m_new.save() results.append(m_new) return results This allows for inheritance of CallResultTypeForm, just in case that's ever necessary.
Overriding the save method in Django ModelForm
I'm having trouble overriding a ModelForm save method. This is the error I'm receiving: Exception Type: TypeError Exception Value: save() got an unexpected keyword argument 'commit' My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields, and to save each of those objects. Helpful nudge in the right direction would be ace. File models.py class CallResultType(models.Model): id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True) callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id') campaign = models.ForeignKey('Campaign', db_column='icampaign_id') callType = models.ForeignKey('CallType', db_column='icall_type_id') agent = models.BooleanField(db_column='bagent', default=True) teamLeader = models.BooleanField(db_column='bTeamLeader', default=True) active = models.BooleanField(db_column='bactive', default=True) File forms.py from django.forms import ModelForm, ModelMultipleChoiceField from callresults.models import * class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, force_insert=False, force_update=False): for cr in self.callResult: for c in self.campain: for ct in self.callType: m = CallResultType(self) # this line is probably wrong m.callResult = cr m.campaign = c m.calltype = ct m.save() class Meta: model = CallResultType File admin.py class CallResultTypeAdmin(admin.ModelAdmin): form = CallResultTypeForm
[ "In your save you have to have the argument commit. If anything overrides your form, or wants to modify what it's saving, it will do save(commit=False), modify the output, and then save it itself.\nAlso, your ModelForm should return the model it's saving. Usually a ModelForm's save will look something like:\ndef save(self, commit=True):\n m = super(CallResultTypeForm, self).save(commit=False)\n # do custom stuff\n if commit:\n m.save()\n return m\n\nRead up on the save method.\nFinally, a lot of this ModelForm won't work just because of the way you are accessing things. Instead of self.callResult, you need to use self.fields['callResult'].\nUPDATE: In response to your answer:\nAside: Why not just use ManyToManyFields in the Model so you don't have to do this? Seems like you're storing redundant data and making more work for yourself (and me :P).\nfrom django.db.models import AutoField \ndef copy_model_instance(obj): \n \"\"\"\n Create a copy of a model instance. \n M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case)\n See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/\n \"\"\" \n initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()]) \n return obj.__class__(**initial) \n\nclass CallResultTypeForm(ModelForm):\n callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())\n campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())\n callType = ModelMultipleChoiceField(queryset=CallType.objects.all())\n\n def save(self, commit=True, *args, **kwargs):\n m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs)\n results = []\n for cr in self.callResult:\n for c in self.campain:\n for ct in self.callType:\n m_new = copy_model_instance(m)\n m_new.callResult = cr\n m_new.campaign = c\n m_new.calltype = ct\n if commit:\n m_new.save()\n results.append(m_new)\n return results\n\nThis allows for inheritance of CallResultTypeForm, just in case that's ever necessary.\n" ]
[ 167 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0000817284_django_django_admin_django_forms_python.txt
Q: Python/Twisted - TCP packet fragmentation? In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a length header? Or do I have to do this manually? If so, what way would that be? A: In the dataReceived method you get back the data as a string of indeterminate length meaning that it may be a whole message in your protocol or it may only be part of the message that some 'client' sent to you. You will have to inspect the data to see if it comprises a whole message in your protocol. I'm currently using Twisted on one of my projects to implement a protocol and decided to use the struct module to pack/unpack my data. The protocol I am implementing has a fixed header size so I don't construct any messages until I've read at least HEADER_SIZE amount of bytes. The total message size is declared in this header data portion. I guess you don't really need to define a message length as part of your protocol but it helps. If you didn't define one you would have to have a special delimiter that determines when a message begins/ends. Sort of how the FIX protocol uses the SOH byte to delimit fields. Though it does have a required field that tells you how long a message is (just not how many fields are in a message). A: When dealing with TCP, you should really forget all notion of 'packets'. TCP is a stream protocol - you stream data in and data streams out the other side. Once the data is sent, it is allowed to arrive in as many or as few blocks as it wants, as long as the data all arrives in the right order. You'll have to manually do the delimitation as with other languages, with a length field, or a message type field, or a special delimiter character, etc. A: You can also use a LineReceiver protocol
Python/Twisted - TCP packet fragmentation?
In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a length header? Or do I have to do this manually? If so, what way would that be?
[ "In the dataReceived method you get back the data as a string of indeterminate length meaning that it may be a whole message in your protocol or it may only be part of the message that some 'client' sent to you. You will have to inspect the data to see if it comprises a whole message in your protocol.\nI'm currently using Twisted on one of my projects to implement a protocol and decided to use the struct module to pack/unpack my data. The protocol I am implementing has a fixed header size so I don't construct any messages until I've read at least HEADER_SIZE amount of bytes. The total message size is declared in this header data portion.\nI guess you don't really need to define a message length as part of your protocol but it helps. If you didn't define one you would have to have a special delimiter that determines when a message begins/ends. Sort of how the FIX protocol uses the SOH byte to delimit fields. Though it does have a required field that tells you how long a message is (just not how many fields are in a message).\n", "When dealing with TCP, you should really forget all notion of 'packets'. TCP is a stream protocol - you stream data in and data streams out the other side. Once the data is sent, it is allowed to arrive in as many or as few blocks as it wants, as long as the data all arrives in the right order. You'll have to manually do the delimitation as with other languages, with a length field, or a message type field, or a special delimiter character, etc.\n", "You can also use a LineReceiver protocol\n" ]
[ 6, 6, 2 ]
[]
[]
[ "packet", "python", "tcp", "twisted" ]
stackoverflow_0000460144_packet_python_tcp_twisted.txt
Q: Update Facebooks Status using Python Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ? A: Check out PyFacebook which has a tutorial, from... Facebook! Blatantly ripped from the documentation on that page and untested, you'd probably do something like this: import facebook fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY') fb.auth.createToken() fb.login() fb.auth.getSession() fb.set_status('Checking out StackOverFlow.com') A: The Facebook Developers site for Python is a great place to start. You should be able to accomplish this with a REST call. http://wiki.developers.facebook.com/index.php/Python
Update Facebooks Status using Python
Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?
[ "Check out PyFacebook which has a tutorial, from... Facebook!\nBlatantly ripped from the documentation on that page and untested, you'd probably do something like this:\nimport facebook\nfb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')\nfb.auth.createToken()\nfb.login()\nfb.auth.getSession()\nfb.set_status('Checking out StackOverFlow.com')\n\n", "The Facebook Developers site for Python is a great place to start. You should be able to accomplish this with a REST call.\nhttp://wiki.developers.facebook.com/index.php/Python\n" ]
[ 12, 3 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0000817431_facebook_python.txt
Q: What's a good way to mix RSS feeds using Python? SimplePie lets you merge feeds together: http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together. A: This may be a good start for you. I wrote it a long time ago for one very specific combination, but I don't think I wrote it too specifically for my needs. A:  Planet is a feed aggregator written in Python. Its development is basically dead, but the code lives on in several forks, including Planet Venus. A: Atomisator is a data aggregator framework. Its purpose is to provide an engine to build any kind of data by merging several sources of data. It was developed as an example application in the book Expert Python Programming. You can use different In- and Output Formats. An RSS aggregartor is part of the examples. A: I'm using Yahoo pipes for that task. It's a set a very powerful tools. I havo pipes join feeds based on certain criteria, and have it generate a compliant rss feed that i then process with universal feed parser.
What's a good way to mix RSS feeds using Python?
SimplePie lets you merge feeds together: http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.
[ "This may be a good start for you. I wrote it a long time ago for one very specific combination, but I don't think I wrote it too specifically for my needs.\n", " Planet is a feed aggregator written in Python. Its development is basically dead, but the code lives on in several forks, including Planet Venus.\n", "Atomisator is a data aggregator framework. Its purpose is to provide an engine to build any kind of data by merging several sources of data. It was developed as an example application in the book Expert Python Programming. You can use different In- and Output Formats. An RSS aggregartor is part of the examples.\n", "I'm using Yahoo pipes for that task. It's a set a very powerful tools. I havo pipes join feeds based on certain criteria, and have it generate a compliant rss feed that i then process with universal feed parser.\n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "django", "feed", "parsing", "python", "rss" ]
stackoverflow_0000816118_django_feed_parsing_python_rss.txt
Q: Python's random: What happens if I don't use seed(someValue)? a)In this case does the random number generator uses the system's clock (making the seed change) on each run? b)Is the seed used to generate the pseudo-random values of expovariate(lambda)? A: "Use the Source, Luke!"...;-). Studying https://svn.python.org/projects/python/trunk/Lib/random.py will rapidly reassure you;-). What happens when seed isn't set (that's the "i is None" case): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds and the expovariate: random = self.random u = random() while u <= 1e-7: u = random() return -_log(u)/lambd obviously uses the same underlying random generator as every other method, and so is identically affected by the seeding or lack thereof (really, how else would it have been done?-) A: a) It typically uses the system clock, the clock on some systems may only have ms precision and so seed twice very quickly may result in the same value. seed(self, a=None) Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. http://pydoc.org/2.5.1/random.html#Random-seed b) I would imagine expovariate does, but I can't find any proof. It would be silly if it didn't. A: current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability). Random Docs
Python's random: What happens if I don't use seed(someValue)?
a)In this case does the random number generator uses the system's clock (making the seed change) on each run? b)Is the seed used to generate the pseudo-random values of expovariate(lambda)?
[ "\"Use the Source, Luke!\"...;-). Studying https://svn.python.org/projects/python/trunk/Lib/random.py will rapidly reassure you;-).\nWhat happens when seed isn't set (that's the \"i is None\" case):\nif a is None:\n try:\n a = long(_hexlify(_urandom(16)), 16)\n except NotImplementedError:\n import time\n a = long(time.time() * 256) # use fractional seconds\n\nand the expovariate:\nrandom = self.random\nu = random()\nwhile u <= 1e-7:\n u = random()\nreturn -_log(u)/lambd\n\nobviously uses the same underlying random generator as every other method, and so is identically affected by the seeding or lack thereof (really, how else would it have been done?-)\n", "a) It typically uses the system clock, the clock on some systems may only have ms precision and so seed twice very quickly may result in the same value.\n\nseed(self, a=None)\n Initialize internal state from hashable object.\nNone or no argument seeds from current time or from an operating\nsystem specific randomness source if available.\n\nhttp://pydoc.org/2.5.1/random.html#Random-seed\n\nb) I would imagine expovariate does, but I can't find any proof. It would be silly if it didn't.\n", "\ncurrent system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).\n\nRandom Docs\n" ]
[ 18, 6, 3 ]
[]
[]
[ "python", "random", "seed" ]
stackoverflow_0000817705_python_random_seed.txt
Q: Dynamically change range in Python? So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query. The pagination looks like 1 2 3 4 5 6 7 Next If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like 1 2 3 7 8 9 10 Next So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get_num_pages returns 7 What I am doing is iterating over items on each page so I have something like for page in range(1,num_pages + 1): # do some stuff here Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this. A: You could probably çreate a generator that has mutable state that determines when it terminates... but what about something simple like this? page = 1 while page < num_pages + 1: # do stuff that possibly updates num_pages here page += 1 A: Here's a code free answer, but I think it's simple if you take advantage of what beautiful soup lets you do: To start with, on the first page you have somewhere the page numbers & links; from your question they look like this: 1 2 3 4 5 6 7 [next] Different sites handle paging differently, some give a link to jump to beginning/end, but on yours you say it looks like this after the first 7 pages: 1 2 3 ... 7 8 9 10 [next] Now, at some point, you will get to the end, it's going to look like this: 1 2 3 ... 20 21 22 23 Notice there's no [next] link. So forget about generators and ranges and keeping track of intermediate ranges, etc. Just do this: use beautiful soup to identify the page # links on a given page, along with the next button. Every time you see a [next] link, follow it and reparse with beautiful soup When you hit a page where there is no next link, the last # page link is the total number of pages. A: I like John's while-based solution, but to use a for you could do something like: pages = range(1, num_pages+1) for p in pages: ...possibly pages.extend(range(something, something)) here... that is, you have to give a name to the range you're looping on, so you can extend it when needed. Changing the container you're iterating on is normally frowned upon, but in this specific and highly-constrained case it can actually be a useful idiom.
Dynamically change range in Python?
So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query. The pagination looks like 1 2 3 4 5 6 7 Next If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like 1 2 3 7 8 9 10 Next So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get_num_pages returns 7 What I am doing is iterating over items on each page so I have something like for page in range(1,num_pages + 1): # do some stuff here Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this.
[ "You could probably çreate a generator that has mutable state that determines when it terminates... but what about something simple like this?\npage = 1\nwhile page < num_pages + 1:\n # do stuff that possibly updates num_pages here\n page += 1\n\n", "Here's a code free answer, but I think it's simple if you take advantage of what beautiful soup lets you do:\nTo start with, on the first page you have somewhere the page numbers & links; from your question they look like this:\n1 2 3 4 5 6 7 [next]\n\nDifferent sites handle paging differently, some give a link to jump to beginning/end, but on yours you say it looks like this after the first 7 pages:\n1 2 3 ... 7 8 9 10 [next]\n\nNow, at some point, you will get to the end, it's going to look like this:\n1 2 3 ... 20 21 22 23\n\nNotice there's no [next] link.\nSo forget about generators and ranges and keeping track of intermediate ranges, etc. Just do this:\n\nuse beautiful soup to identify the page # links on a given page, along with the next button.\nEvery time you see a [next] link, follow it and reparse with beautiful soup\nWhen you hit a page where there is no next link, the last # page link is the total number of pages.\n\n", "I like John's while-based solution, but to use a for you could do something like:\npages = range(1, num_pages+1)\nfor p in pages:\n ...possibly pages.extend(range(something, something)) here...\n\nthat is, you have to give a name to the range you're looping on, so you can extend it when needed. Changing the container you're iterating on is normally frowned upon, but in this specific and highly-constrained case it can actually be a useful idiom.\n" ]
[ 6, 3, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0000816712_beautifulsoup_python.txt
Q: callable as instancemethod? Let's say we've got a metaclass CallableWrappingMeta which walks the body of a new class, wrapping its methods with a class, InstanceMethodWrapper: import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though InstanceMethodWrapper is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it). A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, InstanceMethodWrapper is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much). I also tried some dead-ends. Subclassing types.MethodType and types.UnboundMethodType didn't go anywhere. A little introspection, and it appears they decend from type. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point. Any ideas? A: Just enrich you InstanceMethodWrapper class with a __get__ (which can perfectly well just return self) -- that is, make that class into a descriptor type, so that its instances are descriptor objects. See http://users.rcn.com/python/download/Descriptor.htm for background and details. BTW, if you're on Python 2.6 or better, consider using a class-decorator instead of that metaclass -- we added class decorators exactly because so many metaclasses were being used just for such decoration purposes, and decorators are really much simpler to use. A: Edit: I lie yet again. The __?attr__ attributes on functions are readonly, but apparently do not always throw an AttributeException exception when you assign? I dunno. Back to square one! Edit: This doesn't actually solve the problem, as the wrapping function won't proxy attribute requests to the InstanceMethodWrapper. I could, of course, duck-punch the __?attr__ attributes in the decorator--and it is what I'm doing now--but that's ugly. Better ideas are very welcome. Of course, I immediately realized that combining a simple decorator with our classes will do the trick: def methodize(method, callable): "Circumvents the fact that callables are not converted to instance methods." @wraps(method) def wrapper(*args, **kw): return wrapper._callable(*args, **kw) wrapper._callable = callable return wrapper Then you add the decorator to the call to InstanceMethodWrapper in the metaclass: cls_dict[k] = methodize(v, InstanceMethodWrapper(v)) Poof. A little oblique, but it works. A: I'm guessing you are trying to make a metaclass that wraps every method in the class with a custom function. Here is my version which I think is a little bit less oblique. import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): instance = type.__new__(mcls, name, bases, cls_dict) for k in dir(instance): v = getattr(instance, k) if isinstance(v, types.MethodType): setattr(instance, k, instanceMethodWrapper(v)) return instance def instanceMethodWrapper(function): def customfunc(*args, **kw): print "instanceMethodWrapper(*%r, **%r )" % (args, kw) return function(*args, **kw) return customfunc class Bar(object): __metaclass__ = CallableWrappingMeta def method(self, a, b): print a,b a = Bar() a.method("foo","bar") A: I think you need to be more specific about your problem. The original question talks about wrapping a function, but your subsequent answer seems to talk about preserving function attributes, which seems to be a new factor. If you spelled out your design goals more clearly, it might be easier to answer your question.
callable as instancemethod?
Let's say we've got a metaclass CallableWrappingMeta which walks the body of a new class, wrapping its methods with a class, InstanceMethodWrapper: import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though InstanceMethodWrapper is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it). A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, InstanceMethodWrapper is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much). I also tried some dead-ends. Subclassing types.MethodType and types.UnboundMethodType didn't go anywhere. A little introspection, and it appears they decend from type. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point. Any ideas?
[ "Just enrich you InstanceMethodWrapper class with a __get__ (which can perfectly well just return self) -- that is, make that class into a descriptor type, so that its instances are descriptor objects. See http://users.rcn.com/python/download/Descriptor.htm for background and details.\nBTW, if you're on Python 2.6 or better, consider using a class-decorator instead of that metaclass -- we added class decorators exactly because so many metaclasses were being used just for such decoration purposes, and decorators are really much simpler to use.\n", "Edit: I lie yet again. The __?attr__ attributes on functions are readonly, but apparently do not always throw an AttributeException exception when you assign? I dunno. Back to square one!\nEdit: This doesn't actually solve the problem, as the wrapping function won't proxy attribute requests to the InstanceMethodWrapper. I could, of course, duck-punch the __?attr__ attributes in the decorator--and it is what I'm doing now--but that's ugly. Better ideas are very welcome.\n\nOf course, I immediately realized that combining a simple decorator with our classes will do the trick:\ndef methodize(method, callable):\n \"Circumvents the fact that callables are not converted to instance methods.\"\n @wraps(method)\n def wrapper(*args, **kw):\n return wrapper._callable(*args, **kw)\n wrapper._callable = callable\n return wrapper\n\nThen you add the decorator to the call to InstanceMethodWrapper in the metaclass:\ncls_dict[k] = methodize(v, InstanceMethodWrapper(v))\n\nPoof. A little oblique, but it works.\n", "I'm guessing you are trying to make a metaclass that wraps every method in the class with a custom function.\nHere is my version which I think is a little bit less oblique.\nimport types\n\nclass CallableWrappingMeta(type):\n def __new__(mcls, name, bases, cls_dict):\n instance = type.__new__(mcls, name, bases, cls_dict)\n for k in dir(instance):\n v = getattr(instance, k)\n if isinstance(v, types.MethodType):\n setattr(instance, k, instanceMethodWrapper(v))\n\n return instance\n\ndef instanceMethodWrapper(function):\n def customfunc(*args, **kw):\n print \"instanceMethodWrapper(*%r, **%r )\" % (args, kw)\n return function(*args, **kw)\n return customfunc\n\nclass Bar(object):\n __metaclass__ = CallableWrappingMeta\n\n def method(self, a, b):\n print a,b\n\na = Bar()\na.method(\"foo\",\"bar\")\n\n", "I think you need to be more specific about your problem. The original question talks about wrapping a function, but your subsequent answer seems to talk about preserving function attributes, which seems to be a new factor. If you spelled out your design goals more clearly, it might be easier to answer your question.\n" ]
[ 4, 0, 0, 0 ]
[]
[]
[ "metaclass", "methods", "python", "python_descriptors" ]
stackoverflow_0000815947_metaclass_methods_python_python_descriptors.txt
Q: C55: More Info? I saw a PyCon09 keynote presentation (slides: http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55) given by the reddit guys, and in it they mention a CSS compiler called C55. They said it would be open sourced soon. It looks cool - does anyone have more information about how it works, why they created it (aside from the fact that CSS is a pain), etc...? A: Just from the talk, the main advantage over simply generating CSS from templates is that it allows nesting, which is conceptually a lot nicer to work with. So you could do something like this in C55 (obviously I'm kind of making up the syntax): div.content { color: $content_color ; .left { float: left; }; .right { float: right; }; };
C55: More Info?
I saw a PyCon09 keynote presentation (slides: http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55) given by the reddit guys, and in it they mention a CSS compiler called C55. They said it would be open sourced soon. It looks cool - does anyone have more information about how it works, why they created it (aside from the fact that CSS is a pain), etc...?
[ "Just from the talk, the main advantage over simply generating CSS from templates is that it allows nesting, which is conceptually a lot nicer to work with.\nSo you could do something like this in C55 (obviously I'm kind of making up the syntax):\ndiv.content\n{\n color: $content_color ;\n\n .left\n {\n float: left;\n };\n .right\n {\n float: right;\n };\n};\n\n" ]
[ 3 ]
[]
[]
[ "css", "python", "reddit" ]
stackoverflow_0000818016_css_python_reddit.txt
Q: In what way would you present an algorithm to detect collisions between different objects? While working on a really only-for-fun project I encountered some problem. There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens. The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now: For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'. Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple. More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have Some kind of generic way to say if Object A collides with Object B. The code as it is now looks somewhat like: class WorldCreature: def detectCollision(self, otherObject): # do something if collision: self.onCollision(otherObject) otherObject.onCollision(self) class Ball(WorldCreature): # someing here class Line(WorldCreature): # someing here Now, the collision detection mechanizm should depend on what objects can collide. So will the effect. Should I just keep a list of all the objects in memory and loop through all them in every single step? Or, is there some better way to improve the performance of this task? A: Use a quadtree. They're used to eliminate large regions that you know are outside a collision radius, plus they let you quickly search for the closest point. As far as actual collision detection goes, since you're only using convex objects, take a look at Metanet Software's tutorial on the separating axis theorem. In their flagship game, they actually use a grid to find all the objects to check for collision against, but it shouldn't be too hard to use a quadtree instead. (I remember reading an article on quadtrees that used circles in a grid to illustrate how you can find the points within a radius. I can't seem to find it though.) A: The answer to this depends on a number of factors, such as how many objects there are, how many are moving vs. non-moving, how fast they move, etc. I think that the right place to start is by getting the core collision detection and behavior code correct while ignoring the optimizations you might do to prune collision checks, etc. Once the core code is correct, you can start running experiments to see what will perform well for you. I would recommend some kind of spatial subdivision technique, such as kd-trees (although in 2d, you may as well use quadtrees). Fundamentally, though, there's probably no single right answer, except what you are able to determine by coding up your game and experimenting with it. A: Python. Kinda strange beast for me 8) I have c++ experience creating games -- so I talk from this point of view. First of all (you can skip this if you have low number of objects) you need broad-phase collision detection. Already mentioned quadtree is just one possible implementation. Broad-phase is needed to find pairs of possibly colliding objects. Then goes the narrow phase -- when pairs are checked. I used the following scheme (note -- this was created with primitives in mind, if you need polyhedra collisions -- just use GJK and spheres, plus rays,segments): Everything that needs collisions have CollisionObject which handles transform and store CollisionPrimitive (box, sphere etc) Each CollisionPrimitive has type_id -- when you write A_B_CheckIntersection -- the first object always have lower type_id For each Pair in the list that you get from broad phase -- you swap objects if needed and index an array where pointers to specific collision functions are stored. Sure -- for that you should have them have identical interfaces (c++) but it is easy 8) As for specific collision routines: visit http://realtimerendering.com/intersections.html It is good place to start A: I think Hough Transform should help somehow.
In what way would you present an algorithm to detect collisions between different objects?
While working on a really only-for-fun project I encountered some problem. There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens. The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now: For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'. Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple. More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have Some kind of generic way to say if Object A collides with Object B. The code as it is now looks somewhat like: class WorldCreature: def detectCollision(self, otherObject): # do something if collision: self.onCollision(otherObject) otherObject.onCollision(self) class Ball(WorldCreature): # someing here class Line(WorldCreature): # someing here Now, the collision detection mechanizm should depend on what objects can collide. So will the effect. Should I just keep a list of all the objects in memory and loop through all them in every single step? Or, is there some better way to improve the performance of this task?
[ "Use a quadtree. They're used to eliminate large regions that you know are outside a collision radius, plus they let you quickly search for the closest point.\nAs far as actual collision detection goes, since you're only using convex objects, take a look at Metanet Software's tutorial on the separating axis theorem. In their flagship game, they actually use a grid to find all the objects to check for collision against, but it shouldn't be too hard to use a quadtree instead.\n(I remember reading an article on quadtrees that used circles in a grid to illustrate how you can find the points within a radius. I can't seem to find it though.)\n", "The answer to this depends on a number of factors, such as how many objects there are, how many are moving vs. non-moving, how fast they move, etc. I think that the right place to start is by getting the core collision detection and behavior code correct while ignoring the optimizations you might do to prune collision checks, etc.\nOnce the core code is correct, you can start running experiments to see what will perform well for you. I would recommend some kind of spatial subdivision technique, such as kd-trees (although in 2d, you may as well use quadtrees). \nFundamentally, though, there's probably no single right answer, except what you are able to determine by coding up your game and experimenting with it.\n", "Python. Kinda strange beast for me 8)\nI have c++ experience creating games -- so I talk from this point of view.\nFirst of all (you can skip this if you have low number of objects) you need broad-phase collision detection. Already mentioned quadtree is just one possible implementation.\nBroad-phase is needed to find pairs of possibly colliding objects.\nThen goes the narrow phase -- when pairs are checked.\nI used the following scheme (note -- this was created with primitives in mind, if you need polyhedra collisions -- just use GJK and spheres, plus rays,segments):\nEverything that needs collisions have CollisionObject which handles transform and store CollisionPrimitive (box, sphere etc)\nEach CollisionPrimitive has type_id -- when you write A_B_CheckIntersection -- the first object always have lower type_id\nFor each Pair in the list that you get from broad phase -- you swap objects if needed and index an array where pointers to specific collision functions are stored.\nSure -- for that you should have them have identical interfaces (c++) but it is easy 8)\nAs for specific collision routines: visit http://realtimerendering.com/intersections.html \nIt is good place to start\n", "I think Hough Transform should help somehow.\n" ]
[ 5, 1, 1, 0 ]
[]
[]
[ "collision_detection", "python" ]
stackoverflow_0000646539_collision_detection_python.txt
Q: Shouldn't __metaclass__ force the use of a metaclass in Python? I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the global or class level. To test this out, I wrote the following program: p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta: __metaclass__ = M p(2) __metaclass__ = M class GlobalMeta: pass p(3) M('NotMeta2', (), {}) p(4) However, when I run it, I get the following output: C:\Documents and Settings\Daniel Wong\Desktop>python --version Python 3.0.1 C:\Documents and Settings\Daniel Wong\Desktop>python meta.py 1 2 3 The rain in Spain 4 Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here? A: In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition: class ClassMeta(metaclass=M): pass Specifying a __metaclass__ class property or global variable is old syntax from Python 2.x and not longer supported. See also "What's new in Python 3" and PEP 2115. A: This works as you expect in Python 2.6 (and earlier), but in 3.0 metaclasses are specified differently: class ArgMeta(metaclass=M): ... A: The syntax of metaclasses has changed in Python 3.0. The __metaclass__ attribute is no longer special at either the class nor the module level. To do what you're trying to do, you need to specify metaclass as a keyword argument to the class statement: p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta(metaclass=M): pass Yields: 1 The rain in Spain As you'd expect.
Shouldn't __metaclass__ force the use of a metaclass in Python?
I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting __metaclass__ to M at the global or class level. To test this out, I wrote the following program: p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta: __metaclass__ = M p(2) __metaclass__ = M class GlobalMeta: pass p(3) M('NotMeta2', (), {}) p(4) However, when I run it, I get the following output: C:\Documents and Settings\Daniel Wong\Desktop>python --version Python 3.0.1 C:\Documents and Settings\Daniel Wong\Desktop>python meta.py 1 2 3 The rain in Spain 4 Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here?
[ "In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition:\nclass ClassMeta(metaclass=M):\n pass\n\nSpecifying a __metaclass__ class property or global variable is old syntax from Python 2.x and not longer supported. See also \"What's new in Python 3\" and PEP 2115.\n", "This works as you expect in Python 2.6 (and earlier), but in 3.0 metaclasses are specified differently:\nclass ArgMeta(metaclass=M): ...\n\n", "The syntax of metaclasses has changed in Python 3.0. The __metaclass__ attribute is no longer special at either the class nor the module level. To do what you're trying to do, you need to specify metaclass as a keyword argument to the class statement:\np = print\n\nclass M(type):\n def __init__(*args):\n type.__init__(*args)\n print(\"The rain in Spain\")\n\np(1)\nclass ClassMeta(metaclass=M): pass\n\nYields:\n1\nThe rain in Spain\n\nAs you'd expect.\n" ]
[ 14, 2, 2 ]
[]
[]
[ "metaclass", "oop", "python", "python_3.x" ]
stackoverflow_0000818483_metaclass_oop_python_python_3.x.txt
Q: Web-Based Music Library (programming concept) So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows: Does this sound like a good project to begin building databases from scratch with? What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language. If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see? My idea for building up the indexing script would be as follows: Get it to populate the database with only the filenames From the extension of the filename, determine format Get file size Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc) Check if all files still exist on disk, and if not, flag the file as unavailable Another script would go in later and check if the files are back, if they are not, the will remove the row from the database. A: I think this is a fine project to learn programming with. By using your own "product" you can really get after things that are missing and are much more motivated to learn and better your program - this is known as dogfooding. Curiously enough, the book Dive Into Python, although a little old, covers in some detail how to extract the ID3 information of music files using Python. Since that's the book most often recommended for beginners, I bet that'd be as good a place to start as any. A: Working on something you care about is the best way to learn programming, so I think this is a great idea. I also recommend Python as a place to start. Have fun! A: If you use Python, you could build it with the Google App Engine. It gives you a very nice database interface, and the tutorial will take you from 'Hello world!' to a functioning web app. You don't even need to upload the result to Google; you can just run it in the dev environment and it will be accessible within your home network. A: I think python would be excellent choice as easy to learn but have advanced features too good web frameworks available e.g. django which you can run on your machine Word class Free python hosting available i.e. google app engine Libraries available for almost anything imaginable e.g. for reading your mp3 tags you can use http://id3-py.sourceforge.net/ for searching you can use pylucene http://lucene.apache.org/pylucene/ the best search engine available.
Web-Based Music Library (programming concept)
So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows: Does this sound like a good project to begin building databases from scratch with? What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language. If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see? My idea for building up the indexing script would be as follows: Get it to populate the database with only the filenames From the extension of the filename, determine format Get file size Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc) Check if all files still exist on disk, and if not, flag the file as unavailable Another script would go in later and check if the files are back, if they are not, the will remove the row from the database.
[ "I think this is a fine project to learn programming with. By using your own \"product\" you can really get after things that are missing and are much more motivated to learn and better your program - this is known as dogfooding. Curiously enough, the book Dive Into Python, although a little old, covers in some detail how to extract the ID3 information of music files using Python. Since that's the book most often recommended for beginners, I bet that'd be as good a place to start as any.\n", "Working on something you care about is the best way to learn programming, so I think this is a great idea.\nI also recommend Python as a place to start. Have fun!\n", "If you use Python, you could build it with the Google App Engine. It gives you a very nice database interface, and the tutorial will take you from 'Hello world!' to a functioning web app.\nYou don't even need to upload the result to Google; you can just run it in the dev environment and it will be accessible within your home network.\n", "I think python would be excellent choice as \n\neasy to learn but have advanced features too\ngood web frameworks available e.g. django which you can run on your machine\nWord class Free python hosting available i.e. google app engine\nLibraries available for almost anything imaginable e.g. for reading your mp3 tags you can use http://id3-py.sourceforge.net/\nfor searching you can use pylucene http://lucene.apache.org/pylucene/\nthe best search engine available.\n\n" ]
[ 3, 1, 1, 1 ]
[]
[]
[ "mysql", "php", "python" ]
stackoverflow_0000818752_mysql_php_python.txt
Q: Spliting a file into lines in Python using re.split I'm trying to split a file with a list comprehension using code similar to: lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)? A: Put the regular expression hammer away :-) You can iterate over a file directly; readlines() is almost obsolete these days. Read about str.strip() (and its friends, lstrip() and rstrip()). Don't use file as a variable name. It's bad form, because file is a built-in function. You can write your code as: lines = [] f = open(filename) for line in f: if not line.startswith('com'): lines.append(line.strip()) If you are still getting blank lines in there, you can add in a test: lines = [] f = open(filename) for line in f: if line.strip() and not line.startswith('com'): lines.append(line.strip()) If you really want it in one line: lines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')] Finally, if you're on python 2.6, look at the with statement to improve things a little more. A: lines = file.readlines() edit: or if you didnt want blank lines in there, you can do lines = filter(lambda a:(a!='\n'), file.readlines()) edit^2: to remove trailing newines, you can do lines = [re.sub('\n','',line) for line in filter(lambda a:(a!='\n'), file.readlines())] A: another handy trick, especially when you need the line number, is to use enumerate: fp = open("myfile.txt", "r") for n, line in enumerate(fp.readlines()): dosomethingwith(n, line) i only found out about enumerate quite recently but it has come in handy quite a few times since then. A: This should work, and eliminate the regular expressions as well: all_lines = (line.rstrip() for line in open(filename) if "com" not in line) # filter out the empty lines lines = filter(lambda x : x, all_lines) Since you're using a list comprehension and not a generator expression (so the whole file gets loaded into memory anyway), here's a shortcut that avoids code to filter out empty lines: lines = [line for line in open(filename).read().splitlines() if "com" not in line]
Spliting a file into lines in Python using re.split
I'm trying to split a file with a list comprehension using code similar to: lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?
[ "Put the regular expression hammer away :-)\n\nYou can iterate over a file directly; readlines() is almost obsolete these days.\nRead about str.strip() (and its friends, lstrip() and rstrip()).\nDon't use file as a variable name. It's bad form, because file is a built-in function.\n\nYou can write your code as:\nlines = []\nf = open(filename)\nfor line in f:\n if not line.startswith('com'):\n lines.append(line.strip())\n\nIf you are still getting blank lines in there, you can add in a test:\nlines = []\nf = open(filename)\nfor line in f:\n if line.strip() and not line.startswith('com'):\n lines.append(line.strip())\n\nIf you really want it in one line:\nlines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')]\n\nFinally, if you're on python 2.6, look at the with statement to improve things a little more.\n", "lines = file.readlines()\nedit:\nor if you didnt want blank lines in there, you can do\nlines = filter(lambda a:(a!='\\n'), file.readlines()) \nedit^2:\nto remove trailing newines, you can do \nlines = [re.sub('\\n','',line) for line in filter(lambda a:(a!='\\n'), file.readlines())]\n", "another handy trick, especially when you need the line number, is to use enumerate:\n\nfp = open(\"myfile.txt\", \"r\")\nfor n, line in enumerate(fp.readlines()):\n dosomethingwith(n, line)\n\ni only found out about enumerate quite recently but it has come in handy quite a few times since then.\n", "This should work, and eliminate the regular expressions as well:\nall_lines = (line.rstrip()\n for line in open(filename)\n if \"com\" not in line)\n# filter out the empty lines\nlines = filter(lambda x : x, all_lines)\n\nSince you're using a list comprehension and not a generator expression (so the whole file gets loaded into memory anyway), here's a shortcut that avoids code to filter out empty lines:\nlines = [line\n for line in open(filename).read().splitlines()\n if \"com\" not in line]\n\n" ]
[ 9, 3, 1, 0 ]
[]
[]
[ "list_comprehension", "python", "regex" ]
stackoverflow_0000818705_list_comprehension_python_regex.txt
Q: Creating dictionaries with pre-defined keys In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created? A: You can also have the dict subclass restrict the keys to a predefined list, by overriding __setitem__() >>> class LimitedDict(dict): _keys = "a b c".split() def __init__(self, valtype=int): for key in LimitedDict._keys: self[key] = valtype() def __setitem__(self, key, val): if key not in LimitedDict._keys: raise KeyError dict.__setitem__(self, key, val) >>> limited = LimitedDict() >>> limited['a'] 0 >>> limited['a'] = 3 >>> limited['a'] 3 >>> limited['z'] = 0 Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> limited['z'] = 0 File "<pyshell#56>", line 8, in __setitem__ raise KeyError KeyError >>> len(limited) 3 A: You can easily extend any built in type. This is how you'd do it with a dict: >>> class MyClass(dict): ... def __init__(self, *args, **kwargs): ... self['mykey'] = 'myvalue' ... self['mykey2'] = 'myvalue2' ... >>> x = MyClass() >>> x['mykey'] 'myvalue' >>> x {'mykey2': 'myvalue2', 'mykey': 'myvalue'} I wasn't able to find the Python documentation that talks about this, but the very popular book Dive Into Python (available for free online) has a few examples on doing this. A: Yes, in Python dict is a class , so you can subclass it: class SubDict(dict): def __init__(self): dict.__init__(self) self.update({ 'foo': 'bar', 'baz': 'spam',}) Here you override dict's __init__() method (a method which is called when an instance of the class is created). Inside __init__ you first call supercalss's __init__() method, which is a common practice when you whant to expand on the functionality of the base class. Then you update the new instance of SubDictionary with your initial data. subDict = SubDict() print subDict # prints {'foo': 'bar', 'baz': 'spam'} A: I'm not sure this is what you're looking for, but when I read your post I immediately thought you were looking to dynamically generate keys for counting exercises. Unlike perl, which will do this for you by default, grep{$_{$_}++} qw/ a a b c c c /; print map{$_."\t".$_{$_}."\n"} sort {$_{$b}$_{$a}} keys %_; c 3 a 2 b 1 Python won't give you this for free: l = ["a","a","b","c","c","c"] d = {} for item in l: d[item] += 1 Traceback (most recent call last): File "./y.py", line 6, in d[item] += 1 KeyError: 'a' however, defaultdict will do this for you, from collections import defaultdict from operator import itemgetter l = ["a","a","b","c","c","c"] d = defaultdict(int) for item in l: d[item] += 1 dl = sorted(d.items(),key=itemgetter(1), reverse=True) for item in dl: print item ('c', 3) ('a', 2) ('b', 1) A: Just create a subclass of dict and add the keys in the init method. class MyClass(dict) def __init__(self): """Creates a new dict with default values"""" self['key1'] = 'value1' Remember though, that in python any class that 'acts like a dict' is usually treated like one, so you don't have to worry too much about it being a subclass, you could instead implement the dict methods, although the above approach is probably more useful to you :).
Creating dictionaries with pre-defined keys
In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
[ "You can also have the dict subclass restrict the keys to a predefined list, by overriding __setitem__()\n>>> class LimitedDict(dict):\n _keys = \"a b c\".split()\n def __init__(self, valtype=int):\n for key in LimitedDict._keys:\n self[key] = valtype()\n def __setitem__(self, key, val):\n if key not in LimitedDict._keys:\n raise KeyError\n dict.__setitem__(self, key, val)\n\n\n>>> limited = LimitedDict()\n>>> limited['a']\n0\n>>> limited['a'] = 3\n>>> limited['a']\n3\n>>> limited['z'] = 0\n\nTraceback (most recent call last):\n File \"<pyshell#61>\", line 1, in <module>\n limited['z'] = 0\n File \"<pyshell#56>\", line 8, in __setitem__\n raise KeyError\nKeyError\n>>> len(limited)\n3\n\n", "You can easily extend any built in type. This is how you'd do it with a dict:\n>>> class MyClass(dict):\n... def __init__(self, *args, **kwargs):\n... self['mykey'] = 'myvalue'\n... self['mykey2'] = 'myvalue2'\n...\n>>> x = MyClass()\n>>> x['mykey']\n'myvalue'\n>>> x\n{'mykey2': 'myvalue2', 'mykey': 'myvalue'}\n\nI wasn't able to find the Python documentation that talks about this, but the very popular book Dive Into Python (available for free online) has a few examples on doing this.\n", "Yes, in Python dict is a class , so you can subclass it:\n class SubDict(dict):\n def __init__(self):\n dict.__init__(self)\n self.update({\n 'foo': 'bar',\n 'baz': 'spam',})\n\nHere you override dict's __init__() method (a method which is called when an instance of the class is created). Inside __init__ you first call supercalss's __init__() method, which is a common practice when you whant to expand on the functionality of the base class. Then you update the new instance of SubDictionary with your initial data.\n subDict = SubDict()\n print subDict # prints {'foo': 'bar', 'baz': 'spam'}\n\n", "I'm not sure this is what you're looking for, but when I read your post I immediately thought you were looking to dynamically generate keys for counting exercises.\nUnlike perl, which will do this for you by default,\n\ngrep{$_{$_}++} qw/ a a b c c c /;\nprint map{$_.\"\\t\".$_{$_}.\"\\n\"} sort {$_{$b}$_{$a}} keys %_;\n\nc 3\na 2\nb 1\n\nPython won't give you this for free:\n\nl = [\"a\",\"a\",\"b\",\"c\",\"c\",\"c\"]\nd = {}\nfor item in l:\n d[item] += 1\n\nTraceback (most recent call last):\n File \"./y.py\", line 6, in \n d[item] += 1\nKeyError: 'a'\n\nhowever, defaultdict will do this for you,\n\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nl = [\"a\",\"a\",\"b\",\"c\",\"c\",\"c\"]\nd = defaultdict(int)\nfor item in l:\n d[item] += 1\n\ndl = sorted(d.items(),key=itemgetter(1), reverse=True)\nfor item in dl:\n print item\n\n('c', 3)\n('a', 2)\n('b', 1)\n\n", "Just create a subclass of dict and add the keys in the init method.\n\nclass MyClass(dict)\n\ndef __init__(self):\n \"\"\"Creates a new dict with default values\"\"\"\"\n\n self['key1'] = 'value1'\n\n\nRemember though, that in python any class that 'acts like a dict' is usually treated like one, so you don't have to worry too much about it being a subclass, you could instead implement the dict methods, although the above approach is probably more useful to you :).\n" ]
[ 12, 10, 3, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0000817884_dictionary_python.txt
Q: Is there a way to correctly sort unicode strings in SQLite using Python? Is there a simple way to order rows with unicode data in SQLite? A: SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for more details. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQLite library svelte and easy to statically link in. However, you can create a collator, that sorts however you please, then tell SQLite to use it. As the other poster hinted at, there are collators in the source tree that do this using ICU. However, you can also use your own, which makes sense if you're using a library like GLib that has its own Unicode-awareness. A: There is a library called ICU that can do proper unicode sorting for you; there's a good description in this other question: How to sort text in sqlite3 with specified locale?
Is there a way to correctly sort unicode strings in SQLite using Python?
Is there a simple way to order rows with unicode data in SQLite?
[ "SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for more details. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQLite library svelte and easy to statically link in. \nHowever, you can create a collator, that sorts however you please, then tell SQLite to use it. As the other poster hinted at, there are collators in the source tree that do this using ICU. However, you can also use your own, which makes sense if you're using a library like GLib that has its own Unicode-awareness.\n", "There is a library called ICU that can do proper unicode sorting for you; there's a good description in this other question:\nHow to sort text in sqlite3 with specified locale?\n" ]
[ 5, 2 ]
[]
[]
[ "python", "sqlite", "unicode" ]
stackoverflow_0000819211_python_sqlite_unicode.txt
Q: A wxPython timeline widget I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for: Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a ruler. It is possible to zoom in and out, and to scroll, and the ruler updates to reflect where / how deep you are on the timeline. Only a finite segment of the timeline is "occupied", i.e., actually contains data. The rest is empty. It is possible to select with the mouse any time point on the timeline, and, of course, it is possible to let it "play": to traverse the timeline from left to right in a specified speed. If you know something that's at least close to what I describe, I'd be interested. If you want to know what the job of this widget is: It's for a program for running simulations. The program calculates the simulation in the background, extending the "occupied" part of the timeline. It is possible to select different points in the timeline to observe the state of the system in a certain timepoint, and of course it is possible to play the simulation. Thanks! A: A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a wxSlider. This is far from ideal, but it'll get you up and running. You can also look at creating a custom widget -- that'd definitely do what you want, but it will be a lot of work. Sorry I don't have anything better, but I figured some answer is better than nothing. A: I have been working on a timeline widget for use in Task Coach (http://www.taskcoach.org). I haven't released it separately yet, but it is fully isolated from the rest of the Task Coach source code so you should be able to rip it out quite easily. See http://taskcoach.svn.sourceforge.net/viewvc/taskcoach/trunk/taskcoach/taskcoachlib/thirdparty/timeline/
A wxPython timeline widget
I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for: Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a ruler. It is possible to zoom in and out, and to scroll, and the ruler updates to reflect where / how deep you are on the timeline. Only a finite segment of the timeline is "occupied", i.e., actually contains data. The rest is empty. It is possible to select with the mouse any time point on the timeline, and, of course, it is possible to let it "play": to traverse the timeline from left to right in a specified speed. If you know something that's at least close to what I describe, I'd be interested. If you want to know what the job of this widget is: It's for a program for running simulations. The program calculates the simulation in the background, extending the "occupied" part of the timeline. It is possible to select different points in the timeline to observe the state of the system in a certain timepoint, and of course it is possible to play the simulation. Thanks!
[ "A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a wxSlider. This is far from ideal, but it'll get you up and running. You can also look at creating a custom widget -- that'd definitely do what you want, but it will be a lot of work. Sorry I don't have anything better, but I figured some answer is better than nothing. \n", "I have been working on a timeline widget for use in Task Coach (http://www.taskcoach.org). I haven't released it separately yet, but it is fully isolated from the rest of the Task Coach source code so you should be able to rip it out quite easily. See http://taskcoach.svn.sourceforge.net/viewvc/taskcoach/trunk/taskcoach/taskcoachlib/thirdparty/timeline/\n" ]
[ 1, 1 ]
[]
[]
[ "controls", "python", "timeline", "widget", "wxpython" ]
stackoverflow_0000715950_controls_python_timeline_widget_wxpython.txt
Q: Working with a QString encoding Is there a Python library which can detect (and perhaps decode) encoding of the string? I found chardet but it gives me an error, using: chardet.detect(self.ui.TextFrom.toPlainText()) got: = chardet.detect(self.ui.TextFrom.toPlainText()) File .... u.feed(aBuf) File .... if self._highBitDetector.search(aBuf): TypeError: buffer size mismatch Also: print type(self.ui.TextFrom.toPlainText()) # <class 'PyQt4.QtCore.QString'> A: You need to convert your QString to a Python string before passing it to chardet. Change this: chardet.detect(self.ui.TextFrom.toPlainText()) to this: chardet.detect(str(self.ui.TextFrom.toPlainText())) A: I guess this is another option. http://cthedot.de/encutils/ A collection of helper functions to detect encodings of text files (like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.
Working with a QString encoding
Is there a Python library which can detect (and perhaps decode) encoding of the string? I found chardet but it gives me an error, using: chardet.detect(self.ui.TextFrom.toPlainText()) got: = chardet.detect(self.ui.TextFrom.toPlainText()) File .... u.feed(aBuf) File .... if self._highBitDetector.search(aBuf): TypeError: buffer size mismatch Also: print type(self.ui.TextFrom.toPlainText()) # <class 'PyQt4.QtCore.QString'>
[ "You need to convert your QString to a Python string before passing it to chardet. Change this:\nchardet.detect(self.ui.TextFrom.toPlainText())\n\nto this:\nchardet.detect(str(self.ui.TextFrom.toPlainText()))\n\n", "I guess this is another option.\nhttp://cthedot.de/encutils/\n\nA collection of helper functions to detect encodings of text files (like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.\n\n" ]
[ 7, 2 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0000819310_encoding_python.txt
Q: Python, who is calling my python module I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ?? A: This will do it: import os if os.environ.has_key('REQUEST_METHOD'): # You're being run as a CGI script. else: # You're being run from the command line. A: This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should provide a uniform environment. You'll be happiest if you design your scripts to work in exactly one consistent way. Build things like this. myscript.py - the "real work" - defined in functions and classes. myscript_cgi.py - a CGI interface that imports myscript and uses the classes and functions. myscript_cli.py - the command-line interface that parses the command-line options, imports myscript, and uses the classes and functions. A single script that does all three things (real work, cgi interface, cli interface) is usually a mistake.
Python, who is calling my python module
I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ??
[ "This will do it:\nimport os\nif os.environ.has_key('REQUEST_METHOD'):\n # You're being run as a CGI script.\nelse:\n # You're being run from the command line.\n\n", "This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should provide a uniform environment.\nYou'll be happiest if you design your scripts to work in exactly one consistent way. Build things like this.\n\nmyscript.py - the \"real work\" - defined in functions and classes. \nmyscript_cgi.py - a CGI interface that imports myscript and uses the classes and functions.\nmyscript_cli.py - the command-line interface that parses the command-line options, imports myscript, and uses the classes and functions.\n\nA single script that does all three things (real work, cgi interface, cli interface) is usually a mistake.\n" ]
[ 9, 6 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000819217_cgi_python.txt
Q: How do I handle exceptions when using threading and Queue? If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs). from threading import Thread from Queue import Queue from time import sleep def do_work(item): sleep(0.5) print "working" , item def worker(): while True: item = q.get() do_work(item) q.task_done() q = Queue() num_worker_threads = 10 for i in range(num_worker_threads): t = Thread(target=worker) # t.setDaemon(True) t.start() for item in range(1, 10000): q.put(item) q.join() # block until all tasks are done A: The simplest way is to start all the worker threads as daemon threads, then just have your main loop be while True: sleep(1) Hitting Ctrl+C will throw an exception in your main thread, and all of the daemon threads will exit when the interpreter exits. This assumes you don't want to perform cleanup in all of those threads before they exit. A more complex way is to have a global stopped Event: stopped = Event() def worker(): while not stopped.is_set(): try: item = q.get_nowait() do_work(item) except Empty: # import the Empty exception from the Queue module stopped.wait(1) Then your main loop can set the stopped Event to False when it gets a KeyboardInterrupt try: while not stopped.is_set(): stopped.wait(1) except KeyboardInterrupt: stopped.set() This lets your worker threads finish what they're doing you want instead of just having every worker thread be a daemon and exit in the middle of execution. You can also do whatever cleanup you want. Note that this example doesn't make use of q.join() - this makes things more complex, though you can still use it. If you do then your best bet is to use signal handlers instead of exceptions to detect KeyboardInterrupts. For example: from signal import signal, SIGINT def stop(signum, frame): stopped.set() signal(SIGINT, stop) This lets you define what happens when you hit Ctrl+C without affecting whatever your main loop is in the middle of. So you can keep doing q.join() without worrying about being interrupted by a Ctrl+C. Of course, with my above examples, you don't need to be joining, but you might have some other reason for doing so.
How do I handle exceptions when using threading and Queue?
If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs). from threading import Thread from Queue import Queue from time import sleep def do_work(item): sleep(0.5) print "working" , item def worker(): while True: item = q.get() do_work(item) q.task_done() q = Queue() num_worker_threads = 10 for i in range(num_worker_threads): t = Thread(target=worker) # t.setDaemon(True) t.start() for item in range(1, 10000): q.put(item) q.join() # block until all tasks are done
[ "The simplest way is to start all the worker threads as daemon threads, then just have your main loop be\nwhile True:\n sleep(1)\n\nHitting Ctrl+C will throw an exception in your main thread, and all of the daemon threads will exit when the interpreter exits. This assumes you don't want to perform cleanup in all of those threads before they exit.\nA more complex way is to have a global stopped Event:\nstopped = Event()\ndef worker():\n while not stopped.is_set():\n try:\n item = q.get_nowait()\n do_work(item)\n except Empty: # import the Empty exception from the Queue module\n stopped.wait(1)\n\nThen your main loop can set the stopped Event to False when it gets a KeyboardInterrupt\ntry:\n while not stopped.is_set():\n stopped.wait(1)\nexcept KeyboardInterrupt:\n stopped.set()\n\nThis lets your worker threads finish what they're doing you want instead of just having every worker thread be a daemon and exit in the middle of execution. You can also do whatever cleanup you want.\nNote that this example doesn't make use of q.join() - this makes things more complex, though you can still use it. If you do then your best bet is to use signal handlers instead of exceptions to detect KeyboardInterrupts. For example:\nfrom signal import signal, SIGINT\ndef stop(signum, frame):\n stopped.set()\nsignal(SIGINT, stop)\n\nThis lets you define what happens when you hit Ctrl+C without affecting whatever your main loop is in the middle of. So you can keep doing q.join() without worrying about being interrupted by a Ctrl+C. Of course, with my above examples, you don't need to be joining, but you might have some other reason for doing so.\n" ]
[ 6 ]
[]
[]
[ "exception", "multithreading", "python" ]
stackoverflow_0000820111_exception_multithreading_python.txt
Q: SyntaxError in finally (Django) I'm using Django, and I have the following error: Exception Type: SyntaxError Exception Value: invalid syntax (views.py, line 115) My viws.py code looks like this: def myview(request): try: [...] except MyExceptionClass, e: [...] finally: render_to_response('template.html', {}, context_instance = RequestContext(request)) Where MyExceptionClass is a class extending Exception, and line 115 is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea? Thanks a lot! A: What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block. You can work around this by nesting try blocks. def myview(request): try: try: [...] except MyExceptionClass, e: [...] finally: render_to_response( 'template.html', {}, context_instance = RequestContext(request) ) A: Nadia is right, so if you're stuck with Python 2.4 or earlier, use two try blocks: try: try: [...] except MyExceptionClass, e: [...] finally: render_to_response(...) A: In Python 3, should be: except MyExceptionClass as e: [....] In your case, this is not the case.
SyntaxError in finally (Django)
I'm using Django, and I have the following error: Exception Type: SyntaxError Exception Value: invalid syntax (views.py, line 115) My viws.py code looks like this: def myview(request): try: [...] except MyExceptionClass, e: [...] finally: render_to_response('template.html', {}, context_instance = RequestContext(request)) Where MyExceptionClass is a class extending Exception, and line 115 is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea? Thanks a lot!
[ "What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block.\nYou can work around this by nesting try blocks.\ndef myview(request):\n try:\n try:\n [...]\n except MyExceptionClass, e:\n [...]\n finally:\n render_to_response(\n 'template.html', {}, context_instance = RequestContext(request)\n )\n\n", "Nadia is right, so if you're stuck with Python 2.4 or earlier, use two try blocks:\ntry:\n try:\n [...]\n except MyExceptionClass, e:\n [...]\nfinally:\n render_to_response(...)\n\n", "In Python 3, should be:\nexcept MyExceptionClass as e:\n [....]\n\nIn your case, this is not the case.\n" ]
[ 14, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000820778_django_python.txt
Q: Pylons or TurboGears vs. .NET or Java We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff). Their web app will have some data analysis that we'll offload as well as a twang of social networking features. (basically all they have so far is some Flex mockups for UX) I'm looking for some evidence with regard to development time, or other reasons that will help our argument to reassure the customer. The other options is that we're barking up the wrong tree and have no idea. I hope that's not the case. Any references to case studies or whatnot would be nice. The best I could find are http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html and http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html which are a bit dated (wrt to TG2 and whatnot) Thanks! A: If you're looking for a success story for a customer, Virgin Charter is using Pylons with SQLAlchemy for their site. This is a high-value transaction system as people are booking very expensive flights through the site. For a more high-traffic site, Reddit is now running on Pylons, along with Charlie Rose. SQLAlchemy and Mako were both designed by Mike Bayer (A veteran Java programmer), SQLAlchemy being based on the best of Hibernate and with the same powerful principles and patterns that Hibernate supports. If they're wary of deploying something they're not familiar with, Pylons runs on Jython, and the latest SQLAlchemy (0.6 branch) is about ready on Jython too. This would let you package up a full Pylons app into a WAR file for deployment which would reassure their Java-types. For general Python, consider pointing out all the big animation studios that use it, and the other various srouces S.Lott points out. A: It's almost easier to build a quick Proof of Concept service that demonstrates how clean and simple it is. A simple SQLAlchemy mapping with a quick demo of query processing. A simple template showing how cool Mako is. A simple Pylons app to put the two together. Most important -- use their application and their data. Not a lame hello world; not an existing tutorial. If they want to compare your clean, elegant demo of their app with .NET and J2EE, they'll see that other languages lead to a much, much bigger code base. Edit Show them this: http://python.org/about/success/ Also, one of the best Python demos is to do things the way the SQLAlchemy and Django tutorials do things -- in interactive python from the >>> prompt. Nothing is more exciting than programming which is so simple you can do it interactively. You won't find a lot of compelling case studies. Python is a community. .Net and J2EE are products. .Net has Microsoft's advertising backing it; Microsoft can afford to do extensive surveys and studies of their product. Same for Sun (soon to be Oracle) and J2EE -- lots of marketing hype backing up their claims. Python just has what's on the Python.org site (http://python.org/about/). The various related projects (Pylons, Mako and SQLAlchemy) don't have lavish case study whitepapers. They do have a large number of downloads, and lots of word of mouth. But if someone's looking for "proof" that Python works better than .Net, there's not going to be much.
Pylons or TurboGears vs. .NET or Java
We're embarking on a project for a client. They plan on having about 50k users by the end of the year. We're pushing to use Pylons w/ Mako and SQLAlchemy, and our contact there is excited about it, but some of his colleagues are wary because it's not .NET or J2ee (they're used to enterprisey stuff). Their web app will have some data analysis that we'll offload as well as a twang of social networking features. (basically all they have so far is some Flex mockups for UX) I'm looking for some evidence with regard to development time, or other reasons that will help our argument to reassure the customer. The other options is that we're barking up the wrong tree and have no idea. I hope that's not the case. Any references to case studies or whatnot would be nice. The best I could find are http://www.oracle.com/technology/pub/articles/rubio-python-turbogears.html and http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html which are a bit dated (wrt to TG2 and whatnot) Thanks!
[ "If you're looking for a success story for a customer, Virgin Charter is using Pylons with SQLAlchemy for their site. This is a high-value transaction system as people are booking very expensive flights through the site.\nFor a more high-traffic site, Reddit is now running on Pylons, along with Charlie Rose.\nSQLAlchemy and Mako were both designed by Mike Bayer (A veteran Java programmer), SQLAlchemy being based on the best of Hibernate and with the same powerful principles and patterns that Hibernate supports.\nIf they're wary of deploying something they're not familiar with, Pylons runs on Jython, and the latest SQLAlchemy (0.6 branch) is about ready on Jython too. This would let you package up a full Pylons app into a WAR file for deployment which would reassure their Java-types.\nFor general Python, consider pointing out all the big animation studios that use it, and the other various srouces S.Lott points out.\n", "It's almost easier to build a quick Proof of Concept service that demonstrates how clean and simple it is.\nA simple SQLAlchemy mapping with a quick demo of query processing.\nA simple template showing how cool Mako is.\nA simple Pylons app to put the two together.\nMost important -- use their application and their data. Not a lame hello world; not an existing tutorial.\nIf they want to compare your clean, elegant demo of their app with .NET and J2EE, they'll see that other languages lead to a much, much bigger code base.\n\nEdit\nShow them this: http://python.org/about/success/\nAlso, one of the best Python demos is to do things the way the SQLAlchemy and Django tutorials do things -- in interactive python from the >>> prompt. Nothing is more exciting than programming which is so simple you can do it interactively.\nYou won't find a lot of compelling case studies. Python is a community. .Net and J2EE are products. .Net has Microsoft's advertising backing it; Microsoft can afford to do extensive surveys and studies of their product. Same for Sun (soon to be Oracle) and J2EE -- lots of marketing hype backing up their claims.\nPython just has what's on the Python.org site (http://python.org/about/). The various related projects (Pylons, Mako and SQLAlchemy) don't have lavish case study whitepapers. They do have a large number of downloads, and lots of word of mouth. \nBut if someone's looking for \"proof\" that Python works better than .Net, there's not going to be much.\n" ]
[ 5, 3 ]
[ "They are crazy if they want to use j2ee imho. Visual Studio/C# is very nice, especially if you are not trying to do anything tricky. However, if you want to customize the C# way of doing things beyond what it was explicitly designed for it can quickly turn into a mess -- you get mired in automatically generated XML configuration files &c. Of course, I also think that Pylons with SQLAlchemy might turn into a mess because they too generate so much stuff that you ultimatly might end up having to reconfigure. If you want complete control, I would recommend a less intrusive environment, like Werkzueg. Please read my essay on writing MVC with no invisible means of support.\n" ]
[ -1 ]
[ "jakarta_ee", "java", "pylons", "python", "wsgi" ]
stackoverflow_0000783488_jakarta_ee_java_pylons_python_wsgi.txt
Q: SQL TOP 1 analog for lists in Python Here is an example of my input csv file: ... 0.7,0.5,0.35,14.4,0.521838919218 0.7,0.5,0.35,14.4,0.521893472678 0.7,0.5,0.35,14.4,0.521948026139 0.7,0.5,0.35,14.4,0.522002579599 ... I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iterations of this and outer cycles): for line in foo: if float(line[-1]) > random.random(): res = line break ... How can I make this better and faster? EDIT: I was advised to use bisect for this task, but I don't know how to do it. A: The fastest approach is to use bisect (assuming the float list is ordered). You can do it like this: import bisect float_list = [line[-1] for line in foo] index = bisect.bisect(float_list, random.random()) if index < len(float_list) result = foo[index] else: result = None # None exists The float list has to be ordered for this to work. A: You might actually be able to use the appropriate SQL command if you import the CSV file into SQLite. Python has a built-in sqlite library you can use to query the database.
SQL TOP 1 analog for lists in Python
Here is an example of my input csv file: ... 0.7,0.5,0.35,14.4,0.521838919218 0.7,0.5,0.35,14.4,0.521893472678 0.7,0.5,0.35,14.4,0.521948026139 0.7,0.5,0.35,14.4,0.522002579599 ... I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iterations of this and outer cycles): for line in foo: if float(line[-1]) > random.random(): res = line break ... How can I make this better and faster? EDIT: I was advised to use bisect for this task, but I don't know how to do it.
[ "The fastest approach is to use bisect (assuming the float list is ordered). You can do it like this:\nimport bisect\n\nfloat_list = [line[-1] for line in foo]\nindex = bisect.bisect(float_list, random.random())\nif index < len(float_list)\n result = foo[index]\nelse:\n result = None # None exists\n\nThe float list has to be ordered for this to work.\n", "You might actually be able to use the appropriate SQL command if you import the CSV file into SQLite. Python has a built-in sqlite library you can use to query the database.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "tsql" ]
stackoverflow_0000821416_python_tsql.txt
Q: How do content discovery engines, like Zemanta and Open Calais work? I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance? A: Michal Finkelstein from OpenCalais here. First, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to: http://opencalais.com/tagging-information http://opencalais.com/how-does-calais-learn Also feel free to follow us on Twitter (@OpenCalais) or to email us at [email protected] Now to the answer: OpenCalais is based on a decade of research and development in the fields of Natural Language Processing and Text Analytics. We support the full "NLP Stack" (as we like to call it): From text tokenization, morphological analysis and POS tagging, to shallow parsing and identifying nominal and verbal phrases. Semantics come into play when we look for Entities (a.k.a. Entity Extraction, Named Entity Recognition). For that purpose we have a sophisticated rule-based system that combines discovery rules as well as lexicons/dictionaries. This combination allows us to identify names of companies/persons/films, etc., even if they don't exist in any available list. For the most prominent entities (such as people, companies) we also perform anaphora resolution, cross-reference and name canonization/normalization at the article level, so we'll know that 'John Smith' and 'Mr. Smith', for example, are likely referring to the same person. So the short answer to your question is - no, it's not just about matching against large databases. Events/Facts are really interesting because they take our discovery rules one level deeper; we find relations between entities and label them with the appropriate type, for example M&As (relations between two or more companies), Employment Changes (relations between companies and people), and so on. Needless to say, Event/Fact extraction is not possible for systems that are based solely on lexicons. For the most part, our system is tuned to be precision-oriented, but we always try to keep a reasonable balance between accuracy and entirety. By the way there are some cool new metadata capabilities coming out later this month so stay tuned. Regards, Michal A: I'm not familiar with the specific services listed, but the field of natural language processing has developed a number of techniques that enable this sort of information extraction from general text. As Sean stated, once you have candidate terms, it's not to difficult to search for those terms with some of the other entities in context and then use the results of that search to determine how confident you are that the term extracted is an actual entity of interest. OpenNLP is a great project if you'd like to play around with natural language processing. The capabilities you've named would probably be best accomplished with Named Entity Recognizers (NER) (algorithms that locate proper nouns, generally, and sometimes dates as well) and/or Word Sense Disambiguation (WSD) (eg: the word 'bank' has different meanings depending on it's context, and that can be very important when extracting information from text. Given the sentences: "the plane banked left", "the snow bank was high", and "they robbed the bank" you can see how dissambiguation can play an important part in language understanding) Techniques generally build on each other, and NER is one of the more complex tasks, so to do NER successfully, you will generally need accurate tokenizers (natural language tokenizers, mind you -- statistical approaches tend to fare the best), string stemmers (algorithms that conflate similar words to common roots: so words like informant and informer are treated equally), sentence detection ('Mr. Jones was tall.' is only one sentence, so you can't just check for punctuation), part-of-speech taggers (POS taggers), and WSD. There is a python port of (parts of) OpenNLP called NLTK (http://nltk.sourceforge.net) but I don't have much experience with it yet. Most of my work has been with the Java and C# ports, which work well. All of these algorithms are language-specific, of course, and they can take significant time to run (although, it is generally faster than reading the material you are processing). Since the state-of-the-art is largely based on statistical techniques, there is also a considerable error rate to take into account. Furthermore, because the error rate impacts all the stages, and something like NER requires numerous stages of processing, (tokenize -> sentence detect -> POS tag -> WSD -> NER) the error rates compound. A: Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names, Places, Companies, etc. Then, it is just another step to do some kind of search for those entities and return meta data. Zementa probably does something similar, but matches the phrases against meta-data attached to images in order to acquire related results. It certainly isn't easy.
How do content discovery engines, like Zemanta and Open Calais work?
I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? How would a service like Zemanta know what images to suggest to a piece of text for instance?
[ "Michal Finkelstein from OpenCalais here.\nFirst, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to:\nhttp://opencalais.com/tagging-information\nhttp://opencalais.com/how-does-calais-learn\nAlso feel free to follow us on Twitter (@OpenCalais) or to email us at [email protected]\nNow to the answer:\nOpenCalais is based on a decade of research and development in the fields of Natural Language Processing and Text Analytics.\nWe support the full \"NLP Stack\" (as we like to call it):\nFrom text tokenization, morphological analysis and POS tagging, to shallow parsing and identifying nominal and verbal phrases.\nSemantics come into play when we look for Entities (a.k.a. Entity Extraction, Named Entity Recognition). For that purpose we have a sophisticated rule-based system that combines discovery rules as well as lexicons/dictionaries. This combination allows us to identify names of companies/persons/films, etc., even if they don't exist in any available list.\nFor the most prominent entities (such as people, companies) we also perform anaphora resolution, cross-reference and name canonization/normalization at the article level, so we'll know that 'John Smith' and 'Mr. Smith', for example, are likely referring to the same person.\nSo the short answer to your question is - no, it's not just about matching against large databases.\nEvents/Facts are really interesting because they take our discovery rules one level deeper; we find relations between entities and label them with the appropriate type, for example M&As (relations between two or more companies), Employment Changes (relations between companies and people), and so on. Needless to say, Event/Fact extraction is not possible for systems that are based solely on lexicons.\nFor the most part, our system is tuned to be precision-oriented, but we always try to keep a reasonable balance between accuracy and entirety.\nBy the way there are some cool new metadata capabilities coming out later this month so stay tuned.\nRegards,\nMichal\n", "I'm not familiar with the specific services listed, but the field of natural language processing has developed a number of techniques that enable this sort of information extraction from general text. As Sean stated, once you have candidate terms, it's not to difficult to search for those terms with some of the other entities in context and then use the results of that search to determine how confident you are that the term extracted is an actual entity of interest.\nOpenNLP is a great project if you'd like to play around with natural language processing. The capabilities you've named would probably be best accomplished with Named Entity Recognizers (NER) (algorithms that locate proper nouns, generally, and sometimes dates as well) and/or Word Sense Disambiguation (WSD) (eg: the word 'bank' has different meanings depending on it's context, and that can be very important when extracting information from text. Given the sentences: \"the plane banked left\", \"the snow bank was high\", and \"they robbed the bank\" you can see how dissambiguation can play an important part in language understanding)\nTechniques generally build on each other, and NER is one of the more complex tasks, so to do NER successfully, you will generally need accurate tokenizers (natural language tokenizers, mind you -- statistical approaches tend to fare the best), string stemmers (algorithms that conflate similar words to common roots: so words like informant and informer are treated equally), sentence detection ('Mr. Jones was tall.' is only one sentence, so you can't just check for punctuation), part-of-speech taggers (POS taggers), and WSD.\nThere is a python port of (parts of) OpenNLP called NLTK (http://nltk.sourceforge.net) but I don't have much experience with it yet. Most of my work has been with the Java and C# ports, which work well. \nAll of these algorithms are language-specific, of course, and they can take significant time to run (although, it is generally faster than reading the material you are processing). Since the state-of-the-art is largely based on statistical techniques, there is also a considerable error rate to take into account. Furthermore, because the error rate impacts all the stages, and something like NER requires numerous stages of processing, (tokenize -> sentence detect -> POS tag -> WSD -> NER) the error rates compound.\n", "Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names, Places, Companies, etc. Then, it is just another step to do some kind of search for those entities and return meta data.\nZementa probably does something similar, but matches the phrases against meta-data attached to images in order to acquire related results.\nIt certainly isn't easy.\n" ]
[ 9, 7, 0 ]
[]
[]
[ "python", "ruby", "semantics", "zemanta" ]
stackoverflow_0000022059_python_ruby_semantics_zemanta.txt
Q: what python feature is illustrated in this code? I read Storm ORM's tutorial at https://storm.canonical.com/Tutorial, and I stumbled upon the following piece of code : store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") I'm not sure that the second argument of the find method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ? A: Person.name has a overloaded __eq__ method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the find() method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern. In Storm, it is implemented with the Comparable object. A: Person.name is an instance of some type with a custom __eq__ method. While __eq__ normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See Python special method names for more on this and related methods. Probably the most confusing/misleading part of this (especially if you're used to other OO languages like Java) is that Person.name and person.name (where person is an instance of Person) don't have to have any relationship to each other. For example: class Person(object): name = "name of class" def __init__(self): self.name = "name of instance" person = Person() print Person.name print person.name This will print: name of class name of instance Note that the class property is just set in the class body, while the instance property is set in the __init__ method. In your case, you'd set Person.name to the object with the custom __eq__ method that returns a lambda, something like this: class LambdaThingy(object): def __init__(self, attrname): self.__attrname = attrname def __eq__(self, other): return lambda x: getattr(x, self.__attrname) == other class Person(object): name = LambdaThingy('name') def __init__(self, name): self.name = name equals_fred = Person.name == "Fred" equals_barney = Person.name == "Barney" fred = Person("Fred") print equals_fred(fred) print equals_barney(fred) This prints: True False This is certainly skirting the edge of being "too clever", so I'd be very cautious about using this in production code. An explicit lambda would probably be a lot clearer to future maintainers, even if it is a bit more verbose. A: The magic is in the Person.name property, which results in a type that overloads __eq__ (&c) to return non-bools. Storm's sources are online for you to browse (and CAUTIOUSLY imitate;-) at http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/ -- as you'll see, they don't go light on the "black magic";-) A: It does not look like a python lambda to me. I did not read the code for Storm but Miles is probably right in that it uses a lazy evaluation schema. To learn more about python lambda functions read the excellent chapter of Dive Into Python. A: since I'm a Java programmer... I'm guessing... it is operator overloading? Person.name == is an operator overloaded that instead do comparison... it produces a SQL query my 0.02$
what python feature is illustrated in this code?
I read Storm ORM's tutorial at https://storm.canonical.com/Tutorial, and I stumbled upon the following piece of code : store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") I'm not sure that the second argument of the find method will be evaluated to True/False. I think it will be interpreted as a lambda. If that is true, how can I achieve the same effect in my functions ?
[ "Person.name has a overloaded __eq__ method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the find() method to obtain the attribute and value that it will use for filtering. I would describe this as a type of lazy evaluation pattern.\nIn Storm, it is implemented with the Comparable object.\n", "Person.name is an instance of some type with a custom __eq__ method. While __eq__ normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See Python special method names for more on this and related methods.\nProbably the most confusing/misleading part of this (especially if you're used to other OO languages like Java) is that Person.name and person.name (where person is an instance of Person) don't have to have any relationship to each other. For example:\nclass Person(object):\n name = \"name of class\"\n def __init__(self):\n self.name = \"name of instance\"\n\nperson = Person()\nprint Person.name\nprint person.name\n\nThis will print:\n\nname of class\nname of instance\n\n\nNote that the class property is just set in the class body, while the instance property is set in the __init__ method.\nIn your case, you'd set Person.name to the object with the custom __eq__ method that returns a lambda, something like this:\nclass LambdaThingy(object):\n def __init__(self, attrname):\n self.__attrname = attrname\n\n def __eq__(self, other):\n return lambda x: getattr(x, self.__attrname) == other\n\nclass Person(object):\n name = LambdaThingy('name')\n\n def __init__(self, name):\n self.name = name\n\nequals_fred = Person.name == \"Fred\"\nequals_barney = Person.name == \"Barney\"\n\nfred = Person(\"Fred\")\n\nprint equals_fred(fred)\nprint equals_barney(fred)\n\nThis prints:\nTrue\nFalse\n\nThis is certainly skirting the edge of being \"too clever\", so I'd be very cautious about using this in production code. An explicit lambda would probably be a lot clearer to future maintainers, even if it is a bit more verbose.\n", "The magic is in the Person.name property, which results in a type that overloads __eq__ (&c) to return non-bools. Storm's sources are online for you to browse (and CAUTIOUSLY imitate;-) at http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/ -- as you'll see, they don't go light on the \"black magic\";-)\n", "It does not look like a python lambda to me. I did not read the code for Storm but Miles is probably right in that it uses a lazy evaluation schema.\nTo learn more about python lambda functions read the excellent chapter of Dive Into Python.\n", "since I'm a Java programmer... I'm guessing... \nit is operator overloading? Person.name == is an operator overloaded that instead do comparison... it produces a SQL query\nmy 0.02$\n" ]
[ 22, 9, 8, 1, 0 ]
[]
[]
[ "language_features", "python" ]
stackoverflow_0000821855_language_features_python.txt
Q: Implement Blackjack in Python I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it: Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins. Ok, this is what I have gotten so far. "This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press <ENTER> to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 <= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer < total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer > total3: print("Too bad, the dealer beat you!") Ok, nevermind, I fixed it :D I just changed the Hit and Stand to Yes or No if total2 < 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") A: This can get you started: http://docs.python.org/library/random.html http://docs.python.org/library/strings.html http://docs.python.org/library/stdtypes.html http://docs.python.org/reference/index.html I see you have added some code; that's good. Think about the parts of your program that will need to exist. You will need some representation of "cards" -- cards have important features such as their value, their suit, etc. Given a card, you should be able to tell what its value is, whether it's a Jack or an Ace or a 2 of hearts. Read up on "classes" in Python to get started with this. You will also have a hand of cards -- the cards your dealer is currently holding, and the cards your player is currently holding. A "hand" is a collection of cards, which you (the programmer) can add new cards to (when a card is dealt). You might want to do that using "lists" or "arrays" or "classes" that contain those arrays. A hand also has a value, which is usually the sum of card values, but as you know, Aces are special (they can be 1 or 11), so you'll need to treat that case correctly with some "if statements". You will also have a deck; a deck is a special collection -- it has exactly 52 cards when it starts, and none of the cards are repeated (you could, of course, be using several decks to play, but that's a complication you can solve later). How do you populate a deck like that? Your program will want to "deal" from the deck -- so you'll need a way to keep track of which cards have been dealt to players. That's a lot of stuff. Try writing down all the logic of what your program needs to do in simple sentences, without worrying about Python. This is called "pseudo-code". It's not a real program, it's just a plan for what exactly you are going to do -- it's useful the way a map is useful. If you are going to a place you've been to a 100 times, you don't need a map, but if you are driving to some town you've never been to, you want to plan out your route first, before getting behind the wheel.. Update your question with your pseudocode, and any attempts you have made (or will have made) to translate the pseudocode to Python. A: I agreed with SquareCog's comment - some additional information about what you've tried and what's not working and what you're confused about would be helpful. Some info that might be helpful, though: Regarding the generation of numbers between 1-10, ace, king, queen, and jack: it might be helpful to assign each card a numeric index. 2-10 are obvious, and you can make your own values for jack, queen, king, and ace. One thing to especially note is that there's no 1, if you're also generating ace. Once you've assigned numbers, the random module can help. There are standard comparison methods that can be used to recognize the difference between "Hit" or "Stand". Notably the == operator. Since you're generating hands, it should be easy to check whether they are certain combinations. As far as calculating scores, a good starting point would be to use addition. Edit: based on your subsequent comments, it seems like you might benefit from some of the "Python for non-programmer" guides. A: In your code, you wrote: Ace = 1 or 11 I'm afraid this doesn't do what you think. Start the python interpreter, and then type 1 or 11 into it. Here's what I get: >>> 1 or 11 1 What this means is that when you type: Ace = 1 or 11, python first evaluates the 1 or 11 bit, and then it sets Ace to be that. In other words, your code is equivalent to: Ace = 1 I suggest you forget about the two possible values for an Ace; just leave it as 1 only. Simplify the rules, get something working, and then you can look at making a full blackjack game. A: Here's a tip to get started: Instead of drawing a number between 1 and 10 and doing something different for face cards, draw a number between 1 and 13, and define a function (or even a class) that interprets these numbers as cards. For example, 1 would map to Ace, 11 to Jack, 2 to a deuce, etc. A: Check all of your inputs. As a young lad, I wrote my blackjack program in Fortran. One of my users pointed out that he could: Enter a negative number as a bet. Deliberately lose. The program would then do exactly what it was programmed to do: Subtract the negative bet from the total won/lost. Which is (of course) equivalent to adding a positive number to the total. Sometimes, you can win by losing....
Implement Blackjack in Python
I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it: Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins. Ok, this is what I have gotten so far. "This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press <ENTER> to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 <= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer < total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer > total3: print("Too bad, the dealer beat you!") Ok, nevermind, I fixed it :D I just changed the Hit and Stand to Yes or No if total2 < 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND")
[ "This can get you started:\nhttp://docs.python.org/library/random.html\nhttp://docs.python.org/library/strings.html\nhttp://docs.python.org/library/stdtypes.html\nhttp://docs.python.org/reference/index.html\nI see you have added some code; that's good.\nThink about the parts of your program that will need to exist. You will need some representation of \"cards\" -- cards have important features such as their value, their suit, etc. Given a card, you should be able to tell what its value is, whether it's a Jack or an Ace or a 2 of hearts. Read up on \"classes\" in Python to get started with this.\nYou will also have a hand of cards -- the cards your dealer is currently holding, and the cards your player is currently holding. A \"hand\" is a collection of cards, which you (the programmer) can add new cards to (when a card is dealt). You might want to do that using \"lists\" or \"arrays\" or \"classes\" that contain those arrays. A hand also has a value, which is usually the sum of card values, but as you know, Aces are special (they can be 1 or 11), so you'll need to treat that case correctly with some \"if statements\".\nYou will also have a deck; a deck is a special collection -- it has exactly 52 cards when it starts, and none of the cards are repeated (you could, of course, be using several decks to play, but that's a complication you can solve later). How do you populate a deck like that? Your program will want to \"deal\" from the deck -- so you'll need a way to keep track of which cards have been dealt to players.\nThat's a lot of stuff. Try writing down all the logic of what your program needs to do in simple sentences, without worrying about Python. This is called \"pseudo-code\". It's not a real program, it's just a plan for what exactly you are going to do -- it's useful the way a map is useful. If you are going to a place you've been to a 100 times, you don't need a map, but if you are driving to some town you've never been to, you want to plan out your route first, before getting behind the wheel..\nUpdate your question with your pseudocode, and any attempts you have made (or will have made) to translate the pseudocode to Python.\n", "I agreed with SquareCog's comment - some additional information about what you've tried and what's not working and what you're confused about would be helpful.\nSome info that might be helpful, though:\nRegarding the generation of numbers between 1-10, ace, king, queen, and jack: it might be helpful to assign each card a numeric index. 2-10 are obvious, and you can make your own values for jack, queen, king, and ace. One thing to especially note is that there's no 1, if you're also generating ace. Once you've assigned numbers, the random module can help.\nThere are standard comparison methods that can be used to recognize the difference between \"Hit\" or \"Stand\". Notably the == operator.\nSince you're generating hands, it should be easy to check whether they are certain combinations. As far as calculating scores, a good starting point would be to use addition.\nEdit: based on your subsequent comments, it seems like you might benefit from some of the \"Python for non-programmer\" guides.\n", "In your code, you wrote:\nAce = 1 or 11\n\nI'm afraid this doesn't do what you think. Start the python interpreter, and then type 1 or 11 into it. Here's what I get:\n>>> 1 or 11\n1\n\nWhat this means is that when you type: Ace = 1 or 11, python first evaluates the 1 or 11 bit, and then it sets Ace to be that. In other words, your code is equivalent to:\nAce = 1\n\nI suggest you forget about the two possible values for an Ace; just leave it as 1 only. Simplify the rules, get something working, and then you can look at making a full blackjack game.\n", "Here's a tip to get started: Instead of drawing a number between 1 and 10 and doing something different for face cards, draw a number between 1 and 13, and define a function (or even a class) that interprets these numbers as cards. For example, 1 would map to Ace, 11 to Jack, 2 to a deuce, etc.\n", "Check all of your inputs. As a young lad, I wrote my blackjack program in Fortran. One of my users pointed out that he could:\n\nEnter a negative number as a bet.\nDeliberately lose.\n\nThe program would then do exactly what it was programmed to do:\n\nSubtract the negative bet from the total won/lost.\nWhich is (of course) equivalent to adding a\npositive number to the total.\n\nSometimes, you can win by losing....\n" ]
[ 14, 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000551840_python.txt
Q: Parse a .txt file I have a .txt file like: Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ? How can i get them by column wise parsing or else how. I need an immediate help...Waiting for an appropriate solution as usual A: for line in open('thefile.txt'): fields = line.split('|') if len(fields) < 4: continue if fields[3].trim() != 'FUNC': continue dowhateveryouwishwith(line, fields) A: I think this might cost less than the use of regexes though i am not totally clear on what you are trying to accomplish symbolList=[] for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] pass if 'FUNC' not in line: pass else: symbolList.append((tempname,line.split('|')[0])) I have learned from other posts it is cheaper and better to wrap up all of the data when you are reading through a file the first time. Thus if you wanted to wrap up the whole datafile in one pass then you could do the following instead fullDict={} for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] if '|' not in line: pass else: tempDict={} dataList=[dataItem.strip() for dataItem in line.strip().split('|')] name=dataList[0].strip() tempDict['Value']=dataList[1] tempDict['Class']=dataList[2] tempDict['Type']=dataList[3] tempDict['Size']=dataList[4] tempDict['Line']=dataList[5] tempDict['Section']=dataList[6] tempDict['o.name']=tempname fullDict[name]=tempDict tempDict={} Then if you want the Func type you would use the following: funcDict={} for record in fullDict: if fullDict[record]['Type']=='FUNC': funcDict[record]=fullDict[record] Sorry for being so obsessive but I am trying to get a better handle on creating list comprehensions and I decided that this was worthy of a shot A: Here is a basic approach. What do you think? # Suppose you have filename "thefile.txt" import re obj = '' for line in file('thefile.txt'): # Checking for the .o file match = re.search('Symbols from (.*):', line) if match: obj = match.groups()[0] # Checking for the symbols. if re.search('|', line): columns = [x.strip() for x in a.split('|')] if columns[3] == 'FUNC': print 'File %s has a FUNC named %s' % (obj, columns[0])
Parse a .txt file
I have a .txt file like: Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ? How can i get them by column wise parsing or else how. I need an immediate help...Waiting for an appropriate solution as usual
[ "for line in open('thefile.txt'):\n fields = line.split('|')\n if len(fields) < 4: continue\n if fields[3].trim() != 'FUNC': continue\n dowhateveryouwishwith(line, fields)\n\n", "I think this might cost less than the use of regexes though i am not totally clear on what you are trying to accomplish\nsymbolList=[]\nfor line in open('datafile.txt','r'):\nif '.o' in line:\n tempname=line.split()[-1][0:-2]\n pass\n\nif 'FUNC' not in line:\n pass\n\nelse:\n symbolList.append((tempname,line.split('|')[0]))\n\nI have learned from other posts it is cheaper and better to wrap up all of the data when you are reading through a file the first time. Thus if you wanted to wrap up the whole datafile in one pass then you could do the following instead\nfullDict={}\nfor line in open('datafile.txt','r'):\n if '.o' in line:\n tempname=line.split()[-1][0:-2]\n if '|' not in line:\n pass\n else:\n tempDict={}\n dataList=[dataItem.strip() for dataItem in line.strip().split('|')]\n name=dataList[0].strip()\n tempDict['Value']=dataList[1]\n tempDict['Class']=dataList[2]\n tempDict['Type']=dataList[3]\n tempDict['Size']=dataList[4]\n tempDict['Line']=dataList[5]\n tempDict['Section']=dataList[6]\n tempDict['o.name']=tempname\n fullDict[name]=tempDict\n tempDict={}\n\nThen if you want the Func type you would use the following:\nfuncDict={}\nfor record in fullDict:\n if fullDict[record]['Type']=='FUNC':\n funcDict[record]=fullDict[record]\n\nSorry for being so obsessive but I am trying to get a better handle on creating list comprehensions and I decided that this was worthy of a shot\n", "Here is a basic approach. What do you think?\n# Suppose you have filename \"thefile.txt\"\nimport re\n\nobj = ''\nfor line in file('thefile.txt'):\n # Checking for the .o file\n match = re.search('Symbols from (.*):', line)\n if match:\n obj = match.groups()[0]\n\n # Checking for the symbols.\n if re.search('|', line):\n columns = [x.strip() for x in a.split('|')]\n if columns[3] == 'FUNC':\n print 'File %s has a FUNC named %s' % (obj, columns[0])\n\n" ]
[ 9, 4, 2 ]
[]
[]
[ "parsing", "python", "text_files" ]
stackoverflow_0000818936_parsing_python_text_files.txt
Q: I need a regex for the href attribute for an mp3 file url in python Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module: import re urls = re.finditer('http://(.*?).mp3', htmlcode) The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one : for url in urls: mp3fileurl = url.group(0) This technique, however, only works sometimes. I realize regular expressions will not be as reliable as a fully fledged parser module. But, sometimes, this is not reliable for the same page. I sometimes receive everything before http for some url entries. I am relatively new to regular expressions. So, I am just wondering if there is a more reliable way to go about it. Thanks in advance. New to stackoverflow and looking forward to contributing some answers as well. A: As pointed out by the other answers, using regular expressions to parse HTML = bad, bad idea. With that in mind, I will add in code of my favorite parser: BeautifulSoup: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(htmlcode) links = soup.findAll('a', href=True) mp3s = [l for l in links if l['href'].endswith('.mp3')] for song in mp3s: print link['href'] A: First, yeah, you should probably be using an HTML parser. Here's some sample code using the HTMLParser module that comes with Python: from HTMLParser import HTMLParser class ImgSrcHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.srcs = [] def handle_starttag(self, tag, attrs): if tag == 'img': self.srcs.append(dict(attrs).get('src')) parser = ImgSrcHTMLParser() parser.feed(html) for src in parser.srcs: print src This collects the src from img tags. It should be pretty easy to adapt it to your purposes assuming you want the href of 'a' tags that end in '.mp3'. Assuming you really want to use a regex, there are some issues with your regex. You aren't delimiting the URL and you're using dot inside the URL. The worst side-effect of this is that a non-mp3 URL followed by an mp3-URL will be treated as one long URL. eg: "http://foo/bar.gif snarf snarf http://baz/quux.mp3". You probably want to require some kind of delimiter (spaces, quotes, depends on what you're doing) and disallow some characters inside URLs (probably the same characters and/or any characters that aren't allowed in URLs). Also, you forgot to escape the "." in ".mp3". So "http://foo/mp3icon.gif" will match as "http://foo/mp3". A: As always I suggest using a html parser like lxml.html instead of regular expressions to extract informations from html files: import lxml.html tree = lxml.html.fromstring(htmlcode) for link in tree.findall(".//a"): url = link.get("href") if url.endswith(".mp3"): print url
I need a regex for the href attribute for an mp3 file url in python
Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module: import re urls = re.finditer('http://(.*?).mp3', htmlcode) The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one : for url in urls: mp3fileurl = url.group(0) This technique, however, only works sometimes. I realize regular expressions will not be as reliable as a fully fledged parser module. But, sometimes, this is not reliable for the same page. I sometimes receive everything before http for some url entries. I am relatively new to regular expressions. So, I am just wondering if there is a more reliable way to go about it. Thanks in advance. New to stackoverflow and looking forward to contributing some answers as well.
[ "As pointed out by the other answers, using regular expressions to parse HTML = bad, bad idea.\nWith that in mind, I will add in code of my favorite parser: BeautifulSoup:\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(htmlcode)\nlinks = soup.findAll('a', href=True)\nmp3s = [l for l in links if l['href'].endswith('.mp3')]\nfor song in mp3s:\n print link['href']\n\n", "First, yeah, you should probably be using an HTML parser. Here's some sample code using the HTMLParser module that comes with Python:\nfrom HTMLParser import HTMLParser\n\nclass ImgSrcHTMLParser(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.srcs = []\n\n def handle_starttag(self, tag, attrs):\n if tag == 'img':\n self.srcs.append(dict(attrs).get('src'))\n\nparser = ImgSrcHTMLParser()\nparser.feed(html)\nfor src in parser.srcs:\n print src\n\nThis collects the src from img tags. It should be pretty easy to adapt it to your purposes assuming you want the href of 'a' tags that end in '.mp3'.\nAssuming you really want to use a regex, there are some issues with your regex. You aren't delimiting the URL and you're using dot inside the URL. The worst side-effect of this is that a non-mp3 URL followed by an mp3-URL will be treated as one long URL. eg: \"http://foo/bar.gif snarf snarf http://baz/quux.mp3\". You probably want to require some kind of delimiter (spaces, quotes, depends on what you're doing) and disallow some characters inside URLs (probably the same characters and/or any characters that aren't allowed in URLs). Also, you forgot to escape the \".\" in \".mp3\". So \"http://foo/mp3icon.gif\" will match as \"http://foo/mp3\".\n", "As always I suggest using a html parser like lxml.html instead of regular expressions to extract informations from html files:\nimport lxml.html\n\ntree = lxml.html.fromstring(htmlcode)\nfor link in tree.findall(\".//a\"):\n url = link.get(\"href\")\n if url.endswith(\".mp3\"):\n print url\n\n" ]
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000822260_python_regex.txt
Q: How do I iterate over the HTML attributes of a Beautiful Soup element? How do I iterate over the HTML attributes of a Beautiful Soup element? Like, given: <foo bar="asdf" blah="123">xyz</foo> I want "bar" and "blah". A: from BeautifulSoup import BeautifulSoup page = BeautifulSoup('<foo bar="asdf" blah="123">xyz</foo>') for attr, value in page.find('foo').attrs: print attr, "=", value # Prints: # bar = asdf # blah = 123
How do I iterate over the HTML attributes of a Beautiful Soup element?
How do I iterate over the HTML attributes of a Beautiful Soup element? Like, given: <foo bar="asdf" blah="123">xyz</foo> I want "bar" and "blah".
[ "from BeautifulSoup import BeautifulSoup\npage = BeautifulSoup('<foo bar=\"asdf\" blah=\"123\">xyz</foo>')\nfor attr, value in page.find('foo').attrs:\n print attr, \"=\", value\n\n# Prints:\n# bar = asdf\n# blah = 123\n\n" ]
[ 32 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0000822571_beautifulsoup_python.txt
Q: WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order I'm learning wxPython so most of the libraries and classes are new to me. I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform. Does wxPython provide functionality that prevents me from doing a if platform.system() == 'Linux' kind of hack? A: The appearance of a dialog can change only if you use stock dialogs (like wx.FileDialog), if you make your own the layout will stay the same on every platform. wx.Dialog has a CreateStdDialogButtonSizer method that creates a wx.StdDialogButtonSizer with standard buttons where you might see differences in layout on different platforms but you don't have to use that. A: You can use a StdDialogButtonSizer http://www.wxpython.org/docs/api/wx.StdDialogButtonSizer-class.html So long as your buttons have the standard IDs they will be put in the correct order. Just to add a wrinkle though, on a Mac for instance, a preferences dialog would not have OK / Cancel buttons. It would automatically apply the preferences as they were entered (or at least on dialog close). So you'd still have to do some platform sniffing in that case. A: If you're going to use wx (or any other x-platform toolkit) you'd better trust that it does the right thing, mon!-) A: There's the GenericMessageDialog widget that should do the right thing depending on the platform (but I've never used it so I'm not sure it does). See the wxPython demo. You can also use the SizedControls addon library (it's part of wxPython). The SizedDialog class helps to create dialogs that conform to the Human Interface Guidelines of each platform. See the wxPython demo.
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
I'm learning wxPython so most of the libraries and classes are new to me. I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform. Does wxPython provide functionality that prevents me from doing a if platform.system() == 'Linux' kind of hack?
[ "The appearance of a dialog can change only if you use stock dialogs (like wx.FileDialog), if you make your own the layout will stay the same on every platform.\nwx.Dialog has a CreateStdDialogButtonSizer method that creates a wx.StdDialogButtonSizer with standard buttons where you might see differences in layout on different platforms but you don't have to use that.\n", "You can use a StdDialogButtonSizer\nhttp://www.wxpython.org/docs/api/wx.StdDialogButtonSizer-class.html\nSo long as your buttons have the standard IDs they will be put in the correct order.\nJust to add a wrinkle though, on a Mac for instance, a preferences dialog would not have OK / Cancel buttons. It would automatically apply the preferences as they were entered (or at least on dialog close). So you'd still have to do some platform sniffing in that case.\n", "If you're going to use wx (or any other x-platform toolkit) you'd better trust that it does the right thing, mon!-)\n", "There's the GenericMessageDialog widget that should do the right thing depending on the platform (but I've never used it so I'm not sure it does). See the wxPython demo. \nYou can also use the SizedControls addon library (it's part of wxPython). The SizedDialog class helps to create dialogs that conform to the Human Interface Guidelines of each platform. See the wxPython demo.\n" ]
[ 4, 2, 0, 0 ]
[]
[]
[ "cross_platform", "python", "user_interface", "wxpython" ]
stackoverflow_0000818942_cross_platform_python_user_interface_wxpython.txt
Q: Why is this recursive statement wrong? This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to: def getNormal(self): normal = normalvariate(40,20) while (normal <=1): normal = normalvariate (40,20) return normal But I'm curious on why the previous recursive statement gets busted. This is the complete source code, in case you're interested. """ bank21: One counter with impatient customers """ from SimPy.SimulationTrace import * from random import * ## Model components ------------------------ class Source(Process): """ Source generates customers randomly """ def generate(self,number): for i in range(number): c = Customer(name = "Customer%02d"%(i,)) activate(c,c.visit(tiempoDeUso=15.0)) validateTime=now() if validateTime<=600: interval = getLambda(self) t = expovariate(interval) yield hold,self,t #esta es la rata de generación else: detenerGeneracion=999 yield hold,self,detenerGeneracion class Customer(Process): """ Customer arrives, is served and leaves """ def visit(self,tiempoDeUso=0): arrive = now() # arrival time print "%8.3f %s: Here I am "%(now(),self.name) yield (request,self,counter),(hold,self,maxWaitTime) wait = now()-arrive # waiting time if self.acquired(counter): print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait) tiempoDeUso=getNormal(self) yield hold,self,tiempoDeUso yield release,self,counter print "%8.3f %s: Completed"%(now(),self.name) else: print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait) ## Experiment data ------------------------- maxTime = 60*10.5 # minutes maxWaitTime = 12.0 # minutes. maximum time to wait ## Model ---------------------------------- def model(): global counter #seed(98989) counter = Resource(name="Las maquinas",capacity=20) initialize() source = Source('Source') firstArrival= expovariate(20.0/60.0) #chequear el expovariate activate(source, source.generate(number=99999),at=firstArrival) simulate(until=maxTime) def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) def getLambda (self): actualTime=now() if (actualTime <=60): return 20.0/60.0 if (actualTime>60)and (actualTime<=120): return 25.0/60.0 if (actualTime>120)and (actualTime<=180): return 40.0/60.0 if (actualTime>180)and (actualTime<=240): return 30.0/60.0 if (actualTime>240)and (actualTime<=300): return 35.0/60.0 if (actualTime>300)and (actualTime<=360): return 42.0/60.0 if (actualTime>360)and (actualTime<=420): return 50.0/60.0 if (actualTime>420)and (actualTime<=480): return 55.0/60.0 if (actualTime>480)and (actualTime<=540): return 45.0/60.0 if (actualTime>540)and (actualTime<=600): return 10.0/60.0 ## Experiment ---------------------------------- model() A: I think you want return getnormal(self) instead of getnormal(self) If the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The abs() function wants a number, and it doesn't know what to do with a None. Also, you could avoid recursion (and the cost of creating a new stack frame) by using def getNormal(self): normal = 0 while normal < 1: normal = normalvariate(40,20) return normal A: You need to have: return getNormal(self) instead of getNormal(self) Really though, there's no need for recursion: def getNormal(self): normal = 0 while normal < 1: normal = normalvariate(40,20) return normal A: I am not entirely sure, but I think you need to change your method to the following: def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: return getNormal(self)
Why is this recursive statement wrong?
This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to: def getNormal(self): normal = normalvariate(40,20) while (normal <=1): normal = normalvariate (40,20) return normal But I'm curious on why the previous recursive statement gets busted. This is the complete source code, in case you're interested. """ bank21: One counter with impatient customers """ from SimPy.SimulationTrace import * from random import * ## Model components ------------------------ class Source(Process): """ Source generates customers randomly """ def generate(self,number): for i in range(number): c = Customer(name = "Customer%02d"%(i,)) activate(c,c.visit(tiempoDeUso=15.0)) validateTime=now() if validateTime<=600: interval = getLambda(self) t = expovariate(interval) yield hold,self,t #esta es la rata de generación else: detenerGeneracion=999 yield hold,self,detenerGeneracion class Customer(Process): """ Customer arrives, is served and leaves """ def visit(self,tiempoDeUso=0): arrive = now() # arrival time print "%8.3f %s: Here I am "%(now(),self.name) yield (request,self,counter),(hold,self,maxWaitTime) wait = now()-arrive # waiting time if self.acquired(counter): print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait) tiempoDeUso=getNormal(self) yield hold,self,tiempoDeUso yield release,self,counter print "%8.3f %s: Completed"%(now(),self.name) else: print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait) ## Experiment data ------------------------- maxTime = 60*10.5 # minutes maxWaitTime = 12.0 # minutes. maximum time to wait ## Model ---------------------------------- def model(): global counter #seed(98989) counter = Resource(name="Las maquinas",capacity=20) initialize() source = Source('Source') firstArrival= expovariate(20.0/60.0) #chequear el expovariate activate(source, source.generate(number=99999),at=firstArrival) simulate(until=maxTime) def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) def getLambda (self): actualTime=now() if (actualTime <=60): return 20.0/60.0 if (actualTime>60)and (actualTime<=120): return 25.0/60.0 if (actualTime>120)and (actualTime<=180): return 40.0/60.0 if (actualTime>180)and (actualTime<=240): return 30.0/60.0 if (actualTime>240)and (actualTime<=300): return 35.0/60.0 if (actualTime>300)and (actualTime<=360): return 42.0/60.0 if (actualTime>360)and (actualTime<=420): return 50.0/60.0 if (actualTime>420)and (actualTime<=480): return 55.0/60.0 if (actualTime>480)and (actualTime<=540): return 45.0/60.0 if (actualTime>540)and (actualTime<=600): return 10.0/60.0 ## Experiment ---------------------------------- model()
[ "I think you want \nreturn getnormal(self)\n\ninstead of\ngetnormal(self)\n\nIf the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The abs() function wants a number, and it doesn't know what to do with a None.\nAlso, you could avoid recursion (and the cost of creating a new stack frame) by using\ndef getNormal(self):\n normal = 0\n while normal < 1:\n normal = normalvariate(40,20)\n return normal\n\n", "You need to have:\nreturn getNormal(self)\n\ninstead of\ngetNormal(self)\n\nReally though, there's no need for recursion:\ndef getNormal(self):\n normal = 0\n while normal < 1:\n normal = normalvariate(40,20)\n\n return normal\n\n", "I am not entirely sure, but I think you need to change your method to the following:\ndef getNormal(self):\n\nnormal = normalvariate(40,20)\n\nif (normal>=1):\n return normal\nelse:\n return getNormal(self)\n\n" ]
[ 8, 1, 1 ]
[]
[]
[ "python", "recursion", "simpy" ]
stackoverflow_0000823141_python_recursion_simpy.txt
Q: Yaml merge in Python So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where: In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones. In any case where the user supplied yaml does not overlap the default tree, the default tree persists. Any superflous branches in the tree provided by the user supplied yaml are appended. I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free. A: You could use PyYAML for parsing the files, and then the following function to merge two trees: def merge(user, default): if isinstance(user,dict) and isinstance(default,dict): for k,v in default.iteritems(): if k not in user: user[k] = v else: user[k] = merge(user[k],v) return user Optionally, you could do a deep-copy of the user-tree before calling this function.
Yaml merge in Python
So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where: In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones. In any case where the user supplied yaml does not overlap the default tree, the default tree persists. Any superflous branches in the tree provided by the user supplied yaml are appended. I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.
[ "You could use PyYAML for parsing the files, and then the following function to merge two trees:\ndef merge(user, default):\n if isinstance(user,dict) and isinstance(default,dict):\n for k,v in default.iteritems():\n if k not in user:\n user[k] = v\n else:\n user[k] = merge(user[k],v)\n return user\n\nOptionally, you could do a deep-copy of the user-tree before calling this function.\n" ]
[ 22 ]
[]
[]
[ "configuration", "python", "yaml" ]
stackoverflow_0000823196_configuration_python_yaml.txt
Q: How can I use Numerical Python with Python 2.6 I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (NumPy) with Python 2.6 in Windows. I'm getting the following error... Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from numpy.core.numeric import array,dot,all File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\__init__.py", line 39, in <module> import core File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\core\__init__.py", line 5, in <module> import multiarray ImportError: Module use of python25.dll conflicts with this version of Python. It appears that the existing module is trying to use the python25.dll file. Is there any way I can tell it to use the python26.dll file instead without modifying the source code? A: How did you install it? NumPy doesn't currently have a Python 2.6 binary. If you have LAPACK/ATLAS/BLAS, etc. and a development environment you should be able to compile numpy from sources. Otherwise I think you're stuck with using Python 2.5 on Windows if you need NumPy. The next version of NumPy should have a 2.6 binary, and it's likely to be out within the next month or so. [Edit]: It appears that a pygame developer created a NumPy 1.2.1 binary for Python 2.6 on Windows, available here. A: NumPy 1.3.0 is available for Python 2.6 now.
How can I use Numerical Python with Python 2.6
I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python (NumPy) with Python 2.6 in Windows. I'm getting the following error... Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from numpy.core.numeric import array,dot,all File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\__init__.py", line 39, in <module> import core File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\core\__init__.py", line 5, in <module> import multiarray ImportError: Module use of python25.dll conflicts with this version of Python. It appears that the existing module is trying to use the python25.dll file. Is there any way I can tell it to use the python26.dll file instead without modifying the source code?
[ "How did you install it? NumPy doesn't currently have a Python 2.6 binary.\nIf you have LAPACK/ATLAS/BLAS, etc. and a development environment you should be able to compile numpy from sources. Otherwise I think you're stuck with using Python 2.5 on Windows if you need NumPy.\nThe next version of NumPy should have a 2.6 binary, and it's likely to be out within the next month or so.\n[Edit]: It appears that a pygame developer created a NumPy 1.2.1 binary for Python 2.6 on Windows, available here.\n", "NumPy 1.3.0 is available for Python 2.6 now.\n" ]
[ 9, 3 ]
[]
[]
[ "numpy", "python", "windows" ]
stackoverflow_0000417664_numpy_python_windows.txt
Q: Why Python informixdb package is throwing an error! I have downloaded & installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box! "A procedure entry point sqli_describe_input_stmt could not be located in the dynamic link isqlit09a.dll" Any ideas what's happening? Platform: Windows Vista (Biz Edition), Python 2.5. A: Which version of IBM Informix Connect (I-Connect) or IBM Informix ClientSDK (CSDK) are you using? The 'describe input' function is a more recent addition, but it is likely that you have it. Have you been able to connect to any Informix DBMS from the command shell? If not, then the suspicion must be that you don't have the correct environment. You would probably need to specify $INFORMIXDIR (or %INFORMIXDIR% - I'm going to omit '$' and '%' sigils from here on); you would need to set INFORMIXSERVER to connect successfully; you would need to have the correct directory (probably INFORMIXDIR/bin on Windows; on Unix, it would be INFORMIXDIR/lib and INFORMIXDIR/lib/esql or INFORMIXDIR/lib/odbc) on your PATH. A: Does other way to connect to database work? Can you use (configure in control panel) ODBC? If ODBC works then you can use Python win32 extensions (ActiveState distribution comes with it) and there is ODBC support. You can also use Jython which can work with ODBC via JDBC-ODBC bridge or with Informix JDBC driver.
Why Python informixdb package is throwing an error!
I have downloaded & installed the latest Python InformixDB package, but when I try to import it from the shell, I am getting the following error in the form of a Windows dialog box! "A procedure entry point sqli_describe_input_stmt could not be located in the dynamic link isqlit09a.dll" Any ideas what's happening? Platform: Windows Vista (Biz Edition), Python 2.5.
[ "Which version of IBM Informix Connect (I-Connect) or IBM Informix ClientSDK (CSDK) are you using? The 'describe input' function is a more recent addition, but it is likely that you have it.\nHave you been able to connect to any Informix DBMS from the command shell? If not, then the suspicion must be that you don't have the correct environment. You would probably need to specify $INFORMIXDIR (or %INFORMIXDIR% - I'm going to omit '$' and '%' sigils from here on); you would need to set INFORMIXSERVER to connect successfully; you would need to have the correct directory (probably INFORMIXDIR/bin on Windows; on Unix, it would be INFORMIXDIR/lib and INFORMIXDIR/lib/esql or INFORMIXDIR/lib/odbc) on your PATH.\n", "Does other way to connect to database work?\nCan you use (configure in control panel) ODBC? If ODBC works then you can use Python win32 extensions (ActiveState distribution comes with it) and there is ODBC support. You can also use Jython which can work with ODBC via JDBC-ODBC bridge or with Informix JDBC driver.\n" ]
[ 1, 0 ]
[]
[]
[ "informix", "python" ]
stackoverflow_0000801515_informix_python.txt
Q: How can I make a change to a module without restarting python interpreter? I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing. Is there an easier way to do this? Thanks, Charlie A: The built-in function reload is what you're looking for. A: It sounds like you want to reload the module, for which there is a built-in function reload(module). That said, when I looked it up just now (to make sure I had my reference right, Google returned a couple of discussions (granted they are several years old) pointing out problems using reload(). You might want to review those if reload() causes you headaches. A: Have a look at IPython http://ipython.scipy.org. It has various features that make working with Python code interactively easier. Some screenshots and tips.
How can I make a change to a module without restarting python interpreter?
I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing. Is there an easier way to do this? Thanks, Charlie
[ "The built-in function reload is what you're looking for.\n", "It sounds like you want to reload the module, for which there is a built-in function reload(module). That said, when I looked it up just now (to make sure I had my reference right, Google returned a couple of discussions (granted they are several years old) pointing out problems using reload(). You might want to review those if reload() causes you headaches.\n", "Have a look at IPython http://ipython.scipy.org. It has various features that make working with Python code interactively easier.\nSome screenshots and tips.\n" ]
[ 10, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000820431_python.txt
Q: logging in mod_python/apache What is the standard way to make python's logging module work with apache/modpython? I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request. Is there an easy way to set this up? A: I've never done it, but it seems that writing a subclass of logging.Handler shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python installed currently but you should be able to call logging.root.addHandler(ApacheLogHandler()) somewhere and get it to work out. YMMV. import logging import apache class ApacheLogHandler(logging.Handler): LEVEL_MAP = { logging.DEBUG: apache.APLOG_DEBUG, logging.INFO: apache.APLOG_INFO, logging.WARNING: apache.APLOG_WARNING, logging.ERROR: apache.APLOG_ERR, logging.CRITICAL: apache.APLOG_CRIT, } def __init__(self, request=None): self.log_error = apache.log_error if request is not None: self.log_error = request.log_error def emit(self,record): apacheLevel = apache.APLOG_DEBUG if record.levelno in ApacheLogHandler.LEVEL_MAP: apacheLevel = ApacheLogHandler.LEVEL_MAP[record.levelno] self.log_error(record.getMessage(), apacheLevel)
logging in mod_python/apache
What is the standard way to make python's logging module work with apache/modpython? I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request. Is there an easy way to set this up?
[ "I've never done it, but it seems that writing a subclass of logging.Handler shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python installed currently but you should be able to call logging.root.addHandler(ApacheLogHandler()) somewhere and get it to work out. YMMV.\nimport logging\nimport apache\n\nclass ApacheLogHandler(logging.Handler):\n LEVEL_MAP = {\n logging.DEBUG: apache.APLOG_DEBUG,\n logging.INFO: apache.APLOG_INFO,\n logging.WARNING: apache.APLOG_WARNING,\n logging.ERROR: apache.APLOG_ERR,\n logging.CRITICAL: apache.APLOG_CRIT,\n }\n def __init__(self, request=None):\n self.log_error = apache.log_error\n if request is not None:\n self.log_error = request.log_error\n def emit(self,record):\n apacheLevel = apache.APLOG_DEBUG\n if record.levelno in ApacheLogHandler.LEVEL_MAP:\n apacheLevel = ApacheLogHandler.LEVEL_MAP[record.levelno]\n self.log_error(record.getMessage(), apacheLevel)\n\n" ]
[ 2 ]
[ "We use the following. It's documented completely here.\n\nWe use logging.fileConfig with a logging.ini file.\nEach module uses logger= logging.getLogger(__name__)\nThen we can do logger.error(\"blah blah blah\") throughout our application.\n\nIt works perfectly. The logging.ini file defines where the log file goes so that we can keep it with other log files for our web app.\n" ]
[ -1 ]
[ "apache", "logging", "mod_python", "python" ]
stackoverflow_0000822875_apache_logging_mod_python_python.txt
Q: App dock icon in wxPython In wxPython on Mac OS X is it possible to display a custom icon when an application is launched. Right now when I launch the app I wrote, a blank white icon is displayed in the dock. How would I go about changing it? A: I have this in my setup file to add an icon: from setuptools import setup APP = ['MyApp.py'] DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'iconfile': 'MyAppIcon.icns' } setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) I think you have to use an icns file. I used img2icns to create one.
App dock icon in wxPython
In wxPython on Mac OS X is it possible to display a custom icon when an application is launched. Right now when I launch the app I wrote, a blank white icon is displayed in the dock. How would I go about changing it?
[ "I have this in my setup file to add an icon:\nfrom setuptools import setup\n\nAPP = ['MyApp.py']\nDATA_FILES = []\nOPTIONS = {'argv_emulation': True, \n 'iconfile': 'MyAppIcon.icns' }\n\nsetup(\n app=APP,\n data_files=DATA_FILES,\n options={'py2app': OPTIONS},\n setup_requires=['py2app'],\n)\n\nI think you have to use an icns file. I used img2icns to create one.\n" ]
[ 1 ]
[]
[]
[ "macos", "python", "wxpython" ]
stackoverflow_0000824458_macos_python_wxpython.txt
Q: Best way for Parsing ANSI and UTF-16LE files using Python 2/3? I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa. Is there a straightforward way to open up the files using the correct file encoding? A: Use the chardet library to detect the encoding. A: You can check for the BOM at the beginning of the file to check whether it's UTF. Then unicode.decode accordingly (using one of the standard encodings). EDIT Or, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf_16_le'. A: What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's “Hello” in windows-1252: 93 48 65 6C 6C 6F 94 ...and in UTF-16LE: 1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20 Aside from the curly quotes, each character maps to the same value, with the addition of a trailing zero byte. In fact, that's true for every character in the ISO-8859-1 character set (windows-1252 extends ISO-8859-1 to add mappings for several printing characters—like curly quotes—to replace the control characters in the range 0x80..0x9F). If you know all the files are either windows-1252 or UTF-16LE, a quick scan for zeroes should be all you need to figure out which is which. There's a good reason why chardet is so slow and complex, but in this case I think you can get away with quick and dirty.
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa. Is there a straightforward way to open up the files using the correct file encoding?
[ "Use the chardet library to detect the encoding.\n", "You can check for the BOM at the beginning of the file to check whether it's UTF.\nThen unicode.decode accordingly (using one of the standard encodings).\nEDIT\nOr, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf_16_le'.\n", "What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's “Hello” in windows-1252:\n93 48 65 6C 6C 6F 94\n\n...and in UTF-16LE:\n1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20\n\nAside from the curly quotes, each character maps to the same value, with the addition of a trailing zero byte. In fact, that's true for every character in the ISO-8859-1 character set (windows-1252 extends ISO-8859-1 to add mappings for several printing characters—like curly quotes—to replace the control characters in the range 0x80..0x9F).\nIf you know all the files are either windows-1252 or UTF-16LE, a quick scan for zeroes should be all you need to figure out which is which. There's a good reason why chardet is so slow and complex, but in this case I think you can get away with quick and dirty. \n" ]
[ 4, 0, 0 ]
[]
[]
[ "ansi", "encoding", "python", "utf_16" ]
stackoverflow_0000819396_ansi_encoding_python_utf_16.txt
Q: rules for slugs and unicode After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles. url encoding is very restrictive. See http://www.blooberry.com/indexdot/html/topics/urlencoding.htm So, for example how do folks deal with for title slugs for things like "Una lágrima cayó en la arena" One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be "una-lagrima-cayo-en-la-arena" However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded. I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? EDIT: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data. A conversion table for the extended ASCII would be nice. Any pointers? Also, since people are asking, I'm using python, running on Google App Engine A: Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in slughifi library. It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEngine). A: I simply use utf-8 for URL paths. As long as the domain is non-IDN FF3, IE works fine with this. Google reads and displays them correctly. The IRI RFC allows Unicode. Just make sure you parse the incoming urls correctly. A: In general this is going to depend on the language you expect to get. If your primary userbase is Japanese, dropping everything but ISO-8859-1 characters is unlikely to go over well. That said, one option might be to use transliteration mode, if your character set conversion library supports it. For example, with GNU iconv, one can do: ] echo Una lágrima cayó en la arena|iconv -f utf8 -t ascii//TRANSLIT Una lagrima cayo en la arena As you can see, the accented characters were automatically converted to something in the ASCII range. How to translate this to code will of course depend on the language you're using, but if your language is based on GNU iconv for charset conversion (and if it's on linux, it probably is), this trick can probably be applied directly by simply specifying "ascii//TRANSLIT" as the convert-to character set. One thing to note with this, however, is it's only effective with characters that "look like" something in ASCII. For example: ] echo 我輩は猫である。名前はまだない。|iconv -f utf8 -t ascii//TRANSLIT ???????????????? As you can see, it's not much help for Japanese, and needs further processing afterward to remove characters not suitable for URLs. A: If all else fails, you could use a conversion table, but there might be a better performing solution available. What server side language are you using?
rules for slugs and unicode
After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles. url encoding is very restrictive. See http://www.blooberry.com/indexdot/html/topics/urlencoding.htm So, for example how do folks deal with for title slugs for things like "Una lágrima cayó en la arena" One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be "una-lagrima-cayo-en-la-arena" However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded. I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO_8859-1 range (<255) and drop everything else? EDIT: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data. A conversion table for the extended ASCII would be nice. Any pointers? Also, since people are asking, I'm using python, running on Google App Engine
[ "Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in slughifi library. It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEngine).\n", "I simply use utf-8 for URL paths. As long as the domain is non-IDN FF3, IE works fine with this. Google reads and displays them correctly. The IRI RFC allows Unicode. Just make sure you parse the incoming urls correctly.\n", "In general this is going to depend on the language you expect to get. If your primary userbase is Japanese, dropping everything but ISO-8859-1 characters is unlikely to go over well.\nThat said, one option might be to use transliteration mode, if your character set conversion library supports it. For example, with GNU iconv, one can do:\n] echo Una lágrima cayó en la arena|iconv -f utf8 -t ascii//TRANSLIT\nUna lagrima cayo en la arena\n\nAs you can see, the accented characters were automatically converted to something in the ASCII range. How to translate this to code will of course depend on the language you're using, but if your language is based on GNU iconv for charset conversion (and if it's on linux, it probably is), this trick can probably be applied directly by simply specifying \"ascii//TRANSLIT\" as the convert-to character set.\nOne thing to note with this, however, is it's only effective with characters that \"look like\" something in ASCII. For example:\n] echo 我輩は猫である。名前はまだない。|iconv -f utf8 -t ascii//TRANSLIT \n????????????????\n\nAs you can see, it's not much help for Japanese, and needs further processing afterward to remove characters not suitable for URLs.\n", "If all else fails, you could use a conversion table, but there might be a better performing solution available. What server side language are you using?\n" ]
[ 8, 4, 2, 1 ]
[]
[]
[ "friendly_url", "google_app_engine", "python", "unicode", "url" ]
stackoverflow_0000820496_friendly_url_google_app_engine_python_unicode_url.txt
Q: Initialisation of keyword args in Python Why does the following: class A(object): def __init__(self, var=[]): self._var = var print 'var = %s %s' % (var, id(var)) a1 = A() a1._var.append('one') a2 = A() result in: var = [] 182897439952 var = ['one'] 182897439952 I don't understand why it is not using a new instance of a list when using optional keyword arguments, can anyone explain this? A: The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called. If you want a new one each time, do this: class A(object): def __init__(self, var=None): if var is None: var = [] self._var = var A: This is simply wrong. You can't (meaningfully) provide a mutable object as a default value in a function declaration. class A(object): def __init__(self, var=[]): self._var = var print 'var = %s %s' % (var, id(var)) You must do something like this. class A(object): def __init__(self, var=None): self._var = var if var is not None else [] print 'var = %s %s' % (var, id(var)) A: The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called. Exactly. To work around this assign None int he function definiton and check for None in the function body: class A(object): def __init__(self, var=None): if var is None: var = [] self._var = var print 'var = %s %s' % (var, id(var))
Initialisation of keyword args in Python
Why does the following: class A(object): def __init__(self, var=[]): self._var = var print 'var = %s %s' % (var, id(var)) a1 = A() a1._var.append('one') a2 = A() result in: var = [] 182897439952 var = ['one'] 182897439952 I don't understand why it is not using a new instance of a list when using optional keyword arguments, can anyone explain this?
[ "The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called.\nIf you want a new one each time, do this:\nclass A(object):\n def __init__(self, var=None):\n if var is None:\n var = []\n self._var = var\n\n", "This is simply wrong. You can't (meaningfully) provide a mutable object as a default value in a function declaration.\nclass A(object):\n def __init__(self, var=[]):\n self._var = var\n print 'var = %s %s' % (var, id(var))\n\nYou must do something like this.\nclass A(object):\n def __init__(self, var=None):\n self._var = var if var is not None else []\n print 'var = %s %s' % (var, id(var))\n\n", "\nThe empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called.\n\nExactly. To work around this assign None int he function definiton and check for None in the function body:\nclass A(object):\n def __init__(self, var=None):\n if var is None:\n var = []\n self._var = var\n print 'var = %s %s' % (var, id(var))\n\n" ]
[ 6, 2, 1 ]
[]
[]
[ "arguments", "initialization", "instantiation", "python" ]
stackoverflow_0000824924_arguments_initialization_instantiation_python.txt
Q: Change/adapt date widget on admin interface I'm configuring the admin site for my new app, and I found a little problem with my setup. I have a 'birth date' field on my database editable via the admin site, but, the date widget isn't very handy for that, because it makes that, if I have to enter i.e. 01-04-1956 in the widget, i would have to page through a lot of years. Also, I don't want people writing the full date manually in only one edit box, as there are always problems with using dashes or slashes as a separator, or introducing date in European, American or Asian format... What would McGyver ( I mean you ) do? A: Use the formfield_overrides option to use a different widget. For example (untested): class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.DateField: {'widget': forms.TextInput}, } Then you'll need to do date conversion/validation yourself.
Change/adapt date widget on admin interface
I'm configuring the admin site for my new app, and I found a little problem with my setup. I have a 'birth date' field on my database editable via the admin site, but, the date widget isn't very handy for that, because it makes that, if I have to enter i.e. 01-04-1956 in the widget, i would have to page through a lot of years. Also, I don't want people writing the full date manually in only one edit box, as there are always problems with using dashes or slashes as a separator, or introducing date in European, American or Asian format... What would McGyver ( I mean you ) do?
[ "Use the formfield_overrides option to use a different widget. For example (untested):\nclass MyModelAdmin(admin.ModelAdmin):\n formfield_overrides = {\n models.DateField: {'widget': forms.TextInput},\n }\n\nThen you'll need to do date conversion/validation yourself.\n" ]
[ 4 ]
[]
[]
[ "date", "django", "python", "widget" ]
stackoverflow_0000825253_date_django_python_widget.txt
Q: What does += mean in Python? I see code like this for example in Python: if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 What does the += mean? A: a += b is essentially the same as a = a + b, except that: + always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable). In a = a + b, a is evaluated twice. Python: Simple Statements A simple statement is comprised within a single logical line. If this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example: # two variables referring to the same list >>> list1 = [] >>> list2 = list1 # += modifies the object pointed to by list1 and list2 >>> list1 += [0] >>> list1, list2 ([0], [0]) # + creates a new, independent object >>> list1 = [] >>> list2 = list1 >>> list1 = list1 + [0] >>> list1, list2 ([0], []) A: a += b is in this case the same as a = a + b In this case cnt += 1 means that cnt is increased by one. Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1. Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''. A: Google 'python += operator' leads you to http://docs.python.org/library/operator.html Search for += once the page loads up for a more detailed answer. A: FYI: it looks like you might have an infinite loop in your example... if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 a condition of entering the loop is that cnt is greater than 0 the loop continues to run as long as cnt is greater than 0 each iteration of the loop increments cnt by 1 The net result is that cnt will always be greater than 0 and the loop will never exit. A: += is the in-place addition operator. It's the same as doing cnt = cnt + 1. For example: >>> cnt = 0 >>> cnt += 2 >>> print cnt 2 >>> cnt += 42 >>> print cnt 44 The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1) There are similar operator for subtraction/multiplication/division/power and others: i -= 1 # same as i = i - 1 i *= 2 # i = i * 2 i /= 3 # i = i / 3 i **= 4 # i = i ** 4 The += operator also works on strings, for example: >>> s = "Hi" >>> s += " there" >>> print s Hi there People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs: If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations. The str.join() method refers to doing the following: mysentence = [] for x in range(100): mysentence.append("test") " ".join(mysentence) ..instead of the more obvious: mysentence = "" for x in range(100): mysentence += " test" The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation) If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.
What does += mean in Python?
I see code like this for example in Python: if cnt > 0 and len(aStr) > 1: while cnt > 0: aStr = aStr[1:]+aStr[0] cnt += 1 What does the += mean?
[ "a += b is essentially the same as a = a + b, except that:\n\n+ always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).\n\nIn a = a + b, a is evaluated twice.\n\nPython: Simple Statements\n\nA simple statement is comprised within a single logical line.\n\n\n\n\nIf this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:\n# two variables referring to the same list\n>>> list1 = []\n>>> list2 = list1\n\n# += modifies the object pointed to by list1 and list2\n>>> list1 += [0]\n>>> list1, list2\n([0], [0])\n\n# + creates a new, independent object\n>>> list1 = []\n>>> list2 = list1\n>>> list1 = list1 + [0]\n>>> list1, list2\n([0], [])\n\n", "a += b\n\nis in this case the same as\na = a + b\n\nIn this case cnt += 1 means that cnt is increased by one.\nNote that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.\nEdit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.\n", "Google 'python += operator' leads you to http://docs.python.org/library/operator.html\nSearch for += once the page loads up for a more detailed answer.\n", "FYI: it looks like you might have an infinite loop in your example...\nif cnt > 0 and len(aStr) > 1:\n while cnt > 0: \n aStr = aStr[1:]+aStr[0]\n cnt += 1\n\n\na condition of entering the loop is that cnt is greater than 0\nthe loop continues to run as long as cnt is greater than 0\neach iteration of the loop increments cnt by 1\n\nThe net result is that cnt will always be greater than 0 and the loop will never exit.\n", "+= is the in-place addition operator.\nIt's the same as doing cnt = cnt + 1. For example:\n>>> cnt = 0\n>>> cnt += 2\n>>> print cnt\n2\n>>> cnt += 42\n>>> print cnt\n44\n\nThe operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)\nThere are similar operator for subtraction/multiplication/division/power and others:\ni -= 1 # same as i = i - 1\ni *= 2 # i = i * 2\ni /= 3 # i = i / 3\ni **= 4 # i = i ** 4\n\nThe += operator also works on strings, for example:\n>>> s = \"Hi\"\n>>> s += \" there\"\n>>> print s\nHi there\n\nPeople tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the \"Sequence Types\" docs:\n\n\nIf s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.\n\n\nThe str.join() method refers to doing the following:\nmysentence = []\nfor x in range(100):\n mysentence.append(\"test\")\n\" \".join(mysentence)\n\n..instead of the more obvious:\nmysentence = \"\"\nfor x in range(100):\n mysentence += \" test\"\n\nThe problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)\nIf you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then \"\".join()'ing it.\n" ]
[ 77, 24, 7, 1, 0 ]
[ "it means \"append \"THIS\" to the current value\"\nexample:\na = \"hello\";\na += \" world\";\nprinting a now will output: \"hello world\"\n" ]
[ -3 ]
[ "python", "syntax" ]
stackoverflow_0000823561_python_syntax.txt
Q: WxPython: FoldPanelBar not really folding I've written the following code using FoldPanelBar: import wx import wx.lib.agw.foldpanelbar as fpb class frame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.text_ctrl_1=wx.TextCtrl(self,-1,style=wx.TE_MULTILINE) self.fpb=fpb.FoldPanelBar(self,-1, style=fpb.FPB_HORIZONTAL) self.fold_panel=self.fpb.AddFoldPanel("Thing") self.thing=wx.TextCtrl(self.fold_panel,-1, size=(400,-1), style=wx.TE_MULTILINE) self.fpb.AddFoldPanelWindow(self.fold_panel, self.thing) self.sizer_1=wx.BoxSizer(wx.HORIZONTAL) self.sizer_1.Add(self.text_ctrl_1,1,wx.EXPAND) self.sizer_1.Add(self.fpb,1,wx.EXPAND) self.SetSizer(self.sizer_1) self.Show() if __name__=="__main__": app=wx.PySimpleApp() frame(None,-1) app.MainLoop() This is what it looks like before folding: alt text http://img23.imageshack.us/img23/4309/before.gif The right textbox is in the fold panel, so when I click the arrow, it disappears. However, it looks like this: alt text http://img22.imageshack.us/img22/6306/afterz.gif I expected the left textbox to grow in size to fill the whole frame. What am I doing wrong? A: This does what you want I think. I haven't tested multiple panels in the foldpanelbar, you might need to limit the size of the foldpanelbar explicitly to prevent it from getting too wide. import wx import wx.lib.agw.foldpanelbar as fpb class frame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.text_ctrl_1=wx.TextCtrl(self, -1, size=(400, 100), style=wx.TE_MULTILINE) self.fpb = fpb.FoldPanelBar(self, -1, style=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE) self.fold_panel = self.fpb.AddFoldPanel("Thing") self.thing = wx.TextCtrl(self.fold_panel, -1, size=(400, -1), style=wx.TE_MULTILINE) self.fpb.AddFoldPanelWindow(self.fold_panel, self.thing) self.fpb.Bind(fpb.EVT_CAPTIONBAR, self.onCaptionBar) self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL) self.sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND) self.sizer_1.Add(self.fpb, 0, wx.EXPAND) self.SetSizer(self.sizer_1) self.ResizeFPB() def onCaptionBar(self, event): event.Skip() wx.CallAfter(self.ResizeFPB) def ResizeFPB(self): sizeNeeded = self.fpb.GetPanelsLength(0, 0)[2] self.fpb.SetMinSize((sizeNeeded, self.fpb.GetSize()[1])) self.Fit() app = wx.App(0) f = frame(None) f.Show() app.MainLoop()
WxPython: FoldPanelBar not really folding
I've written the following code using FoldPanelBar: import wx import wx.lib.agw.foldpanelbar as fpb class frame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.text_ctrl_1=wx.TextCtrl(self,-1,style=wx.TE_MULTILINE) self.fpb=fpb.FoldPanelBar(self,-1, style=fpb.FPB_HORIZONTAL) self.fold_panel=self.fpb.AddFoldPanel("Thing") self.thing=wx.TextCtrl(self.fold_panel,-1, size=(400,-1), style=wx.TE_MULTILINE) self.fpb.AddFoldPanelWindow(self.fold_panel, self.thing) self.sizer_1=wx.BoxSizer(wx.HORIZONTAL) self.sizer_1.Add(self.text_ctrl_1,1,wx.EXPAND) self.sizer_1.Add(self.fpb,1,wx.EXPAND) self.SetSizer(self.sizer_1) self.Show() if __name__=="__main__": app=wx.PySimpleApp() frame(None,-1) app.MainLoop() This is what it looks like before folding: alt text http://img23.imageshack.us/img23/4309/before.gif The right textbox is in the fold panel, so when I click the arrow, it disappears. However, it looks like this: alt text http://img22.imageshack.us/img22/6306/afterz.gif I expected the left textbox to grow in size to fill the whole frame. What am I doing wrong?
[ "This does what you want I think. I haven't tested multiple panels in the foldpanelbar, you might need to limit the size of the foldpanelbar explicitly to prevent it from getting too wide.\nimport wx\nimport wx.lib.agw.foldpanelbar as fpb\n\nclass frame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n self.text_ctrl_1=wx.TextCtrl(self, -1, size=(400, 100),\n style=wx.TE_MULTILINE)\n self.fpb = fpb.FoldPanelBar(self, -1,\n style=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE)\n self.fold_panel = self.fpb.AddFoldPanel(\"Thing\")\n self.thing = wx.TextCtrl(self.fold_panel, -1, size=(400, -1),\n style=wx.TE_MULTILINE)\n self.fpb.AddFoldPanelWindow(self.fold_panel, self.thing)\n self.fpb.Bind(fpb.EVT_CAPTIONBAR, self.onCaptionBar)\n self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)\n self.sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND)\n self.sizer_1.Add(self.fpb, 0, wx.EXPAND)\n self.SetSizer(self.sizer_1)\n self.ResizeFPB()\n\n def onCaptionBar(self, event):\n event.Skip()\n wx.CallAfter(self.ResizeFPB)\n\n def ResizeFPB(self):\n sizeNeeded = self.fpb.GetPanelsLength(0, 0)[2]\n self.fpb.SetMinSize((sizeNeeded, self.fpb.GetSize()[1]))\n self.Fit()\n\n\napp = wx.App(0)\nf = frame(None)\nf.Show()\napp.MainLoop()\n\n" ]
[ 1 ]
[]
[]
[ "python", "sizer", "wxpython" ]
stackoverflow_0000815589_python_sizer_wxpython.txt
Q: Python: finding uid/gid for a given username/groupname (for os.chown) What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic. [Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same code on windows and unix. try: from pwd import getpwnam except: getpwnam = lambda x: (0,0,0) os.chown = lambda x, y, z: True os.chmod = lambda x, y: True os.fchown = os.chown os.fchmod = os.chmod A: Use the pwd and grp modules: from pwd import getpwnam print getpwnam('someuser')[2] # or print getpwnam('someuser').pw_uid print grp.getgrnam('somegroup')[2]
Python: finding uid/gid for a given username/groupname (for os.chown)
What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic. [Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same code on windows and unix. try: from pwd import getpwnam except: getpwnam = lambda x: (0,0,0) os.chown = lambda x, y, z: True os.chmod = lambda x, y: True os.fchown = os.chown os.fchmod = os.chmod
[ "Use the pwd and grp modules:\nfrom pwd import getpwnam \n\nprint getpwnam('someuser')[2]\n# or\nprint getpwnam('someuser').pw_uid\nprint grp.getgrnam('somegroup')[2]\n\n" ]
[ 111 ]
[]
[]
[ "python" ]
stackoverflow_0000826082_python.txt
Q: How to separate content from a file that is a container for binary and other forms of content I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. I would appreciate any help to identify some relevant reading material. I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this: <FILENAME>h65803h6580301.gif <DESCRIPTION>GRAPHIC <TEXT> begin 644 h65803h6580301.gif M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0 M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]? I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE? Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? I can find the lines where the graphics begin: filerefbin=file('myfile.txt','rb') wholeFile=filerefbin.read() import re graphicReg=re.compile('<DESCRIPTION>GRAPHIC') locationGraphics=graphicReg.finditer(wholeFile) graphicsTags=[] for match in locationGraphics: graphicsTags.append(match.span()) I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n I love this site and I love PYTHON This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command: import uu uu.decode(r'c:\test2.txt',r'c:\test.gif') I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it. A: What you're looking at isn't "binary", it's uuencoded. Python's standard library includes the module uu, to handle uuencoded data. The module uu requires the use of temporary files for encoding and decoding. You can accomplish this without resorting to temporary files by using Python's codecs module like this: import codecs data = "Let's just pretend that this is binary data, ok?" uuencode = codecs.getencoder("uu") data_uu, n = uuencode(data) uudecode = codecs.getdecoder("uu") decoded, m = uudecode(data_uu) print """* The initial input: %(data)s * Encoding these %(n)d bytes produces: %(data_uu)s * When we decode these %(m)d bytes, we get the original data back: %(decoded)s""" % globals() A: You definitely need to be reading in binary mode if the content includes JPEG images. As well, Python includes an SGML parser, http://docs.python.org/library/sgmllib.html . There is no example there, but all you need to do is setup do_ methods to handle the sgml tags you wish. A: You need to open(filename,'rb') to open the file in binary mode. Be aware that this will cause python to give You confusing, two-byte line endings on some operating systems.
How to separate content from a file that is a container for binary and other forms of content
I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. I would appreciate any help to identify some relevant reading material. I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this: <FILENAME>h65803h6580301.gif <DESCRIPTION>GRAPHIC <TEXT> begin 644 h65803h6580301.gif M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0 M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]? I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE? Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? I can find the lines where the graphics begin: filerefbin=file('myfile.txt','rb') wholeFile=filerefbin.read() import re graphicReg=re.compile('<DESCRIPTION>GRAPHIC') locationGraphics=graphicReg.finditer(wholeFile) graphicsTags=[] for match in locationGraphics: graphicsTags.append(match.span()) I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n I love this site and I love PYTHON This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command: import uu uu.decode(r'c:\test2.txt',r'c:\test.gif') I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it.
[ "What you're looking at isn't \"binary\", it's uuencoded. Python's standard library includes the module uu, to handle uuencoded data.\nThe module uu requires the use of temporary files for encoding and decoding. You can accomplish this without resorting to temporary files by using Python's codecs module like this:\nimport codecs\n\ndata = \"Let's just pretend that this is binary data, ok?\"\nuuencode = codecs.getencoder(\"uu\")\ndata_uu, n = uuencode(data)\nuudecode = codecs.getdecoder(\"uu\")\ndecoded, m = uudecode(data_uu)\n\nprint \"\"\"* The initial input:\n%(data)s\n* Encoding these %(n)d bytes produces:\n%(data_uu)s\n* When we decode these %(m)d bytes, we get the original data back:\n%(decoded)s\"\"\" % globals()\n\n", "You definitely need to be reading in binary mode if the content includes JPEG images.\nAs well, Python includes an SGML parser, http://docs.python.org/library/sgmllib.html .\nThere is no example there, but all you need to do is setup do_ methods to handle the sgml tags you wish.\n", "You need to open(filename,'rb') to open the file in binary mode. Be aware that this will cause python to give You confusing, two-byte line endings on some operating systems.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "binary", "encoding", "file", "python", "text" ]
stackoverflow_0000822161_binary_encoding_file_python_text.txt
Q: List Comprehensions and Conditions? I am trying to see if I can make this code better using list comprehensions. Lets say that I have the following lists: a_list = [ 'HELLO', 'FOO', 'FO1BAR', 'ROOBAR', 'SHOEBAR' ] regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE), lambda x: re.search(r'RO', x, re.IGNORECASE)] I basically want to add all the elements that do not have any matches in the regex_list into another list. E.g. ==> newlist = [] for each in a_list: for regex in regex_list: if(regex(each) == None): newlist.append(each) How can I do this using list comprehensions? Is it even possible? A: Sure, I think this should do it newlist = [s for s in a_list if not any(r(s) for r in regex_list)] EDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list that doesn't match all the regexes - and what's more, it adds each string once for each regex that it doesn't match. My list comprehension does what I think you meant, which is add only one copy of each string that doesn't match any of the regexes. A: I'd work your code down to this: a_list = [ 'HELLO', 'FOO', 'FO1BAR', 'ROOBAR', 'SHOEBAR' ] regex_func = lambda x: not re.search(r'(FOO|RO)', x, re.IGNORECASE) Then you have two options: Filter newlist = filter(regex_func, a_list) List comprehensions newlist = [x for x in a_list if regex_func(x)]
List Comprehensions and Conditions?
I am trying to see if I can make this code better using list comprehensions. Lets say that I have the following lists: a_list = [ 'HELLO', 'FOO', 'FO1BAR', 'ROOBAR', 'SHOEBAR' ] regex_list = [lambda x: re.search(r'FOO', x, re.IGNORECASE), lambda x: re.search(r'RO', x, re.IGNORECASE)] I basically want to add all the elements that do not have any matches in the regex_list into another list. E.g. ==> newlist = [] for each in a_list: for regex in regex_list: if(regex(each) == None): newlist.append(each) How can I do this using list comprehensions? Is it even possible?
[ "Sure, I think this should do it\nnewlist = [s for s in a_list if not any(r(s) for r in regex_list)]\n\nEDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list that doesn't match all the regexes - and what's more, it adds each string once for each regex that it doesn't match. My list comprehension does what I think you meant, which is add only one copy of each string that doesn't match any of the regexes.\n", "I'd work your code down to this:\na_list = [\n 'HELLO',\n 'FOO',\n 'FO1BAR',\n 'ROOBAR',\n 'SHOEBAR'\n ]\nregex_func = lambda x: not re.search(r'(FOO|RO)', x, re.IGNORECASE) \n\nThen you have two options:\n\nFilter\nnewlist = filter(regex_func, a_list)\nList comprehensions\nnewlist = [x for x in a_list if regex_func(x)]\n\n" ]
[ 18, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0000826407_list_list_comprehension_python.txt
Q: how to get the n-th record of a datastore query Suppose that I have the model Foo in GAE and this query: query = Foo.all().order('-key') I want to get the n-th record. What is the most efficient way to achieve that? Will the solution break if the ordering property is not unique, such as the one below: query = Foo.all().order('-color') edit: n > 1000 edit 2: I want to develop a friendly paging mechanism that shows pages available (such as Page 1, Page 2, ... Page 185) and requires a "?page=x" in the query string, instead of a "?bookmark=XXX". When page = x, the query is to fetch the records beginning from the first record of that page. A: There is no efficient way to do this - in any DBMS. In every case, you have to at least read sequentially through the index records until you find the nth one, then look up the corresponding data record. This is more or less what fetch(count, offset) does in GAE, with the additional limitation of 1000 records. A better approach to this is to keep a 'bookmark', consisting of the value of the field you're ordering on for the last entity you retrieved, and the entity's key. Then, when you want to continue from where you left off, you can add the field's value as the lower bound of an inequality query, and skip records until you match or exceed the last one you saw. If you want to provide 'friendly' page offsets to users, what you can do is to use memcache to store an association between a start offset and a bookmark (order_property, key) tuple. When you generate a page, insert or update the bookmark for the entity following the last one. When you fetch a page, use the bookmark if it exists, or generate it the hard way, by doing queries with offsets - potentially multiple queries if the offset is high enough. A: Documentation for the Query class can be found at: http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query The query class provides fetch witch takes a limit and a offset in your case 1 and n The running time of the fetch grows linearly with the offset + the limit so the only way to optimize in your case would be to make sure that the records you want to access most often are closer to the beginning of the array. You could use query.filter('key = ', n) query.get() which would return the first match with a key of n
how to get the n-th record of a datastore query
Suppose that I have the model Foo in GAE and this query: query = Foo.all().order('-key') I want to get the n-th record. What is the most efficient way to achieve that? Will the solution break if the ordering property is not unique, such as the one below: query = Foo.all().order('-color') edit: n > 1000 edit 2: I want to develop a friendly paging mechanism that shows pages available (such as Page 1, Page 2, ... Page 185) and requires a "?page=x" in the query string, instead of a "?bookmark=XXX". When page = x, the query is to fetch the records beginning from the first record of that page.
[ "There is no efficient way to do this - in any DBMS. In every case, you have to at least read sequentially through the index records until you find the nth one, then look up the corresponding data record. This is more or less what fetch(count, offset) does in GAE, with the additional limitation of 1000 records.\nA better approach to this is to keep a 'bookmark', consisting of the value of the field you're ordering on for the last entity you retrieved, and the entity's key. Then, when you want to continue from where you left off, you can add the field's value as the lower bound of an inequality query, and skip records until you match or exceed the last one you saw.\nIf you want to provide 'friendly' page offsets to users, what you can do is to use memcache to store an association between a start offset and a bookmark (order_property, key) tuple. When you generate a page, insert or update the bookmark for the entity following the last one. When you fetch a page, use the bookmark if it exists, or generate it the hard way, by doing queries with offsets - potentially multiple queries if the offset is high enough.\n", "Documentation for the Query class can be found at:\nhttp://code.google.com/appengine/docs/python/datastore/queryclass.html#Query\nThe query class provides fetch witch takes a limit and a offset\nin your case 1 and n\nThe running time of the fetch grows linearly with the offset + the limit\nso the only way to optimize in your case would be to make sure that the records you want\nto access most often are closer to the beginning of the array.\nYou could use \nquery.filter('key = ', n)\nquery.get()\nwhich would return the first match with a key of n\n" ]
[ 3, 2 ]
[]
[]
[ "custompaging", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0000826724_custompaging_google_app_engine_google_cloud_datastore_python.txt
Q: Python interpreter with Linux Screen I was working with Python with a Linux terminal screen. When I typed: help(somefunction) It printed the appropriate output, but then my screen was stuck, and at the bottom of the terminal was "(end)". How do I get unstuck? Thanks in advance. A: The standard on GNU (or other Unix-like) systems is to use the environment variable PAGER for the command that should receive output for viewing one screenful ("page") at a time. Mine is set to: $ echo $PAGER less Yours might be set to more, or a different command, or not set at all in which case a system-wide default command will be used. It sounds like yours is modelled after the more program. The program is showing you page-by-page output, and in this case telling you you're at the end. Most of them (basically, any pager more modern than more) allow you to go forward and backward in the output by using the cursor control keys (arrows and PgUp/PgDown), and many other operations besides. Since you can do all these things wherever you are in the output, the program needs an explicit command from you to know that you're done navigating the output. In all likelihood that command is the keypress q. For more information on how to drive your pager, e.g. less, read its manpage with the command man less (which, of course, will show pages of output using the pager program :-) A: That program uses your pager, which is by default more. You can exit just by pressing q.
Python interpreter with Linux Screen
I was working with Python with a Linux terminal screen. When I typed: help(somefunction) It printed the appropriate output, but then my screen was stuck, and at the bottom of the terminal was "(end)". How do I get unstuck? Thanks in advance.
[ "The standard on GNU (or other Unix-like) systems is to use the environment variable PAGER for the command that should receive output for viewing one screenful (\"page\") at a time.\nMine is set to:\n$ echo $PAGER\nless\n\nYours might be set to more, or a different command, or not set at all in which case a system-wide default command will be used.\nIt sounds like yours is modelled after the more program. The program is showing you page-by-page output, and in this case telling you you're at the end.\nMost of them (basically, any pager more modern than more) allow you to go forward and backward in the output by using the cursor control keys (arrows and PgUp/PgDown), and many other operations besides.\nSince you can do all these things wherever you are in the output, the program needs an explicit command from you to know that you're done navigating the output. In all likelihood that command is the keypress q.\nFor more information on how to drive your pager, e.g. less, read its manpage with the command man less (which, of course, will show pages of output using the pager program :-)\n", "That program uses your pager, which is by default more. You can exit just by pressing q.\n" ]
[ 10, 5 ]
[]
[]
[ "linux", "python", "terminal" ]
stackoverflow_0000827879_linux_python_terminal.txt
Q: Extract domain name from a host name Is there a programatic way to find the domain name from a given hostname? given -> www.yahoo.co.jp return -> yahoo.co.jp The approach that works but is very slow is: split on "." and remove 1 group from the left, join and query an SOA record using dnspython when a valid SOA record is returned, consider that a domain Is there a cleaner/faster way to do this without using regexps? A: There's no trivial definition of which "domain name" is the parent of any particular "host name". Your current method of traversing up the tree until you see an SOA record is actually the most correct. Technically, what you're doing there is finding a "zone cut", and in the vast majority of cases that will correspond to the point at which the domain was delegated from its TLD. Any method that relies on mere text parsing of the host name without reference to the DNS is doomed to failure. Alternatively, make use of the centrally maintained lists of delegation-centric domains from http://publicsuffix.org/, but beware that these lists can be incomplete and/or out of date. See also this question where all of this has been gone over before... A: You can use partition instead of split: >>> 'www.yahoo.co.jp'.partition('.')[2] 'yahoo.co.jp' This will help with the parsing but obviously won't check if the returned string is a valid domain. A: Your algorithm is the right one. Since zone cuts are not reflected in the domain name (you see domain cuts - the dots - but not zone cuts), it is the only correct one. An approximate algorithm is to use a list of zones, like the one mentioned by Alnitak. Remember that these static lists are not authoritative, they lack many registries, they are stale, etc.
Extract domain name from a host name
Is there a programatic way to find the domain name from a given hostname? given -> www.yahoo.co.jp return -> yahoo.co.jp The approach that works but is very slow is: split on "." and remove 1 group from the left, join and query an SOA record using dnspython when a valid SOA record is returned, consider that a domain Is there a cleaner/faster way to do this without using regexps?
[ "There's no trivial definition of which \"domain name\" is the parent of any particular \"host name\".\nYour current method of traversing up the tree until you see an SOA record is actually the most correct.\nTechnically, what you're doing there is finding a \"zone cut\", and in the vast majority of cases that will correspond to the point at which the domain was delegated from its TLD.\nAny method that relies on mere text parsing of the host name without reference to the DNS is doomed to failure.\nAlternatively, make use of the centrally maintained lists of delegation-centric domains from http://publicsuffix.org/, but beware that these lists can be incomplete and/or out of date.\nSee also this question where all of this has been gone over before...\n", "You can use partition instead of split:\n>>> 'www.yahoo.co.jp'.partition('.')[2]\n'yahoo.co.jp'\n\nThis will help with the parsing but obviously won't check if the returned string is a valid domain.\n", "Your algorithm is the right one. Since zone cuts are not reflected in the domain name (you see domain cuts - the dots - but not zone cuts), it is the only correct one.\nAn approximate algorithm is to use a list of zones, like the one mentioned by Alnitak. Remember that these static lists are not authoritative, they lack many registries, they are stale, etc.\n" ]
[ 15, 4, 1 ]
[]
[]
[ "dns", "hostname", "python" ]
stackoverflow_0000825694_dns_hostname_python.txt
Q: Why in the world does Tkinter break using canvas.create_image? I've got a python GUI app in the workings, which I intend to use on both Windows and Mac. The documentation on Tkinter isn't the greatest, and google-fu has failed me. In short, I'm doing: c = Canvas( master=frame, width=settings.WINDOW_SIZE[0], height=settings.WINDOW_SIZE[1], background=settings.CANVAS_COLOUR ) file = PhotoImage(file=os.path.join('path', 'to', 'gif')) c.create_bitmap(position, image=file) c.pack() root.mainloop() If I comment out the create_bitmap line, the app draws fine. If I comment it back in, I get the following error: _tkinter.TclError: unknown option "-image" Which is odd. Tkinter is fine, according to the python tests (ie, importing _tkinter, Tkinter, and doing Tk()). I've since installed PIL against my windows setup (XP SP3, Python 2.6) imagining that it was doing some of the heavy lifting at a low level. It doesn't seem to be; I still get the aforementioned error. The full stacktrace, excluding the code I've already pasted, is: File "C:\Python26\lib\lib-tk\Tkinter.py", line 2153, in create_bitmap return self._create('bitmap', args, kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 2147, in _create *(args + self._options(cnf, kw)))) Anyone able to shed any light? A: Tk has two types of graphics, bitmap and image. Images come in two flavours, bitmap and photo. Bitmaps and Images of type bitmap are not the same thing, which leads to confusion in docs. PhotoImage creates an image of type photo, and needs an image object in the canvas, so the solution is, as you already concluded, to use create_image. A: Short answer: Don't use create_bitmap when you mean to use create_image. A: The create_bitmap() method does not have an image argument; it has a bitmap argument instead. The error you get comes from the fact that in Tkinter, a Tcl interpreter is running embedded in the Python process, and all GUI interaction goes back and forth between Python and Tcl; so, the error you get comes from the fact that Tcl replies "I don't know any -image option in the .create_bitmap call". In any case, like Jeff said, you probably want the create_image method.
Why in the world does Tkinter break using canvas.create_image?
I've got a python GUI app in the workings, which I intend to use on both Windows and Mac. The documentation on Tkinter isn't the greatest, and google-fu has failed me. In short, I'm doing: c = Canvas( master=frame, width=settings.WINDOW_SIZE[0], height=settings.WINDOW_SIZE[1], background=settings.CANVAS_COLOUR ) file = PhotoImage(file=os.path.join('path', 'to', 'gif')) c.create_bitmap(position, image=file) c.pack() root.mainloop() If I comment out the create_bitmap line, the app draws fine. If I comment it back in, I get the following error: _tkinter.TclError: unknown option "-image" Which is odd. Tkinter is fine, according to the python tests (ie, importing _tkinter, Tkinter, and doing Tk()). I've since installed PIL against my windows setup (XP SP3, Python 2.6) imagining that it was doing some of the heavy lifting at a low level. It doesn't seem to be; I still get the aforementioned error. The full stacktrace, excluding the code I've already pasted, is: File "C:\Python26\lib\lib-tk\Tkinter.py", line 2153, in create_bitmap return self._create('bitmap', args, kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 2147, in _create *(args + self._options(cnf, kw)))) Anyone able to shed any light?
[ "Tk has two types of graphics, bitmap and image. Images come in two flavours, bitmap and photo. Bitmaps and Images of type bitmap are not the same thing, which leads to confusion in docs.\nPhotoImage creates an image of type photo, and needs an image object in the canvas, so the solution is, as you already concluded, to use create_image.\n", "Short answer:\nDon't use create_bitmap when you mean to use create_image.\n", "The create_bitmap() method does not have an image argument; it has a bitmap argument instead.\nThe error you get comes from the fact that in Tkinter, a Tcl interpreter is running embedded in the Python process, and all GUI interaction goes back and forth between Python and Tcl; so, the error you get comes from the fact that Tcl replies \"I don't know any -image option in the .create_bitmap call\".\nIn any case, like Jeff said, you probably want the create_image method.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "python", "python_imaging_library", "tk_toolkit", "tkinter" ]
stackoverflow_0000824988_python_python_imaging_library_tk_toolkit_tkinter.txt
Q: Python - Save the context I need to save the context of the program before exiting ... I've put all the needed stuff to an object that I've previously created a I tried many times to picke it, but no way !! I continuously have errors like : PicklingError: Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at 0x2a969cd9c0> OSError: [Errno 1] Operation not permitted: [the file that I am referencing is rwx for all] the code that I use is : f = open ("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 'w').close() os.chmod("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 0777) f = open ("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 'w') pickle.dump(useCaseList, f) Any knows how can I solve these problems or has another solution ? Thanks in advance A: See the python doc What can be pickled and unpickled. You have objects that can not be pickled.
Python - Save the context
I need to save the context of the program before exiting ... I've put all the needed stuff to an object that I've previously created a I tried many times to picke it, but no way !! I continuously have errors like : PicklingError: Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at 0x2a969cd9c0> OSError: [Errno 1] Operation not permitted: [the file that I am referencing is rwx for all] the code that I use is : f = open ("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 'w').close() os.chmod("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 0777) f = open ("/xxxx/yyyy/toto/titi/important_stuff//impo/tmp/contest.obj", 'w') pickle.dump(useCaseList, f) Any knows how can I solve these problems or has another solution ? Thanks in advance
[ "See the python doc What can be pickled and unpickled. You have objects that can not be pickled.\n" ]
[ 3 ]
[]
[]
[ "pickle", "python", "serialization" ]
stackoverflow_0000828494_pickle_python_serialization.txt
Q: wxPython - Redrawing Error when replacing wxFrame's Panel I'm creating a small wxPython utility for the first time, and I'm stuck on a problem. I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components. 1: Is there a better way of dynamically adding content to a panel? 2: Why, in the following example, do I get a a strange redraw error in which in the panel is drawn only in the top left hand corner, and when resized, the panel is drawn correctly? (WinXP, Python 2.5, latest wxPython) Thank you for the help! import wx class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'TimeTablr') #Variables self.iCalFiles = ['Empty', 'Empty', 'Empty'] self.panel = wx.Panel(self, -1) self.layoutElements() def layoutElements(self): self.panel.Destroy() self.panel = wx.Panel(self, -1) #Buttons self.getFilesButton = wx.Button(self.panel, 1, 'Get Files') self.calculateButton = wx.Button(self.panel, 2, 'Calculate') self.quitButton = wx.Button(self.panel, 3, 'Quit Application') #Binds self.Bind(wx.EVT_BUTTON, self.Quit, id=3) self.Bind(wx.EVT_BUTTON, self.getFiles, id=1) #Layout Managers vbox = wx.BoxSizer(wx.VERTICAL) #Panel Contents self.ctrlsToDescribe = [] self.fileNames = [] for iCalFile in self.iCalFiles: self.ctrlsToDescribe.append(wx.TextCtrl(self.panel, -1)) self.fileNames.append(wx.StaticText(self.panel, -1, iCalFile)) #Add Components to Layout Managers for i in range(0, len(self.ctrlsToDescribe)): hboxtemp = wx.BoxSizer(wx.HORIZONTAL) hboxtemp.AddStretchSpacer() hboxtemp.Add(self.fileNames[i], 1, wx.EXPAND) hboxtemp.AddStretchSpacer() hboxtemp.Add(self.ctrlsToDescribe[i], 2, wx.EXPAND) hboxtemp.AddStretchSpacer() vbox.Add(hboxtemp) finalHBox = wx.BoxSizer(wx.HORIZONTAL) finalHBox.Add(self.getFilesButton) finalHBox.Add(self.calculateButton) finalHBox.Add(self.quitButton) vbox.Add(finalHBox) self.panel.SetSizer(vbox) self.Show() def Quit(self, event): self.Destroy() def getFiles(self, event): self.iCalFiles = ['Example1','Example1','Example1','Example1','Example1','Example1'] self.layoutElements() self.Update() app = wx.App() MainFrame() app.MainLoop() del app A: 1) I beleive the Sizer will let you insert elements into the existing ordering of them. That would probably be a bit faster. 2) I don't see the behavior you're describing on OSX, but at a guess, try calling self.Layout() before self.Show() in layoutElements? A: I had a similar problem where the panel would be squished into the upper-right corner. I solved it by calling panel.Fit(). In your example, you should call self.panel.Fit() after self.panel.SetSizer(vbox)
wxPython - Redrawing Error when replacing wxFrame's Panel
I'm creating a small wxPython utility for the first time, and I'm stuck on a problem. I would like to add components to an already created frame. To do this, I am destroying the frame's old panel, and creating a new panel with all new components. 1: Is there a better way of dynamically adding content to a panel? 2: Why, in the following example, do I get a a strange redraw error in which in the panel is drawn only in the top left hand corner, and when resized, the panel is drawn correctly? (WinXP, Python 2.5, latest wxPython) Thank you for the help! import wx class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'TimeTablr') #Variables self.iCalFiles = ['Empty', 'Empty', 'Empty'] self.panel = wx.Panel(self, -1) self.layoutElements() def layoutElements(self): self.panel.Destroy() self.panel = wx.Panel(self, -1) #Buttons self.getFilesButton = wx.Button(self.panel, 1, 'Get Files') self.calculateButton = wx.Button(self.panel, 2, 'Calculate') self.quitButton = wx.Button(self.panel, 3, 'Quit Application') #Binds self.Bind(wx.EVT_BUTTON, self.Quit, id=3) self.Bind(wx.EVT_BUTTON, self.getFiles, id=1) #Layout Managers vbox = wx.BoxSizer(wx.VERTICAL) #Panel Contents self.ctrlsToDescribe = [] self.fileNames = [] for iCalFile in self.iCalFiles: self.ctrlsToDescribe.append(wx.TextCtrl(self.panel, -1)) self.fileNames.append(wx.StaticText(self.panel, -1, iCalFile)) #Add Components to Layout Managers for i in range(0, len(self.ctrlsToDescribe)): hboxtemp = wx.BoxSizer(wx.HORIZONTAL) hboxtemp.AddStretchSpacer() hboxtemp.Add(self.fileNames[i], 1, wx.EXPAND) hboxtemp.AddStretchSpacer() hboxtemp.Add(self.ctrlsToDescribe[i], 2, wx.EXPAND) hboxtemp.AddStretchSpacer() vbox.Add(hboxtemp) finalHBox = wx.BoxSizer(wx.HORIZONTAL) finalHBox.Add(self.getFilesButton) finalHBox.Add(self.calculateButton) finalHBox.Add(self.quitButton) vbox.Add(finalHBox) self.panel.SetSizer(vbox) self.Show() def Quit(self, event): self.Destroy() def getFiles(self, event): self.iCalFiles = ['Example1','Example1','Example1','Example1','Example1','Example1'] self.layoutElements() self.Update() app = wx.App() MainFrame() app.MainLoop() del app
[ "1) I beleive the Sizer will let you insert elements into the existing ordering of them. That would probably be a bit faster.\n2) I don't see the behavior you're describing on OSX, but at a guess, try calling self.Layout() before self.Show() in layoutElements?\n", "I had a similar problem where the panel would be squished into the upper-right corner. I solved it by calling panel.Fit().\nIn your example, you should call self.panel.Fit() after self.panel.SetSizer(vbox)\n" ]
[ 1, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000561991_python_wxpython_wxwidgets.txt
Q: List a dictionary In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC|00000050| |.text Symbols from _ashrdi3.o: Name Value Class Type Size Line Section __ashrdi3 |00000000| T | FUNC|00000058| |.text Symbols from _fixdfdi.o: Name Value Class Type Size Line Section __fixdfdi |00000000| T | FUNC|0000004c| |.text __fixunsdfdi | | U | NOTYPE| | |*UND* How can I create a dictionary like: dictOfTables {'__ctype_tab.o':{'__ctype': Name:...,Value:...,Class:...,Type:...,Size:...,Line:...,Section:...}} etc. for the above text? A: Appending doesn't make sense to the concept of dictionary in the same way as for list. Instead, it's more sensible to speak in terms of inserting and removing key/values, as there's no "end" to append to - the dict is unordered. From your desired output, it looks like you want to have a dict of dicts of dicts, (ie {filename : { symbol : { key:value }}. I think you can get this from your input with something like this: import re header_re = re.compile('Symbols from (.*):') def read_syms(f): """Read list of symbols from provided iterator and return dict of values""" d = {} headings=None for line in f: line = line.strip() if not line: return d # Finished. if headings is None: headings = [x.strip() for x in line.split()] continue # First line is headings items = [x.strip() for x in line.split("|")] d[items[0]] = dict(zip(headings[1:], items[1:])) return d f=open('input.txt') d={} for line in f: m=header_re.match(line) if m: d[m.group(1)] = read_syms(f) A: Look into using an ordered dictionary. I don't think this is in official Python yet, but there's a reference implementation available in the PEP.
List a dictionary
In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC|00000050| |.text Symbols from _ashrdi3.o: Name Value Class Type Size Line Section __ashrdi3 |00000000| T | FUNC|00000058| |.text Symbols from _fixdfdi.o: Name Value Class Type Size Line Section __fixdfdi |00000000| T | FUNC|0000004c| |.text __fixunsdfdi | | U | NOTYPE| | |*UND* How can I create a dictionary like: dictOfTables {'__ctype_tab.o':{'__ctype': Name:...,Value:...,Class:...,Type:...,Size:...,Line:...,Section:...}} etc. for the above text?
[ "Appending doesn't make sense to the concept of dictionary in the same way as for list. Instead, it's more sensible to speak in terms of inserting and removing key/values, as there's no \"end\" to append to - the dict is unordered.\nFrom your desired output, it looks like you want to have a dict of dicts of dicts, (ie {filename : { symbol : { key:value }}. I think you can get this from your input with something like this:\nimport re\n\nheader_re = re.compile('Symbols from (.*):')\n\ndef read_syms(f):\n \"\"\"Read list of symbols from provided iterator and return dict of values\"\"\"\n d = {}\n headings=None\n for line in f:\n line = line.strip()\n if not line: return d # Finished.\n\n if headings is None:\n headings = [x.strip() for x in line.split()]\n continue # First line is headings\n\n items = [x.strip() for x in line.split(\"|\")]\n d[items[0]] = dict(zip(headings[1:], items[1:]))\n return d\n\nf=open('input.txt')\nd={}\nfor line in f:\n m=header_re.match(line)\n if m:\n d[m.group(1)] = read_syms(f)\n\n", "Look into using an ordered dictionary. I don't think this is in official Python yet, but there's a reference implementation available in the PEP.\n" ]
[ 7, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0000828578_dictionary_list_python.txt
Q: What is the proper procedure for offering a patch to the Python documentation? I'm about to dive into the source code for the cgi.py module again because the MiniFieldStorage class is mentioned in the documentation, but not actually documented. It occurred to me that I have done this so many times that maybe I could write documentation for it. If I did, how should I submit it? A: There's a page regarding Documentation Development on the official web site which looks like a good starting point. It appears as though you simply add to the issue tracker and attach a patch in the normal way. In particular, it points to Documenting Python, which appears to be a rather exhaustive guide on formatting documentation; style guidelines, etc. A: I would suggest posting an issue to the documentation bug tracker, including the patch of course. This is mentioned in the section on contributing on the site. If that doesn't work, or seems slow, I guess you can dig up developers to bug directly, but that can also be considered impolite, so read up first on the proper etiquette.
What is the proper procedure for offering a patch to the Python documentation?
I'm about to dive into the source code for the cgi.py module again because the MiniFieldStorage class is mentioned in the documentation, but not actually documented. It occurred to me that I have done this so many times that maybe I could write documentation for it. If I did, how should I submit it?
[ "There's a page regarding Documentation Development on the official web site which looks like a good starting point. It appears as though you simply add to the issue tracker and attach a patch in the normal way.\nIn particular, it points to Documenting Python, which appears to be a rather exhaustive guide on formatting documentation; style guidelines, etc.\n", "I would suggest posting an issue to the documentation bug tracker, including the patch of course. This is mentioned in the section on contributing on the site.\nIf that doesn't work, or seems slow, I guess you can dig up developers to bug directly, but that can also be considered impolite, so read up first on the proper etiquette.\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000829341_python.txt
Q: Controlling VirtualBox via COM from Python? I'm trying to control latest Sun VirtualBox via it's COM interface from Python. But, unfortunately, the following code don't work: import win32com.client VBOX_GUID = "{B1A7A4F2-47B9-4A1E-82B2-07CCD5323C3F}" try : oVbox = win32com.client.Dispatch( VBOX_GUID ) oVbox.FindMachine( "kubuntu" ) except Exception as oEx: print str( oEx ) Error is general "(-2147467262, 'No such interface supported', None, None)" It seems that the wrong part is my COM handing via Python. Anyone can drop a look and suggest some obvious thing i'm doing wrong? A: The problem is that the object returned by FindMachine("kubuntu") does not support the IDispatch interface, and win32com does not support that. You could use my comtypes package http://starship.python.net/crew/theller/comtypes/ for that, but you need to patch the version in the repository to make it work with the VirtualBox type libraries. Here's a demo session: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from comtypes.client import CreateObject >>> box = CreateObject("VirtualBox.VirtualBox") >>> m = box.FindMachine("Fedora") >>> print m.State 4 >>> print m.CpuCount 1 >>> print m.Name Fedora >>> And here is the patch that you need: Index: automation.py =================================================================== --- automation.py (revision 507) +++ automation.py (working copy) @@ -753,6 +753,8 @@ c_float: VT_R4, c_double: VT_R8, + c_ulonglong: VT_I8, + VARIANT_BOOL: VT_BOOL, BSTR: VT_BSTR,
Controlling VirtualBox via COM from Python?
I'm trying to control latest Sun VirtualBox via it's COM interface from Python. But, unfortunately, the following code don't work: import win32com.client VBOX_GUID = "{B1A7A4F2-47B9-4A1E-82B2-07CCD5323C3F}" try : oVbox = win32com.client.Dispatch( VBOX_GUID ) oVbox.FindMachine( "kubuntu" ) except Exception as oEx: print str( oEx ) Error is general "(-2147467262, 'No such interface supported', None, None)" It seems that the wrong part is my COM handing via Python. Anyone can drop a look and suggest some obvious thing i'm doing wrong?
[ "The problem is that the object returned by FindMachine(\"kubuntu\") does not support the IDispatch interface, and win32com does not support that.\nYou could use my comtypes package http://starship.python.net/crew/theller/comtypes/ for that, but you need to patch the version in the repository to make it work with the VirtualBox type libraries.\nHere's a demo session:\nPython 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from comtypes.client import CreateObject\n>>> box = CreateObject(\"VirtualBox.VirtualBox\")\n>>> m = box.FindMachine(\"Fedora\")\n>>> print m.State\n4\n>>> print m.CpuCount\n1\n>>> print m.Name\nFedora\n>>>\n\nAnd here is the patch that you need:\nIndex: automation.py\n===================================================================\n--- automation.py (revision 507)\n+++ automation.py (working copy)\n@@ -753,6 +753,8 @@\n c_float: VT_R4,\n c_double: VT_R8,\n\n+ c_ulonglong: VT_I8,\n+\n VARIANT_BOOL: VT_BOOL,\n\n BSTR: VT_BSTR,\n\n" ]
[ 3 ]
[]
[]
[ "com", "python", "virtualbox" ]
stackoverflow_0000826494_com_python_virtualbox.txt
Q: Cocoa client/server application Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application? I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course. The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself. Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything. What do you think? Real world examples will be greatly appreciated. Thanks in advance. A: If you have control of both the client and server, and you can limit the client to OS X only, I second Marc's answer. Cocoa's distributed objects are an amazing technology and make RPC-style client-server apps very easy. If the requirements above are too restrictive for you, you still have many options available to you in the Cocoa world: You can code the entire client app in Python using PyObjC. With this approach, you can use the standard network code that you're familiar with from the Python standard library. Twisted also integrates nicely with the Cocoa run loop (examples in the PyObjC example code) and I've had a lot of success using Twisted for network communication from with in a Cocoa app. If you choose to go this route, you may want to code the client app in Objective-C and load the python code as a plugin (using NSBundle). PyObjC's py2app can compile loadable bundles from python code. You can use NSURLConnection for high-level access to an HTTP-based server. Dropping down a level of abstraction, you can use Cocoa's NSStream to implement your network protocol. The class documentation is here, with links to example code demonstrating HTTP and SOAP protocols. You can drop a further level down and use the CFNetwork classes. NSStream is based on CFNetwork, but you have lower-level control over the line using CFNetwork. Finally, the Apple technology for client-server architectures is the WebObjects framework. A: Cocoa has Portable Distributed Objects, which let you build a client / server application in pure Objective-C and Cocoa which can communicate across processes or across a network. Unfortunately it's one of the harder things to learn in Cocoa. Distributed objects haven't been updated to keep up with new technologies like bindings, there's not a lot of examples or documentation (and many of the tutorials are old, some even pre-dating OS X). There's also a lot of "gotchas," even for experienced Cocoa programmers, in the way objects are transmitted across the wire either as a copy or a proxy object. For example, you can transmit an NSURL from a server and it will seem fine if you convert it to a string or look at it in the debugger, but your client will crash if you try to use it in an NSURLConnection. Depending on your experience it may be easier and quicker to use a web service, but it's still worth looking in to if you'd like to keep the entire project in Cocoa. Here's a tutorial if you'd like to see an example. A: Generally, the ideas of all other client/server frameworks are applicable. Take a look at this link: http://developer.apple.com/internet/webservices/webservicescoreandcfnetwork.html A: I have written a server and a client class for use in Cocoa. Using these classes makes it very easy to produce a server or client application without the knowledge about sockets and that C-stuff Just have a look at my website or at the sourceforge.net project site.
Cocoa client/server application
Is there a way in Cocoa that is currently considered best practice for creating a multi-tier or client server application? I'm an experienced web developer and I really love Python. I'm new to Cocoa though. The application I'm toying with writing is a patient management system for a large hospital. The system is expected to store huge amounts of data over time but the data transferred during a single session is very light (mostly just text). The communication is assumed to occur over a local network (wired or wireless). It has to be highly secure, of course. The best I could come up with is to write a Python REST web service and connect to it through the Cocoa app. Maybe I'll even use Python to code the Cocoa app itself. Looking at Cocoa, I see really great technologies in Cocoa like CoreData but I couldn't find anything similar for client server development. I just want to make sure that I'm not missing anything. What do you think? Real world examples will be greatly appreciated. Thanks in advance.
[ "If you have control of both the client and server, and you can limit the client to OS X only, I second Marc's answer. Cocoa's distributed objects are an amazing technology and make RPC-style client-server apps very easy.\nIf the requirements above are too restrictive for you, you still have many options available to you in the Cocoa world:\n\nYou can code the entire client app in Python using PyObjC. With this approach, you can use the standard network code that you're familiar with from the Python standard library. Twisted also integrates nicely with the Cocoa run loop (examples in the PyObjC example code) and I've had a lot of success using Twisted for network communication from with in a Cocoa app. If you choose to go this route, you may want to code the client app in Objective-C and load the python code as a plugin (using NSBundle). PyObjC's py2app can compile loadable bundles from python code.\nYou can use NSURLConnection for high-level access to an HTTP-based server.\nDropping down a level of abstraction, you can use Cocoa's NSStream to implement your network protocol. The class documentation is here, with links to example code demonstrating HTTP and SOAP protocols.\nYou can drop a further level down and use the CFNetwork classes. NSStream is based on CFNetwork, but you have lower-level control over the line using CFNetwork.\n\nFinally, the Apple technology for client-server architectures is the WebObjects framework.\n", "Cocoa has Portable Distributed Objects, which let you build a client / server application in pure Objective-C and Cocoa which can communicate across processes or across a network. \nUnfortunately it's one of the harder things to learn in Cocoa. Distributed objects haven't been updated to keep up with new technologies like bindings, there's not a lot of examples or documentation (and many of the tutorials are old, some even pre-dating OS X). There's also a lot of \"gotchas,\" even for experienced Cocoa programmers, in the way objects are transmitted across the wire either as a copy or a proxy object. For example, you can transmit an NSURL from a server and it will seem fine if you convert it to a string or look at it in the debugger, but your client will crash if you try to use it in an NSURLConnection.\nDepending on your experience it may be easier and quicker to use a web service, but it's still worth looking in to if you'd like to keep the entire project in Cocoa. Here's a tutorial if you'd like to see an example.\n", "Generally, the ideas of all other client/server frameworks are applicable.\nTake a look at this link: http://developer.apple.com/internet/webservices/webservicescoreandcfnetwork.html\n", "I have written a server and a client class for use in Cocoa.\nUsing these classes makes it very easy to produce a server or client application without the knowledge about sockets and that C-stuff\nJust have a look at my website or at the sourceforge.net project site.\n" ]
[ 6, 3, 1, 0 ]
[ "Look at the api's for NSConnection and NSDownload to handle the network connection. The NSString class also has methods like + stringWithContentsOfURL:encoding:error: that may be useful.\nThen there is NSXMLParser and NSXMLDocument for reading xml data.\n" ]
[ -1 ]
[ "client_server", "cocoa", "pyobjc", "python", "web_services" ]
stackoverflow_0000409354_client_server_cocoa_pyobjc_python_web_services.txt
Q: str.format() -> how to left-justify >>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt) there are 100 students and 20 teachers What would be the code so that the output became: there are 100 students and 20 teachers Thanks. A: print 'there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt) While the old % operator uses - for alignment, the new format method uses < and >
str.format() -> how to left-justify
>>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt) there are 100 students and 20 teachers What would be the code so that the output became: there are 100 students and 20 teachers Thanks.
[ "print 'there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt)\n\nWhile the old % operator uses - for alignment, the new format method uses < and >\n" ]
[ 22 ]
[]
[]
[ "python" ]
stackoverflow_0000829667_python.txt
Q: Django: custom constructor for form class, trouble with accessing data from request.POST I have written custom constructor for a form, the whole form class looks like this: class UploadForm(forms.Form): file = forms.FileField(label = "Plik") def __init__(self, coto, naglowek, *args, **kwargs): super(UploadForm, self).__init__(*args, **kwargs) self.coto = coto self.naglowek = naglowek When submitting form, in my view, I have something like if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): add_form(request.FILES['file']) return HttpResponseRedirect('uploaded/') The problem is, that when I am creating form in this way in my view, I am not passing coto and naglowek, so when I am calling form.is_valid() --> it returns false. The template which passess it looks like: <table class="uploadform"> <form action="." method="POST" enctype="multipart/form-data"> {% for form in forms %} <tr> <td>{{ form.naglowek }}</td> <td>{{ form.file }}</td> <td><input type="submit" name="{{ form.coto }}" id="{{ form.coto }}" value="Wyślij"></td> </tr> {% endfor %} </form> </table> I would be grateful for any suggestions. [EDIT] I might not say this clearlly enough, but I will try my best: When I am submitting this form, in view, I need to know which submit button was pressed - I have many of them assigned to single form. From what I know, when I am assigning id to submit button, it should be availible in post, right? The trick is, that it is not availible. I have two questions: * What needs to be done, If I want to know which submit button was pressed? Is assigning the name the only way? * Is there any error in my logic? A: Your question is a mess. There's code and there's an edit with another question. The edit question has nothing to do with the title. Please update this question to be your real question. If you have multiple submit buttons, you must give them distinct names or values (or both). Here's our code which uses distinct values to distinguish which button was clicked. <form method="post" action="." enctype="multipart/form-data"> <input type="hidden" name="object_id" value="{{e.id}}"/> {% ifequal object.workflow "uploaded" %} <input type="submit" name="action" value="Validate"/> <br/> <input type="submit" name="action" value="Delete"/> {% endifequal %} {% ifequal object.workflow "validated" %} <input type="submit" name="action" value="Load"/> {% endifequal %} {% ifequal object.workflow "processed" %} <input type="submit" name="action" value="Undo"/> {% endifequal %} {% ifequal object.workflow "failed" %} <input type="submit" name="action" value="Validate"/> {% endifequal %} </form> The view function has this kind of thing: if request.POST['action'] == "Delete": to change the action based on the button. A: request.POST['coto'] request.POST['naglowek'] I guess. A: You've redefined default form constructor and change its parameters order. So you have to instantiate your custom form with explicit naming of arguments: form = UploadForm(data=request.POST, files=request.FILES, coto=..., naglowek=...)
Django: custom constructor for form class, trouble with accessing data from request.POST
I have written custom constructor for a form, the whole form class looks like this: class UploadForm(forms.Form): file = forms.FileField(label = "Plik") def __init__(self, coto, naglowek, *args, **kwargs): super(UploadForm, self).__init__(*args, **kwargs) self.coto = coto self.naglowek = naglowek When submitting form, in my view, I have something like if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): add_form(request.FILES['file']) return HttpResponseRedirect('uploaded/') The problem is, that when I am creating form in this way in my view, I am not passing coto and naglowek, so when I am calling form.is_valid() --> it returns false. The template which passess it looks like: <table class="uploadform"> <form action="." method="POST" enctype="multipart/form-data"> {% for form in forms %} <tr> <td>{{ form.naglowek }}</td> <td>{{ form.file }}</td> <td><input type="submit" name="{{ form.coto }}" id="{{ form.coto }}" value="Wyślij"></td> </tr> {% endfor %} </form> </table> I would be grateful for any suggestions. [EDIT] I might not say this clearlly enough, but I will try my best: When I am submitting this form, in view, I need to know which submit button was pressed - I have many of them assigned to single form. From what I know, when I am assigning id to submit button, it should be availible in post, right? The trick is, that it is not availible. I have two questions: * What needs to be done, If I want to know which submit button was pressed? Is assigning the name the only way? * Is there any error in my logic?
[ "Your question is a mess. There's code and there's an edit with another question. The edit question has nothing to do with the title.\nPlease update this question to be your real question. \nIf you have multiple submit buttons, you must give them distinct names or values (or both). Here's our code which uses distinct values to distinguish which button was clicked.\n <form method=\"post\" action=\".\" enctype=\"multipart/form-data\">\n <input type=\"hidden\" name=\"object_id\" value=\"{{e.id}}\"/>\n {% ifequal object.workflow \"uploaded\" %}\n <input type=\"submit\" name=\"action\" value=\"Validate\"/>\n <br/>\n <input type=\"submit\" name=\"action\" value=\"Delete\"/>\n {% endifequal %}\n {% ifequal object.workflow \"validated\" %}\n <input type=\"submit\" name=\"action\" value=\"Load\"/>\n {% endifequal %}\n {% ifequal object.workflow \"processed\" %}\n <input type=\"submit\" name=\"action\" value=\"Undo\"/>\n {% endifequal %}\n {% ifequal object.workflow \"failed\" %}\n <input type=\"submit\" name=\"action\" value=\"Validate\"/>\n {% endifequal %}\n </form>\n\nThe view function has this kind of thing:\n if request.POST['action'] == \"Delete\":\n\nto change the action based on the button.\n", "request.POST['coto']\nrequest.POST['naglowek']\n\nI guess.\n", "You've redefined default form constructor and change its parameters order. So you have to instantiate your custom form with explicit naming of arguments:\nform = UploadForm(data=request.POST, files=request.FILES, coto=..., naglowek=...)\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "django", "post", "python", "webforms" ]
stackoverflow_0000829156_django_post_python_webforms.txt
Q: Mosso Python Module Has anybody had success installing the Mosso (cloudfiles) python module? I'm trying to install it and getting the following error. python-cloudfiles-1.3.1]# python setup.py install running install running build running build_py running install_lib byte-compiling /usr/lib/python2.3/site-packages/cloudfiles/container.py to container.pyc File "/usr/lib/python2.3/site-packages/cloudfiles/container.py", line 74 @requires_name(InvalidContainerName) ^ SyntaxError: invalid syntax byte-compiling /usr/lib/python2.3/site-packages/cloudfiles/storage_object.py to storage_object.pyc File "/usr/lib/python2.3/site-packages/cloudfiles/storage_object.py", line 85 @requires_name(InvalidObjectName) ^ SyntaxError: invalid syntax A: It looks like you're running a version of Python prior to 2.4 - the syntax it's complaining about (the @ symbol, known as a "decorator") was introduced in Python 2.4.
Mosso Python Module
Has anybody had success installing the Mosso (cloudfiles) python module? I'm trying to install it and getting the following error. python-cloudfiles-1.3.1]# python setup.py install running install running build running build_py running install_lib byte-compiling /usr/lib/python2.3/site-packages/cloudfiles/container.py to container.pyc File "/usr/lib/python2.3/site-packages/cloudfiles/container.py", line 74 @requires_name(InvalidContainerName) ^ SyntaxError: invalid syntax byte-compiling /usr/lib/python2.3/site-packages/cloudfiles/storage_object.py to storage_object.pyc File "/usr/lib/python2.3/site-packages/cloudfiles/storage_object.py", line 85 @requires_name(InvalidObjectName) ^ SyntaxError: invalid syntax
[ "It looks like you're running a version of Python prior to 2.4 - the syntax it's complaining about (the @ symbol, known as a \"decorator\") was introduced in Python 2.4.\n" ]
[ 5 ]
[]
[]
[ "cloudfiles", "module", "mosso", "python" ]
stackoverflow_0000829916_cloudfiles_module_mosso_python.txt
Q: crontab in python I'm writing code in python for some sort of daemon that has to execute a specific action at a certain instance in time defined by a crontab string. Is there a module I can use? If not, can someone paste/link an algorithm I can use to check whether the instance of time defined by the crontab has occured in the time from when the previous check was done. Thanks. A: sched ftw A: Kronos is another option. Here is a similar SO question. A: You might want to take a look at pycron.
crontab in python
I'm writing code in python for some sort of daemon that has to execute a specific action at a certain instance in time defined by a crontab string. Is there a module I can use? If not, can someone paste/link an algorithm I can use to check whether the instance of time defined by the crontab has occured in the time from when the previous check was done. Thanks.
[ "sched ftw\n", "Kronos is another option.\nHere is a similar SO question.\n", "You might want to take a look at pycron.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "crontab", "python" ]
stackoverflow_0000826882_crontab_python.txt
Q: Is Python2.6 stable enough for production use? Or should I just stick with Python2.5 for a bit longer? A: From python.org: The current production versions are Python 2.6.2 and Python 3.0.1. So, yes. Python 3.x contains some backwards incompatible changes, so python.org also says: start with Python 2.6 since more existing third party software is compatible with Python 2 than Python 3 right now A: Ubuntu has switched to 2.6 in it's latest release, and has not had any significant problems. So I would say "yes, it's stable". A: It depends from libraries you use. For example there is no precompiled InformixDB package for 2.6 if you have to use Python on Windows. Also web2py framework sticks with 2.5 because of some bug in 2.6. Personally I use CPython 2.6 (workhorse) and 3.0 (experimental), and Jython 2.5 beta (for my test with JDBC and ODBC). A: Yes it it, but this is not the right question. The right question is "can I use Python 2.6, taking in consideration the incompatibilities it introduces ?". And the short answser is "most probably yes, unless you use a specific lib that wouldn't work with 2.6, which is pretty rare". A: I've found 2.6 to be fairly good with two exceptions: If you're using it on a server, I've had trouble in the past with some libraries which are used by elements of the server (Debian Etch IIRC). It's possible with a bit of jiggery pokery to maintain several versions of python in unison though if you're careful :-) This is no-longer true, but the last time I tried 2.6, wxPython had not been updated which meant all my gui tools I've written broke. There's now a version available that's built against 2.6. So I'd suggest you check all the modules you use and check their compatibility with 2.6... A: I recently switched from python2.5 to 2.6 for my research project involving lots of 3rd party libs (scipy, pydot, etc.) and swig related stuff. The only thing I had to change was to convert all strings with s = unicode(s, "utf-8") before I fed them into the logging module. Otherwise, I got everytime Traceback (most recent call last): File "/usr/lib/python2.6/logging/__init__.py", line 773, in emit stream.write(fs % msg.encode("UTF-8")) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 31: ordinal not in range(128)
Is Python2.6 stable enough for production use?
Or should I just stick with Python2.5 for a bit longer?
[ "From python.org:\n\nThe current production versions are\n Python 2.6.2 and Python 3.0.1.\n\nSo, yes.\nPython 3.x contains some backwards incompatible changes, so python.org also says:\n\nstart with Python 2.6 since more\n existing third party software is\n compatible with Python 2 than Python 3\n right now\n\n", "Ubuntu has switched to 2.6 in it's latest release, and has not had any significant problems. So I would say \"yes, it's stable\".\n", "It depends from libraries you use. For example there is no precompiled InformixDB package for 2.6 if you have to use Python on Windows.\nAlso web2py framework sticks with 2.5 because of some bug in 2.6.\nPersonally I use CPython 2.6 (workhorse) and 3.0 (experimental), and Jython 2.5 beta (for my test with JDBC and ODBC).\n", "Yes it it, but this is not the right question. The right question is \"can I use Python 2.6, taking in consideration the incompatibilities it introduces ?\". And the short answser is \"most probably yes, unless you use a specific lib that wouldn't work with 2.6, which is pretty rare\".\n", "I've found 2.6 to be fairly good with two exceptions:\n\nIf you're using it on a server, I've had trouble in the past with some libraries which are used by elements of the server (Debian Etch IIRC). It's possible with a bit of jiggery pokery to maintain several versions of python in unison though if you're careful :-)\nThis is no-longer true, but the last time I tried 2.6, wxPython had not been updated which meant all my gui tools I've written broke. There's now a version available that's built against 2.6.\n\nSo I'd suggest you check all the modules you use and check their compatibility with 2.6...\n", "I recently switched from python2.5 to 2.6 for my research project involving lots of 3rd party libs (scipy, pydot, etc.) and swig related stuff. \nThe only thing I had to change was to convert all strings with\n\ns = unicode(s, \"utf-8\")\n\nbefore I fed them into the logging module.\nOtherwise, I got everytime \n\nTraceback (most recent call last):\n File \"/usr/lib/python2.6/logging/__init__.py\", line 773, in emit\n stream.write(fs % msg.encode(\"UTF-8\"))\n UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 31: ordinal not in range(128) \n\n" ]
[ 18, 10, 6, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000828862_python.txt
Q: Python double pointer I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python The C code double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; Python so far import ctypes null_ptr = ctypes.c_void_p() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) The issue being the null_ptr has an int value (memory address?) but there is no way to read the array?! A: My ctypes is rusty, but I believe you want POINTER(c_float) instead of c_void_p. So try this: null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc A: To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested): vdata = ctypes.c_void_p() length = ctypes.c_ulong(0) pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length)) fdata = ctypes.cast(vdata, POINTER(float)) A: You'll also probably want to be passing the null_ptr using byref, e.g. pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length)) A: When you pass pointer arguments without using ctypes.pointer or ctypes.byref, their contents simply get set to the integer value of the memory address (i.e., the pointer bits). These arguments should be passed with byref (or pointer, but byref has less overhead): data = ctypes.pointer(ctypes.c_float()) nbytes = ctypes.c_sizeof() pa_stream_peek(s, byref(data), byref(nbytes)) nfloats = nbytes.value / ctypes.sizeof(c_float) v = data[nfloats - 1]
Python double pointer
I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python The C code double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; Python so far import ctypes null_ptr = ctypes.c_void_p() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) The issue being the null_ptr has an int value (memory address?) but there is no way to read the array?!
[ "My ctypes is rusty, but I believe you want POINTER(c_float) instead of c_void_p. \nSo try this:\nnull_ptr = POINTER(c_float)()\npa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))\nnull_ptr[0]\nnull_ptr[5] # etc\n\n", "To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested):\nvdata = ctypes.c_void_p()\nlength = ctypes.c_ulong(0)\npa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length))\nfdata = ctypes.cast(vdata, POINTER(float))\n\n", "You'll also probably want to be passing the null_ptr using byref, e.g.\npa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length))\n\n", "When you pass pointer arguments without using ctypes.pointer or ctypes.byref, their contents simply get set to the integer value of the memory address (i.e., the pointer bits). These arguments should be passed with byref (or pointer, but byref has less overhead):\ndata = ctypes.pointer(ctypes.c_float())\nnbytes = ctypes.c_sizeof()\npa_stream_peek(s, byref(data), byref(nbytes))\nnfloats = nbytes.value / ctypes.sizeof(c_float)\nv = data[nfloats - 1]\n\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0000828139_ctypes_python.txt
Q: Python Iterator Help + lxml I have this script- import lxml from lxml.cssselect import CSSSelector from lxml.etree import fromstring from lxml.html import parse website = parse('http://example.com').getroot() selector = website.cssselect('.name') for i in range(0,18): print selector[i].text_content() As you can see the for loop stops after a number of times that I set beforehand. I want the for loop to stop only after it has printed everything. A: The CSSSelector.cssselect() method returns an iterable, so you can just do: for element in selector: print element.text_content() A: What about for e in selector: print e.text_content() ? A: I would expect you want a for loop like: selectors = website.cssselect('.name , .name, .desc') for selector in selectors: print selector.text_content()
Python Iterator Help + lxml
I have this script- import lxml from lxml.cssselect import CSSSelector from lxml.etree import fromstring from lxml.html import parse website = parse('http://example.com').getroot() selector = website.cssselect('.name') for i in range(0,18): print selector[i].text_content() As you can see the for loop stops after a number of times that I set beforehand. I want the for loop to stop only after it has printed everything.
[ "The CSSSelector.cssselect() method returns an iterable, so you can just do:\nfor element in selector:\n print element.text_content()\n\n", "What about\nfor e in selector:\n print e.text_content()\n\n?\n", "I would expect you want a for loop like:\nselectors = website.cssselect('.name , .name, .desc')\n\nfor selector in selectors: \n print selector.text_content()\n\n" ]
[ 5, 2, 2 ]
[]
[]
[ "for_loop", "iterator", "lxml", "python" ]
stackoverflow_0000830600_for_loop_iterator_lxml_python.txt
Q: Using Python multiprocessing while importing a module via file path I'm writing a program which imports a module using a file path, with the function imp.load_source(module_name,module_path). It seems to cause a problem when I try to pass objects from this module into a Process. An example: import multiprocessing import imp class MyProcess(multiprocessing.Process): def __init__(self,thing): multiprocessing.Process.__init__(self) self.thing=thing def run(self): x=self.thing if __name__=="__main__": module=imp.load_source('life', 'C:\\Documents and Settings\\User\\workspace\\GarlicSim\\src\\simulations\\life\\life.py') thing=module.step print(thing) p=MyProcess(thing) p.start() Note: for this code to "work", you must substitute the parameters I gave to imp.load_source with something else: It has to be some Python file on your computer, preferably not in the same folder. Then, in thing=module.step, instead of step put in some random function or class that is defined in that .py file. I am getting the following traceback: <function step at 0x00D5B030> Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "C:\Python26\lib\pickle.py", line 1124, in find_class __import__(module) ImportError: No module named life So what do I do? EDIT: I'm using Python 2.6.2c1 on Win XP. A: Probably it does not work because of placing of import code into main block. Code below works on Windows XP, Python 2.6. Then life module will also be imported in new process. import multiprocessing import imp class MyProcess(multiprocessing.Process): def __init__(self,thing): multiprocessing.Process.__init__(self) self.thing=thing def run(self): print("Exiting self.thing") self.thing() print("Finished") life=imp.load_source('life', r'd:\temp5\life.py') if __name__=="__main__": p=MyProcess(life.step) p.start()
Using Python multiprocessing while importing a module via file path
I'm writing a program which imports a module using a file path, with the function imp.load_source(module_name,module_path). It seems to cause a problem when I try to pass objects from this module into a Process. An example: import multiprocessing import imp class MyProcess(multiprocessing.Process): def __init__(self,thing): multiprocessing.Process.__init__(self) self.thing=thing def run(self): x=self.thing if __name__=="__main__": module=imp.load_source('life', 'C:\\Documents and Settings\\User\\workspace\\GarlicSim\\src\\simulations\\life\\life.py') thing=module.step print(thing) p=MyProcess(thing) p.start() Note: for this code to "work", you must substitute the parameters I gave to imp.load_source with something else: It has to be some Python file on your computer, preferably not in the same folder. Then, in thing=module.step, instead of step put in some random function or class that is defined in that .py file. I am getting the following traceback: <function step at 0x00D5B030> Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "C:\Python26\lib\pickle.py", line 1124, in find_class __import__(module) ImportError: No module named life So what do I do? EDIT: I'm using Python 2.6.2c1 on Win XP.
[ "Probably it does not work because of placing of import code into main block.\nCode below works on Windows XP, Python 2.6. Then life module will also be imported in new process.\nimport multiprocessing\nimport imp\n\nclass MyProcess(multiprocessing.Process):\n def __init__(self,thing):\n multiprocessing.Process.__init__(self)\n self.thing=thing\n def run(self):\n print(\"Exiting self.thing\")\n self.thing()\n print(\"Finished\")\n\nlife=imp.load_source('life', r'd:\\temp5\\life.py')\n\nif __name__==\"__main__\":\n p=MyProcess(life.step)\n p.start()\n\n" ]
[ 1 ]
[ "test.py on any folder:\nimport multiprocessing\nimport imp\n\nclass MyProcess(multiprocessing.Process):\n def __init__(self,thing):\n multiprocessing.Process.__init__(self)\n self.thing=thing\n def run(self):\n print 'running...', self.thing()\n\n\nif __name__==\"__main__\":\n module=imp.load_source('life', '/tmp/life.py')\n thing=module.step\n print(thing)\n p=MyProcess(thing)\n p.start()\n\nlife.py on /tmp:\ndef step():\n return 'It works!'\n\nRunning test.py:\n$ python test.py\n<function step at 0xb7dc4d4c>\nrunning... It works!\n\nI just tested and it works, so you must be doing something else wrong. Please edit your question and paste the real code that is not working.\nI am Using ubuntu Jaunty 9.04 with default python (Python 2.6.2 release26-maint, Apr 19 2009, 01:56:41). Don't know if your problem is windows-only, because I don't have windows available to test. \nThat's a reason that mangling with import paths is a bad idea. You'll never get it right for all platforms/environments, and your users will probably get angry. Better just use the python way of finding modules, which is by placing the module on the python module search path. That would work consistently everywhere.\n", "I've just done the following, running on XP with Python 2.5...\nD:\\Experiments\\ModuleLoading\\test.py\nimport imp\n\nif __name__==\"__main__\":\n module=imp.load_source('life', r'D:\\Experiments\\ModuleLoading\\somefolder\\life.py')\n thing=module.step\n print(thing)\n\nD:\\Experiments\\ModuleLoading\\somefolder\\step.py\ndef step():\n return 'It works!'\n\n...and running the script gives:\nD:\\jcage\\Projects\\Experiments\\ModuleLoading>test.py\n<function step at 0x00A0B470>\n\n...so try that first and make sure the module can load without multiprocessing?\n[Edit] Okay, so it's definitely a problem importing into the forked process. There's some bits and pieces in the documentation which are specific to windows:\n\nMore picklability\nEnsure that all arguments to Process.__init__() are picklable. This means, in particular, that bound or unbound methods cannot be used directly as the target argument on Windows — just define a function and use that instead.\n Also, if you subclass Process then make sure that instances will be picklable when the Process.start() method is called.\nGlobal variables\nBear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that Process.start() was called.\n However, global variables which are just module level constants cause no problems.\nSafe importing of main module\nMake sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).\n\n[Edit2] Is there any reason why you can't do the importing in the process? I think the problem is that when you launch the new process it's not running in the same address space so trying to access functions in the original thread won't work.\nYou could do this for D:\\Experiments\\ModuleLoading\\test.py instead:\nfrom multiprocessing import Process\nimport imp\n\nclass MyProcess(Process):\n def __init__(self):\n Process.__init__(self)\n\n def run(self):\n print 'run called...'\n module=imp.load_source('life', r'D:\\Experiments\\ModuleLoading\\somefolder\\life.py')\n print 'running...', module.step()\n\nif __name__==\"__main__\":\n p=MyProcess()\n p.start()\n\n" ]
[ -1, -1 ]
[ "import", "module", "multiprocessing", "python" ]
stackoverflow_0000829123_import_module_multiprocessing_python.txt