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: Fetching just the Key/id from a ReferenceProperty in App Engine I could use a little help in AppEngine land... Using the [Python] API I create relationships like this example from the docs: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name As I understand it, that example will make two datastore queries. One to fetch the Story and then one to deference the Author inorder to access the name. But I want to be able to fetch the id, so do something like: story = db.get(story_key) author_id = story.author.key().id() I want to just get the id from the reference. I do not want to have to deference (therefore query the datastore) the ReferenceProperty value. From reading the documentation it says that the value of a ReferenceProperty is a Key Which leads me to think that I could just call .id() on the reference's value. But it also says: The ReferenceProperty model provides features for Key property values such as automatic dereferencing. I can't find anything that explains when this referencing takes place? Is it safe to call .id() on the ReferenceProperty's value? Can it be assumed that calling .id() will not cause a datastore lookup? A: Answering my own question for the sake of helping fellow searchers... As suspected calling story.author.key().id() or even story.author.id() will result in datastore queries. The correct method dictated by the API docs is: story = db.get(story_key) author_id = Story.author.get_value_for_datastore(story).id()
Fetching just the Key/id from a ReferenceProperty in App Engine
I could use a little help in AppEngine land... Using the [Python] API I create relationships like this example from the docs: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name As I understand it, that example will make two datastore queries. One to fetch the Story and then one to deference the Author inorder to access the name. But I want to be able to fetch the id, so do something like: story = db.get(story_key) author_id = story.author.key().id() I want to just get the id from the reference. I do not want to have to deference (therefore query the datastore) the ReferenceProperty value. From reading the documentation it says that the value of a ReferenceProperty is a Key Which leads me to think that I could just call .id() on the reference's value. But it also says: The ReferenceProperty model provides features for Key property values such as automatic dereferencing. I can't find anything that explains when this referencing takes place? Is it safe to call .id() on the ReferenceProperty's value? Can it be assumed that calling .id() will not cause a datastore lookup?
[ "Answering my own question for the sake of helping fellow searchers...\nAs suspected calling story.author.key().id() or even story.author.id() will result in datastore queries. The correct method dictated by the API docs is:\nstory = db.get(story_key)\nauthor_id = Story.author.get_value_for_datastore(story).id()\n\n" ]
[ 27 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003044121_google_app_engine_google_cloud_datastore_python.txt
Q: regular expression - function body extracting in Python script, for every method definition in some C++ code of the form: return_value ClassName::MethodName(args) {MehodBody} I need to extract three parts: the class name, the method name and the method body for further processing. Finding and extracting the ClassName and MethodName is easy, but is there any simple way to extract the body of the method? With all possible '{' and '}' inside it? Or are regexes unsuitable for such task? A: >>> s = """return_value ClassName::MethodName(args) {MehodBody {} } """ >>> re.findall(r'\b(\w+)::(\w+)\([^{]+\{(.+)}', s, re.S) [('ClassName', 'MethodName', 'MehodBody {} ')] A: I would recommend that you use the parser module rather than regexps since it will handle things like multiple line functions, different indentations and will abort on malformed input so that you can manage things better. "Avoid regexps if you can" is one of the rules I live by since they're often more trouble that they're worth. Edit: Oh okay. I misread your question. I thought you wanted to parse Python code itself. I googled a little bit and found this but it's C only. Perhaps you can extend that? The grammar for C++ is there in the "C++ programming language book"
regular expression - function body extracting
in Python script, for every method definition in some C++ code of the form: return_value ClassName::MethodName(args) {MehodBody} I need to extract three parts: the class name, the method name and the method body for further processing. Finding and extracting the ClassName and MethodName is easy, but is there any simple way to extract the body of the method? With all possible '{' and '}' inside it? Or are regexes unsuitable for such task?
[ ">>> s = \"\"\"return_value ClassName::MethodName(args)\n{MehodBody {} } \"\"\"\n>>> re.findall(r'\\b(\\w+)::(\\w+)\\([^{]+\\{(.+)}', s, re.S)\n[('ClassName', 'MethodName', 'MehodBody {} ')]\n\n", "I would recommend that you use the parser module rather than regexps since it will handle things like multiple line functions, different indentations and will abort on malformed input so that you can manage things better. \"Avoid regexps if you can\" is one of the rules I live by since they're often more trouble that they're worth.\n\nEdit:\nOh okay. I misread your question. I thought you wanted to parse Python code itself. I googled a little bit and found this but it's C only. Perhaps you can extend that? The grammar for C++ is there in the \"C++ programming language book\"\n" ]
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003044426_python_regex.txt
Q: Using python imaplib to "delete" an email from Gmail? Can you delete emails with imaplib? If so how? A: Use the store method (of the IMAP4 object representing your connection) to set the r'\Deleted' flag on the message number you want to delete, as the example in the docs show; then the expunge method to actually perform all deletions so marked. Gmail's implementation of IMAP has subtly different semantics, by default, but if you want you can tweak it to behave much more like a traditional IMAP implementation (where the above sequence works) -- basically you have to enable the "Advanced IMAP Controls" lab, then follow the instructions at the URL I gave to get exactly the IMAP semantics you desire (physically deleting rather than archiving "deleted" mails, waiting or not for expunge, and so forth). A: Deleting an email over IMAP is performed in two phases: mark one or more items for deletion: imap.store(msg_no, '+FLAGS', '\\Deleted') expunge the mailbox: imap.expunge() (imap is your IMAP4 object) A: imap.uid('STORE', list_of_msgno , '+FLAGS', '(\Deleted)') imap.expunge() i.e imap.uid('STORE', '2, 4, 9, 12' , '+FLAGS', '(\Deleted)') Here (2, 4, 9, 12) are uid of the messages which are going to be deleted.
Using python imaplib to "delete" an email from Gmail?
Can you delete emails with imaplib? If so how?
[ "Use the store method (of the IMAP4 object representing your connection) to set the r'\\Deleted' flag on the message number you want to delete, as the example in the docs show; then the expunge method to actually perform all deletions so marked.\nGmail's implementation of IMAP has subtly different semantics, by default, but if you want you can tweak it to behave much more like a traditional IMAP implementation (where the above sequence works) -- basically you have to enable the \"Advanced IMAP Controls\" lab, then follow the instructions at the URL I gave to get exactly the IMAP semantics you desire (physically deleting rather than archiving \"deleted\" mails, waiting or not for expunge, and so forth).\n", "Deleting an email over IMAP is performed in two phases:\n\nmark one or more items for deletion: imap.store(msg_no, '+FLAGS', '\\\\Deleted')\nexpunge the mailbox: imap.expunge()\n\n(imap is your IMAP4 object)\n", "imap.uid('STORE', list_of_msgno , '+FLAGS', '(\\Deleted)') \nimap.expunge() \n\ni.e \nimap.uid('STORE', '2, 4, 9, 12' , '+FLAGS', '(\\Deleted)') \n\nHere (2, 4, 9, 12) are uid of the messages which are going to be deleted.\n" ]
[ 22, 19, 11 ]
[]
[]
[ "email", "imap", "python" ]
stackoverflow_0001777264_email_imap_python.txt
Q: Many-to-many relationship on same table with association object Related (for the no-association-object use case): SQLAlchemy Many-to-Many Relationship on a Single Table Building a many-to-many relationship is easy. Building a many-to-many relationship on the same table is almost as easy, as documented in the above question. Building a many-to-many relationship with an association object is also easy. What I can't seem to find is the right way to combine association objects and many-to-many relationships with the left and right sides being the same table. So, starting from the simple, naïve, and clearly wrong version that I've spent forever trying to massage into the right version: t_groups = Table('groups', metadata, Column('id', Integer, primary_key=True), ) t_group_groups = Table('group_groups', metadata, Column('parent_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False), Column('child_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False), Column('expires', DateTime), ) mapper(Group_To_Group, t_group_groups, properties={ 'parent_group':relationship(Group), 'child_group':relationship(Group), }) What's the right way to map this relationship? A: I guess you are getting an error like Could not determine join condition between parent/child tables... In this case, Change the mapper for Group_To_Group to the following: mapper(Group_To_Group, t_group_groups, properties={ 'parent_group':relationship(Group, primaryjoin=(t_group_groups.c.parent_group_id==t_groups.c.id),), 'child_group':relationship(Group, primaryjoin=(t_group_groups.c.child_group_id==t_groups.c.id),), }) also you might want to add the backref so that you can navigate the relations from the Group objects as well.
Many-to-many relationship on same table with association object
Related (for the no-association-object use case): SQLAlchemy Many-to-Many Relationship on a Single Table Building a many-to-many relationship is easy. Building a many-to-many relationship on the same table is almost as easy, as documented in the above question. Building a many-to-many relationship with an association object is also easy. What I can't seem to find is the right way to combine association objects and many-to-many relationships with the left and right sides being the same table. So, starting from the simple, naïve, and clearly wrong version that I've spent forever trying to massage into the right version: t_groups = Table('groups', metadata, Column('id', Integer, primary_key=True), ) t_group_groups = Table('group_groups', metadata, Column('parent_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False), Column('child_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False), Column('expires', DateTime), ) mapper(Group_To_Group, t_group_groups, properties={ 'parent_group':relationship(Group), 'child_group':relationship(Group), }) What's the right way to map this relationship?
[ "I guess you are getting an error like Could not determine join condition between parent/child tables...\nIn this case, Change the mapper for Group_To_Group to the following:\nmapper(Group_To_Group, t_group_groups, properties={\n 'parent_group':relationship(Group,\n primaryjoin=(t_group_groups.c.parent_group_id==t_groups.c.id),),\n 'child_group':relationship(Group,\n primaryjoin=(t_group_groups.c.child_group_id==t_groups.c.id),),\n})\n\nalso you might want to add the backref so that you can navigate the relations from the Group objects as well.\n" ]
[ 6 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003043770_python_sqlalchemy.txt
Q: Python: Using minidom to search for nodes with a certain text I am currently faced with XML that looks like this: <ID>345754</ID> This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754". A: vartec's answer needs correcting (sorry I'm not sure I can do that), it should read: xmldoc = xml.dom.minidom.parse('your.xml') matchingNodes = [node for node in xmldoc.getElementsByTagName("ID") if node.firstChild.nodeValue == '345754'] Two things were wrong with it: (i) tag names are case sensitive so matching on "id" won't work and (ii) for an element node .nodeValue will be None, you need access to the text nodes that is inside the element node which contains the value you want. A: xmldoc = minidom.parse('your.xml') matchingNodes = [node for node in xmldoc.getElementsByTagName("id") if node.nodeValue == '345754'] See also: How to get whole text of an Element in xml.minidom? All nodeValue fields are None when parsing XML
Python: Using minidom to search for nodes with a certain text
I am currently faced with XML that looks like this: <ID>345754</ID> This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".
[ "vartec's answer needs correcting (sorry I'm not sure I can do that), it should read:\nxmldoc = xml.dom.minidom.parse('your.xml')\nmatchingNodes = [node for node in xmldoc.getElementsByTagName(\"ID\") if \nnode.firstChild.nodeValue == '345754']\n\nTwo things were wrong with it: (i) tag names are case sensitive so matching on \"id\" won't work and (ii) for an element node .nodeValue will be None, you need access to the text nodes that is inside the element node which contains the value you want.\n", "xmldoc = minidom.parse('your.xml')\nmatchingNodes = [node for node in xmldoc.getElementsByTagName(\"id\") if node.nodeValue == '345754']\n\nSee also:\n\nHow to get whole text of an Element in xml.minidom?\nAll nodeValue fields are None when parsing XML\n\n" ]
[ 10, 4 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0000706453_minidom_python_xml.txt
Q: Bubble Breaker Game Solver better than greedy? For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:Bubble Break Game The random (N,M,C) board consists N rows x M columns with C colors The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. I create a prototype in python which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times. What other approaches could yield high scores besides the exhaustive search? I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic. A: According to this paper, determining if you can empty the board (which is related to the problem you want to solve) is NP-Complete. That doesn't mean that you won't be able to find a good algorithm, it just means that you likely won't find an efficient one. A: I'm thinking you could try a branch and bound search with the following idea: Given a state of the game S, you branch on S by breaking it up in m sets Si where each Si is the state after taking a legal move of all m legal moves given the state S You need two functions U(S) and L(S) that compute a lower and upper bound respectively of a given state S. For the U(S) function I'm thinking calculate the score that you would get if you were able to freely shuffle K bubbles in the board (each move) and arrange the blocks in such a way that would result in the highest score, where K is a value you choose yourself. When your calculating U(S) for a given S it should go quicker if you choose higher K (the conditions are relaxed) so choosing the value of K will be a trade of for quickness of finding U(S) and quality (how tight an upper bound U(S) is.) For the L(S) function calculate the score that you would get if you simply randomly kept click until you got to a state that could not be solved any further. You can do this several times taking the highest lower bound that you get. Once you have these two functions you can apply standard Bound and Branch search. Note that the speed of your search is going to greatly depend on how tight your Upper Bound is and how tight your Lower Bound is. A: To get a faster solution than exhaustive search, I think what you want is probably dynamic programming. In dynamic programming, you find some sort of "step" that takes you possibly closer to your solution, and keep track of the results of each step in a big matrix. Then, once you have filled in the matrix, you can find the best result, and then work backward to get a path through the matrix that leads to the best result. The matrix is effectively a form of memoization. Dynamic programming is discussed in The Algorithm Design Manual but there is also plenty of discussion of it on the web. Here's a good intro: http://20bits.com/articles/introduction-to-dynamic-programming/ I'm not sure exactly what the "step" is for this problem. Perhaps you could make a scoring metric for a board that simply sums the points for each of the bubble groups, and then record this score as you try popping balloons? Good steps would tend to cause bubble groups to coalesce, improving the score, and bad steps would break up bubble groups, making the score worse. A: You can translate this problem into problem of searching shortest path on graph. http://en.wikipedia.org/wiki/Shortest_path_problem I would try whit A* and heuristics would include number of islands. A: In my chess program I use some ideas which could probably adapted to this problem. Move Ordering. First find all possible moves, store them in a list, and sort them according to some heuristic. The "better" ones first, the "bad" ones last. For example, this could be a function of the size of the group (prefer medium sized groups), or the number of adjacent colors, groups, etc. Iterative Deepening. Instead of running a pure depth-first search, cut of the search after a certain deep and use some heuristic to assess the result. Now research the tree with "better" moves first. Pruning. Don't search moves which seems "obviously" bad, according to some, again, heuristic. This involves the risk that you won't find the optimal solution anymore, but depending on your heuristics you will very likely find it much earlier. Hash Tables. No need to store every board you come accross, just remember a certain number and overwrite older ones. A: I'm almost finished writing my version of the "solver" in Java. It does both exhaustive search, which takes fricking ages for larger board sizes, and a directed search based on a "pool" of possible paths, which is pruned after every generation, and a fitness function used to prune the pool. I'm just trying to tune the fitness function now... Update - this is now available at http://bubblesolver.sourceforge.net/
Bubble Breaker Game Solver better than greedy?
For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:Bubble Break Game The random (N,M,C) board consists N rows x M columns with C colors The goal is to get the highest score by picking the sequence of bubble groups that ultimately leads to the highest score A bubble group is 2 or more bubbles of the same color that are adjacent to each other in either x or y direction. Diagonals do not count When a group is picked, the bubbles disappear, any holes are filled with bubbles from above first, ie shift down, then any holes are filled by shifting right A bubble group score = n * (n - 1) where n is the number of bubbles in the bubble group The first algorithm is a simple exhaustive recursive algorithm which explores going through the board row by row and column by column picking bubble groups. Once the bubble group is picked, we create a new board and try to solve that board, recursively descending down Some of the ideas I am using include normalized memoization. Once a board is solved we store the board and the best score in a memoization table. I create a prototype in python which shows a (2,15,5) board takes 8859 boards to solve in about 3 seconds. A (3,15,5) board takes 12,384,726 boards in 50 minutes on a server. The solver rate is ~3k-4k boards/sec and gradually decreases as the memoization search takes longer. Memoization table grows to 5,692,482 boards, and hits 6,713,566 times. What other approaches could yield high scores besides the exhaustive search? I don't seen any obvious way to divide and conquer. But trending towards larger and larger bubbles groups seems to be one approach Thanks to David Locke for posting the paper link which talks above a window solver which uses a constant-depth lookahead heuristic.
[ "According to this paper, determining if you can empty the board (which is related to the problem you want to solve) is NP-Complete. That doesn't mean that you won't be able to find a good algorithm, it just means that you likely won't find an efficient one.\n", "I'm thinking you could try a branch and bound search with the following idea:\n\nGiven a state of the game S, you branch on S by breaking it up in m sets Si where each Si is the state after taking a legal move of all m legal moves given the state S\nYou need two functions U(S) and L(S) that compute a lower and upper bound respectively of a given state S. \nFor the U(S) function I'm thinking calculate the score that you would get if you were able to freely shuffle K bubbles in the board (each move) and arrange the blocks in such a way that would result in the highest score, where K is a value you choose yourself. When your calculating U(S) for a given S it should go quicker if you choose higher K (the conditions are relaxed) so choosing the value of K will be a trade of for quickness of finding U(S) and quality (how tight an upper bound U(S) is.)\nFor the L(S) function calculate the score that you would get if you simply randomly kept click until you got to a state that could not be solved any further. You can do this several times taking the highest lower bound that you get.\n\nOnce you have these two functions you can apply standard Bound and Branch search. Note that the speed of your search is going to greatly depend on how tight your Upper Bound is and how tight your Lower Bound is.\n", "To get a faster solution than exhaustive search, I think what you want is probably dynamic programming. In dynamic programming, you find some sort of \"step\" that takes you possibly closer to your solution, and keep track of the results of each step in a big matrix. Then, once you have filled in the matrix, you can find the best result, and then work backward to get a path through the matrix that leads to the best result. The matrix is effectively a form of memoization.\nDynamic programming is discussed in The Algorithm Design Manual but there is also plenty of discussion of it on the web. Here's a good intro: http://20bits.com/articles/introduction-to-dynamic-programming/\nI'm not sure exactly what the \"step\" is for this problem. Perhaps you could make a scoring metric for a board that simply sums the points for each of the bubble groups, and then record this score as you try popping balloons? Good steps would tend to cause bubble groups to coalesce, improving the score, and bad steps would break up bubble groups, making the score worse.\n", "You can translate this problem into problem of searching shortest path on graph. http://en.wikipedia.org/wiki/Shortest_path_problem\nI would try whit A* and heuristics would include number of islands.\n", "In my chess program I use some ideas which could probably adapted to this problem.\n\nMove Ordering. First find all\npossible moves, store them in a list,\nand sort them according to some\nheuristic. The \"better\" ones first,\nthe \"bad\" ones last. For example,\nthis could be a function of the size\nof the group (prefer medium sized\ngroups), or the number of adjacent\ncolors, groups, etc.\nIterative Deepening. Instead of\nrunning a pure depth-first search,\ncut of the search after a certain\ndeep and use some heuristic to assess\nthe result. Now research the tree\nwith \"better\" moves first.\nPruning. Don't search moves which\nseems \"obviously\" bad, according to\nsome, again, heuristic. This involves\nthe risk that you won't find the\noptimal solution anymore, but\ndepending on your heuristics you will\nvery likely find it much earlier.\nHash Tables. No need to store every\nboard you come accross, just remember\na certain number and overwrite older\nones.\n\n", "I'm almost finished writing my version of the \"solver\" in Java. It does both exhaustive search, which takes fricking ages for larger board sizes, and a directed search based on a \"pool\" of possible paths, which is pruned after every generation, and a fitness function used to prune the pool. I'm just trying to tune the fitness function now...\nUpdate - this is now available at http://bubblesolver.sourceforge.net/\n" ]
[ 7, 1, 1, 1, 1, 1 ]
[ "This isn't my area of expertise, but I would like to recommend a book to you. Get a copy of The Algorithm Design Manual by Steven Skiena. This has a whole list of different algorithms, and once you read through it you can use it as a reference. If nothing else it will help you consider your options.\n" ]
[ -1 ]
[ "algorithm", "language_agnostic", "python" ]
stackoverflow_0001541101_algorithm_language_agnostic_python.txt
Q: Python vs. Java performance (runtime speed) Possible Duplicate: is python slower than java/C#? Ignoring all the characteristics of each languages and focusing SOLELY on speed, which language is better performance-wise? You'd think this would be a rather simple question to answer, but I haven't found a decent one. I'm aware that some types of operations may be faster with python, and vice-versa, but I cannot find any detailed information on this. Can anyone shed some light on the performance differences? A: Java is faster than Python. Easily. Python is favorable for many things; speed isn't necessarily one of them. References python.org/Language Comparisons C++ vs Java vs Python vs Ruby : a first impression A subjective analysis of two high-level, object-oriented languages: Comparing Python to Java A: If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit? For example: Does it count when Java executes an empty loop faster than Python? Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away? Or is that "a language characteristic"? Do you want to know how many bytecodes each language can execute per second? Which ones? Only the fast ones or all of them? How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime? Do you include code compilation times (which are extra in Java but always included in Python)? Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context. A: There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement. A: Different languages do different things with different levels of efficiency. The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.
Python vs. Java performance (runtime speed)
Possible Duplicate: is python slower than java/C#? Ignoring all the characteristics of each languages and focusing SOLELY on speed, which language is better performance-wise? You'd think this would be a rather simple question to answer, but I haven't found a decent one. I'm aware that some types of operations may be faster with python, and vice-versa, but I cannot find any detailed information on this. Can anyone shed some light on the performance differences?
[ "Java is faster than Python. Easily.\nPython is favorable for many things; speed isn't necessarily one of them.\nReferences\n\npython.org/Language Comparisons\n\nC++ vs Java vs Python vs Ruby : a first impression\nA subjective analysis of two high-level, object-oriented languages: Comparing Python to Java\n\n\n", "If you ignore the characteristics of both languages, how do you define \"SPEED\"? Which features should be in your benchmark and which do you want to omit?\nFor example:\n\nDoes it count when Java executes an empty loop faster than Python?\nOr is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?\nOr is that \"a language characteristic\"?\nDo you want to know how many bytecodes each language can execute per second?\nWhich ones? Only the fast ones or all of them?\nHow do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?\nDo you include code compilation times (which are extra in Java but always included in Python)?\n\nConclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.\n", "There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.\n", "Different languages do different things with different levels of efficiency.\nThe Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.\n" ]
[ 82, 34, 13, 8 ]
[]
[]
[ "java", "performance", "python" ]
stackoverflow_0003044620_java_performance_python.txt
Q: On thread safety in python using D-Bus asynchronous method calls I write a python class which makes asynchronous method calls using D-Bus. When my reply_handler is called, it stores data in list. This list can be used by another class methods at the same time. Is it safe or I can use only synchronized data structures like Queue class? A: If you do not modify the list outside of the callback context, then you do not necessarily need synchronization - you will just need to be aware that the list object's state is volatile. If the list must be modified both in the callback handler as well as, say, the main execution context (or other threads, etc.), then yes you will need synchronization. The Python synchronized Queue works naturally for message pumps - allowing you to perform actions sequentially in the order that the events come in one of your own contexts. This benefits code simplicity and readability as well since major state changes are easier to track. Callbacks generally shouldn't be too complicated anyway as the outside context in which the callbacks are called shouldn't (and probably doesn't) have to deal with exceptions raised from your code. There are also potential timing considerations as well - the callback will block the async emitter's context - so keeping the handler short and sweet is also good.
On thread safety in python using D-Bus asynchronous method calls
I write a python class which makes asynchronous method calls using D-Bus. When my reply_handler is called, it stores data in list. This list can be used by another class methods at the same time. Is it safe or I can use only synchronized data structures like Queue class?
[ "If you do not modify the list outside of the callback context, then you do not necessarily need synchronization - you will just need to be aware that the list object's state is volatile. \nIf the list must be modified both in the callback handler as well as, say, the main execution context (or other threads, etc.), then yes you will need synchronization. \nThe Python synchronized Queue works naturally for message pumps - allowing you to perform actions sequentially in the order that the events come in one of your own contexts. This benefits code simplicity and readability as well since major state changes are easier to track. Callbacks generally shouldn't be too complicated anyway as the outside context in which the callbacks are called shouldn't (and probably doesn't) have to deal with exceptions raised from your code. There are also potential timing considerations as well - the callback will block the async emitter's context - so keeping the handler short and sweet is also good.\n" ]
[ 0 ]
[]
[]
[ "dbus", "python", "thread_safety" ]
stackoverflow_0003044596_dbus_python_thread_safety.txt
Q: How can I make an alt+number global hotkey in Python? I want to make a global hotkey, with alt+1, 2, ..., that paste some string in the clipboard. How can I do that? A: As an alternative, I would recommend using each tool for what it was designed to do. That is, use AutoHotkey for setting the hot-keys and for other types of Windows automation. AutoHotkey (AHK) connects with Python very well in several ways (many are discussed in the AHK forums). One interesting way is using autohotkey.dll - AHK's functionality wrapped into a DLL which you can call with ctypes. AHK was designed for Windows automation, and tasks like this are trivial for it. Much more complex tasks are, too. You can just save yourself hours of digging the API docs. AHK can be compiled into an .exe weighing a few hundred of KBs so you can distribute it with any Windows application. A: The pyhook module provides a reasonably easy way of using Windows Keyboard hooks. A: I believe you need to work at the Windows API level (no higher-level functions do that), with RegisterHotKey (first argument a null pointer) to associate the global hotkey to the current thread's message queue -- said thread must then go on to serving its normal Windows message loop. I suspect you'll want to run the whole thing as a Windows service -- e.g. per this recipe, which uses the Python for Windows Extensions -- to make sure it's always running while the system is up.
How can I make an alt+number global hotkey in Python?
I want to make a global hotkey, with alt+1, 2, ..., that paste some string in the clipboard. How can I do that?
[ "As an alternative, I would recommend using each tool for what it was designed to do. That is, use AutoHotkey for setting the hot-keys and for other types of Windows automation. AutoHotkey (AHK) connects with Python very well in several ways (many are discussed in the AHK forums). One interesting way is using autohotkey.dll - AHK's functionality wrapped into a DLL which you can call with ctypes.\nAHK was designed for Windows automation, and tasks like this are trivial for it. Much more complex tasks are, too. You can just save yourself hours of digging the API docs. AHK can be compiled into an .exe weighing a few hundred of KBs so you can distribute it with any Windows application.\n", "The pyhook module provides a reasonably easy way of using Windows Keyboard hooks.\n", "I believe you need to work at the Windows API level (no higher-level functions do that), with RegisterHotKey (first argument a null pointer) to associate the global hotkey to the current thread's message queue -- said thread must then go on to serving its normal Windows message loop. I suspect you'll want to run the whole thing as a Windows service -- e.g. per this recipe, which uses the Python for Windows Extensions -- to make sure it's always running while the system is up.\n" ]
[ 3, 3, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003042201_python_windows.txt
Q: How to convert string "0671" or "0x45" into integer form with 0 and 0x in the beginning I wanted to make my own encryption algorithm and decryption algorithm , encryption algorithm works fine and converts ascii value of the characters into alternate hexadecimal and octal representations. But when I tried decryption, problem occured as it return int('0671') = 671, as 0671 is string type in the following code. Is there a method to convert "ox56" into integer form?????? NOTE: Following string is alternate octal and hexa of ascii value of char. ///////////////DECRYPTION/////// l="01630x7401620x6901560x67" f=len(l) k=0 d=0 x=[] for i in range(0,f,4): g=l[i:i+4] print g k=k+1 if(k%2==0): p=g print p else: p=int(g) print p A: there you go (s is the string) int(s,0)
How to convert string "0671" or "0x45" into integer form with 0 and 0x in the beginning
I wanted to make my own encryption algorithm and decryption algorithm , encryption algorithm works fine and converts ascii value of the characters into alternate hexadecimal and octal representations. But when I tried decryption, problem occured as it return int('0671') = 671, as 0671 is string type in the following code. Is there a method to convert "ox56" into integer form?????? NOTE: Following string is alternate octal and hexa of ascii value of char. ///////////////DECRYPTION/////// l="01630x7401620x6901560x67" f=len(l) k=0 d=0 x=[] for i in range(0,f,4): g=l[i:i+4] print g k=k+1 if(k%2==0): p=g print p else: p=int(g) print p
[ "there you go (s is the string)\nint(s,0)\n\n" ]
[ 2 ]
[]
[]
[ "octal", "python" ]
stackoverflow_0003045202_octal_python.txt
Q: Should I use a class in this: Reading a XML file using lxml This question is in continuation to my previous question, in which I asked about passing around an ElementTree. I need to read the XML files only and to solve this, I decided to create a global ElementTree and then parse it wherever required. My question is: Is this an acceptable practice? I heard global variables are bad. If I don't make it global, I was suggested to make a class. But do I really need to create a class? What benefits would I have from that approach. Note that I would be handling only one ElementTree instance per run, the operations are read-only. If I don't use a class, how and where do I declare that ElementTree so that it available globally? (Note that I would be importing this module) Please answer this question in the respect that I am a beginner to development, and at this stage I can't figure out whether to use a class or just go with the functional style programming approach. A: Pragmatically, is your code expected to grow? Even though people herald OOP as the right way, I found that sometimes it's better to weigh cost:benefit(s) whenever you refactor a piece of code. If you are looking to grow this, then OOP is a better option in that you can extend and customise any future use case, while saving yourself from unnecessary time wasted in code maintenance. Otherwise, if it ain't broken, don't fix it, IMHO. A: I generally find myself regretting it when I give in to the temptation to give a module, for example, a load_file() method that sets a global that the module's other functions can then use to find the file they're supposed to be talking about. It makes testing far more difficult, for example, and as soon as I need two XML files there is a problem. Plus, every single function needs to check whether the file's there and give an error if it's not. If I want to be functional, I simply therefore have every function take the XML file as an argument. If I want to be object oriented, I'll have a MyXMLFile class whose methods can just look at self.xmlfile or whatever. The two approaches are more or less equivalent when there's just one single thing, like a file, to be passed around; but when the number of things in the "state" becomes larger than a few, then I find classes simpler because I can stick all of those things in the class. (Am I answering your question? I'm still a big vague on what kind of answer you want.) A: There are a few reasons that global variables are bad. First, it gets you in the habit of declaring global variables which is not good practice, though in some cases globals make sense -- PI, for instance. Globals also create problems when you on purpose or accidentally re-use the name locally. Or worse, when you think you're using the name locally but in reality you're assigning a new value to the global variable. This particular problem is language dependent, and python handles it differently in different cases. class A: def __init__(self): self.name = 'hi' x = 3 a = A() def foo(): a.name = 'Bedevere' x = 9 foo() print x, a.name #outputs 3 Bedevere The benefit of creating a class and passing your class around is you will get a defined, constant behavior, especially since you should be calling class methods, which operate on the class itself. class Knights: def __init__(self, name='Bedevere'): self.name = name def knight(self): self.name = 'Sir ' + self.name def speak(self): print self.name + ":", "Run away!" class FerociousRabbit: def __init__(self): self.death = "awaits you with sharp pointy teeth!" def speak(self): print "Squeeeeeeee!" def cave(thing): thing.speak() if isinstance(thing, Knights): thing.knight() def scene(): k = Knights() k2 = Knights('Launcelot') b = FerociousRabbit() for i in (b, k, k2): cave(i) This example illustrates a few good principles. First, the strength of python when calling functions - FerociousRabbit and Knights are two different classes but they have the same function speak(). In other languages, in order to do something like this, they would at least have to have the same base class. The reason you would want to do this is it allows you to write a function (cave) that can operate on any class that has a 'speak()' method. You could create any other method and pass it to the cave function: class Tim: def speak(self): print "Death awaits you with sharp pointy teeth!" So in your case, when dealing with an elementTree, say sometime down the road you need to also start parsing an apache log. Well if you're doing purely functional program you're basically hosed. You can modify and extend your current program, but if you wrote your functions well, you could just add a new class to the mix and (technically) everything will be peachy keen.
Should I use a class in this: Reading a XML file using lxml
This question is in continuation to my previous question, in which I asked about passing around an ElementTree. I need to read the XML files only and to solve this, I decided to create a global ElementTree and then parse it wherever required. My question is: Is this an acceptable practice? I heard global variables are bad. If I don't make it global, I was suggested to make a class. But do I really need to create a class? What benefits would I have from that approach. Note that I would be handling only one ElementTree instance per run, the operations are read-only. If I don't use a class, how and where do I declare that ElementTree so that it available globally? (Note that I would be importing this module) Please answer this question in the respect that I am a beginner to development, and at this stage I can't figure out whether to use a class or just go with the functional style programming approach.
[ "Pragmatically, is your code expected to grow? Even though people herald OOP as the right way, I found that sometimes it's better to weigh cost:benefit(s) whenever you refactor a piece of code. If you are looking to grow this, then OOP is a better option in that you can extend and customise any future use case, while saving yourself from unnecessary time wasted in code maintenance. Otherwise, if it ain't broken, don't fix it, IMHO.\n", "I generally find myself regretting it when I give in to the temptation to give a module, for example, a load_file() method that sets a global that the module's other functions can then use to find the file they're supposed to be talking about. It makes testing far more difficult, for example, and as soon as I need two XML files there is a problem. Plus, every single function needs to check whether the file's there and give an error if it's not.\nIf I want to be functional, I simply therefore have every function take the XML file as an argument.\nIf I want to be object oriented, I'll have a MyXMLFile class whose methods can just look at self.xmlfile or whatever.\nThe two approaches are more or less equivalent when there's just one single thing, like a file, to be passed around; but when the number of things in the \"state\" becomes larger than a few, then I find classes simpler because I can stick all of those things in the class.\n(Am I answering your question? I'm still a big vague on what kind of answer you want.)\n", "There are a few reasons that global variables are bad. First, it gets you in the habit of declaring global variables which is not good practice, though in some cases globals make sense -- PI, for instance. Globals also create problems when you on purpose or accidentally re-use the name locally. Or worse, when you think you're using the name locally but in reality you're assigning a new value to the global variable. This particular problem is language dependent, and python handles it differently in different cases.\nclass A:\n def __init__(self):\n self.name = 'hi'\n\nx = 3\na = A()\n\ndef foo():\n a.name = 'Bedevere'\n x = 9\n\nfoo()\nprint x, a.name #outputs 3 Bedevere\n\nThe benefit of creating a class and passing your class around is you will get a defined, constant behavior, especially since you should be calling class methods, which operate on the class itself.\nclass Knights:\n def __init__(self, name='Bedevere'):\n self.name = name\n def knight(self):\n self.name = 'Sir ' + self.name\n def speak(self):\n print self.name + \":\", \"Run away!\"\n\nclass FerociousRabbit:\n def __init__(self):\n self.death = \"awaits you with sharp pointy teeth!\"\n def speak(self):\n print \"Squeeeeeeee!\"\n\ndef cave(thing):\n thing.speak()\n if isinstance(thing, Knights):\n thing.knight()\n\ndef scene():\n k = Knights()\n k2 = Knights('Launcelot')\n b = FerociousRabbit()\n for i in (b, k, k2):\n cave(i)\n\nThis example illustrates a few good principles. First, the strength of python when calling functions - FerociousRabbit and Knights are two different classes but they have the same function speak(). In other languages, in order to do something like this, they would at least have to have the same base class. The reason you would want to do this is it allows you to write a function (cave) that can operate on any class that has a 'speak()' method. You could create any other method and pass it to the cave function:\nclass Tim:\n def speak(self):\n print \"Death awaits you with sharp pointy teeth!\"\n\nSo in your case, when dealing with an elementTree, say sometime down the road you need to also start parsing an apache log. Well if you're doing purely functional program you're basically hosed. You can modify and extend your current program, but if you wrote your functions well, you could just add a new class to the mix and (technically) everything will be peachy keen.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003045038_design_patterns_python.txt
Q: Using Pycairo to generate images dynamically and serve in Django I want to generate a dynamically created png image with Pycairo and serve it usign Django. I read this: Serve a dynamically generated image with Django. Is there a way to transport data from Pycairo surface directly into HTTP response? I'm doing this for now: data = surface.to_rgba() im = Image.frombuffer ("RGBA", (width, height), data, "raw", "RGBA", 0,1) response = HttpResponse(mimetype="image/png") im.save(response, "PNG") return response But it actually doesn't work because there isn't a to_rgba call (this call I found using Google code but doesn't work). EDIT: The to_rgba can be replaced by the correct call get_data(), but I still want to know if I can bypass PIL altogether. A: def someView(request): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100) context = cairo.Context(surface) # Draw something ... response = HttpResponse(mimetype="image/png") surface.write_to_png(response) return response A: You can try this: http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django It's about SVG but I think it will be easy to adapt
Using Pycairo to generate images dynamically and serve in Django
I want to generate a dynamically created png image with Pycairo and serve it usign Django. I read this: Serve a dynamically generated image with Django. Is there a way to transport data from Pycairo surface directly into HTTP response? I'm doing this for now: data = surface.to_rgba() im = Image.frombuffer ("RGBA", (width, height), data, "raw", "RGBA", 0,1) response = HttpResponse(mimetype="image/png") im.save(response, "PNG") return response But it actually doesn't work because there isn't a to_rgba call (this call I found using Google code but doesn't work). EDIT: The to_rgba can be replaced by the correct call get_data(), but I still want to know if I can bypass PIL altogether.
[ "def someView(request):\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)\n context = cairo.Context(surface)\n # Draw something ...\n\n response = HttpResponse(mimetype=\"image/png\")\n surface.write_to_png(response)\n return response\n\n", "You can try this:\nhttp://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django\nIt's about SVG but I think it will be easy to adapt\n" ]
[ 7, 0 ]
[]
[]
[ "django", "image", "pycairo", "python", "python_imaging_library" ]
stackoverflow_0003004854_django_image_pycairo_python_python_imaging_library.txt
Q: Python and object/class attrs - what's going on? Can someone explain why Python does the following? >>> class Foo(object): ... bar = [] ... >>> a = Foo() >>> b = Foo() >>> a.bar.append(1) >>> b.bar [1] >>> a.bar = 1 >>> a.bar 1 >>> b.bar [1] >>> a.bar = [] >>> a.bar [] >>> b.bar [1] >>> del a.bar >>> a.bar [1] It's rather confusing! A: This is because the way you have written it, bar is a class variable rather than an instance variable. To define an instance variable, bind it in the constructor: class Foo(object): def __init__(self): self.bar = [] Note that it now belongs to a single instance of Foo (self) rather than the Foo class, and you will see the results you expect when you assign to it. A: When you declare an element in the class like that it is shared by all instances of the class. To make a proper class member that belongs to each instance, separately, create it in __init__ like the following: class Foo(object): def __init__(self): self.bar = [] A: In the beginning, bar is a class variable and it is shared between a and b, both a.bar and b.bar refer to the same object. When you assign a new value to a.bar, this does not overwrite the class variable, it adds a new instance variable to the a object, hiding the class variable when you access a.bar. If you delete a.bar (the instance variable), then a.bar resolves again to the class variable. b.bar on the other hand always refers to the class variable, it's not influenced by the additional bar on the a object or any values assigned to that. To set the class variable you can access it through the class itself: Foo.bar = 1 A: >>> class Foo(object): ... bar = [] ... bar is a shared class variable, not an instance variable. I believe that deals with most of your confusion. To make it a instance var, define it in class's __init__ per the other answers. >>> a = Foo() >>> b = Foo() >>> a.bar.append(1) >>> b.bar [1] This is the proof of that. >>> a.bar = 1 >>> a.bar 1 >>> b.bar [1] Now you've redefined a.bar as a instance variable. That's what happens when you define variables externally by default. >>> a.bar = [] >>> a.bar [] >>> b.bar [1] >>> del a.bar >>> a.bar [1] Same again. b.bar is still the shared class variable. A: As others have said the code as written creates a class variable rather than an instance variable. You need to assign in __init__ to create an instance variable. Hopefully this annotated copy of your code is helpful in explaining what's going on at each stage: >>> class Foo(object): ... bar = [] # defines a class variable on Foo (shared by all instances) ... >>> a = Foo() >>> b = Foo() >>> a.bar.append(1) # appends the value 1 to the previously empty list Foo.bar >>> b.bar # returns the value of the class variable Foo.bar [1] >>> a.bar = 1 # binds 1 to the instance variable a.bar, masking the access >>> a.bar # you previously had to the class variable through a.bar 1 >>> b.bar # b doesn't have an instance variable 'bar' so this still [1] # returns the class variable >>> a.bar = [] # bind a's instance variable to to an empty list >>> a.bar [] >>> b.bar # b doesn't have an instance variable 'bar' so this still [1] # returns the class variable >>> del a.bar # unbinds a's instance variable unmasking the class variable >>> a.bar # so a.bar now returns the list with 1 in it. [1] Also, printing out the value of Foo.bar (the class variable accessed via the class rather than via an instance) after each of your statements might help clarify what is going on. A: On a related note, you should be aware of this pitfall that you might see sometime soon: class A: def __init__(self, mylist = []): self.mylist = mylist a = A() a2 = A() a.mylist.append(3) print b.mylist #prints [3] ??? This confuses a lot of folks and has to do with how the code is interpreted. Python actually interprets the function headings first, so it evaluates __init__(self, mylist = []) and stores a reference to that list as the default parameter. That means that all instances of A will (unless provided their own list) reference the original list. The correct code for doing such a thing would be class A: def __init__(self, mylist=None): if mylist: self.mylist = mylist else: self.mylist = [] or if you want a shorter expression you can use the ternary syntax: self.mylist = mylist if mylist else []
Python and object/class attrs - what's going on?
Can someone explain why Python does the following? >>> class Foo(object): ... bar = [] ... >>> a = Foo() >>> b = Foo() >>> a.bar.append(1) >>> b.bar [1] >>> a.bar = 1 >>> a.bar 1 >>> b.bar [1] >>> a.bar = [] >>> a.bar [] >>> b.bar [1] >>> del a.bar >>> a.bar [1] It's rather confusing!
[ "This is because the way you have written it, bar is a class variable rather than an instance variable.\nTo define an instance variable, bind it in the constructor:\nclass Foo(object):\n def __init__(self):\n self.bar = []\n\nNote that it now belongs to a single instance of Foo (self) rather than the Foo class, and you will see the results you expect when you assign to it.\n", "When you declare an element in the class like that it is shared by all instances of the class. To make a proper class member that belongs to each instance, separately, create it in __init__ like the following:\nclass Foo(object):\n def __init__(self):\n self.bar = []\n\n", "In the beginning, bar is a class variable and it is shared between a and b, both a.bar and b.bar refer to the same object.\nWhen you assign a new value to a.bar, this does not overwrite the class variable, it adds a new instance variable to the a object, hiding the class variable when you access a.bar. If you delete a.bar (the instance variable), then a.bar resolves again to the class variable.\nb.bar on the other hand always refers to the class variable, it's not influenced by the additional bar on the a object or any values assigned to that.\nTo set the class variable you can access it through the class itself:\nFoo.bar = 1\n\n", ">>> class Foo(object):\n... bar = []\n...\n\nbar is a shared class variable, not an instance variable. I believe that deals with most of your confusion. To make it a instance var, define it in class's __init__ per the other answers.\n>>> a = Foo()\n>>> b = Foo()\n>>> a.bar.append(1)\n>>> b.bar\n[1]\n\nThis is the proof of that.\n>>> a.bar = 1\n>>> a.bar\n1\n>>> b.bar\n[1]\n\nNow you've redefined a.bar as a instance variable. That's what happens when you define variables externally by default.\n>>> a.bar = []\n>>> a.bar\n[]\n>>> b.bar\n[1]\n>>> del a.bar\n>>> a.bar\n[1]\n\nSame again. b.bar is still the shared class variable.\n", "As others have said the code as written creates a class variable rather than an instance variable. You need to assign in __init__ to create an instance variable.\nHopefully this annotated copy of your code is helpful in explaining what's going on at each stage:\n>>> class Foo(object):\n... bar = [] # defines a class variable on Foo (shared by all instances)\n...\n>>> a = Foo()\n>>> b = Foo()\n>>> a.bar.append(1) # appends the value 1 to the previously empty list Foo.bar\n>>> b.bar # returns the value of the class variable Foo.bar\n[1]\n>>> a.bar = 1 # binds 1 to the instance variable a.bar, masking the access\n>>> a.bar # you previously had to the class variable through a.bar\n1\n>>> b.bar # b doesn't have an instance variable 'bar' so this still\n[1] # returns the class variable\n>>> a.bar = [] # bind a's instance variable to to an empty list\n>>> a.bar\n[]\n>>> b.bar # b doesn't have an instance variable 'bar' so this still\n[1] # returns the class variable\n>>> del a.bar # unbinds a's instance variable unmasking the class variable\n>>> a.bar # so a.bar now returns the list with 1 in it.\n[1]\n\nAlso, printing out the value of Foo.bar (the class variable accessed via the class rather than via an instance) after each of your statements might help clarify what is going on.\n", "On a related note, you should be aware of this pitfall that you might see sometime soon:\nclass A:\n def __init__(self, mylist = []):\n self.mylist = mylist\n\n\na = A()\na2 = A()\n\na.mylist.append(3)\nprint b.mylist #prints [3] ???\n\nThis confuses a lot of folks and has to do with how the code is interpreted. Python actually interprets the function headings first, so it evaluates __init__(self, mylist = []) and stores a reference to that list as the default parameter. That means that all instances of A will (unless provided their own list) reference the original list. The correct code for doing such a thing would be\nclass A:\n def __init__(self, mylist=None):\n if mylist:\n self.mylist = mylist\n else:\n self.mylist = []\n\nor if you want a shorter expression you can use the ternary syntax:\nself.mylist = mylist if mylist else []\n\n" ]
[ 7, 0, 0, 0, 0, 0 ]
[]
[]
[ "class_attributes", "python" ]
stackoverflow_0003045246_class_attributes_python.txt
Q: Python - How to find a correlation between two vectors? Given two vectors X and Y, I have to find their correlation, i.e. their linear dependence/independence. Both vectors have equal dimension. The result should be a floating point number from [-1.0 .. 1.0]. Example: X=[-1, 2, 0] Y=[ 4, 2, -0.3] Find y = cor(X,Y) such that y belongs to [-1.0 .. 1.0]. It should be a simple construction involving a list-comprehension. No external library is allowed. UPDATE: ok, if the dot product is enough, then here is my solution: nX = 1/(sum([x*x for x in X]) ** 0.5) nY = 1/(sum([y*y for y in Y]) ** 0.5) cor = sum([(x*nX)*(y*nY) for x,y in zip(X,Y) ]) right? A: Sounds like a dot product to me. Solve the equation for the cosine of the angle between the two vectors, which is always in the range [-1, 1], and you'll have what you want. It's equal to the dot product divided by the magnitudes of two vectors. A: Since range is supposed to be [-1, 1] I think that the Pearson Correlation can be ok for your purposes. Also dot-product would work but you'll have to normalize vectors before calculating it and you can have a -1,1 range just if you have also negative values.. otherwise you would have 0,1 A: Don't assume because a formula is algebraically correct that its direct implementation in code will work. There can be numerical problems with some definitions of correlation. See How to calculate correlation accurately
Python - How to find a correlation between two vectors?
Given two vectors X and Y, I have to find their correlation, i.e. their linear dependence/independence. Both vectors have equal dimension. The result should be a floating point number from [-1.0 .. 1.0]. Example: X=[-1, 2, 0] Y=[ 4, 2, -0.3] Find y = cor(X,Y) such that y belongs to [-1.0 .. 1.0]. It should be a simple construction involving a list-comprehension. No external library is allowed. UPDATE: ok, if the dot product is enough, then here is my solution: nX = 1/(sum([x*x for x in X]) ** 0.5) nY = 1/(sum([y*y for y in Y]) ** 0.5) cor = sum([(x*nX)*(y*nY) for x,y in zip(X,Y) ]) right?
[ "Sounds like a dot product to me.\nSolve the equation for the cosine of the angle between the two vectors, which is always in the range [-1, 1], and you'll have what you want.\nIt's equal to the dot product divided by the magnitudes of two vectors.\n", "Since range is supposed to be [-1, 1] I think that the Pearson Correlation can be ok for your purposes.\nAlso dot-product would work but you'll have to normalize vectors before calculating it and you can have a -1,1 range just if you have also negative values.. otherwise you would have 0,1\n", "Don't assume because a formula is algebraically correct that its direct implementation in code will work. There can be numerical problems with some definitions of correlation.\nSee How to calculate correlation accurately\n" ]
[ 4, 4, 2 ]
[]
[]
[ "algorithm", "list_comprehension", "math", "python" ]
stackoverflow_0003045040_algorithm_list_comprehension_math_python.txt
Q: python: iif or (x ? a : b) Possible Duplicate: Python Ternary Operator If Python would support the (x ? a : b) syntax from C/C++, I would write: print paid ? ("paid: " + str(paid) + " €") : "not paid" I really don't want to have an if-check and two independent prints here (because that is only an example above, in my code, it looks much more complicated and would really be stupid to have almost the same code twice). However, Python does not support this operator or any similar operator (afaik). What is the easiest/cleanest/most common way to do this? I have searched a bit and seen someone defining an iif(cond,iftrue,iffalse) function, inspired from Visual Basic. I wondered if I really have to add that code and if/why there is no such basic function in the standard library. A: Try print ("paid: " + str(paid) + " €") if paid else "not paid"
python: iif or (x ? a : b)
Possible Duplicate: Python Ternary Operator If Python would support the (x ? a : b) syntax from C/C++, I would write: print paid ? ("paid: " + str(paid) + " €") : "not paid" I really don't want to have an if-check and two independent prints here (because that is only an example above, in my code, it looks much more complicated and would really be stupid to have almost the same code twice). However, Python does not support this operator or any similar operator (afaik). What is the easiest/cleanest/most common way to do this? I have searched a bit and seen someone defining an iif(cond,iftrue,iffalse) function, inspired from Visual Basic. I wondered if I really have to add that code and if/why there is no such basic function in the standard library.
[ "Try\n print (\"paid: \" + str(paid) + \" €\") if paid else \"not paid\"\n\n" ]
[ 22 ]
[]
[]
[ "iif_function", "python", "ternary_operator" ]
stackoverflow_0003045675_iif_function_python_ternary_operator.txt
Q: Simulate Browser Resources Expansion Behavior With Python I'm looking for a way to simulate browser resources expansion behavior. The flow I'm trying to address is the following: Access an initial URL (e.g. http://example.dmn/index.htm) Parse the html response received (e.g. index.htm) Find the resources that a browser will fetch as a result of the index parsing, e.g.: Images Flash Embedded videos/audio Frames /iFrames Repeat the process recursively for each new resource found I'm not expecting to follow links (href), only page resources that will be fetched automatically by a browser when the page is first accessed. Do you have a suggestion how to preform this simulation? Are there any Python projects/libraries that may help ? Thanks A: You may wish to look at the Windmill Testing Framework which allows you to write tests in Python for web apps. A: You might want to look at spider.py, and robotparser. Barring those doing what you want automatically, you can dig into the HTML soup yourself with BeautifulSoup. A: You may want to take a look at Scrapy. It may not provide all the exact features you need, but can be easily extended to do so.
Simulate Browser Resources Expansion Behavior With Python
I'm looking for a way to simulate browser resources expansion behavior. The flow I'm trying to address is the following: Access an initial URL (e.g. http://example.dmn/index.htm) Parse the html response received (e.g. index.htm) Find the resources that a browser will fetch as a result of the index parsing, e.g.: Images Flash Embedded videos/audio Frames /iFrames Repeat the process recursively for each new resource found I'm not expecting to follow links (href), only page resources that will be fetched automatically by a browser when the page is first accessed. Do you have a suggestion how to preform this simulation? Are there any Python projects/libraries that may help ? Thanks
[ "You may wish to look at the Windmill Testing Framework which allows you to write tests in Python for web apps.\n", "You might want to look at spider.py, and robotparser. Barring those doing what you want automatically, you can dig into the HTML soup yourself with BeautifulSoup.\n", "You may want to take a look at Scrapy.\nIt may not provide all the exact features you need, but can be easily extended to do so.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "html", "http", "python", "scrapy", "web_scraping" ]
stackoverflow_0003044005_html_http_python_scrapy_web_scraping.txt
Q: Join a list of lists together into one list in Python I have a list which consists of many lists. Here is an example, [ [Obj, Obj, Obj, Obj], [Obj], [Obj], [ [Obj,Obj], [Obj,Obj,Obj] ] ] Is there a way to join all these items together as one list, so the output will be something like [Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj] A: Yes, here's one way to do it: def flatten(lst): for elem in lst: if type(elem) in (tuple, list): for i in flatten(elem): yield i else: yield elem Please note, this creates a generator, so if you need a list, wrap it in list(): flattenedList = list(flatten(nestedList)) A: Stolen from MonkeySage, here: def iter_flatten(iterable): it = iter(iterable) for e in it: if isinstance(e, (list, tuple)): for f in iter_flatten(e): yield f else: yield e
Join a list of lists together into one list in Python
I have a list which consists of many lists. Here is an example, [ [Obj, Obj, Obj, Obj], [Obj], [Obj], [ [Obj,Obj], [Obj,Obj,Obj] ] ] Is there a way to join all these items together as one list, so the output will be something like [Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]
[ "Yes, here's one way to do it:\ndef flatten(lst):\n for elem in lst:\n if type(elem) in (tuple, list):\n for i in flatten(elem):\n yield i\n else:\n yield elem\n\nPlease note, this creates a generator, so if you need a list, wrap it in list():\nflattenedList = list(flatten(nestedList))\n\n", "Stolen from MonkeySage, here:\ndef iter_flatten(iterable):\n it = iter(iterable)\n for e in it:\n if isinstance(e, (list, tuple)):\n for f in iter_flatten(e):\n yield f\n else:\n yield e\n\n" ]
[ 7, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003046217_list_python.txt
Q: Convert a GTK python script to C The following script will take a screenshot on a Gnome desktop. import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1]) pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1]) if (pb != None): pb.save("screenshot.png", "png") print "Screenshot saved to screenshot.png." else: print "Unable to get the screenshot." Now, I've been trying to convert this to C and use it in one of the apps I am writing but so far i've been unsuccessful. Is there any what to do this in C (on Linux)? Thanks! Jess. A: I tested this and it does work, but there might be a simpler way to go from GdkPixbuf to a png this was just the first one I found. (There's no gdk_pixbuf_save()) #include <unistd.h> #include <stdio.h> #include <gdk/gdk.h> #include <cairo.h> int main(int argc, char **argv) { gdk_init(&argc, &argv); GdkWindow *w = gdk_get_default_root_window(); gint width, height; gdk_drawable_get_size(GDK_DRAWABLE(w), &width, &height); GdkPixbuf *pb = gdk_pixbuf_get_from_drawable(NULL, GDK_DRAWABLE(w), NULL, 0,0,0,0,width,height); if(pb != NULL) { cairo_surface_t *surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height); cairo_t *cr = cairo_create(surf); gdk_cairo_set_source_pixbuf(cr, pb, 0, 0); cairo_paint(cr); cairo_surface_write_to_png(surf, "screenshot.png"); g_print("Screenshot saved to screenshot.png.\n"); } else { g_print("Unable to get the screenshot.\n"); } return 0; } you'd compile like this: (assuming you save it as screenshot.c) gcc -std=gnu99 `pkg-config --libs --cflags gdk-2.0` screenshot.c -o screenshot Edit: the stuff to save the pixbuf could also look like: (note I didn't try this out, but it's only one line...) Thanks to kaizer.se for pointing out my fail at doc reading :P gdk_pixbuf_save(pb, "screenshot.png", "png", NULL, NULL);
Convert a GTK python script to C
The following script will take a screenshot on a Gnome desktop. import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1]) pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1]) if (pb != None): pb.save("screenshot.png", "png") print "Screenshot saved to screenshot.png." else: print "Unable to get the screenshot." Now, I've been trying to convert this to C and use it in one of the apps I am writing but so far i've been unsuccessful. Is there any what to do this in C (on Linux)? Thanks! Jess.
[ "I tested this and it does work, but there might be a simpler way to go from GdkPixbuf to a png this was just the first one I found. (There's no gdk_pixbuf_save())\n#include <unistd.h>\n#include <stdio.h>\n#include <gdk/gdk.h>\n#include <cairo.h>\n\nint main(int argc, char **argv)\n{\n gdk_init(&argc, &argv);\n\n GdkWindow *w = gdk_get_default_root_window();\n\n gint width, height;\n gdk_drawable_get_size(GDK_DRAWABLE(w), &width, &height);\n\n GdkPixbuf *pb = gdk_pixbuf_get_from_drawable(NULL, \n GDK_DRAWABLE(w), \n NULL, \n 0,0,0,0,width,height);\n\n if(pb != NULL) {\n cairo_surface_t *surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, \n width, height);\n cairo_t *cr = cairo_create(surf);\n gdk_cairo_set_source_pixbuf(cr, pb, 0, 0);\n cairo_paint(cr);\n cairo_surface_write_to_png(surf, \"screenshot.png\");\n g_print(\"Screenshot saved to screenshot.png.\\n\");\n } else {\n g_print(\"Unable to get the screenshot.\\n\");\n }\n return 0;\n}\n\nyou'd compile like this: (assuming you save it as screenshot.c)\ngcc -std=gnu99 `pkg-config --libs --cflags gdk-2.0` screenshot.c -o screenshot\n\nEdit: the stuff to save the pixbuf could also look like: (note I didn't try this out, but it's only one line...) Thanks to kaizer.se for pointing out my fail at doc reading :P\ngdk_pixbuf_save(pb, \"screenshot.png\", \"png\", NULL, NULL);\n\n" ]
[ 3 ]
[]
[]
[ "c", "gtk", "linux", "python", "screenshot" ]
stackoverflow_0003045850_c_gtk_linux_python_screenshot.txt
Q: Dragon NaturallySpeaking Programmers Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the (really expensive) SDK, I don't even know that it would work then. Microsoft has the ability to write a (Python) program where it's speech recognizer can wait until it detects a speech event and then process it. It also has the handy quality of being able to suggest alternative phrases to the one that it thinks is the best guess and recording the .wav file for later use. Sample code: spEngine = MsSpeech() spEngine.setEventHandler(RecoEventHandler(spEngine.context)) class RecoEventHandler(SpRecoContext): def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): res = win32com.client.Dispatch(Result) phrase = res.PhraseInfo.GetText() #from here I would save it as XML # write reco phrases altPhrases = reco.Alternates(NBEST) for phrase in altPhrases: nodePhrase = self.doc.createElement(TAG_PHRASE) I can not seem to make DNS do this. The closest I can do-hickey it to is: while keepGoing == True: yourWords = raw_input("Your input: ") transcript_el = createTranscript(doc, "user", yourWords) speech_el.appendChild(transcript_el) if yourWords == 'bye': break It even has the horrible side effect of making the user say "new-line" after every sentence! Not the preferred solution at all! Is there anyway to make DNS do what Microsoft Speech does? FYI: I know the logical solution would be to simply switch to Microsoft Speech but let's assume, just for grins and giggles, that that is not an option. UPDATE - Has anyone bought the SDK? Did you find it useful? A: Solution: download Natlink - http://qh.antenna.nl/unimacro/installation/installation.html It's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work properly and it works for every version of Python BUT 2.4. Documentation for all supported commands is found under C:\NatLink\NatLink\MiscScripts\natlink.txt after you download it. It's under all the updates at the top of the file. Example code: #make sure DNS is running before you start if not natlink.isNatSpeakRunning(): raiseError('must start up Dragon NaturallySpeaking first!') shutdownServer() return #connect to natlink and load the grammer it's supposed to recognize natlink.natConnect() loggerGrammar = LoggerGrammar() loggerGrammar.initialize() if natlink.getMicState() == 'off': natlink.setMicState('on') userName = 'Danni' natlink.openUser(userName) #natlink.waitForSpeech() continuous loop waiting for input. #Results are sent to gotResultsObject method of the logger grammar natlink.waitForSpeech() natlink.natDisconnect() The code's severely abbreviated from my production version but I hope you get the idea. Only problem now is that I still have to returned to the mini-window natlink.waitForSpeech() creates to click 'close' before I can exit the program safely. A way to signal the window to close from python without using the timeout parameter would be fantastic.
Dragon NaturallySpeaking Programmers
Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the (really expensive) SDK, I don't even know that it would work then. Microsoft has the ability to write a (Python) program where it's speech recognizer can wait until it detects a speech event and then process it. It also has the handy quality of being able to suggest alternative phrases to the one that it thinks is the best guess and recording the .wav file for later use. Sample code: spEngine = MsSpeech() spEngine.setEventHandler(RecoEventHandler(spEngine.context)) class RecoEventHandler(SpRecoContext): def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result): res = win32com.client.Dispatch(Result) phrase = res.PhraseInfo.GetText() #from here I would save it as XML # write reco phrases altPhrases = reco.Alternates(NBEST) for phrase in altPhrases: nodePhrase = self.doc.createElement(TAG_PHRASE) I can not seem to make DNS do this. The closest I can do-hickey it to is: while keepGoing == True: yourWords = raw_input("Your input: ") transcript_el = createTranscript(doc, "user", yourWords) speech_el.appendChild(transcript_el) if yourWords == 'bye': break It even has the horrible side effect of making the user say "new-line" after every sentence! Not the preferred solution at all! Is there anyway to make DNS do what Microsoft Speech does? FYI: I know the logical solution would be to simply switch to Microsoft Speech but let's assume, just for grins and giggles, that that is not an option. UPDATE - Has anyone bought the SDK? Did you find it useful?
[ "Solution: download Natlink - http://qh.antenna.nl/unimacro/installation/installation.html\nIt's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work properly and it works for every version of Python BUT 2.4. \nDocumentation for all supported commands is found under C:\\NatLink\\NatLink\\MiscScripts\\natlink.txt after you download it. It's under all the updates at the top of the file.\nExample code:\n#make sure DNS is running before you start\nif not natlink.isNatSpeakRunning():\n raiseError('must start up Dragon NaturallySpeaking first!')\n shutdownServer()\n return\n#connect to natlink and load the grammer it's supposed to recognize\nnatlink.natConnect()\nloggerGrammar = LoggerGrammar()\nloggerGrammar.initialize()\nif natlink.getMicState() == 'off':\n natlink.setMicState('on')\nuserName = 'Danni'\nnatlink.openUser(userName)\n#natlink.waitForSpeech() continuous loop waiting for input. \n#Results are sent to gotResultsObject method of the logger grammar\nnatlink.waitForSpeech()\nnatlink.natDisconnect()\n\nThe code's severely abbreviated from my production version but I hope you get the idea. Only problem now is that I still have to returned to the mini-window natlink.waitForSpeech() creates to click 'close' before I can exit the program safely. A way to signal the window to close from python without using the timeout parameter would be fantastic. \n" ]
[ 8 ]
[]
[]
[ "naturallyspeaking", "python", "speech", "speech_recognition" ]
stackoverflow_0002952899_naturallyspeaking_python_speech_speech_recognition.txt
Q: Django model class and custom property today a weird problem occurred to me: I have a model class in Django and added a custom property to it that shall not be saved into the database and therefore is not representative in the model's structure: class Category(models.Model): groups = models.ManyToManyField(Group) title = defaultdict() Now, when I'm within the shell or writing a test and I do the following: c1 = Category.objects.create() c1.title['de'] = 'german title' print c1.title['de'] # prints "german title" c2 = Category.objects.create() print c2.title['de'] # prints "german title" <-- WTF? It seems that 'title' is kind of global. If I change the title to a simple string it works as expected, so it has to do something with the dict? I also tried setting title as a property: title = property(_title) But that did not work, too. So, how can I solve this? Thank you in advance! EDIT: Here is the intention of the base problem to provide you with a better look at the whole surrounding environment as requested: In our model structure, we have a model class that stores translations. This class is unbound from all the other classes that have relations with each other. The translation class stores the translated value, a language key, a translation key and the package and class the translation belongs to. Some model classes can have properties that can be translated into different languages. These properties are not mapped within the Django model structure as this is not truly possible in our eyes. Each of these classes with translatable properties, let's call them translatable, can have one or more of these properties. That's what the translation key is for. E.g. if there is a class Category with a translatable property "title", the model translation will store "module.somewhere.Category" as package/class, "title" as translation key, and e.g. for german the translation value "Kategorie" and the language key "de". My aim is to ease the access to these properties. So all these model classes inherit from a plain class called "Translatable". It has a method for resolving the module path and name of the class (for the later storing within the translation database table) and a "_propertize" method that takes the name of the property. Properties instantiate a class "Translator" that is unique for each translatable property name. This class does the resolving of the real translation value from the translation model class and some stuff for automatically resolving the translation of the currently chosen language. A: Don't do it that way. Your title attribute is completely "global". It's part of the class, not part of each instance. Do something like this. class Category(models.Model): groups = models.ManyToManyField(Group) @property def title(self): return self._title def save( self, *args, **kw ): try: self._title except AttributeError: self._title= defaultdict() super( Category, self ).save( *args, **kw ) If you could define your actual use case, it might be possible to simplify this a great deal.
Django model class and custom property
today a weird problem occurred to me: I have a model class in Django and added a custom property to it that shall not be saved into the database and therefore is not representative in the model's structure: class Category(models.Model): groups = models.ManyToManyField(Group) title = defaultdict() Now, when I'm within the shell or writing a test and I do the following: c1 = Category.objects.create() c1.title['de'] = 'german title' print c1.title['de'] # prints "german title" c2 = Category.objects.create() print c2.title['de'] # prints "german title" <-- WTF? It seems that 'title' is kind of global. If I change the title to a simple string it works as expected, so it has to do something with the dict? I also tried setting title as a property: title = property(_title) But that did not work, too. So, how can I solve this? Thank you in advance! EDIT: Here is the intention of the base problem to provide you with a better look at the whole surrounding environment as requested: In our model structure, we have a model class that stores translations. This class is unbound from all the other classes that have relations with each other. The translation class stores the translated value, a language key, a translation key and the package and class the translation belongs to. Some model classes can have properties that can be translated into different languages. These properties are not mapped within the Django model structure as this is not truly possible in our eyes. Each of these classes with translatable properties, let's call them translatable, can have one or more of these properties. That's what the translation key is for. E.g. if there is a class Category with a translatable property "title", the model translation will store "module.somewhere.Category" as package/class, "title" as translation key, and e.g. for german the translation value "Kategorie" and the language key "de". My aim is to ease the access to these properties. So all these model classes inherit from a plain class called "Translatable". It has a method for resolving the module path and name of the class (for the later storing within the translation database table) and a "_propertize" method that takes the name of the property. Properties instantiate a class "Translator" that is unique for each translatable property name. This class does the resolving of the real translation value from the translation model class and some stuff for automatically resolving the translation of the currently chosen language.
[ "Don't do it that way. Your title attribute is completely \"global\". It's part of the class, not part of each instance.\nDo something like this.\nclass Category(models.Model):\n groups = models.ManyToManyField(Group)\n @property\n def title(self):\n return self._title\n def save( self, *args, **kw ):\n try:\n self._title\n except AttributeError:\n self._title= defaultdict()\n super( Category, self ).save( *args, **kw )\n\nIf you could define your actual use case, it might be possible to simplify this a great deal.\n" ]
[ 9 ]
[]
[]
[ "class", "django", "django_models", "python" ]
stackoverflow_0003046398_class_django_django_models_python.txt
Q: How does Qt work (exactly)? When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application? How exactly does this work? Does Qt compile to the desired platform, or does it bundle some "dlls" (libs), or how does it do it? Is it different from programming a Java application, that runs cross-platform. If you use Python to write a Qt application with Python bindings, does your end user need to have Python installed? A: Qt (ideally) provides source compatibility, not binary compatibility. You still have to compile the application separately for each platform, and use the appropriate dynamic Qt libraries (which also need to be compiled separately, and have some platform-specific code). For your final question, the user would need Python, the Qt libraries, and the binding library (e.g. pyqt), but there are various ways to bundle these. A: PyQT [and its open source cousin PySide] are a great cross-platform QT binding for python, but it is not a magic solution for shipping your application for all platforms without doing any packaging/installer maintenance. I think maybe you might be expecting some magic. QT is a cross-platform library written in C++. That means, you can write your C++ or Python (or other language with bindings) code once, and create a "window" (a form, a dialog box, something on the screen) and populate it with controls (buttons, and all that) and not have to deal with the platform differences in how buttons are made in Windows, Linux, and on Mac OS X. Because it is a library, it can be packaged in multiple ways. It can be "statically linked" (built into your executable/binary/app) or "dynamically linked" (known as a DLL in windows, a shared library or on unix/linux or as a framework, in mac os x). It is not always "installed" on a computer, unless it is a shared library. Even when it is "installed" onto a computer, multiple versions might exist on that computer, and so it is not proper to think of it as being an extension to your computer, but rather an extension to an application (a program) on your computer. If you use Python bindings for QT, then your installation package for your application needs to include the QT binding's binary files (python extensions), the basic Python runtime environment including the Python executable and basic libraries, and your program's source code. It is possible to package most of this up into a single "bundle". On Mac OS X, for instance, all this can easily be put into a an ".app" bundle, and on Windows, and Linux, I believe there are packaging and installation tools that can help you do this easily. Even though you will only need to write the user interface code for your application once, you will not magically get the ability to ship an application on all three primary platforms at once, without doing at least the building of the installer or packaging, separately for each platform. Users expect to download a setup/install package for Windows or Mac OS X, and perhaps for Unix/Linux it depends further on which distribution you install. Update thanks to AdamW for this nokia link providing deployment information A: The problem is your definition of "installed". For Qt to work, the executable just has to have access to the proper libraries. Of course that for each platform a different executable and libraries have to be produced (see Qt docs). About Python, if you are to run a Python executable you have to have it installed (in a more traditional kind of way). Unless you are running with py2exe in Windows, for instance.
How does Qt work (exactly)?
When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application? How exactly does this work? Does Qt compile to the desired platform, or does it bundle some "dlls" (libs), or how does it do it? Is it different from programming a Java application, that runs cross-platform. If you use Python to write a Qt application with Python bindings, does your end user need to have Python installed?
[ "Qt (ideally) provides source compatibility, not binary compatibility. You still have to compile the application separately for each platform, and use the appropriate dynamic Qt libraries (which also need to be compiled separately, and have some platform-specific code). \nFor your final question, the user would need Python, the Qt libraries, and the binding library (e.g. pyqt), but there are various ways to bundle these.\n", "PyQT [and its open source cousin PySide] are a great cross-platform QT binding for python, but it is not a magic solution for shipping your application for all platforms without doing any packaging/installer maintenance. I think maybe you might be expecting some magic.\nQT is a cross-platform library written in C++. That means, you can write your C++ or Python (or other language with bindings) code once, and create a \"window\" (a form, a dialog box, something on the screen) and populate it with controls (buttons, and all that) and not have to deal with the platform differences in how buttons are made in Windows, Linux, and on Mac OS X.\nBecause it is a library, it can be packaged in multiple ways. It can be \"statically linked\" (built into your executable/binary/app) or \"dynamically linked\" (known as a DLL in windows, a shared library or on unix/linux or as a framework, in mac os x). It is not always \"installed\" on a computer, unless it is a shared library.\nEven when it is \"installed\" onto a computer, multiple versions might exist on that computer, and so it is not proper to think of it as being an extension to your computer, but rather an extension to an application (a program) on your computer.\nIf you use Python bindings for QT, then your installation package for your application needs to include the QT binding's binary files (python extensions), the basic Python runtime environment including the Python executable and basic libraries, and your program's source code. It is possible to package most of this up into a single \"bundle\". On Mac OS X, for instance, all this can easily be put into a an \".app\" bundle, and on Windows, and Linux, I believe there are packaging and installation tools that can help you do this easily.\nEven though you will only need to write the user interface code for your application once, you will not magically get the ability to ship an application on all three primary platforms at once, without doing at least the building of the installer or packaging, separately for each platform. Users expect to download a setup/install package for Windows or Mac OS X, and perhaps for Unix/Linux it depends further on which distribution you install. \nUpdate thanks to AdamW for this nokia link providing deployment information\n", "The problem is your definition of \"installed\". For Qt to work, the executable just has to have access to the proper libraries.\nOf course that for each platform a different executable and libraries have to be produced (see Qt docs).\nAbout Python, if you are to run a Python executable you have to have it installed (in a more traditional kind of way). Unless you are running with py2exe in Windows, for instance.\n" ]
[ 15, 13, 5 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0003045745_python_qt.txt
Q: Can this code be further optimized? i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries` A: def get_list(file, cmp, fout): ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp)) return fout[ind].rstrip('\n').split(' ') root = r'c:\begpython\wavnk' header = 6 for lst in lists: save = database_index[lst] index, base, _, abs2, abs1, *_ = save using_data[index] = save base = os.path.join(root, base.replace('phone', 'text')) fin, fout = base + '.pm', base + '.mcep' file = open(fin) fout = open(fout).readlines() [next(file) for _ in range(header)] file = [float(line.partition(' ')[0]) for line in file] join_cost_index_end[index] = get_list(file, float(abs1), fout) join_cost_index_strt[index] = get_list(file, float(abs2), fout) Don't: convert string to string multiple times, it'll remain a string convert value within loop when it could be done outside the loop use single-letter for meaning variables iterate over sequences with range(len(sequence)) copy-paste bits of code: use functions use any code without reading docs first rely on SO for psychic debugging. A: x1=open(p , 'r') x2=open(p ,'r') Why open the same file twice? Are you expecting it to change?
Can this code be further optimized?
i understand that the code given below will not be compltely understood unless i explain my whole of previous and next lines of code. But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries`
[ "def get_list(file, cmp, fout):\n ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp))\n return fout[ind].rstrip('\\n').split(' ')\n\nroot = r'c:\\begpython\\wavnk'\nheader = 6\nfor lst in lists:\n save = database_index[lst]\n index, base, _, abs2, abs1, *_ = save\n using_data[index] = save\n\n base = os.path.join(root, base.replace('phone', 'text'))\n fin, fout = base + '.pm', base + '.mcep'\n file = open(fin)\n fout = open(fout).readlines()\n [next(file) for _ in range(header)]\n file = [float(line.partition(' ')[0]) for line in file]\n join_cost_index_end[index] = get_list(file, float(abs1), fout)\n join_cost_index_strt[index] = get_list(file, float(abs2), fout)\n\nDon't:\n\nconvert string to string multiple times, it'll remain a string\nconvert value within loop when it could be done outside the loop\nuse single-letter for meaning variables\niterate over sequences with range(len(sequence))\ncopy-paste bits of code: use functions\nuse any code without reading docs first\nrely on SO for psychic debugging.\n\n", "x1=open(p , 'r')\nx2=open(p ,'r')\n\nWhy open the same file twice? Are you expecting it to change?\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003046145_python.txt
Q: Finding out event that called a CGI script What I want is to be able to make my CGI script do different things depending on what action initiated the calling of the script. For example, if one button is pressed, a database is cleared. If another button is pressed, a form is submitted and that data is added to the database. Should I be doing something like adding the name of the form/button to the end of the POST data submitted in jQuery and then .poping it off in the script? Or is there some other data that's already sent in the POST that I could get from FieldStorage that would give me the information I need to decide what the script should do when it's called? And what if I wasn't using javascript? Would I have to have a hidden field that gets submitted with the name of the form/button? Or is it best to use a different target script for each button on a page? A: POST request includes all the elements of the form you submit. So, if you have a form with several submit buttons: <form id="mytestform" target="/cgi-bin/script.py" method="POST"> <input type="submit" name="ClearDB" value="Clear DB"/> <input type="submit" name="TestDB" value="Test DB"/> <input type="text" name="hostname" /> </form> then you would get a POST request with request data looking like: ClearDB=Clear%20DB&hostname= every time you submit the form using the "Clear DB" button. Basically, to get the name of the button you pressed to submit the form, you just need to search for the button's name. Another approach is using same name for buttons, but different values: <form id="mytestform" target="/cgi-bin/script.py" method="POST"> <input type="submit" name="action" value="Clear"/> <input type="submit" name="action" value="Test"/> </form> Then you just need to check for the value of the request element you get (in the case above it would be "action"). In Python you would therefore just need to get the value you got via the FieldStorage class indeed, using FieldStorage.getfirst() method.
Finding out event that called a CGI script
What I want is to be able to make my CGI script do different things depending on what action initiated the calling of the script. For example, if one button is pressed, a database is cleared. If another button is pressed, a form is submitted and that data is added to the database. Should I be doing something like adding the name of the form/button to the end of the POST data submitted in jQuery and then .poping it off in the script? Or is there some other data that's already sent in the POST that I could get from FieldStorage that would give me the information I need to decide what the script should do when it's called? And what if I wasn't using javascript? Would I have to have a hidden field that gets submitted with the name of the form/button? Or is it best to use a different target script for each button on a page?
[ "POST request includes all the elements of the form you submit. So, if you have a form with several submit buttons:\n <form id=\"mytestform\" target=\"/cgi-bin/script.py\" method=\"POST\">\n <input type=\"submit\" name=\"ClearDB\" value=\"Clear DB\"/>\n <input type=\"submit\" name=\"TestDB\" value=\"Test DB\"/>\n <input type=\"text\" name=\"hostname\" />\n </form>\n\nthen you would get a POST request with request data looking like: ClearDB=Clear%20DB&hostname= every time you submit the form using the \"Clear DB\" button. \nBasically, to get the name of the button you pressed to submit the form, you just need to search for the button's name. Another approach is using same name for buttons, but different values:\n<form id=\"mytestform\" target=\"/cgi-bin/script.py\" method=\"POST\">\n <input type=\"submit\" name=\"action\" value=\"Clear\"/>\n <input type=\"submit\" name=\"action\" value=\"Test\"/>\n</form>\n\nThen you just need to check for the value of the request element you get (in the case above it would be \"action\").\nIn Python you would therefore just need to get the value you got via the FieldStorage class indeed, using FieldStorage.getfirst() method.\n" ]
[ 1 ]
[]
[]
[ "cgi", "jquery", "python" ]
stackoverflow_0002864877_cgi_jquery_python.txt
Q: How can I have multiple navigation paths with Django, like a simplifies wizard path and a full path? Lets say I have an application with a structure such as: System set date set name set something Other set death ray target calibrate and I want to have "back" and "next" buttons on a page. The catch is, if you're going in via the "wizard", I want the nav path to be something like "set name" -> "set death ray target" -> "set name". If you go via the Advanced options menu, I want to just iterate options... "set date" -> "set name" -> "set something" -> "set death ray target" -> calibrate. So far, I'm thinking I have to use different URIs, but that's that. Any ideia how this could be done? Thanks. A: Have a look at the django form wizard.
How can I have multiple navigation paths with Django, like a simplifies wizard path and a full path?
Lets say I have an application with a structure such as: System set date set name set something Other set death ray target calibrate and I want to have "back" and "next" buttons on a page. The catch is, if you're going in via the "wizard", I want the nav path to be something like "set name" -> "set death ray target" -> "set name". If you go via the Advanced options menu, I want to just iterate options... "set date" -> "set name" -> "set something" -> "set death ray target" -> calibrate. So far, I'm thinking I have to use different URIs, but that's that. Any ideia how this could be done? Thanks.
[ "Have a look at the django form wizard. \n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "path", "python", "redirect" ]
stackoverflow_0003047196_django_django_templates_path_python_redirect.txt
Q: Is this a valid quine? def start(fileName): fileReader = open(fileName) for row in fileReader: print row, if __name__ == "__main__": import sys if len(sys.argv) <= 1: print "usage quine /path/to/file" sys.exit(-1) fileName = sys.argv[0] start(fileName) python quine.py foo A: No, a quine shouldn't take in any input: A quine takes no input. Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms. From Quine (computing). UPDATE You need to encode the source into the quine itself. A quine consists of two parts: code that does the actual printing and data that represents the source code. It seems recursive, but isn't really. For a good quine tutorial, I recommend checking out this link; it's what I used to create a quine in a language that I designed. A: Quines can't access the filesystem, so no. As Wikipedia states, "Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms.". Reference: Wikipedia: Quine (computing)
Is this a valid quine?
def start(fileName): fileReader = open(fileName) for row in fileReader: print row, if __name__ == "__main__": import sys if len(sys.argv) <= 1: print "usage quine /path/to/file" sys.exit(-1) fileName = sys.argv[0] start(fileName) python quine.py foo
[ "No, a quine shouldn't take in any input:\n\nA quine takes no input. Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms.\n\nFrom Quine (computing).\nUPDATE\nYou need to encode the source into the quine itself. A quine consists of two parts: code that does the actual printing and data that represents the source code. It seems recursive, but isn't really. For a good quine tutorial, I recommend checking out this link; it's what I used to create a quine in a language that I designed.\n", "Quines can't access the filesystem, so no. As Wikipedia states, \"Allowing input would permit the source code to be fed to the program via the keyboard, opening the source file of the program, and similar mechanisms.\". \nReference:\nWikipedia: Quine (computing)\n" ]
[ 9, 2 ]
[]
[]
[ "python", "quine" ]
stackoverflow_0003047583_python_quine.txt
Q: Where is Python language used? I am a web developer and usually use PHP, JavaScript or MySQL. I have heard lot about Python. But I have no idea where it is used and why it is used. Just like PHP, ASP, ColdFusion, .NET are used to build websites, and C, C++, Java are used to build software or desktop apps. Where does Python fit in this? What can Python do that these other languages cannot do? A: Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications. And by the way, What can you do with PHP that you can't do with ASP or JSP? What can you do with Java that you can't do with C++? A: All the languages you've mentioned are Turing Complete, so in theory there is nothing one can do and another can't. In practice of course, there are differences, especially in productivity and efficiency. Compared to C, C++ and Java, which are static typed, Python is a dynamic language and can help you write the same code in significantly fewer lines. Python has a moto "batteries included", which means that the standard library offers all the things needed to build a complex application. Other languages would need external libraries for this. On top of this, since Python is an old and mature language (older than Java), many external libraries (for game development and scientific calculations just to mention a few) have been evolved. So Python can be used to program desktop applications and in fact in some cases more efficiently than other traditional languages. Python is also a scripting language. This means that you can easily and quickly write scripts and simple tests with it. More recently python is also used for web frameworks. Since there is a big code base and many python programmers, this was a logical thing to do. These web frameworks follow the practice mainly introduced by Ruby on Rails. A: With a few exceptions, Python is used pretty much wherever a programmer who knows Python wants to focus on solving a problem instead of struggling with implementation details. You'll find it in games, web applications, network servers, scientific computing, media tools, application scripting, etc. (There's a somewhat old list of some organizations that use it here.) People who know it well tend to love it because it strikes a very rare balance of conciseness and clarity, and (perhaps to a lesser extent) because it has a rich set of useful libraries. Some places where Python isn't used as much: Web browser scripts (because browsers implement JavaScript, not Python, though there are ways around that) Large GUI applications (perhaps because good GUI bindings are relatively new) Graphics engines (for performance reasons, but note that Python is sometimes used for the controlling logic that makes use of a graphics engine) Small embedded devices (although some folks have had success with compact, stripped-down and special-purpose implementations of Python, and we're starting to see python tools for building applications on smart phones and tablets.) A: Your categorization is not correct: php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications. On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more). Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame). Python can also be translated into binary code like java. A: Many websites uses Django or Zope/Plone web framework, these are written in Python. Python is used a lot for writing system administration software, usually when bash scripts (shell script) isn't up to the job, but going C/C++ is an overkill. This is also the spectrum where perl, awk, etc stands. Gentoo's emerge/portage is one example. Mercurial/HG is a distributed version control system (DVCS) written in python. Many desktop applications are also written in Python. The original Bittorrent was written in python. Python is also used as the scripting languages for GIMP, Inkscape, Blender, OpenOffice, etc. Python allows advanced users to write plugins and access advanced functionalities that cannot typically be used through a GUI. A: Python is used for developing sites. It's more highlevel than php. Python is used for linux dekstop applications. For example, the most of Ubuntu configurations utilites are pythonic. A: Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.
Where is Python language used?
I am a web developer and usually use PHP, JavaScript or MySQL. I have heard lot about Python. But I have no idea where it is used and why it is used. Just like PHP, ASP, ColdFusion, .NET are used to build websites, and C, C++, Java are used to build software or desktop apps. Where does Python fit in this? What can Python do that these other languages cannot do?
[ "Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications. \nAnd by the way,\n\nWhat can you do with PHP that you can't do with ASP or JSP?\nWhat can you do with Java that you can't do with C++?\n\n", "All the languages you've mentioned are Turing Complete, so in theory there is nothing one can do and another can't. In practice of course, there are differences, especially in productivity and efficiency. Compared to C, C++ and Java, which are static typed, Python is a dynamic language and can help you write the same code in significantly fewer lines. Python has a moto \"batteries included\", which means that the standard library offers all the things needed to build a complex application. Other languages would need external libraries for this. On top of this, since Python is an old and mature language (older than Java), many external libraries (for game development and scientific calculations just to mention a few) have been evolved. So Python can be used to program desktop applications and in fact in some cases more efficiently than other traditional languages.\nPython is also a scripting language. This means that you can easily and quickly write scripts and simple tests with it.\nMore recently python is also used for web frameworks. Since there is a big code base and many python programmers, this was a logical thing to do. These web frameworks follow the practice mainly introduced by Ruby on Rails.\n", "With a few exceptions, Python is used pretty much wherever a programmer who knows Python wants to focus on solving a problem instead of struggling with implementation details. You'll find it in games, web applications, network servers, scientific computing, media tools, application scripting, etc. (There's a somewhat old list of some organizations that use it here.) People who know it well tend to love it because it strikes a very rare balance of conciseness and clarity, and (perhaps to a lesser extent) because it has a rich set of useful libraries.\nSome places where Python isn't used as much:\n\nWeb browser scripts (because browsers implement JavaScript, not Python, though there are ways around that)\nLarge GUI applications (perhaps because good GUI bindings are relatively new)\nGraphics engines (for performance reasons, but note that Python is sometimes used for the controlling logic that makes use of a graphics engine)\nSmall embedded devices (although some folks have had success with compact, stripped-down and special-purpose implementations of Python, and we're starting to see python tools for building applications on smart phones and tablets.)\n\n", "Your categorization is not correct:\nphp, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.\nOn the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).\nPython is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).\nPython can also be translated into binary code like java.\n", "Many websites uses Django or Zope/Plone web framework, these are written in Python.\nPython is used a lot for writing system administration software, usually when bash scripts (shell script) isn't up to the job, but going C/C++ is an overkill. This is also the spectrum where perl, awk, etc stands. Gentoo's emerge/portage is one example. Mercurial/HG is a distributed version control system (DVCS) written in python.\nMany desktop applications are also written in Python. The original Bittorrent was written in python.\nPython is also used as the scripting languages for GIMP, Inkscape, Blender, OpenOffice, etc. Python allows advanced users to write plugins and access advanced functionalities that cannot typically be used through a GUI.\n", "Python is used for developing sites. It's more highlevel than php.\nPython is used for linux dekstop applications. For example, the most of Ubuntu configurations utilites are pythonic.\n", "Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.\n" ]
[ 23, 17, 14, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003043085_python.txt
Q: Django QuerySet filter + order_by + limit So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1] median_score = median_exam.score But it always returns an empty list. I can get the result I want with this: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) exams = Exam.objects.filter(assessment=assessment.id).order_by('score') median_score = median_exam[median].score I would just prefer not to have to query the entire set of exams. I thought about just writing a raw MySQL query that looks something like: SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1 But if possible, I'd like to stay within Django's ORM. Mostly, it's just bothering me that I can't seem to use order_by with a filter and a limit. Any ideas? A: Your slice syntax is wrong. The value after the colon is not the count of elements to get, but the index of the end of the slice. Using 'median' on its own without a colon, as you do in your second example, would work.
Django QuerySet filter + order_by + limit
So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1] median_score = median_exam.score But it always returns an empty list. I can get the result I want with this: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) exams = Exam.objects.filter(assessment=assessment.id).order_by('score') median_score = median_exam[median].score I would just prefer not to have to query the entire set of exams. I thought about just writing a raw MySQL query that looks something like: SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1 But if possible, I'd like to stay within Django's ORM. Mostly, it's just bothering me that I can't seem to use order_by with a filter and a limit. Any ideas?
[ "Your slice syntax is wrong. The value after the colon is not the count of elements to get, but the index of the end of the slice. Using 'median' on its own without a colon, as you do in your second example, would work.\n" ]
[ 5 ]
[]
[]
[ "django", "django_orm", "django_queryset", "python" ]
stackoverflow_0003047549_django_django_orm_django_queryset_python.txt
Q: How can I update only certain fields in a Django model form? I have a model form that I use to update a model. class Turtle(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=True) class TurtleForm(forms.ModelForm): class Meta: model = Turtle Sometimes I don't need to update the entire model, but only want to update one of the fields. So when I POST the form only has information for the description. When I do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model. turtle_form = TurtleForm(request.POST, instance=object) if turtle_form.is_valid(): turtle_form.save() Is there any way to make this happen? Thanks! A: Only use specified fields: class FirstModelForm(forms.ModelForm): class Meta: model = TheModel fields = ('title',) def clean_title(self.... See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude It is common to use different ModelForms for a model in different views, when you need different features. So creating another form for the model that uses the same behaviour (say clean_<fieldname> methods etc.) use: class SecondModelForm(FirstModelForm): class Meta: model = TheModel fields = ('title', 'description') A: If you don't want to update a field, remove it from the form via the Meta exclude tuple: class Meta: exclude = ('title',)
How can I update only certain fields in a Django model form?
I have a model form that I use to update a model. class Turtle(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=True) class TurtleForm(forms.ModelForm): class Meta: model = Turtle Sometimes I don't need to update the entire model, but only want to update one of the fields. So when I POST the form only has information for the description. When I do that the model never saves because it thinks that the name is being blanked out while my intent is that the name not change and just be used from the model. turtle_form = TurtleForm(request.POST, instance=object) if turtle_form.is_valid(): turtle_form.save() Is there any way to make this happen? Thanks!
[ "Only use specified fields:\nclass FirstModelForm(forms.ModelForm):\n class Meta:\n model = TheModel\n fields = ('title',)\n def clean_title(self....\n\nSee http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#controlling-which-fields-are-used-with-fields-and-exclude\nIt is common to use different ModelForms for a model in different views, when you need different features. So creating another form for the model that uses the same behaviour (say clean_<fieldname> methods etc.) use:\nclass SecondModelForm(FirstModelForm):\n class Meta:\n model = TheModel\n fields = ('title', 'description')\n\n", "If you don't want to update a field, remove it from the form via the Meta exclude tuple:\nclass Meta:\n exclude = ('title',)\n\n" ]
[ 9, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003047700_django_python.txt
Q: Using end of word mark with unicode in regular expressions in Python The following matches in Idle, but does not match when run in a method in a module file: import re re.search('\\bשלום\\b','שלום עולם',re.UNICODE) while the following matches in both cases: import re re.search('שלום','שלום עולם',re.UNICODE) (Notice that stackoverflow erroneously switches the first and second items in the line above as this is a right to left language) How can I make the first code match inside a py file? Update: What I should have written for the first segment is that it matches in Idle, but does not match when run in eclipse console with PyDev. A: Seems to work for me when I'm using unicode strings: # -*- coding: utf-8 -*- import re match = re.search(u'\\bשלום\\b', u'שלום עולם', re.U) See it in action: http://codepad.org/xWz5cZj5
Using end of word mark with unicode in regular expressions in Python
The following matches in Idle, but does not match when run in a method in a module file: import re re.search('\\bשלום\\b','שלום עולם',re.UNICODE) while the following matches in both cases: import re re.search('שלום','שלום עולם',re.UNICODE) (Notice that stackoverflow erroneously switches the first and second items in the line above as this is a right to left language) How can I make the first code match inside a py file? Update: What I should have written for the first segment is that it matches in Idle, but does not match when run in eclipse console with PyDev.
[ "Seems to work for me when I'm using unicode strings:\n# -*- coding: utf-8 -*-\n\nimport re\nmatch = re.search(u'\\\\bשלום\\\\b', u'שלום עולם', re.U)\n\nSee it in action: http://codepad.org/xWz5cZj5\n" ]
[ 2 ]
[]
[]
[ "python", "regex", "right_to_left", "unicode" ]
stackoverflow_0003046528_python_regex_right_to_left_unicode.txt
Q: How do I check if two html-strings are equivalent with python? I need to compare two strings, containing HTML text. The test should return true if the html strings are equivalent, i.e. differ only in whitespace and comments. Is there any module that can be used for this task? A: There's this wrapper around HTMLTidy. HTMLTidy allows you to suppress comments and normalize formatting, etc., so that should do the trick.
How do I check if two html-strings are equivalent with python?
I need to compare two strings, containing HTML text. The test should return true if the html strings are equivalent, i.e. differ only in whitespace and comments. Is there any module that can be used for this task?
[ "There's this wrapper around HTMLTidy. HTMLTidy allows you to suppress comments and normalize formatting, etc., so that should do the trick.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003048297_python.txt
Q: Ubuntu One Folder Sync Filter I am trying to modify the Ubuntu One File syncing python scripts to not including things like .iso's. I have got as far as finding this file: /usr/share/pyshared/ubuntuone/u1sync/constants.py Inside is this piece of code: import re # the name of the directory u1sync uses to keep metadata about a mirror METADATA_DIR_NAME = u".ubuntuone-sync" # filenames to ignore SPECIAL_FILE_RE = re.compile(".*\\.(" "(u1)?partial|part|" "(u1)?conflict(\\.[0-9]+)?)$") How can I edit this last section (regex?) and make it ignore .iso files??? I'm fairly sure this is the place to put it! Pretty sure this is standard python action :) Any help would be appreciated. Thanks kindly. Andy A: The regex documentation for python would be the place to look that up. For isos you could probably just add a "|.*\.iso$" to the last line. A: UbuntuOne should really have a .ignore file or equally.... I want to ignore lots of stuff... .pyc, .blend1 just for start. UPDATE: it has - take a look at: https://answers.launchpad.net/ubuntuone-client/+question/114731 OBSOLETE ANSWER: To answer... .*\\. is in the beginning of the old pattern, so replacing: "(u1)?conflict(\.[0-9]+)?)$") with: "(u1)?conflict(\.[0-9]+)?|iso)$") Should do it. Listing strings after each other in Python is just concatenating them so it's all one string. A: The regex to match iso files would be ".*\\.iso$" Which is match anything ending with ".iso" I think you can add that as another line in the re.compile call but someone who knows python better than I do could confirm that. A: "You have a problem, so you think 'Hey, I'll just use a regex'. Now you have two problems" Here's a much easier solution to your problem: def shouldIignore(filename): ext = filename.split('.')[-1] # Get the extension ignorelist = ('.iso', '.pyc', '.blend1', '.bigfile') if ext in ignorelist: return True return False And here's the added bonus - it should take all of 3 minutes? to extend this to get the extensions from an ignore file. HTH
Ubuntu One Folder Sync Filter
I am trying to modify the Ubuntu One File syncing python scripts to not including things like .iso's. I have got as far as finding this file: /usr/share/pyshared/ubuntuone/u1sync/constants.py Inside is this piece of code: import re # the name of the directory u1sync uses to keep metadata about a mirror METADATA_DIR_NAME = u".ubuntuone-sync" # filenames to ignore SPECIAL_FILE_RE = re.compile(".*\\.(" "(u1)?partial|part|" "(u1)?conflict(\\.[0-9]+)?)$") How can I edit this last section (regex?) and make it ignore .iso files??? I'm fairly sure this is the place to put it! Pretty sure this is standard python action :) Any help would be appreciated. Thanks kindly. Andy
[ "The regex documentation for python would be the place to look that up.\nFor isos you could probably just add a \"|.*\\.iso$\" to the last line.\n", "UbuntuOne should really have a .ignore file or equally.... I want to ignore lots of stuff... .pyc, .blend1 just for start.\nUPDATE: it has - take a look at:\nhttps://answers.launchpad.net/ubuntuone-client/+question/114731\nOBSOLETE ANSWER:\nTo answer... .*\\\\. is in the beginning of the old pattern, so replacing:\n\"(u1)?conflict(\\.[0-9]+)?)$\")\nwith:\n\"(u1)?conflict(\\.[0-9]+)?|iso)$\")\nShould do it.\nListing strings after each other in Python is just concatenating them so it's all one string.\n", "The regex to match iso files would be\n\".*\\\\.iso$\"\n\nWhich is match anything ending with \".iso\"\nI think you can add that as another line in the re.compile call but someone who knows python better than I do could confirm that.\n", "\"You have a problem, so you think 'Hey, I'll just use a regex'. Now you have two problems\"\nHere's a much easier solution to your problem:\ndef shouldIignore(filename):\n ext = filename.split('.')[-1] # Get the extension\n ignorelist = ('.iso', '.pyc', '.blend1', '.bigfile')\n if ext in ignorelist:\n return True\n return False\n\nAnd here's the added bonus - it should take all of 3 minutes? to extend this to get the extensions from an ignore file.\nHTH\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "cloud_platform", "python", "ubuntu", "ubuntu_10.04" ]
stackoverflow_0003005602_cloud_platform_python_ubuntu_ubuntu_10.04.txt
Q: Modify Django Forms I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html. Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fields for day, month and year and constructs a python date object from that. However, a django form creates a single textbox in which the correct format (say 2010-06-15) must be entered. As another example, for large fields I need to replace <input> with <textarea>. I'd like to take advantage of Django's forms for simple validation but I need something simpler for my users. So my question is: can I intercept the rendering of one of these objects to write out the html as I like? If so, do I have to do all the writing myself or can I only do those objects I wish to re-write? Thanks in advance. A: Yes, you can. You just have to override the default widget that gets rendered for the field. Look in the docs for all the necessary information. You can also define custom widgets if the necessity arises, e.g. a date field rendered with dropdowns instead of a single text field. Google for them, there are already some pretty nifty widgets out there :)
Modify Django Forms
I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html. Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fields for day, month and year and constructs a python date object from that. However, a django form creates a single textbox in which the correct format (say 2010-06-15) must be entered. As another example, for large fields I need to replace <input> with <textarea>. I'd like to take advantage of Django's forms for simple validation but I need something simpler for my users. So my question is: can I intercept the rendering of one of these objects to write out the html as I like? If so, do I have to do all the writing myself or can I only do those objects I wish to re-write? Thanks in advance.
[ "Yes, you can.\nYou just have to override the default widget that gets rendered for the field.\nLook in the docs for all the necessary information.\nYou can also define custom widgets if the necessity arises, e.g. a date field rendered with dropdowns instead of a single text field. \nGoogle for them, there are already some pretty nifty widgets out there :)\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003048357_django_django_forms_python.txt
Q: How to force GTK window to stay at a certain width, even when widgets try to expand? How do I force a GTK window object to stay the same size, even when a table inside of it tries to expand? I've tried using gtk.SHRINK when attaching children to the table, but the TextViews within the table still keep expanding to way beyond an acceptable width and expanding the window along with it. A: You can set the size manually pyGtk window docs: http://www.pygtk.org/docs/pygtk/class-gtkwindow.html A: Text views won't expand if you pack them into a gtk.ScrolledWindow. This is not what you directly asked, but I believe should solve your problem in a better way.
How to force GTK window to stay at a certain width, even when widgets try to expand?
How do I force a GTK window object to stay the same size, even when a table inside of it tries to expand? I've tried using gtk.SHRINK when attaching children to the table, but the TextViews within the table still keep expanding to way beyond an acceptable width and expanding the window along with it.
[ "You can set the size manually\npyGtk window docs:\nhttp://www.pygtk.org/docs/pygtk/class-gtkwindow.html\n", "Text views won't expand if you pack them into a gtk.ScrolledWindow. This is not what you directly asked, but I believe should solve your problem in a better way.\n" ]
[ 5, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003047582_pygtk_python.txt
Q: Python TCP Server, writing to clients? I have a tcp server which uses the select call to multiplex reading from clients. I have a client class (MClient) which manages the decoding of incoming data packets while(1) rlist, wlist, xlist = select( input_sockets, output_sockets, [] , 1) for insock in rlist: #any clients???? if insock is server_socket: new_socket, addr = server_socket.accept() input_sockets.append(new_socket) clients[insock.fileno()] = MClient(new_socket, addr, client_id) #dict of clients else: data = insock.recv(512) if data: clients[insock.fileno()].ProcessPacket(data) else: input_sockets.remove(insock) del clients[insock.fileno()] #handle writing to sockets for outsock in wlist: ....not done yet #do some other stuff not associated with the socket I am confused as to how to handle sending data back to the client, i.e how to write to the list 'output_sockets'. I am thinking of setting a flag in my MClient object which indicates that I have data to send back to the client. I would then in my server loop check each of the clients to see if this flag was set, and then poulate the output_list with the corresponding socket. When the socket is available for write, I would then call the appropriate clients write function. This scheme does not seem very elegant, I would like to handle the writing in the main server loop. How would I accomplish this? Thanks A: Here's something I wrote a while back to learn about processing multiple connections with a single thread. It is by no means perfect but illustrates what you want to do. The client object manages the read and write streams of the connection, and makes sure the server has the client socket in the right select() lists. This implements a simple protocol where messages are terminated by newlines. The pumpXXXX() functions just block read/write the streams and manage the read/write buffers. Complete messages are processed only when newlines are found in the buffers. import socket import select class Client(object): '''This object is created for each client connection. It tracks what has been read, what has been written, and processes complete messages terminated by newlines. It responds by returning the original message wrapped in square brackets and terminated by a newline. ''' def __init__(self,who,sock,server): '''who - client address sock - client socket server - server object for this client ''' self.who = who self.readbuf = '' self.writbuf = '' self.server = server self.sock = sock def close(self): '''Removes client from server's reader/writer queues and closes the connection.''' self.sock.close() if self.sock in self.server.readers: self.server.readers.remove(self.sock) if self.sock in self.server.writers: self.server.writers.remove(self.sock) self.server.data.pop(self.sock) def pumprecv(self): '''Server calls pumprecv() when something is readable from the client socket. The data is appended to the client's read buffer.mro Complete messages (if any) are then removed from the buffer and processed.''' try: tmp = self.sock.recv(1000) except socket.error,e: print 'recv',e self.close() else: if tmp: self.readbuf += tmp # Complete messages are processed while '\n' in self.readbuf: msg,self.readbuf = self.readbuf.split('\n',1) print self.who,msg self.writbuf += '[' + msg + ']\n' # New data to send. Make sure client is in the # server's writer queue. if self.sock not in self.server.writers: self.server.writers.append(self.sock) else: self.close() def pumpsend(self): try: # send some data. tmp is #chars sent (may not be all in writbuf). tmp = self.sock.send(self.writbuf) except socket.error,e: print 'send:',e self.close() else: # Removed sent characters from writbuf. self.writbuf = self.writbuf[tmp:] # If writbuf is empty, remove socket from server's write queue. if not self.writbuf: self.server.writers.remove(self.sock) class Server(object): def __init__(self,ip='127.0.0.1',port=9999): self.ssock = socket.socket() self.ssock.bind((ip,port)) self.ssock.listen(5) self.readers = [self.ssock] self.data = {} self.writers = [] self.quit = False def pumpaccept(self): '''Called when server socket is readable to accept a connection and create a Client object.''' csock,who = self.ssock.accept() print 'Connected %s:%d' % who self.readers.append(csock) self.data[csock] = Client(who,csock,self) def serve(self): while not self.quit or self.writers: readable,writable,other = select.select(self.readers,self.writers,[],1.0) # Operate on copies of the queues since the pumpXXX() commands can modify the lists. if self.ssock in readable[:]: self.pumpaccept() readable.remove(self.ssock) for reader in readable[:]: self.data[reader].pumprecv() for writer in writable[:]: self.data[writer].pumpsend() if not readable and not writable and not other: print '.', if __name__ == '__main__': srv = Server() srv.serve() I tested this by starting the server in one console, and running the following code in other consoles to test multiple connections. Make multiple connections, alternate sends from different windows, and send partial messages to see how the server responds. >>> from socket import * >>> s=socket() >>> s.connect(('localhost',9999)) >>> s.send('one\ntwo\nthree') 13 >>> s.send('\nfour\n') 6 >>> s.recv(1024) '[one]\n[two\three]\n[four]\n' >>> s.close() Output should look something like: . . . . . . . . . . . . . . . . . . . Connected 127.0.0.1:1514 . . . . . . . . . ('127.0.0.1', 1514) one . . . . . . . ('127.0.0.1', 1514) two . . . ('127.0.0.1', 1514) three ('127.0.0.1', 1514) four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A: The implementation you describe in your first paragraph sounds like the conventional way of implementing a server using select. If you want to be able to write to the client in the "main server loop", by which I assume you mean having code that looks something like: request = socket.recv() response = process_request(request) socket.send(response) then you'll need to have a separate thread per client.
Python TCP Server, writing to clients?
I have a tcp server which uses the select call to multiplex reading from clients. I have a client class (MClient) which manages the decoding of incoming data packets while(1) rlist, wlist, xlist = select( input_sockets, output_sockets, [] , 1) for insock in rlist: #any clients???? if insock is server_socket: new_socket, addr = server_socket.accept() input_sockets.append(new_socket) clients[insock.fileno()] = MClient(new_socket, addr, client_id) #dict of clients else: data = insock.recv(512) if data: clients[insock.fileno()].ProcessPacket(data) else: input_sockets.remove(insock) del clients[insock.fileno()] #handle writing to sockets for outsock in wlist: ....not done yet #do some other stuff not associated with the socket I am confused as to how to handle sending data back to the client, i.e how to write to the list 'output_sockets'. I am thinking of setting a flag in my MClient object which indicates that I have data to send back to the client. I would then in my server loop check each of the clients to see if this flag was set, and then poulate the output_list with the corresponding socket. When the socket is available for write, I would then call the appropriate clients write function. This scheme does not seem very elegant, I would like to handle the writing in the main server loop. How would I accomplish this? Thanks
[ "Here's something I wrote a while back to learn about processing multiple connections with a single thread. It is by no means perfect but illustrates what you want to do. The client object manages the read and write streams of the connection, and makes sure the server has the client socket in the right select() lists. This implements a simple protocol where messages are terminated by newlines. The pumpXXXX() functions just block read/write the streams and manage the read/write buffers. Complete messages are processed only when newlines are found in the buffers.\nimport socket\nimport select\n\nclass Client(object):\n\n '''This object is created for each client connection. It tracks\n what has been read, what has been written, and processes complete\n messages terminated by newlines. It responds by returning the\n original message wrapped in square brackets and terminated by a\n newline. '''\n\n def __init__(self,who,sock,server):\n\n '''who - client address\n sock - client socket\n server - server object for this client\n '''\n\n self.who = who\n self.readbuf = ''\n self.writbuf = ''\n self.server = server\n self.sock = sock\n\n def close(self):\n\n '''Removes client from server's reader/writer queues and\n closes the connection.'''\n\n self.sock.close()\n if self.sock in self.server.readers:\n self.server.readers.remove(self.sock)\n if self.sock in self.server.writers:\n self.server.writers.remove(self.sock)\n self.server.data.pop(self.sock)\n\n def pumprecv(self):\n\n '''Server calls pumprecv() when something is readable from the\n client socket. The data is appended to the client's read\n buffer.mro Complete messages (if any) are then removed from\n the buffer and processed.'''\n\n try:\n tmp = self.sock.recv(1000)\n except socket.error,e:\n print 'recv',e\n self.close()\n else: \n if tmp:\n self.readbuf += tmp\n\n # Complete messages are processed\n while '\\n' in self.readbuf:\n msg,self.readbuf = self.readbuf.split('\\n',1)\n print self.who,msg\n self.writbuf += '[' + msg + ']\\n'\n # New data to send. Make sure client is in the\n # server's writer queue.\n if self.sock not in self.server.writers:\n self.server.writers.append(self.sock)\n else:\n self.close()\n\n def pumpsend(self):\n try:\n # send some data. tmp is #chars sent (may not be all in writbuf).\n tmp = self.sock.send(self.writbuf)\n except socket.error,e:\n print 'send:',e\n self.close()\n else:\n # Removed sent characters from writbuf.\n self.writbuf = self.writbuf[tmp:]\n # If writbuf is empty, remove socket from server's write queue.\n if not self.writbuf:\n self.server.writers.remove(self.sock)\n\nclass Server(object):\n def __init__(self,ip='127.0.0.1',port=9999):\n self.ssock = socket.socket()\n self.ssock.bind((ip,port))\n self.ssock.listen(5)\n self.readers = [self.ssock]\n self.data = {}\n self.writers = []\n self.quit = False\n\n def pumpaccept(self):\n\n '''Called when server socket is readable to accept a\n connection and create a Client object.'''\n\n csock,who = self.ssock.accept()\n print 'Connected %s:%d' % who\n self.readers.append(csock)\n self.data[csock] = Client(who,csock,self)\n\n def serve(self):\n while not self.quit or self.writers:\n readable,writable,other = select.select(self.readers,self.writers,[],1.0)\n # Operate on copies of the queues since the pumpXXX() commands can modify the lists.\n if self.ssock in readable[:]:\n self.pumpaccept()\n readable.remove(self.ssock)\n for reader in readable[:]:\n self.data[reader].pumprecv()\n for writer in writable[:]:\n self.data[writer].pumpsend()\n\n if not readable and not writable and not other:\n print '.',\n\nif __name__ == '__main__':\n srv = Server()\n srv.serve()\n\nI tested this by starting the server in one console, and running the following code in other consoles to test multiple connections. Make multiple connections, alternate sends from different windows, and send partial messages to see how the server responds.\n>>> from socket import *\n>>> s=socket()\n>>> s.connect(('localhost',9999))\n>>> s.send('one\\ntwo\\nthree')\n13\n>>> s.send('\\nfour\\n')\n6\n>>> s.recv(1024)\n'[one]\\n[two\\three]\\n[four]\\n'\n>>> s.close()\n\nOutput should look something like:\n. . . . . . . . . . . . . . . . . . . Connected 127.0.0.1:1514\n. . . . . . . . . ('127.0.0.1', 1514) one\n. . . . . . . ('127.0.0.1', 1514) two\n. . . ('127.0.0.1', 1514) three\n('127.0.0.1', 1514) four\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n\n", "The implementation you describe in your first paragraph sounds like the conventional way of implementing a server using select.\nIf you want to be able to write to the client in the \"main server loop\", by which I assume you mean having code that looks something like:\nrequest = socket.recv()\nresponse = process_request(request)\nsocket.send(response)\n\nthen you'll need to have a separate thread per client.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "select", "sockets" ]
stackoverflow_0003043394_python_select_sockets.txt
Q: Python 2.6 + JCC + Pylucene issue Greetings, I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code. First of all, I build JCC (windows, using cygwin) python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -> build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -> build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not. Now, I'll make pylucene make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 So, it seems JCC wasn't installed at all. Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again: make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 Has anyone else seen this and found a workaround? A: try: /cygdrive/f/Python26//python.exe setup.py build and /cygdrive/f/Python26//python.exe setup.py build setup.py install I believe you are using python from cygwin for instaling jcc and python from windows for running... A: Few checkpoints error: None mean there is an error on building, it was NOT success, so the extensions does not get build if you are using cygwin, I guess you need to use cygwin version of python, but according to this you using windows version, which is installed in F:\Python - /cygdrive/f/Python26//python.exe, I suggest you to try with mingw32, install mingw32 and try python setup.py build -c mingw32 and python setup.py install A: that just can build jcc and install, top full code. 13998bytes when import,report error. >>> import jcc Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\Python26\lib\site-packages\jcc-2.5.1-py2.6-win32.egg\jcc\__init__.py" , line 29, in <module> from _jcc import initVM ImportError: DLL load failed: 找不到指定的模块。(cant find appointed modules) >>>
Python 2.6 + JCC + Pylucene issue
Greetings, I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code. First of all, I build JCC (windows, using cygwin) python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -> build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -> build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not. Now, I'll make pylucene make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 So, it seems JCC wasn't installed at all. Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again: make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 Has anyone else seen this and found a workaround?
[ "try:\n\n/cygdrive/f/Python26//python.exe setup.py build\n\nand\n\n/cygdrive/f/Python26//python.exe setup.py build setup.py install\n\nI believe you are using python from cygwin for instaling jcc and python from windows for running...\n", "Few checkpoints\n\nerror: None mean there is an error on building, it was NOT success, so the extensions does not get build\nif you are using cygwin, I guess you need to use cygwin version of python, but according to this you using windows version, which is installed in F:\\Python - /cygdrive/f/Python26//python.exe,\nI suggest you to try with mingw32, install mingw32 and try python setup.py build -c mingw32 and python setup.py install\n\n", "that just can build jcc and install,\ntop full code.\n13998bytes\nwhen import,report error.\n>>> import jcc\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"D:\\Python26\\lib\\site-packages\\jcc-2.5.1-py2.6-win32.egg\\jcc\\__init__.py\"\n, line 29, in <module>\n from _jcc import initVM\nImportError: DLL load failed: 找不到指定的模块。(cant find appointed modules)\n>>>\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "jcc", "pylucene", "python" ]
stackoverflow_0000312444_jcc_pylucene_python.txt
Q: Understanding CGI and SQL security from the ground up This question is for learning purposes. Suppose I am writing a simple SQL admin console using CGI and Python. At http://something.com/admin, this admin console should allow me to modify a SQL database (i.e., create and modify tables, and create and modify records) using an ordinary form. In the least secure case, anybody can access http://something.com/admin and modify the database. You can password protect http://something.com/admin. But once you start using the admin console, information is still transmitted in plain text. So then you use HTTPS to secure the transmitted data. Questions: To describe to a learner, how would you incrementally add security to the least secure environment in order to make it most secure? How would you modify/augment my three (possibly erroneous) steps above? What basic tools in Python make your steps possible? Optional: Now that I understand the process, how do sophisticated libraries and frameworks inherently achieve this level of security? A: Security is not a patch job, it's a holistic approach. Incrementally adding security is not a good idea. You should integrate security in your application from the ground up. The best advice I can give you is to try to think like an attacker. Think to yourself: "If I wanted to do something I'm not supposed to be able to do, how would I do it?" If you're designing an application which uses a database, we careful not to allow SQL Injections. You should also be aware of some of the most popular web vulnerabilities if you're making a web app. A: Non-specific to Python, but any administrative features that offer that level of control over a system should be protected with both SSL and an Authentication and Authorization mechanism (login) at the very least. A: The very first concern I have is protecting against CSRF vulnerabilities. Next i would be concerned with Broken Authentication and Session Management. Most importantly in order to maintain a secure session you must use https throughout the entire life of the session. If you where to spill a password or session id or even a sql query in plain text that would be a bad thing.
Understanding CGI and SQL security from the ground up
This question is for learning purposes. Suppose I am writing a simple SQL admin console using CGI and Python. At http://something.com/admin, this admin console should allow me to modify a SQL database (i.e., create and modify tables, and create and modify records) using an ordinary form. In the least secure case, anybody can access http://something.com/admin and modify the database. You can password protect http://something.com/admin. But once you start using the admin console, information is still transmitted in plain text. So then you use HTTPS to secure the transmitted data. Questions: To describe to a learner, how would you incrementally add security to the least secure environment in order to make it most secure? How would you modify/augment my three (possibly erroneous) steps above? What basic tools in Python make your steps possible? Optional: Now that I understand the process, how do sophisticated libraries and frameworks inherently achieve this level of security?
[ "Security is not a patch job, it's a holistic approach.\nIncrementally adding security is not a good idea. You should integrate security in your application from the ground up.\nThe best advice I can give you is to try to think like an attacker. Think to yourself: \"If I wanted to do something I'm not supposed to be able to do, how would I do it?\"\nIf you're designing an application which uses a database, we careful not to allow SQL Injections. You should also be aware of some of the most popular web vulnerabilities if you're making a web app.\n", "Non-specific to Python, but any administrative features that offer that level of control over a system should be protected with both SSL and an Authentication and Authorization mechanism (login) at the very least.\n", "The very first concern I have is protecting against CSRF vulnerabilities. Next i would be concerned with Broken Authentication and Session Management. Most importantly in order to maintain a secure session you must use https throughout the entire life of the session. If you where to spill a password or session id or even a sql query in plain text that would be a bad thing. \n" ]
[ 3, 2, 2 ]
[]
[]
[ "cgi", "python", "security", "sql" ]
stackoverflow_0003048542_cgi_python_security_sql.txt
Q: Another floating point question I have read most of the posts on here regarding floating point, and I understand the basic underlying issue that using IEEE 754 (and just by the nature of storing numbers in binary) certain fractions cannot be represented. I am trying to figure out the following: If both Python and JavaScript use the IEEE 754 standard, why is it that executing the following in Python .1 + .1 Results in 0.20000000000000001 (which is to be expected) Where as in Javascript (in at least Chrome and Firefox) the answer is .2 However performing .1 + .2 In both languages results in 0.30000000000000004 In addition, executing var a = 0.3; in JavaScript and printing a results in 0.3 Where as doing a = 0.3 in Python results in 0.29999999999999999 I would like to understand the reason for this difference in behavior. In addition, many of the posts on OS link to a JavaScript port of Java's BigDecimal, but the link is dead. Does anyone have a copy? A: doing a = 0.3 in Python results in 0.29999999999999999 Not quite -- watch: >>> a = 0.3 >>> print a 0.3 >>> a 0.29999999999999999 As you see, printing a does show 0.3 -- because by default print rounds to 6 or 7 decimal digits, while typing an expression (here a is a single-variable expression) at the prompt shows the result with over twice as many digits (thus revealing floating point's intrinsic limitations). Javascript may have slightly different rounding rules about how to display numbers, and the exact details of the rounding are plenty enough to explain the differences you observe. Note, for example (on a Chrome javascript console): > (1 + .1) * 1000000000 1100000000 > (1 + .1) * 100000000000000 110000000000000.02 see? if you manage to see more digits, the anomalies (which inevitably are there) become visible too. A: and printing. They might both have the same IEEE 754 underlying representation, but that doesn't mean they're forced to print the same way. It looks like Javascript is rounding the output when the difference is small enough. With floating point numbers, the important part is how the binary data is structured, not what it shows on the screen. A: I would like to understand the reason for this difference in behavior. They're different languages. They use different underlying packages. They have different implementations. When you say "Python" -- which implementation are you talking about? C, Jython, IronPython? Did you compare each of those? The Javascript folks seem to handle repeating binary fractions differently from the way the Python folks handle repeating binary fractions. Sometimes Javascript quietly suppresses the error bits at the end. Sometimes it doesn't. That's the reason. You have the source code for both. If you want to know more, you can. Knowing the source code doesn't change much, however.
Another floating point question
I have read most of the posts on here regarding floating point, and I understand the basic underlying issue that using IEEE 754 (and just by the nature of storing numbers in binary) certain fractions cannot be represented. I am trying to figure out the following: If both Python and JavaScript use the IEEE 754 standard, why is it that executing the following in Python .1 + .1 Results in 0.20000000000000001 (which is to be expected) Where as in Javascript (in at least Chrome and Firefox) the answer is .2 However performing .1 + .2 In both languages results in 0.30000000000000004 In addition, executing var a = 0.3; in JavaScript and printing a results in 0.3 Where as doing a = 0.3 in Python results in 0.29999999999999999 I would like to understand the reason for this difference in behavior. In addition, many of the posts on OS link to a JavaScript port of Java's BigDecimal, but the link is dead. Does anyone have a copy?
[ "\ndoing a = 0.3 in Python results in\n 0.29999999999999999\n\nNot quite -- watch:\n>>> a = 0.3\n>>> print a\n0.3\n>>> a\n0.29999999999999999\n\nAs you see, printing a does show 0.3 -- because by default print rounds to 6 or 7 decimal digits, while typing an expression (here a is a single-variable expression) at the prompt shows the result with over twice as many digits (thus revealing floating point's intrinsic limitations).\nJavascript may have slightly different rounding rules about how to display numbers, and the exact details of the rounding are plenty enough to explain the differences you observe. Note, for example (on a Chrome javascript console):\n> (1 + .1) * 1000000000\n 1100000000\n> (1 + .1) * 100000000000000\n 110000000000000.02\n\nsee? if you manage to see more digits, the anomalies (which inevitably are there) become visible too.\n", "\nand printing.\n\nThey might both have the same IEEE 754 underlying representation, but that doesn't mean they're forced to print the same way. It looks like Javascript is rounding the output when the difference is small enough.\nWith floating point numbers, the important part is how the binary data is structured, not what it shows on the screen.\n", "\nI would like to understand the reason for this difference in behavior.\n\n\nThey're different languages.\nThey use different underlying packages.\nThey have different implementations. \n\nWhen you say \"Python\" -- which implementation are you talking about? C, Jython, IronPython? Did you compare each of those?\nThe Javascript folks seem to handle repeating binary fractions differently from the way the Python folks handle repeating binary fractions.\nSometimes Javascript quietly suppresses the error bits at the end. Sometimes it doesn't.\nThat's the reason.\nYou have the source code for both. If you want to know more, you can. Knowing the source code doesn't change much, however.\n" ]
[ 6, 3, 0 ]
[]
[]
[ "floating_point", "javascript", "python" ]
stackoverflow_0003048865_floating_point_javascript_python.txt
Q: How do I override file.write() in Python 3? The code below works on Python 2.6 but not on Python 3.x: old_file_write = file.write class file(): def write(self, d): if isinstance(d, types.bytes): self.buffer.write(d) else: old_file_write(d) # ... some code I cannot change or do not want to change f = open("x") f.write("...") f.write(b"...") sys.stdout.write(b"...") sys.stdout.write("...") print(b"...") print("...") The problem is that in Python 3.x the first line will generate an error: NameError: name 'file' is not defined How can I make this work in Python 3.x? In fact, two years later, I'm still looking for a solution that will work on both versions (2.5+, and 3.x). For those who are still wondering why I am looking for this, it is just in order to be able to make old code (others code, which sometimes you cannot modify) to work with newer versions of python. This is not about my code, it's about how can you write some code that plays nicely with bad code :) A: I see two problems. 1: Your file class isn't inheriting from any specific class. If I've interpreted the situation correctly, it should be a subclass of io.TextIOWrapper. 2: In both Python 2.6 and 3.x, the types module (which would need to be imported in the first place) has no element bytes. The recommended method is to just use bytes on its own. Redone snippet: import io, sys class file(io.TextIOWrapper): def write(self, d, encoding=sys.getdefaultencoding()): if isinstance(d, bytes): d = d.decode(encoding) super().write(d) old_stdout = sys.stdout # In case you want to switch back to it again sys.stdout = file(open(output_file_path, 'w').detach()) # You could also use 'a', 'a+', 'w+', 'r+', etc. Now it should do what you want it to, using sys.stdout.write to the output file that you specify. (If you don't wish to write to a file on disk but instead wish to write to the default sys.stdout buffer, using sys.stdout = file(sys.stdout.detach()) would probably work.) Do note that, since Python 3.x does not have the file class, but 2.6 does have the io module, you will have to use one of the classes of the io module. My above code is just an example, and if you want it to be more flexible you'll have to work that out on your own. That is, depending on what sort of file you're writing to/what mode you're writing to in, you'll probably want to use a different class in io. A: old_file_write = file.write You're using the class-level method of the file class. old_file_write(d) Should never have worked. I believe you're still copying and pasting incorrectly. I think you may have had old_file_write(self,d) Which might have worked. Your approach is not very good. Think about this instead. class MyKindOfFile( file ): def write(self, d): if isinstance(d, types.bytes): self.buffer.write(d) else: super( MyFindOfFile, write )(d) This will work out a LOT better for you, since it uses simple inheritance in a more typical way. A: file objects can write bytes, but you need to open the file in the correct mode fp = open('file.bin', 'wb') # open in binary mode fp.write(b"some bytes") pf.close() If you want to write strings to the disk you need to encode them first.
How do I override file.write() in Python 3?
The code below works on Python 2.6 but not on Python 3.x: old_file_write = file.write class file(): def write(self, d): if isinstance(d, types.bytes): self.buffer.write(d) else: old_file_write(d) # ... some code I cannot change or do not want to change f = open("x") f.write("...") f.write(b"...") sys.stdout.write(b"...") sys.stdout.write("...") print(b"...") print("...") The problem is that in Python 3.x the first line will generate an error: NameError: name 'file' is not defined How can I make this work in Python 3.x? In fact, two years later, I'm still looking for a solution that will work on both versions (2.5+, and 3.x). For those who are still wondering why I am looking for this, it is just in order to be able to make old code (others code, which sometimes you cannot modify) to work with newer versions of python. This is not about my code, it's about how can you write some code that plays nicely with bad code :)
[ "I see two problems.\n1: Your file class isn't inheriting from any specific class. If I've interpreted the situation correctly, it should be a subclass of io.TextIOWrapper.\n2: In both Python 2.6 and 3.x, the types module (which would need to be imported in the first place) has no element bytes. The recommended method is to just use bytes on its own.\nRedone snippet:\nimport io, sys\n\nclass file(io.TextIOWrapper):\n def write(self, d, encoding=sys.getdefaultencoding()):\n if isinstance(d, bytes):\n d = d.decode(encoding)\n super().write(d)\n\nold_stdout = sys.stdout # In case you want to switch back to it again\n\nsys.stdout = file(open(output_file_path, 'w').detach()) # You could also use 'a', 'a+', 'w+', 'r+', etc.\n\nNow it should do what you want it to, using sys.stdout.write to the output file that you specify. (If you don't wish to write to a file on disk but instead wish to write to the default sys.stdout buffer, using sys.stdout = file(sys.stdout.detach()) would probably work.)\nDo note that, since Python 3.x does not have the file class, but 2.6 does have the io module, you will have to use one of the classes of the io module. My above code is just an example, and if you want it to be more flexible you'll have to work that out on your own. That is, depending on what sort of file you're writing to/what mode you're writing to in, you'll probably want to use a different class in io.\n", "old_file_write = file.write \n\nYou're using the class-level method of the file class. \nold_file_write(d)\n\nShould never have worked. I believe you're still copying and pasting incorrectly.\nI think you may have had\nold_file_write(self,d)\n\nWhich might have worked. \nYour approach is not very good. Think about this instead.\nclass MyKindOfFile( file ):\n def write(self, d):\n if isinstance(d, types.bytes):\n self.buffer.write(d)\n else:\n super( MyFindOfFile, write )(d)\n\nThis will work out a LOT better for you, since it uses simple inheritance in a more typical way.\n", "file objects can write bytes, but you need to open the file in the correct mode\nfp = open('file.bin', 'wb') # open in binary mode\nfp.write(b\"some bytes\") \npf.close()\n\nIf you want to write strings to the disk you need to encode them first.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003046066_python_python_3.x.txt
Q: Is there an open source cross-platform push server? I'm currently in need of a (preferably open-source) free push server, that supports both linux and windows. I need something similar to the Ajax Push Engine, but that project unfortunatelly does not work on windows (I could use a virtual machine, but that's not what I'm looking for). I need to be able to push information to/from a python daemon, from a php script, to/from javascript and to a Blackberry application (built with java). Is there any tool that could help me with that? I've also looked into the Orbited project but frankly it lacks a lot of documentation and it's been very complicated to understand it. I'm not sure if it could work for me since it isn't actually a push server, but rather a proxy for it's built in MorbidQ server (or am I wrong?). Would a technology like Advanced Message Queing Protocol work for a project like this? Something like RabbitMQ or ActiveMQ? Thank you very much for the help. A: I like ActiveMQ very much, especially together with Camel. For push web technology, cometd comes first to mind.
Is there an open source cross-platform push server?
I'm currently in need of a (preferably open-source) free push server, that supports both linux and windows. I need something similar to the Ajax Push Engine, but that project unfortunatelly does not work on windows (I could use a virtual machine, but that's not what I'm looking for). I need to be able to push information to/from a python daemon, from a php script, to/from javascript and to a Blackberry application (built with java). Is there any tool that could help me with that? I've also looked into the Orbited project but frankly it lacks a lot of documentation and it's been very complicated to understand it. I'm not sure if it could work for me since it isn't actually a push server, but rather a proxy for it's built in MorbidQ server (or am I wrong?). Would a technology like Advanced Message Queing Protocol work for a project like this? Something like RabbitMQ or ActiveMQ? Thank you very much for the help.
[ "I like ActiveMQ very much, especially together with Camel. \nFor push web technology, cometd comes first to mind.\n" ]
[ 2 ]
[]
[]
[ "comet", "php", "push", "python", "server_push" ]
stackoverflow_0003048941_comet_php_push_python_server_push.txt
Q: SQLAlchemy: How to group by two fields and filter by date So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month. table.id table.datestamp table.field1 table.field2 There should be no duplicate record with the same field1 + 2 compound value in the last month. The steps in my head are: Group by the two fields Look back over the last month's data to make sure this unique grouping doesn't occur. I've got this far, but I don't think this works: result = session.query(table).group_by(\ table.field1, table.field2, func.month(table.timestamp)) But I'm unsure how to do this in sqlalchemy. Could someone advise me? Thanks very much! A: Following should point you in the right direction, also see inline comments: qry = (session.query( table.c.field1, table.c.field2, # #strftime* for year-month works on sqlite; # @todo: find proper function for mysql (as in the question) # Also it is not clear if only MONTH part is enough, so that # May-2001 and May-2009 can be joined, or YEAR-MONTH must be used func.strftime('%Y-%m', table.c.datestamp), func.count(), ) # optionally check only last 2 month data (could have partial months) .filter(table.c.datestamp < datetime.date.today() - datetime.timedelta(60)) .group_by( table.c.field1, table.c.field2, func.strftime('%Y-%m', table.c.datestamp), ) # comment this line out to see all the groups .having(func.count()>1) )
SQLAlchemy: How to group by two fields and filter by date
So I have a table with a datestamp and two fields that I want to make sure that they are unique in the last month. table.id table.datestamp table.field1 table.field2 There should be no duplicate record with the same field1 + 2 compound value in the last month. The steps in my head are: Group by the two fields Look back over the last month's data to make sure this unique grouping doesn't occur. I've got this far, but I don't think this works: result = session.query(table).group_by(\ table.field1, table.field2, func.month(table.timestamp)) But I'm unsure how to do this in sqlalchemy. Could someone advise me? Thanks very much!
[ "Following should point you in the right direction, also see inline comments:\nqry = (session.query(\n table.c.field1,\n table.c.field2, \n\n # #strftime* for year-month works on sqlite; \n \n # @todo: find proper function for mysql (as in the question)\n # Also it is not clear if only MONTH part is enough, so that\n # May-2001 and May-2009 can be joined, or YEAR-MONTH must be used\n func.strftime('%Y-%m', table.c.datestamp),\n func.count(),\n )\n # optionally check only last 2 month data (could have partial months)\n .filter(table.c.datestamp < datetime.date.today() - datetime.timedelta(60))\n .group_by(\n table.c.field1,\n table.c.field2,\n func.strftime('%Y-%m', table.c.datestamp),\n )\n # comment this line out to see all the groups\n .having(func.count()>1)\n )\n\n\n" ]
[ 26 ]
[]
[]
[ "group_by", "mysql", "python", "sql", "sqlalchemy" ]
stackoverflow_0003044455_group_by_mysql_python_sql_sqlalchemy.txt
Q: Specifics of List Membership How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does: def main(): obj = fancy_obj(arg='C:\\') needle = (50, obj) haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle] print (1, fancy_obj(arg='C:\\'),) in haystack print needle in haystack if __name__ == '__main__': main() Which yields: False True This tells me that Python is probably checking the object references, which makes sense. Is there something more definitive I can look at? A: From (An Unofficial) Python Reference Wiki: For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true. So in your example, if the fancy_obj class stored the value of arg in an instance variable and were to implement an __eq__ method that returned True if the two fancy_objs being compared had the same value for arg then (1, fancy_obj(arg='C:\\'),) in haystack would be True. The relevant page of the Standard Library reference is: Built-in Types, specifically 5.6 Sequence Types A: Here is code from the Python SVN: static int list_contains(PyListObject *a, PyObject *el) { Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), Py_EQ); return cmp; } so basically it uses the == with the object and each object in the list. A: Python is using the (equivalent of) the == operator. If the fancy_obj class does not define __eq__ (or the crufty old __cmp__, still supported for backwards compatibility) then equality, ==, "falls back" to identity, is, and that appears to be what's happening here. The relevant docs are here, and I quote: x in s True if an item of s is equal to x, else False and "equal to" means == is true.
Specifics of List Membership
How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does: def main(): obj = fancy_obj(arg='C:\\') needle = (50, obj) haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle] print (1, fancy_obj(arg='C:\\'),) in haystack print needle in haystack if __name__ == '__main__': main() Which yields: False True This tells me that Python is probably checking the object references, which makes sense. Is there something more definitive I can look at?
[ "From (An Unofficial) Python Reference Wiki:\nFor the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.\nSo in your example, if the fancy_obj class stored the value of arg in an instance variable and were to implement an __eq__ method that returned True if the two fancy_objs being compared had the same value for arg then (1, fancy_obj(arg='C:\\\\'),) in haystack would be True. \nThe relevant page of the Standard Library reference is: Built-in Types, specifically 5.6 Sequence Types\n", "Here is code from the Python SVN:\nstatic int\nlist_contains(PyListObject *a, PyObject *el)\n{\n Py_ssize_t i;\n int cmp;\n\n for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)\n cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),\n Py_EQ);\n return cmp;\n}\n\nso basically it uses the == with the object and each object in the list.\n", "Python is using the (equivalent of) the == operator. If the fancy_obj class does not define __eq__ (or the crufty old __cmp__, still supported for backwards compatibility) then equality, ==, \"falls back\" to identity, is, and that appears to be what's happening here.\nThe relevant docs are here, and I quote:\nx in s True if an item of s is equal to x, else False\nand \"equal to\" means == is true.\n" ]
[ 4, 4, 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003049651_list_python.txt
Q: Convert between python array and .NET Array I have a python method that returns a Python byte array.array('c'). Now, I want to copy this array using System.Runtime.InteropServices.Marshal.Copy. This method however expects a .NET array. import array from System.Runtime.InteropServices import Marshal bytes = array.array('c') bytes.append('a') bytes.append('b') bytes.append('c') Marshal.Copy(bytes, dest, 0, 3) Is there a way to make this work without copying the data? If not, how do I convert the data in the Python array to the .NET array? A: To convert a python array to a .NET Array: import array from System import Array, Char x = array.array('c', 'abc') y = Array[Char](x) Here is some information on creating typed Arrays in IronPython: http://www.ironpython.info/index.php?title=Typed_Arrays_in_IronPython
Convert between python array and .NET Array
I have a python method that returns a Python byte array.array('c'). Now, I want to copy this array using System.Runtime.InteropServices.Marshal.Copy. This method however expects a .NET array. import array from System.Runtime.InteropServices import Marshal bytes = array.array('c') bytes.append('a') bytes.append('b') bytes.append('c') Marshal.Copy(bytes, dest, 0, 3) Is there a way to make this work without copying the data? If not, how do I convert the data in the Python array to the .NET array?
[ "To convert a python array to a .NET Array:\nimport array\nfrom System import Array, Char\n\nx = array.array('c', 'abc')\n\ny = Array[Char](x)\n\nHere is some information on creating typed Arrays in IronPython:\nhttp://www.ironpython.info/index.php?title=Typed_Arrays_in_IronPython\n" ]
[ 7 ]
[]
[]
[ ".net", "arrays", "ironpython", "marshalling", "python" ]
stackoverflow_0003020654_.net_arrays_ironpython_marshalling_python.txt
Q: How can I prevent a mod_wsgi django application from repeated reloads? My mod_wsgi django application seems to keep getting reloaded for the first several requests that the client makes. This is killing my performance After enough requests it seems to settle down, and the application no longer seems to be getting reloaded. Any thoughts on why this is happening and how I can prevent it? (I have the following in httpd.conf:MaxRequestsPerChild 0, so that isn't it) A: This is likely because you are using embedded mode of mod_wsgi and Apache on a UNIX system, possibly even with Apache prefork MPM which makes it all worse. In short, in that configuration Apache it is a multi process web server. Combine that with fact that default is to lazily load application on first request, you will see a delay on initial request against each Apache server child process as application loads. Even for Django framework this shouldn't be excessive and would question what your specific application is doing on startup to cause a long delay or large load spike. To understand the issues, make sure you read: http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading Then change to use daemon mode of mod_wsgi instead as documented on mod_wsgi wiki pages. In particular start with: http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide If it is truly warranted that you need to run more than one daemon process and not just being hopeful about what sort of load your application is going to get, and load time is still a concern, then you can configure mod_wsgi using WSGIImportScript and other methods to preload your WSGI application at process start before any requests come in. For Django though, make sure you use WSGI script file described in: http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html and not the one that Django documentation describes as it lazily loads and you can still see problem as well as differences in behaviour between WSGI hosting mechanisms and built in development server.
How can I prevent a mod_wsgi django application from repeated reloads?
My mod_wsgi django application seems to keep getting reloaded for the first several requests that the client makes. This is killing my performance After enough requests it seems to settle down, and the application no longer seems to be getting reloaded. Any thoughts on why this is happening and how I can prevent it? (I have the following in httpd.conf:MaxRequestsPerChild 0, so that isn't it)
[ "This is likely because you are using embedded mode of mod_wsgi and Apache on a UNIX system, possibly even with Apache prefork MPM which makes it all worse. In short, in that configuration Apache it is a multi process web server. Combine that with fact that default is to lazily load application on first request, you will see a delay on initial request against each Apache server child process as application loads.\nEven for Django framework this shouldn't be excessive and would question what your specific application is doing on startup to cause a long delay or large load spike.\nTo understand the issues, make sure you read:\nhttp://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html\nhttp://code.google.com/p/modwsgi/wiki/ProcessesAndThreading\nThen change to use daemon mode of mod_wsgi instead as documented on mod_wsgi wiki pages. In particular start with:\nhttp://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide\nIf it is truly warranted that you need to run more than one daemon process and not just being hopeful about what sort of load your application is going to get, and load time is still a concern, then you can configure mod_wsgi using WSGIImportScript and other methods to preload your WSGI application at process start before any requests come in. For Django though, make sure you use WSGI script file described in:\nhttp://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html\nand not the one that Django documentation describes as it lazily loads and you can still see problem as well as differences in behaviour between WSGI hosting mechanisms and built in development server.\n" ]
[ 5 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0003049646_apache_django_mod_wsgi_python.txt
Q: Django ORM and PostgreSQL connection limits I'm running a Django project on Postgresql 8.1.21 (using Django 1.1.1, Python2.5, psycopg2, Apache2 with mod_wsgi 3.2). We've recently encountered this lovely error: OperationalError: FATAL: connection limit exceeded for non-superusers I'm not the first person to run up against this. There's a lot of discussion about this error, specifically with psycopg, but much of it centers on older versions of Django and/or offer solutions involving edits to code in Django itself. I've yet to find a succinct explanation of how to solve the problem of the Django ORM (or psycopg, whichever is really responsible, in this case) leaving open Postgre connections. Will simply adding connection.close() at the end of every view solve this problem? Better yet, has anyone conclusively solved this problem and kicked this error's ass? Edit: we later upped Postgresql's limit to 500 connections; this prevented the error from cropping up, but replaced it with excessive memory usage. A: This could be caused by other things. For example, configuring Apache/mod_wsgi in a way that theoretically it could accept more concurrent requests than what the database itself may be able to accept at the same time. Have you reviewed your Apache/mod_wsgi configuration and compared limit on maximum clients to that of PostgreSQL to make sure something like that hasn't been done. Obviously this presumes though that you have managed to reach that limit in Apache some how and also depends on how any database connection pooling is set up.
Django ORM and PostgreSQL connection limits
I'm running a Django project on Postgresql 8.1.21 (using Django 1.1.1, Python2.5, psycopg2, Apache2 with mod_wsgi 3.2). We've recently encountered this lovely error: OperationalError: FATAL: connection limit exceeded for non-superusers I'm not the first person to run up against this. There's a lot of discussion about this error, specifically with psycopg, but much of it centers on older versions of Django and/or offer solutions involving edits to code in Django itself. I've yet to find a succinct explanation of how to solve the problem of the Django ORM (or psycopg, whichever is really responsible, in this case) leaving open Postgre connections. Will simply adding connection.close() at the end of every view solve this problem? Better yet, has anyone conclusively solved this problem and kicked this error's ass? Edit: we later upped Postgresql's limit to 500 connections; this prevented the error from cropping up, but replaced it with excessive memory usage.
[ "This could be caused by other things. For example, configuring Apache/mod_wsgi in a way that theoretically it could accept more concurrent requests than what the database itself may be able to accept at the same time. Have you reviewed your Apache/mod_wsgi configuration and compared limit on maximum clients to that of PostgreSQL to make sure something like that hasn't been done. Obviously this presumes though that you have managed to reach that limit in Apache some how and also depends on how any database connection pooling is set up.\n" ]
[ 1 ]
[]
[]
[ "database", "django", "django_orm", "postgresql", "python" ]
stackoverflow_0003049625_database_django_django_orm_postgresql_python.txt
Q: Which is faster? is opening a large file once reading it completely once to list faster (or) opening smaller files whose total sum of size is equal to large file and loading smaller file into list manupalating one by one faster? which is faster?? is the difference is time large enough to impact my program?? total time difference of lesser then of 30 sec is negligible for me A: It depends if your data fit in your available memory. If you need to resort to paging, or virtual memory, then opening a single giant file might become slower than opening more smaller files. This will be even more true if the computation you need to make creates intermediate variables that won't fit in the physical RAM either. So, as long as the file is not that big, one opening will be faster, but if this is not true, then many opening may be faster. At last, note that if you can do many opening, you might be able to do them in parallel and process various parts in different processes, which might make things faster again. A: Obviously one open and close is going to be faster than n opens and closes if you are reading the same amount of data. Plus, when reading a single file the I/O classes you use can take advantage of things like buffering, etc, which makes it even faster. A: If you are reading the file sequentially from start until end, one open/close is faster than multiple open/close operations. However keep in mind that if you need to do a lot of seeking in your 1 big file, then maybe storing separate files won't be slower in that case. Also keep in mind that no matter which approach you are using, you shouldn't read the entire file in at once. Do it in chunks. A: Working with a single file is almost certainly going to be faster: you have to read the same amount of data in both cases, but when working with multiple files, you have that much more housekeeping operations slowing you down. Additionally, you can read data from a single file at the maximum speed the disk can handle, using the disk buffer to the maximum etc., whereas with multiple files, the disk head does a lot more dancing jumping from file to file. A: 30sec time difference? Define large. Everything that fits into an average's computer RAM would probably not take much more time than 30sec in total. A: Why do you think you need to read the file(s) into a list? If you can open several small files and process each independently, then surely that means: (a) that you don't need to read into a list, you can process any file (including 1 large file) a line at a time (avoiding running-out-of-real-memory problems) or (b) what you need to do is more complicated than you have told us.
Which is faster?
is opening a large file once reading it completely once to list faster (or) opening smaller files whose total sum of size is equal to large file and loading smaller file into list manupalating one by one faster? which is faster?? is the difference is time large enough to impact my program?? total time difference of lesser then of 30 sec is negligible for me
[ "It depends if your data fit in your available memory. If you need to resort to paging, or virtual memory, then opening a single giant file might become slower than opening more smaller files. This will be even more true if the computation you need to make creates intermediate variables that won't fit in the physical RAM either.\nSo, as long as the file is not that big, one opening will be faster, but if this is not true, then many opening may be faster.\nAt last, note that if you can do many opening, you might be able to do them in parallel and process various parts in different processes, which might make things faster again.\n", "Obviously one open and close is going to be faster than n opens and closes if you are reading the same amount of data. Plus, when reading a single file the I/O classes you use can take advantage of things like buffering, etc, which makes it even faster.\n", "If you are reading the file sequentially from start until end, one open/close is faster than multiple open/close operations. \nHowever keep in mind that if you need to do a lot of seeking in your 1 big file, then maybe storing separate files won't be slower in that case. \nAlso keep in mind that no matter which approach you are using, you shouldn't read the entire file in at once. Do it in chunks.\n", "Working with a single file is almost certainly going to be faster: you have to read the same amount of data in both cases, but when working with multiple files, you have that much more housekeeping operations slowing you down.\nAdditionally, you can read data from a single file at the maximum speed the disk can handle, using the disk buffer to the maximum etc., whereas with multiple files, the disk head does a lot more dancing jumping from file to file.\n", "30sec time difference? Define large. Everything that fits into an average's computer RAM would probably not take much more time than 30sec in total.\n", "Why do you think you need to read the file(s) into a list?\nIf you can open several small files and process each independently, then surely that means:\n(a) that you don't need to read into a list, you can process any file (including 1 large file) a line at a time (avoiding running-out-of-real-memory problems)\nor\n(b) what you need to do is more complicated than you have told us.\n" ]
[ 6, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003047799_python.txt
Q: Access Denied when using popen - Python I'm using popen in order to send a few commands within a Django app. Problem is that I'm getting [Error 5] Access Denied, apparently I have no access to cmd.exe, which popen seems to use. WindowsError at /test/cmd/ [Error 5] Access is denied: 'C:\WINDOWS\system32\cmd.exe /c dir' I reckon this is because the app sits behind a web server which has limited privileges. Is there anything we can do about it? Help would be awesome! A: Why you have the problem: What you forgot to mention in your question is that you are trying to run it under IIS with ISAPI > ISAPI_WSGI (or FastCGI on IIS 7/6 with flup as FastCGI wrapper for WSGI). It's truly an execute permission issue on c:\windows\system32\cmd.exe I had exactly same problem on IIS 6. Played with pool settings, thinking that setting the pool user to "Local System" or something similar would fix it. Regardless of what user I set the pool to, I would always get Access Denied. I foolishly assumed there is something wrong with cPython pipes, cause running commands under IronPython on the same machine worked. Here is how you fix it: A. Relax user permissions on either IIS service or on c:\windows\system32\cmd.exe (Relaxing permissions on application pool, with tight permissions on IIS process did not help me. My guess is that ISAPI > ISAPI_WSGI runs with permissions limited to those of IIS process.) User running IIS (Web Publishing) service must be added directly, or be in at least one group that has read, execute permissions on c:\windows\system32\cmd.exe Things I did not try: I wonder if instead of changing user permissions on IIS service, changing the user behind "Anonymous" would work. B. If you are serious about making it work on Windows, contemplate ditching cPython for IronPython + NWSGI (look for it on CodePlex) I use NWSGI for simple WSGI apps and CAN run subprocesses with a subprocess.py specifically written for IronPython. (it's here: http://bitbucket.org/jdhardy/code/src/126ce1f8fddd/subprocess.py Check out other repos by same jdhardy. He has some patches specifically to make Django work on .Net, IronPython.)
Access Denied when using popen - Python
I'm using popen in order to send a few commands within a Django app. Problem is that I'm getting [Error 5] Access Denied, apparently I have no access to cmd.exe, which popen seems to use. WindowsError at /test/cmd/ [Error 5] Access is denied: 'C:\WINDOWS\system32\cmd.exe /c dir' I reckon this is because the app sits behind a web server which has limited privileges. Is there anything we can do about it? Help would be awesome!
[ "Why you have the problem:\nWhat you forgot to mention in your question is that you are trying to run it under IIS with ISAPI > ISAPI_WSGI (or FastCGI on IIS 7/6 with flup as FastCGI wrapper for WSGI). \nIt's truly an execute permission issue on c:\\windows\\system32\\cmd.exe \nI had exactly same problem on IIS 6. Played with pool settings, thinking that setting the pool user to \"Local System\" or something similar would fix it. Regardless of what user I set the pool to, I would always get Access Denied. I foolishly assumed there is something wrong with cPython pipes, cause running commands under IronPython on the same machine worked.\nHere is how you fix it:\nA.\nRelax user permissions on either IIS service or on c:\\windows\\system32\\cmd.exe\n(Relaxing permissions on application pool, with tight permissions on IIS process did not help me. My guess is that ISAPI > ISAPI_WSGI runs with permissions limited to those of IIS process.)\nUser running IIS (Web Publishing) service must be added directly, or be in at least one group that has read, execute permissions on c:\\windows\\system32\\cmd.exe\nThings I did not try: I wonder if instead of changing user permissions on IIS service, changing the user behind \"Anonymous\" would work.\nB.\nIf you are serious about making it work on Windows, contemplate ditching cPython for IronPython + NWSGI (look for it on CodePlex) I use NWSGI for simple WSGI apps and CAN run subprocesses with a subprocess.py specifically written for IronPython. (it's here: http://bitbucket.org/jdhardy/code/src/126ce1f8fddd/subprocess.py Check out other repos by same jdhardy. He has some patches specifically to make Django work on .Net, IronPython.)\n" ]
[ 4 ]
[]
[]
[ "cmd", "django", "popen", "python", "windows" ]
stackoverflow_0003049199_cmd_django_popen_python_windows.txt
Q: Hot python input loop I'd like to have something similar to the following pseudo code: while input is not None and timer < 5: input = getChar() timer = time.time() - start if timer >= 5: print "took too long" else: print input Anyway to do this without threading? I would like an input method that returns whatever has been entered since the last time it was called, or None (null) if nothing was entered. A: On *nix you want select with sys.stdin. On Windows you want msvcrt.kbhit() and msvcrt.getch().
Hot python input loop
I'd like to have something similar to the following pseudo code: while input is not None and timer < 5: input = getChar() timer = time.time() - start if timer >= 5: print "took too long" else: print input Anyway to do this without threading? I would like an input method that returns whatever has been entered since the last time it was called, or None (null) if nothing was entered.
[ "On *nix you want select with sys.stdin. On Windows you want msvcrt.kbhit() and msvcrt.getch().\n" ]
[ 4 ]
[]
[]
[ "input", "loops", "python", "timer" ]
stackoverflow_0003050133_input_loops_python_timer.txt
Q: Restarting IIS6 - Python I'm serving a Django app behind IIS 6. I'm wondering if I can restart IIS 6 within Python/Django and what one of the best ways to do would be. Help would be great! A: Besides what's already suggested, you can also use WMI via either the Win32_Service or the IIsWebService class, which inherits from it. There is a Python WMI wrapper available, which is based on pywin32. UPDATE: A quick test of the following worked for me. import wmi c = wmi.WMI() for service in c.Win32_Service(Name="W3SVC"): result, = service.StopService() I didn't test the next piece of code, but something like this should also work: for service in c.IIsWebService(): result, = service.StopService() You can see the documentation for the return values from the StopService and StartService methods. A: The following post shows how to control Windows services from Python: http://fuzzytolerance.info/code/using-python-to-manage-windows-services/ You should be able that to restart the IIS web publishing service (known as 'w3svc') A: I think that you can execute an iisreset via a commandline. I've never tried that with Django but it should work and be quite simple to implement.
Restarting IIS6 - Python
I'm serving a Django app behind IIS 6. I'm wondering if I can restart IIS 6 within Python/Django and what one of the best ways to do would be. Help would be great!
[ "Besides what's already suggested, you can also use WMI via either the Win32_Service or the IIsWebService class, which inherits from it. There is a Python WMI wrapper available, which is based on pywin32.\nUPDATE: A quick test of the following worked for me.\nimport wmi\n\nc = wmi.WMI()\n\nfor service in c.Win32_Service(Name=\"W3SVC\"):\n result, = service.StopService()\n\nI didn't test the next piece of code, but something like this should also work:\nfor service in c.IIsWebService():\n result, = service.StopService()\n\nYou can see the documentation for the return values from the StopService and StartService methods.\n", "The following post shows how to control Windows services from Python: http://fuzzytolerance.info/code/using-python-to-manage-windows-services/\nYou should be able that to restart the IIS web publishing service (known as 'w3svc')\n", "I think that you can execute an iisreset via a commandline. I've never tried that with Django but it should work and be quite simple to implement.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "iis", "iis_6", "python", "windows" ]
stackoverflow_0003036157_django_iis_iis_6_python_windows.txt
Q: Updating a module level shared dictionary A module level dictionary 'd' and is accessed by different threads/requests in a django web application. I need to update 'd' every minute with a new data and the process takes about 5 seconds. What could be best solution where I want the users to get either the old value or the new value of d and nothing in between. I can think of a solution where a temp dictionary is constructed with a new data and assigned to 'd' but not sure how this works! Appreciate your ideas. Thanks A: Probably best -- at module level: import threading dlock = threading.Lock() d = {} and every access to d (not just modifications!) is within a with block: with dlock: found = k in d and the like (if you're on Python 2.5, you'll also need to have from __future__ import with_statement at the top of your module). This protects d with the lock, so changes are serialized. The reason the guard is also needed around non-modifying access to d is that you might otherwise get problems even in "read-like" operations (if k in d:, d.get(k), etc) if the dict gets "changed from right under the operation smack in the middle of it". Alternative architectures can be based on wrapping the dictionary (either to protect all of its needed methods with the lock, or to delegate a special purpose thread to perform all the dictionary operations and communicate with all other threads via Queue.Queue instances), but I think that in this particular case the simple, no-frills solution works for the best.
Updating a module level shared dictionary
A module level dictionary 'd' and is accessed by different threads/requests in a django web application. I need to update 'd' every minute with a new data and the process takes about 5 seconds. What could be best solution where I want the users to get either the old value or the new value of d and nothing in between. I can think of a solution where a temp dictionary is constructed with a new data and assigned to 'd' but not sure how this works! Appreciate your ideas. Thanks
[ "Probably best -- at module level:\nimport threading\ndlock = threading.Lock()\nd = {}\n\nand every access to d (not just modifications!) is within a with block:\nwith dlock:\n found = k in d\n\nand the like (if you're on Python 2.5, you'll also need to have from __future__ import with_statement at the top of your module).\nThis protects d with the lock, so changes are serialized. The reason the guard is also needed around non-modifying access to d is that you might otherwise get problems even in \"read-like\" operations (if k in d:, d.get(k), etc) if the dict gets \"changed from right under the operation smack in the middle of it\".\nAlternative architectures can be based on wrapping the dictionary (either to protect all of its needed methods with the lock, or to delegate a special purpose thread to perform all the dictionary operations and communicate with all other threads via Queue.Queue instances), but I think that in this particular case the simple, no-frills solution works for the best.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003050109_python.txt
Q: Google finance quotes search box Trying to implement a web service which should have exactly the same function as http://www.google.com/finance the search quotes box when user type the stock name or company name, the right stock name is suggested while typing. my service will using historical information from google finance, so get proper quote name from google is a must! anyone knows where i could find this quote list through google finance api? better with python. or anyone can suggest some ideas please? many thanks A: The Google Finance API is documented here. To access it from Python, use the gdata python client.
Google finance quotes search box
Trying to implement a web service which should have exactly the same function as http://www.google.com/finance the search quotes box when user type the stock name or company name, the right stock name is suggested while typing. my service will using historical information from google finance, so get proper quote name from google is a must! anyone knows where i could find this quote list through google finance api? better with python. or anyone can suggest some ideas please? many thanks
[ "The Google Finance API is documented here.\nTo access it from Python, use the gdata python client.\n" ]
[ 0 ]
[]
[]
[ "google_finance_api", "python" ]
stackoverflow_0003049819_google_finance_api_python.txt
Q: Parsing email with Python I'm writing a Python script to process emails returned from Procmail. As suggested in this question, I'm using the following Procmail config: :0: |$HOME/process_mail.py My process_mail.py script is receiving an email via stdin like this: From hostname Tue Jun 15 21:43:30 2010 Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400 Received: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400 Received: by fxm19 with SMTP id 19so170709fxm.3 for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) MIME-Version: 1.0 Received: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Received: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Date: Tue, 15 Jun 2010 20:47:33 -0500 Message-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com> Subject: TEST 12 From: Full Name <username@sender.com> To: username@domain.com Content-Type: text/plain; charset=ISO-8859-1 ONE TWO THREE I'm trying to parse the message in this way: >>> import email >>> msg = email.message_from_string(full_message) I want to get message fields like 'From', 'To' and 'Subject'. However, the message object does not contain any of these fields. What am I doing wrong? A: You must ensure that the lines are not accidentally broken (as they are above, though it's hard to say if that was a copy-paste problem) -- with an intact message such as: Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400 Received: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400 Received: by fxm19 with SMTP id 19so170709fxm.3 for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) MIME-Version: 1.0 Received: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Received: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Date: Tue, 15 Jun 2010 20:47:33 -0500 Message-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com> Subject: TEST 12 From: Full Name <username@sender.com> To: username@domain.com Content-Type: text/plain; charset=ISO-8859-1 ONE TWO THREE then msg = email.message_from_string(msgtxt) print msg['Subject'] prints TEST 12 as desired. A: It looks like you have linefeeds without spaces prepended to the additional lines, which according to RFC 2822 §2.3.2 is illegal: Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field: Subject: This is a test can be represented as: Subject: This is a test It should look something like this: From hostname Tue Jun 15 21:43:30 2010 Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400 Received: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400 Received: by fxm19 with SMTP id 19so170709fxm.3 for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) MIME-Version: 1.0 Received: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Received: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Date: Tue, 15 Jun 2010 20:47:33 -0500 Message-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com> Subject: TEST 12 From: Full Name <username@sender.com> To: username@domain.com Content-Type: text/plain; charset=ISO-8859-1 ONE TWO THREE A: I answer to myself. I found a bug in the code that builds the messages. It's appending linebreaks between some lines, preventing the parser from working properly.
Parsing email with Python
I'm writing a Python script to process emails returned from Procmail. As suggested in this question, I'm using the following Procmail config: :0: |$HOME/process_mail.py My process_mail.py script is receiving an email via stdin like this: From hostname Tue Jun 15 21:43:30 2010 Received: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400 Received: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400 Received: by fxm19 with SMTP id 19so170709fxm.3 for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) MIME-Version: 1.0 Received: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Received: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT) Date: Tue, 15 Jun 2010 20:47:33 -0500 Message-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com> Subject: TEST 12 From: Full Name <username@sender.com> To: username@domain.com Content-Type: text/plain; charset=ISO-8859-1 ONE TWO THREE I'm trying to parse the message in this way: >>> import email >>> msg = email.message_from_string(full_message) I want to get message fields like 'From', 'To' and 'Subject'. However, the message object does not contain any of these fields. What am I doing wrong?
[ "You must ensure that the lines are not accidentally broken (as they are above, though it's hard to say if that was a copy-paste problem) -- with an intact message such as:\nReceived: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400\nReceived: from mail-fx0-f44.google.com (209.85.161.44) by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400\nReceived: by fxm19 with SMTP id 19so170709fxm.3 for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\nMIME-Version: 1.0\nReceived: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\nReceived: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\nDate: Tue, 15 Jun 2010 20:47:33 -0500\nMessage-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com>\nSubject: TEST 12\nFrom: Full Name <username@sender.com>\nTo: username@domain.com\nContent-Type: text/plain; charset=ISO-8859-1\n\nONE\nTWO\nTHREE\n\nthen\nmsg = email.message_from_string(msgtxt)\nprint msg['Subject']\n\nprints TEST 12 as desired.\n", "It looks like you have linefeeds without spaces prepended to the additional lines, which according to RFC 2822 §2.3.2 is illegal:\n\nEach header field is logically a single line of characters comprising\nthe field name, the colon, and the field body. For convenience\nhowever, and to deal with the 998/78 character limitations per line,\nthe field body portion of a header field can be split into a multiple\nline representation; this is called \"folding\". The general rule is\nthat wherever this standard allows for folding white space (not\nsimply WSP characters), a CRLF may be inserted before any WSP. For\nexample, the header field:\n Subject: This is a test\n\ncan be represented as:\n Subject: This\n is a test\n\n\nIt should look something like this:\nFrom hostname Tue Jun 15 21:43:30 2010\nReceived: (qmail 8580 invoked from network); 15 Jun 2010 21:43:22 -0400\nReceived: from mail-fx0-f44.google.com (209.85.161.44)\n by ip-73-187-35-131.ip.secureserver.net with SMTP; 15 Jun 2010 21:43:22 -0400\nReceived: by fxm19 with SMTP id 19so170709fxm.3\n for <username@domain.com>; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\nMIME-Version: 1.0\nReceived: by 10.103.84.1 with SMTP id m1mr2774225mul.26.1276652853684; Tue, 15\n Jun 2010 18:47:33 -0700 (PDT)\nReceived: by 10.123.143.4 with HTTP; Tue, 15 Jun 2010 18:47:33 -0700 (PDT)\nDate: Tue, 15 Jun 2010 20:47:33 -0500\nMessage-ID: <AANLkTikFsIjJ3KYW1HJWcAqQlGXNiXE2YMzrj39I0tdB@mail.gmail.com>\nSubject: TEST 12\nFrom: Full Name <username@sender.com>\nTo: username@domain.com\nContent-Type: text/plain; charset=ISO-8859-1\n\nONE\nTWO\nTHREE\n\n", "I answer to myself.\nI found a bug in the code that builds the messages. It's appending linebreaks between some lines, preventing the parser from working properly.\n" ]
[ 10, 4, 2 ]
[]
[]
[ "email", "mime", "parsing", "python" ]
stackoverflow_0003050298_email_mime_parsing_python.txt
Q: Help with pyHook error I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed. here is the source: import pyHook import pythoncom hm = pyHook.HookManager() def OnKeyboardEvent(event): if event.Alt == 32 and event.KeyID == 49: print 'HERE WILL BE THE CODE' hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() but when I execute, only works with the second press of the second key (number 1 = 49)... and give this error: http://img580.imageshack.us/img580/1858/errord.png How can I solve it? For work at the first pressed time. A: Note from the tutorial that you need a return value at the end of your handler: def OnKeyboardEvent(event): if event.Alt == 32 and event.KeyID == 49: print 'HERE WILL BE THE CODE' # return True to pass the event to other handlers return True I agree it's ambiguous from the docs whether that's required, but you do need to return True or False (or possibly any integer value), with any "false" value (e.g. 0) blocking the event such that no subsequent handlers get it. (This lets you swallow certain keystrokes conditionally, as in the Event Filtering section of the tutorial.) (This wasn't as easy to figure out as it might look! :-) )
Help with pyHook error
I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed. here is the source: import pyHook import pythoncom hm = pyHook.HookManager() def OnKeyboardEvent(event): if event.Alt == 32 and event.KeyID == 49: print 'HERE WILL BE THE CODE' hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() but when I execute, only works with the second press of the second key (number 1 = 49)... and give this error: http://img580.imageshack.us/img580/1858/errord.png How can I solve it? For work at the first pressed time.
[ "Note from the tutorial that you need a return value at the end of your handler:\ndef OnKeyboardEvent(event):\n if event.Alt == 32 and event.KeyID == 49:\n print 'HERE WILL BE THE CODE'\n\n # return True to pass the event to other handlers\n return True\n\nI agree it's ambiguous from the docs whether that's required, but you do need to return True or False (or possibly any integer value), with any \"false\" value (e.g. 0) blocking the event such that no subsequent handlers get it. (This lets you swallow certain keystrokes conditionally, as in the Event Filtering section of the tutorial.)\n(This wasn't as easy to figure out as it might look! :-) )\n" ]
[ 9 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003049068_python_windows.txt
Q: Running pdb from within pdb I'm debugging an script that I'm writing and the result of executing a statement from pdb does not make sense so my natural reaction is to try to trace it with pdb. To paraphrase: Yo dawg, I like python, so can you put my pdb in my pdb so I can debug while I debug? A: It sounds like you're looking for something listed fairly prominently in the docs, which is the set of methods that let you programmatically invoke the debugger on expressions, code in strings, or functions: http://docs.python.org/library/pdb.html#pdb.run http://docs.python.org/library/pdb.html#pdb.runeval http://docs.python.org/library/pdb.html#pdb.runcall I use these when I'm already at the pdb prompt (generally having gotten there by encountering a well-placed pdb.set_trace() statement) and want to test out, for example, variations on some method calls that aren't called in my source but which I can call right in the current context, manually. If that's not what you were looking for, do you simply want the "step" command instead of the "next" command at the prompt? (It's unclear what you really want here. An example might help.)
Running pdb from within pdb
I'm debugging an script that I'm writing and the result of executing a statement from pdb does not make sense so my natural reaction is to try to trace it with pdb. To paraphrase: Yo dawg, I like python, so can you put my pdb in my pdb so I can debug while I debug?
[ "It sounds like you're looking for something listed fairly prominently in the docs, which is the set of methods that let you programmatically invoke the debugger on expressions, code in strings, or functions:\n\nhttp://docs.python.org/library/pdb.html#pdb.run\nhttp://docs.python.org/library/pdb.html#pdb.runeval\nhttp://docs.python.org/library/pdb.html#pdb.runcall\n\nI use these when I'm already at the pdb prompt (generally having gotten there by encountering a well-placed pdb.set_trace() statement) and want to test out, for example, variations on some method calls that aren't called in my source but which I can call right in the current context, manually.\nIf that's not what you were looking for, do you simply want the \"step\" command instead of the \"next\" command at the prompt? (It's unclear what you really want here. An example might help.)\n" ]
[ 0 ]
[]
[]
[ "nested", "pdb", "python" ]
stackoverflow_0003048754_nested_pdb_python.txt
Q: How to write lazy functions which are chainable, in python? I want to write functions which are lazy as well as chainable. What would be the best way. I know that one way would be to do yield instead of return. I want these functions to be lazy in the way similar to how sqlalchemy functions are lazy when asked to fetch the data from DB. A: Generators (functions with yield instead of return) can indeed be seen as "lazy" (and itertools.chain can chain them just as well as any other iterator, if that's what you mean by "chainable"). But if by "chainable" (and lazy) you mean you want to call fee().fie().fo().fum() and have all the "hard work" happen only in fum (which seems closer to what SQLAlchemy does), then generators won't help -- what you need, rather, is the "Promise" design pattern, where each function/method (except the one actually doing all the work) returns an object which records all the conditions, parameters, and constraints on the operation, and the one hard-working function uses that information to finally perform the work. To give a very simple example, say that "the hard work" is performing an RPC call of the form remote(host, **kwargs). You could dress this up in "lazy chainable clothing" as follows: class RPC(object): def __init__(self, host): self._host = host self._kws = {} def doit(self, **morekws): return remote(self._host, **dict(self._kws, **morekws)) def __getattr__(self, name): def setkw(value): self._kws[name] = value return self return setkw Now, RPC(x).foo('bar').baz('bap').doit() calls remote(x, foo=bar, baz=bap) (and of course you can save intermediate stages of the chain, pass them around as arguments, etc, etc, until the call to doit).
How to write lazy functions which are chainable, in python?
I want to write functions which are lazy as well as chainable. What would be the best way. I know that one way would be to do yield instead of return. I want these functions to be lazy in the way similar to how sqlalchemy functions are lazy when asked to fetch the data from DB.
[ "Generators (functions with yield instead of return) can indeed be seen as \"lazy\" (and itertools.chain can chain them just as well as any other iterator, if that's what you mean by \"chainable\").\nBut if by \"chainable\" (and lazy) you mean you want to call fee().fie().fo().fum() and have all the \"hard work\" happen only in fum (which seems closer to what SQLAlchemy does), then generators won't help -- what you need, rather, is the \"Promise\" design pattern, where each function/method (except the one actually doing all the work) returns an object which records all the conditions, parameters, and constraints on the operation, and the one hard-working function uses that information to finally perform the work.\nTo give a very simple example, say that \"the hard work\" is performing an RPC call of the form remote(host, **kwargs). You could dress this up in \"lazy chainable clothing\" as follows:\nclass RPC(object):\n def __init__(self, host):\n self._host = host\n self._kws = {}\n def doit(self, **morekws):\n return remote(self._host, **dict(self._kws, **morekws))\n def __getattr__(self, name):\n def setkw(value):\n self._kws[name] = value\n return self\n return setkw\n\nNow, RPC(x).foo('bar').baz('bap').doit() calls remote(x, foo=bar, baz=bap) (and of course you can save intermediate stages of the chain, pass them around as arguments, etc, etc, until the call to doit).\n" ]
[ 7 ]
[]
[]
[ "lazy_evaluation", "python" ]
stackoverflow_0003050411_lazy_evaluation_python.txt
Q: Parse (extract) DTMF in Python If I have a recorded audio file (MP3), is there any way to get the figure out the DTMF tones that were recorded in pure Python? (If pure python is not available, then Java is okay too. The point being that it should be able to run in Google Appengine) A: First you will need to decode the MP3 into an uncompressed format of raw samples at a given bit depth and sampling rate. Then you look for the frequencies that make up each DTMF tone. Though FFT can be used for this, the cannonical algorithm is The Goertzel Algorithm, which makes use of the fact that you know what frequencies you care about before doing the transformation: http://en.wikipedia.org/wiki/Goertzel_algorithm There does exist some free python code for detecting DTMF using a Goertzel, though I haven't tried it myself, take a look at: http://johnetherton.com/projects/pys60-dtmf-detector A: Do an FFT on the data. You should get spikes at the frequencies of the two tones.
Parse (extract) DTMF in Python
If I have a recorded audio file (MP3), is there any way to get the figure out the DTMF tones that were recorded in pure Python? (If pure python is not available, then Java is okay too. The point being that it should be able to run in Google Appengine)
[ "First you will need to decode the MP3 into an uncompressed format of raw samples at a given bit depth and sampling rate. Then you look for the frequencies that make up each DTMF tone. Though FFT can be used for this, the cannonical algorithm is The Goertzel Algorithm, which makes use of the fact that you know what frequencies you care about before doing the transformation: http://en.wikipedia.org/wiki/Goertzel_algorithm\nThere does exist some free python code for detecting DTMF using a Goertzel, though I haven't tried it myself, take a look at:\nhttp://johnetherton.com/projects/pys60-dtmf-detector\n", "Do an FFT on the data. You should get spikes at the frequencies of the two tones.\n" ]
[ 6, 1 ]
[]
[]
[ "dtmf", "python" ]
stackoverflow_0003050528_dtmf_python.txt
Q: accessing files after setup.py install I'm developing a python application and have a question regarding coding it so that it still works after an user has installed it on his or her machine via setup.py install or similar. In one of my files, I use the following: file = "TestParser/View/MainWindow.ui" cwd = os.getcwd() argv_path = os.path.dirname(sys.argv[0]) file_path = os.path.join(cwd, argv_path, file) in order to get the path to MainWindow.ui, when I only know the path relative to the main script's location. This works regardless of from where I call the main script. The issue is that after an user installs the application on his or her machine, the relative path is different, so this doesn't work. I could use __file__, but according to this, py2exe doesn't have __file__. Is there a standard way of achieving this? Or a better way? EDIT: Should I even worry about py2exe and just use __file__? I have no immediate plans to use py2exe, but I was hoping to learn the proper way of accessing files in this context. A: With setup.py there is never a simple answer that works for all scenarios. Setup.py is a huge PITA to get working with different installation procedures (e.g., "setup.py install", py2exe, py2app). For example, in my app, I have this code to find files needed by the app: def getHome(): if hasattr(sys, "frozen"): if sys.platform == "darwin": # OS X return os.path.join(os.path.dirname(os.path.dirname(sys.executable)), "Resources") return os.path.dirname(sys.executable) else: return os.path.dirname(__file__) "frozen" is set for apps created with py2exe and py2app. So to answer your question, use __file__ and do not worry about py2exe. If you ever need to use py2exe, you will probably need to create a special case anyway.
accessing files after setup.py install
I'm developing a python application and have a question regarding coding it so that it still works after an user has installed it on his or her machine via setup.py install or similar. In one of my files, I use the following: file = "TestParser/View/MainWindow.ui" cwd = os.getcwd() argv_path = os.path.dirname(sys.argv[0]) file_path = os.path.join(cwd, argv_path, file) in order to get the path to MainWindow.ui, when I only know the path relative to the main script's location. This works regardless of from where I call the main script. The issue is that after an user installs the application on his or her machine, the relative path is different, so this doesn't work. I could use __file__, but according to this, py2exe doesn't have __file__. Is there a standard way of achieving this? Or a better way? EDIT: Should I even worry about py2exe and just use __file__? I have no immediate plans to use py2exe, but I was hoping to learn the proper way of accessing files in this context.
[ "With setup.py there is never a simple answer that works for all scenarios. Setup.py is a huge PITA to get working with different installation procedures (e.g., \"setup.py install\", py2exe, py2app).\nFor example, in my app, I have this code to find files needed by the app:\ndef getHome():\n if hasattr(sys, \"frozen\"):\n if sys.platform == \"darwin\": # OS X\n return os.path.join(os.path.dirname(os.path.dirname(sys.executable)), \"Resources\")\n return os.path.dirname(sys.executable)\n else:\n return os.path.dirname(__file__)\n\n\"frozen\" is set for apps created with py2exe and py2app.\nSo to answer your question, use __file__ and do not worry about py2exe. If you ever need to use py2exe, you will probably need to create a special case anyway.\n" ]
[ 1 ]
[]
[]
[ "file", "py2exe", "python", "setup.py" ]
stackoverflow_0002985755_file_py2exe_python_setup.py.txt
Q: Bundle a Python app as a single file to support add-ons or extensions? There are several utilities — all with different procedures, limitations, and target operating systems — for getting a Python package and all of its dependencies and turning them into a single binary program that is easy to ship to customers: http://wiki.python.org/moin/Freeze http://www.pyinstaller.org/ http://www.py2exe.org/ http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html My situation goes one step further: third-party developers will be wanting to write plug-ins, extensions, or add-ons for my application. It is, of course, a daunting question how users on platforms like Windows would most easily install plugins or addons in such a way that my app can easily discover that they have been installed. But beyond that basic question is another: how can a third-party developer bundle their extension with whatever libraries the extension itself needs (which might be binary modules, like lxml) in such a way that the plugin's dependencies become available for import at the same time that the plugin becomes available. How can this be approached? Will my application need its own plug-in area on disk and its own plug-in registry to make this tractable? Or are there general mechanisms, that I could avoid writing myself, that would allow an app that is distributed as a single executable to look around and find plugins that are also installed as single files? A: You should be able to have a plugins directory that your application scans at runtime (or later) to import the code in question. Here's an example that should work with regular .py or .pyc code that even works with plugins stored inside zip files (so users could just drop someplugin.zip in the 'plugins' directory and have it magically work): import re, os, sys class Plugin(object): """ The base class from which all plugins are derived. It is used by the plugin loading functions to find all the installed plugins. """ def __init__(self, foo): self.foo = foo # Any useful base plugin methods would go in here. def get_plugins(plugin_dir): """Adds plugins to sys.path and returns them as a list""" registered_plugins = [] #check to see if a plugins directory exists and add any found plugins # (even if they're zipped) if os.path.exists(plugin_dir): plugins = os.listdir(plugin_dir) pattern = ".py$" for plugin in plugins: plugin_path = os.path.join(plugin_dir, plugin) if os.path.splitext(plugin)[1] == ".zip": sys.path.append(plugin_path) (plugin, ext) = os.path.splitext(plugin) # Get rid of the .zip extension registered_plugins.append(plugin) elif plugin != "__init__.py": if re.search(pattern, plugin): (shortname, ext) = os.path.splitext(plugin) registered_plugins.append(shortname) if os.path.isdir(plugin_path): plugins = os.listdir(plugin_path) for plugin in plugins: if plugin != "__init__.py": if re.search(pattern, plugin): (shortname, ext) = os.path.splitext(plugin) sys.path.append(plugin_path) registered_plugins.append(shortname) return registered_plugins def init_plugin_system(cfg): """ Initializes the plugin system by appending all plugins into sys.path and then using load_plugins() to import them. cfg - A dictionary with two keys: plugin_path - path to the plugin directory (e.g. 'plugins') plugins - List of plugin names to import (e.g. ['foo', 'bar']) """ if not cfg['plugin_path'] in sys.path: sys.path.insert(0, cfg['plugin_path']) load_plugins(cfg['plugins']) def load_plugins(plugins): """ Imports all plugins given a list. Note: Assumes they're all in sys.path. """ for plugin in plugins: __import__(plugin, None, None, ['']) if plugin not in Plugin.__subclasses__(): # This takes care of importing zipped plugins: __import__(plugin, None, None, [plugin]) So lets say I have a plugin named "foo.py" in a directory called 'plugins' (that is in the base dir of my app) that will add a new capability to my application. The contents might look like this: from plugin_stuff import Plugin class Foo(Plugin): """An example plugin.""" self.menu_entry = {'Tools': {'Foo': self.bar}} def bar(self): return "foo plugin!" I could initialize my plugins when I launch my app like so: plugin_dir = "%s/plugins" % os.getcwd() plugin_list = get_plugins(plugin_dir) init_plugin_system({'plugin_path': plugin_dir, 'plugins': plugin_list}) plugins = find_plugins() plugin_menu_entries = [] for plugin in plugins: print "Enabling plugin: %s" % plugin.__name__ plugin_menu_entries.append(plugin.menu_entry)) add_menu_entries(plugin_menu_entries) # This is an imaginary function That should work as long as the plugin is either a .py or .pyc file (assuming it is byte-compiled for the platform in question). It can be standalone file or inside of a directory with an init.py or inside of a zip file with the same rules. How do I know this works? It is how I implemented plugins in PyCI. PyCI is a web application but there's no reason why this method wouldn't work for a regular ol' GUI. For the example above I chose to use an imaginary add_menu_entries() function in conjunction with a Plugin object variable that could be used to add a plugin's methods to your GUI's menus. Hopefully this answer will help you build your own plugin system. If you want to see precisely how it is implemented I recommend you download the PyCI source code and look at plugin_utils.py and the Example plugin in the plugins_enabled directory. A: Here is another example of a Python app that uses plugins: OpenSTV. Here, the plugins can only be Python modules.
Bundle a Python app as a single file to support add-ons or extensions?
There are several utilities — all with different procedures, limitations, and target operating systems — for getting a Python package and all of its dependencies and turning them into a single binary program that is easy to ship to customers: http://wiki.python.org/moin/Freeze http://www.pyinstaller.org/ http://www.py2exe.org/ http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html My situation goes one step further: third-party developers will be wanting to write plug-ins, extensions, or add-ons for my application. It is, of course, a daunting question how users on platforms like Windows would most easily install plugins or addons in such a way that my app can easily discover that they have been installed. But beyond that basic question is another: how can a third-party developer bundle their extension with whatever libraries the extension itself needs (which might be binary modules, like lxml) in such a way that the plugin's dependencies become available for import at the same time that the plugin becomes available. How can this be approached? Will my application need its own plug-in area on disk and its own plug-in registry to make this tractable? Or are there general mechanisms, that I could avoid writing myself, that would allow an app that is distributed as a single executable to look around and find plugins that are also installed as single files?
[ "You should be able to have a plugins directory that your application scans at runtime (or later) to import the code in question. Here's an example that should work with regular .py or .pyc code that even works with plugins stored inside zip files (so users could just drop someplugin.zip in the 'plugins' directory and have it magically work):\nimport re, os, sys\nclass Plugin(object):\n \"\"\"\n The base class from which all plugins are derived. It is used by the\n plugin loading functions to find all the installed plugins.\n \"\"\"\n def __init__(self, foo):\n self.foo = foo\n # Any useful base plugin methods would go in here.\n\ndef get_plugins(plugin_dir):\n \"\"\"Adds plugins to sys.path and returns them as a list\"\"\"\n\n registered_plugins = []\n\n #check to see if a plugins directory exists and add any found plugins\n # (even if they're zipped)\n if os.path.exists(plugin_dir):\n plugins = os.listdir(plugin_dir)\n pattern = \".py$\"\n for plugin in plugins:\n plugin_path = os.path.join(plugin_dir, plugin)\n if os.path.splitext(plugin)[1] == \".zip\":\n sys.path.append(plugin_path)\n (plugin, ext) = os.path.splitext(plugin) # Get rid of the .zip extension\n registered_plugins.append(plugin)\n elif plugin != \"__init__.py\":\n if re.search(pattern, plugin):\n (shortname, ext) = os.path.splitext(plugin)\n registered_plugins.append(shortname)\n if os.path.isdir(plugin_path):\n plugins = os.listdir(plugin_path)\n for plugin in plugins:\n if plugin != \"__init__.py\":\n if re.search(pattern, plugin):\n (shortname, ext) = os.path.splitext(plugin)\n sys.path.append(plugin_path)\n registered_plugins.append(shortname)\n return registered_plugins\n\ndef init_plugin_system(cfg):\n \"\"\"\n Initializes the plugin system by appending all plugins into sys.path and\n then using load_plugins() to import them.\n\n cfg - A dictionary with two keys:\n plugin_path - path to the plugin directory (e.g. 'plugins')\n plugins - List of plugin names to import (e.g. ['foo', 'bar'])\n \"\"\"\n if not cfg['plugin_path'] in sys.path:\n sys.path.insert(0, cfg['plugin_path'])\n load_plugins(cfg['plugins'])\n\ndef load_plugins(plugins):\n \"\"\"\n Imports all plugins given a list.\n Note: Assumes they're all in sys.path.\n \"\"\"\n for plugin in plugins:\n __import__(plugin, None, None, [''])\n if plugin not in Plugin.__subclasses__():\n # This takes care of importing zipped plugins:\n __import__(plugin, None, None, [plugin])\n\nSo lets say I have a plugin named \"foo.py\" in a directory called 'plugins' (that is in the base dir of my app) that will add a new capability to my application. The contents might look like this:\nfrom plugin_stuff import Plugin\n\nclass Foo(Plugin):\n \"\"\"An example plugin.\"\"\"\n self.menu_entry = {'Tools': {'Foo': self.bar}}\n def bar(self):\n return \"foo plugin!\"\n\nI could initialize my plugins when I launch my app like so:\nplugin_dir = \"%s/plugins\" % os.getcwd()\nplugin_list = get_plugins(plugin_dir)\ninit_plugin_system({'plugin_path': plugin_dir, 'plugins': plugin_list})\nplugins = find_plugins()\nplugin_menu_entries = []\nfor plugin in plugins:\n print \"Enabling plugin: %s\" % plugin.__name__\n plugin_menu_entries.append(plugin.menu_entry))\nadd_menu_entries(plugin_menu_entries) # This is an imaginary function\n\nThat should work as long as the plugin is either a .py or .pyc file (assuming it is byte-compiled for the platform in question). It can be standalone file or inside of a directory with an init.py or inside of a zip file with the same rules.\nHow do I know this works? It is how I implemented plugins in PyCI. PyCI is a web application but there's no reason why this method wouldn't work for a regular ol' GUI. For the example above I chose to use an imaginary add_menu_entries() function in conjunction with a Plugin object variable that could be used to add a plugin's methods to your GUI's menus.\nHopefully this answer will help you build your own plugin system. If you want to see precisely how it is implemented I recommend you download the PyCI source code and look at plugin_utils.py and the Example plugin in the plugins_enabled directory.\n", "Here is another example of a Python app that uses plugins: OpenSTV. Here, the plugins can only be Python modules.\n" ]
[ 7, 0 ]
[]
[]
[ "py2app", "py2exe", "pyinstaller", "python", "software_distribution" ]
stackoverflow_0002876967_py2app_py2exe_pyinstaller_python_software_distribution.txt
Q: SQLAlchemy session management in long-running process Scenario: A .NET-based application server (Wonderware IAS/System Platform) hosts automation objects that communicate with various equipment on the factory floor. CPython is hosted inside this application server (using Python for .NET). The automation objects have scripting functionality built-in (using a custom, .NET-based language). These scripts call Python functions. The Python functions are part of a system to track Work-In-Progress on the factory floor. The purpose of the system is to track the produced widgets along the process, ensure that the widgets go through the process in the correct order, and check that certain conditions are met along the process. The widget production history and widget state is stored in a relational database, this is where SQLAlchemy plays its part. For example, when a widget passes a scanner, the automation software triggers the following script (written in the application server's custom scripting language): ' wiget_id and scanner_id provided by automation object ' ExecFunction() takes care of calling a CPython function retval = ExecFunction("WidgetScanned", widget_id, scanner_id); ' if the python function raises an Exception, ErrorOccured will be true ' in this case, any errors should cause the production line to stop. if (retval.ErrorOccured) then ProductionLine.Running = False; InformationBoard.DisplayText = "ERROR: " + retval.Exception.Message; InformationBoard.SoundAlarm = True end if; The script calls the WidgetScanned python function: # pywip/functions.py from pywip.database import session from pywip.model import Widget, WidgetHistoryItem from pywip import validation, StatusMessage from datetime import datetime def WidgetScanned(widget_id, scanner_id): widget = session.query(Widget).get(widget_id) validation.validate_widget_passed_scanner(widget, scanner) # raises exception on error widget.history.append(WidgetHistoryItem(timestamp=datetime.now(), action=u"SCANNED", scanner_id=scanner_id)) widget.last_scanner = scanner_id widget.last_update = datetime.now() return StatusMessage("OK") # ... there are a dozen similar functions My question is: How do I best manage SQLAlchemy sessions in this scenario? The application server is a long-running process, typically running months between restarts. The application server is single-threaded. Currently, I do it the following way: I apply a decorator to the functions I make avaliable to the application server: # pywip/iasfunctions.py from pywip import functions def ias_session_handling(func): def _ias_session_handling(*args, **kwargs): try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise return _ias_session_handling # ... actually I populate this module with decorated versions of all the functions in pywip.functions dynamically WidgetScanned = ias_session_handling(functions.WidgetScanned) Question: Is the decorator above suitable for handling sessions in a long-running process? Should I call session.remove()? The SQLAlchemy session object is a scoped session: # pywip/database.py from sqlalchemy.orm import scoped_session, sessionmaker session = scoped_session(sessionmaker()) I want to keep the session management out of the basic functions. For two reasons: There is another family of functions, sequence functions. The sequence functions call several of the basic functions. One sequence function should equal one database transaction. I need to be able to use the library from other environments. a) From a TurboGears web application. In that case, session management is done by TurboGears. b) From an IPython shell. In that case, commit/rollback will be explicit. (I am truly sorry for the long question. But I felt I needed to explain the scenario. Perhaps not necessary?) A: The described decorator is suitable for long running applications, but you can run into trouble if you accidentally share objects between requests. To make the errors appear earlier and not corrupt anything it is better to discard the session with session.remove(). try: try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise finally: session.remove() Or if you can use the with context manager: try: with session.registry().transaction: return func(*args, **kwargs) finally: session.remove() By the way, you might want to use .with_lockmode('update') on the query so your validate doesn't run on stale data. A: Ask your WonderWare administrator to give you access to the Wonderware Historian, you can track the values of the tags pretty easily via MSSQL calls over sqlalchemy that you can poll every so often. Another option is to use the archestra toolkit to listen for the internal tag updates and have a server deployed as a platform in the galaxy which you can listen from.
SQLAlchemy session management in long-running process
Scenario: A .NET-based application server (Wonderware IAS/System Platform) hosts automation objects that communicate with various equipment on the factory floor. CPython is hosted inside this application server (using Python for .NET). The automation objects have scripting functionality built-in (using a custom, .NET-based language). These scripts call Python functions. The Python functions are part of a system to track Work-In-Progress on the factory floor. The purpose of the system is to track the produced widgets along the process, ensure that the widgets go through the process in the correct order, and check that certain conditions are met along the process. The widget production history and widget state is stored in a relational database, this is where SQLAlchemy plays its part. For example, when a widget passes a scanner, the automation software triggers the following script (written in the application server's custom scripting language): ' wiget_id and scanner_id provided by automation object ' ExecFunction() takes care of calling a CPython function retval = ExecFunction("WidgetScanned", widget_id, scanner_id); ' if the python function raises an Exception, ErrorOccured will be true ' in this case, any errors should cause the production line to stop. if (retval.ErrorOccured) then ProductionLine.Running = False; InformationBoard.DisplayText = "ERROR: " + retval.Exception.Message; InformationBoard.SoundAlarm = True end if; The script calls the WidgetScanned python function: # pywip/functions.py from pywip.database import session from pywip.model import Widget, WidgetHistoryItem from pywip import validation, StatusMessage from datetime import datetime def WidgetScanned(widget_id, scanner_id): widget = session.query(Widget).get(widget_id) validation.validate_widget_passed_scanner(widget, scanner) # raises exception on error widget.history.append(WidgetHistoryItem(timestamp=datetime.now(), action=u"SCANNED", scanner_id=scanner_id)) widget.last_scanner = scanner_id widget.last_update = datetime.now() return StatusMessage("OK") # ... there are a dozen similar functions My question is: How do I best manage SQLAlchemy sessions in this scenario? The application server is a long-running process, typically running months between restarts. The application server is single-threaded. Currently, I do it the following way: I apply a decorator to the functions I make avaliable to the application server: # pywip/iasfunctions.py from pywip import functions def ias_session_handling(func): def _ias_session_handling(*args, **kwargs): try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise return _ias_session_handling # ... actually I populate this module with decorated versions of all the functions in pywip.functions dynamically WidgetScanned = ias_session_handling(functions.WidgetScanned) Question: Is the decorator above suitable for handling sessions in a long-running process? Should I call session.remove()? The SQLAlchemy session object is a scoped session: # pywip/database.py from sqlalchemy.orm import scoped_session, sessionmaker session = scoped_session(sessionmaker()) I want to keep the session management out of the basic functions. For two reasons: There is another family of functions, sequence functions. The sequence functions call several of the basic functions. One sequence function should equal one database transaction. I need to be able to use the library from other environments. a) From a TurboGears web application. In that case, session management is done by TurboGears. b) From an IPython shell. In that case, commit/rollback will be explicit. (I am truly sorry for the long question. But I felt I needed to explain the scenario. Perhaps not necessary?)
[ "The described decorator is suitable for long running applications, but you can run into trouble if you accidentally share objects between requests. To make the errors appear earlier and not corrupt anything it is better to discard the session with session.remove().\ntry:\n try:\n retval = func(*args, **kwargs)\n session.commit()\n return retval\n except:\n session.rollback()\n raise\nfinally:\n session.remove()\n\nOr if you can use the with context manager:\ntry:\n with session.registry().transaction:\n return func(*args, **kwargs)\nfinally:\n session.remove()\n\nBy the way, you might want to use .with_lockmode('update') on the query so your validate doesn't run on stale data.\n", "Ask your WonderWare administrator to give you access to the Wonderware Historian, you can track the values of the tags pretty easily via MSSQL calls over sqlalchemy that you can poll every so often.\nAnother option is to use the archestra toolkit to listen for the internal tag updates and have a server deployed as a platform in the galaxy which you can listen from.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "sqlalchemy", "wonderware" ]
stackoverflow_0001421502_python_sqlalchemy_wonderware.txt
Q: How do you efficiently bulk index lookups? I have these entity kinds: Molecule Atom MoleculeAtom Given a list(molecule_ids) whose lengths is in the hundreds, I need to get a dict of the form {molecule_id: list(atom_ids)}. Likewise, given a list(atom_ids) whose length is in the hunreds, I need to get a dict of the form {atom_id: list(molecule_ids)}. Both of these bulk lookups need to happen really fast. Right now I'm doing something like: atom_ids_by_molecule_id = {} for molecule_id in molecule_ids: moleculeatoms = MoleculeAtom.all().filter('molecule =', db.Key.from_path('molecule', molecule_id)).fetch(1000) atom_ids_by_molecule_id[molecule_id] = [ MoleculeAtom.atom.get_value_for_datastore(ma).id() for ma in moleculeatoms ] Like I said, len(molecule_ids) is in the hundreds. I need to do this kind of bulk index lookup on almost every single request, and I need it to be FAST, and right now it's too slow. Ideas: Will using a Molecule.atoms ListProperty do what I need? Consider that I am storing additional data on the MoleculeAtom node, and remember it's equally important for me to do the lookup in the molecule->atom and atom->molecule directions. Caching? I tried memcaching lists of atom IDs keyed by molecule ID, but I have tons of atoms and molecules, and the cache can't fit it. How about denormalizing the data by creating a new entity kind whose key name is a molecule ID and whose value is a list of atom IDs? The idea is, calling db.get on 500 keys is probably faster than looping through 500 fetches with filters, right? A: Your third approach (denormalizing the data) is, generally speaking, the right one. In particular, db.get by keys is indeed about as fast as the datastore gets. Of course, you'll need to denormalize the other way around too (entity with key name atom ID, value a list of molecule IDs) and will need to update everything carefully when atoms or molecules are altered, added, or deleted -- if you need that to be transactional (multiple such modifications being potentially in play at the same time) you need to arrange ancestor relationships.. but I don't see how to do it for both molecules and atoms at the same time, so maybe that could be a problem. Maybe, if modifications are rare enough (and depending on other aspects of your application), you could serialize the modifications in queued tasks.
How do you efficiently bulk index lookups?
I have these entity kinds: Molecule Atom MoleculeAtom Given a list(molecule_ids) whose lengths is in the hundreds, I need to get a dict of the form {molecule_id: list(atom_ids)}. Likewise, given a list(atom_ids) whose length is in the hunreds, I need to get a dict of the form {atom_id: list(molecule_ids)}. Both of these bulk lookups need to happen really fast. Right now I'm doing something like: atom_ids_by_molecule_id = {} for molecule_id in molecule_ids: moleculeatoms = MoleculeAtom.all().filter('molecule =', db.Key.from_path('molecule', molecule_id)).fetch(1000) atom_ids_by_molecule_id[molecule_id] = [ MoleculeAtom.atom.get_value_for_datastore(ma).id() for ma in moleculeatoms ] Like I said, len(molecule_ids) is in the hundreds. I need to do this kind of bulk index lookup on almost every single request, and I need it to be FAST, and right now it's too slow. Ideas: Will using a Molecule.atoms ListProperty do what I need? Consider that I am storing additional data on the MoleculeAtom node, and remember it's equally important for me to do the lookup in the molecule->atom and atom->molecule directions. Caching? I tried memcaching lists of atom IDs keyed by molecule ID, but I have tons of atoms and molecules, and the cache can't fit it. How about denormalizing the data by creating a new entity kind whose key name is a molecule ID and whose value is a list of atom IDs? The idea is, calling db.get on 500 keys is probably faster than looping through 500 fetches with filters, right?
[ "Your third approach (denormalizing the data) is, generally speaking, the right one. In particular, db.get by keys is indeed about as fast as the datastore gets.\nOf course, you'll need to denormalize the other way around too (entity with key name atom ID, value a list of molecule IDs) and will need to update everything carefully when atoms or molecules are altered, added, or deleted -- if you need that to be transactional (multiple such modifications being potentially in play at the same time) you need to arrange ancestor relationships.. but I don't see how to do it for both molecules and atoms at the same time, so maybe that could be a problem. Maybe, if modifications are rare enough (and depending on other aspects of your application), you could serialize the modifications in queued tasks.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "indexing", "python", "scalability" ]
stackoverflow_0003050304_google_app_engine_indexing_python_scalability.txt
Q: A simple Python extension in C I am trying to create a simple python extension module. I compiled the following code into a transit.so dynamic module #include <python2.6/Python.h> static PyObject* _print(PyObject* self, PyObject* args) { return Py_BuildValue("i", 10); } static PyMethodDef TransitMethods[] = { {"print", _print, METH_VARARGS, ""}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittransit(void) { Py_InitModule("transit", TransitMethods); } However, trying to call this from python import transit transit.print() I obtain an error message File "test.py", line 2 transit.print() ^ SyntaxError: invalid syntax What's wrong with my code? A: I'm guessing that it has to do with using a keyword as a function name. I tried defining a function print() in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.
A simple Python extension in C
I am trying to create a simple python extension module. I compiled the following code into a transit.so dynamic module #include <python2.6/Python.h> static PyObject* _print(PyObject* self, PyObject* args) { return Py_BuildValue("i", 10); } static PyMethodDef TransitMethods[] = { {"print", _print, METH_VARARGS, ""}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittransit(void) { Py_InitModule("transit", TransitMethods); } However, trying to call this from python import transit transit.print() I obtain an error message File "test.py", line 2 transit.print() ^ SyntaxError: invalid syntax What's wrong with my code?
[ "I'm guessing that it has to do with using a keyword as a function name. I tried defining a function print() in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.\n" ]
[ 4 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003050940_c_python.txt
Q: Python __subclasses__() not listing subclasses I cant seem to list all derived classes using the __subclasses__() method. Here's my directory layout: import.py backends __init__.py --digger __init__.py base.py test.py --plugins plugina_plugin.py From import.py i'm calling test.py. test.py in turn iterates over all the files in the plugins directory and loads all of them. test.py looks like this: import os import sys import re sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))))) sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))), 'plugins')) from base import BasePlugin class TestImport: def __init__(self): print 'heeeeello' PLUGIN_DIRECTORY = os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))), 'plugins') for filename in os.listdir (PLUGIN_DIRECTORY): # Ignore subfolders if os.path.isdir (os.path.join(PLUGIN_DIRECTORY, filename)): continue else: if re.match(r".*?_plugin\.py$", filename): print ('Initialising plugin : ' + filename) __import__(re.sub(r".py", r"", filename)) print ('Plugin system initialized') print BasePlugin.__subclasses__() The problem us that the __subclasses__() method doesn't show any derived classes. All plugins in the plugins directory derive from a base class in the base.py file. base.py looks like this: class BasePlugin(object): """ Base """ def __init__(self): pass plugina_plugin.py looks like this: from base import BasePlugin class PluginA(BasePlugin): """ Plugin A """ def __init__(self): pass Could anyone help me out with this? Whatm am i doing wrong? I've racked my brains over this but I cant seem to figure it out Thanks. A: There were no other base.py files. I'm on a WinXP (SP2) with Python 2.6. I added another class to my test.py file called PluginB which used BasePlugin as the base class. When i did print PluginA.__mro__ print PluginB.__mro__ I got: (<class 'plugina_plugin.PluginA'>, <class 'base.BasePlugin'>, <type 'object'>) (<class 'backends.digger.test.PluginB'>, <class 'backends.digger.base.BasePlugin'>, <type 'object'>) As you can see, they're both using the same base plugin but the qualified names are different. This was because in plugina_plugin.py I was importing BasePlugin like this: from base import BasePlugin Instead of: from backends.digger.base import BasePlugin Fixing this fixed it. A: Perhaps the plugins are finding another base.py hiding somewhere (the plugin directory for example). Run with python -v to see if two different base.py are getting imported You can also look at PluginA.__mro__ and confirm that the BasePlugin in there is the right one
Python __subclasses__() not listing subclasses
I cant seem to list all derived classes using the __subclasses__() method. Here's my directory layout: import.py backends __init__.py --digger __init__.py base.py test.py --plugins plugina_plugin.py From import.py i'm calling test.py. test.py in turn iterates over all the files in the plugins directory and loads all of them. test.py looks like this: import os import sys import re sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))))) sys.path.append(os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))), 'plugins')) from base import BasePlugin class TestImport: def __init__(self): print 'heeeeello' PLUGIN_DIRECTORY = os.path.join(os.path.abspath(os.path.dirname(os.path.abspath( __file__ ))), 'plugins') for filename in os.listdir (PLUGIN_DIRECTORY): # Ignore subfolders if os.path.isdir (os.path.join(PLUGIN_DIRECTORY, filename)): continue else: if re.match(r".*?_plugin\.py$", filename): print ('Initialising plugin : ' + filename) __import__(re.sub(r".py", r"", filename)) print ('Plugin system initialized') print BasePlugin.__subclasses__() The problem us that the __subclasses__() method doesn't show any derived classes. All plugins in the plugins directory derive from a base class in the base.py file. base.py looks like this: class BasePlugin(object): """ Base """ def __init__(self): pass plugina_plugin.py looks like this: from base import BasePlugin class PluginA(BasePlugin): """ Plugin A """ def __init__(self): pass Could anyone help me out with this? Whatm am i doing wrong? I've racked my brains over this but I cant seem to figure it out Thanks.
[ "There were no other base.py files. I'm on a WinXP (SP2) with Python 2.6. I added another class to my test.py file called PluginB which used BasePlugin as the base class. When i did \n print PluginA.__mro__\n print PluginB.__mro__\n\nI got:\n(<class 'plugina_plugin.PluginA'>, <class 'base.BasePlugin'>, <type 'object'>)\n(<class 'backends.digger.test.PluginB'>, <class 'backends.digger.base.BasePlugin'>, <type 'object'>)\n\nAs you can see, they're both using the same base plugin but the qualified names are different. This was because in plugina_plugin.py I was importing BasePlugin like this:\nfrom base import BasePlugin\n\nInstead of:\nfrom backends.digger.base import BasePlugin\n\nFixing this fixed it. \n", "Perhaps the plugins are finding another base.py hiding somewhere (the plugin directory for example).\nRun with python -v to see if two different base.py are getting imported\nYou can also look at PluginA.__mro__ and confirm that the BasePlugin in there is the right one\n" ]
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003048337_python.txt
Q: How can I paste some string to the active window in Python? Possible Duplicate: How do I copy a string to the clipboard on Windows using Python? Can someone make me an example or explain to me how can I paste something to the active window with Python? A: It is easiest if you use the SendKeys package. You can find a Windows installer for various Python versions here. The simplest use case, sending plain text, is very simple: import SendKeys SendKeys.SendKeys("Hello world") You can do all sorts of nifty things using key-codes to represent for unprintable characters: import SendKeys SendKeys.SendKeys(""" {LWIN} {PAUSE .25} r Notepad.exe{ENTER} {PAUSE 1} Hello{SPACE}World! {PAUSE 1} %{F4} n """) Read the documentation for full details. If for whatever reason you don't want to introduce a dependency on a non-standard library package, you can do the same thing using COM: import win32api import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run("calc") win32api.Sleep(100) shell.AppActivate("Calculator") win32api.Sleep(100) shell.SendKeys("1{+}") win32api.Sleep(500) shell.SendKeys("2") win32api.Sleep(500) shell.SendKeys("~") # ~ is the same as {ENTER} win32api.Sleep(500) shell.SendKeys("*3") win32api.Sleep(500) shell.SendKeys("~") win32api.Sleep(2500)
How can I paste some string to the active window in Python?
Possible Duplicate: How do I copy a string to the clipboard on Windows using Python? Can someone make me an example or explain to me how can I paste something to the active window with Python?
[ "It is easiest if you use the SendKeys package. You can find a Windows installer for various Python versions here.\nThe simplest use case, sending plain text, is very simple:\nimport SendKeys\nSendKeys.SendKeys(\"Hello world\")\n\nYou can do all sorts of nifty things using key-codes to represent for unprintable characters:\nimport SendKeys\nSendKeys.SendKeys(\"\"\"\n {LWIN}\n {PAUSE .25}\n r\n Notepad.exe{ENTER}\n {PAUSE 1}\n Hello{SPACE}World!\n {PAUSE 1}\n %{F4}\n n\n\"\"\")\n\nRead the documentation for full details.\nIf for whatever reason you don't want to introduce a dependency on a non-standard library package, you can do the same thing using COM:\nimport win32api\nimport win32com.client\n\nshell = win32com.client.Dispatch(\"WScript.Shell\")\nshell.Run(\"calc\")\nwin32api.Sleep(100)\nshell.AppActivate(\"Calculator\")\nwin32api.Sleep(100)\nshell.SendKeys(\"1{+}\")\nwin32api.Sleep(500)\nshell.SendKeys(\"2\")\nwin32api.Sleep(500)\nshell.SendKeys(\"~\") # ~ is the same as {ENTER}\nwin32api.Sleep(500)\nshell.SendKeys(\"*3\")\nwin32api.Sleep(500)\nshell.SendKeys(\"~\")\nwin32api.Sleep(2500)\n\n" ]
[ 2 ]
[]
[]
[ "python", "sendkeys", "windows" ]
stackoverflow_0003051030_python_sendkeys_windows.txt
Q: How do I use python to hit this command and return the result? $whois abc.com I want to use python to hit this command, and then give the result as a String of text. How can I do that? A: You can use subprocess, for example: from subprocess import Popen, PIPE output = Popen(["/usr/bin/whois", "abc.com"], stdout = PIPE).communicate()[0] The stdout = PIPE parameter forces stdout to be written to a temporary pipe instead of the console (if you don't want that, remove the stdout parameter). A: subprocess is fine. On the other hand, the whois protocol is so simple that I do not see why to use an external command (and depend on its availability). Just open a TCP connection to port 43, send a one-line query and read the responses. A: With subprocess.
How do I use python to hit this command and return the result?
$whois abc.com I want to use python to hit this command, and then give the result as a String of text. How can I do that?
[ "You can use subprocess, for example:\nfrom subprocess import Popen, PIPE\noutput = Popen([\"/usr/bin/whois\", \"abc.com\"], stdout = PIPE).communicate()[0]\n\nThe stdout = PIPE parameter forces stdout to be written to a temporary pipe instead of the console (if you don't want that, remove the stdout parameter).\n", "subprocess is fine. On the other hand, the whois protocol is so simple that I do not see why to use an external command (and depend on its availability). Just open a TCP connection to port 43, send a one-line query and read the responses.\n", "With subprocess.\n" ]
[ 4, 1, 0 ]
[]
[]
[ "linux", "python", "unix", "whois" ]
stackoverflow_0003040886_linux_python_unix_whois.txt
Q: redirection follow by post just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected? Is the technique used is to open up new browser window and do a ajax POST from there? Thanks. A: It can work like this: on air ticket booking system you have a html form pointing on certain airline booking website (by action parameter). If user submits data then data lands on airline booking website and this website proceed the request. Usuallly people want to get back to the first site. This can be done by sending return url with request data. Of course there must be an API on the airline booking site to handle such url. This is common mechanism when you do online payments, all kind of reservations, etc. Not sure about your idea to use ajax calls. Simple html form is enough here. Note that also making ajax calls between different domains can be recognized as attempt to access the restricted url.
redirection follow by post
just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected? Is the technique used is to open up new browser window and do a ajax POST from there? Thanks.
[ "It can work like this:\non air ticket booking system you have a html form pointing on certain airline booking website (by action parameter). If user submits data then data lands on airline booking website and this website proceed the request.\nUsuallly people want to get back to the first site. This can be done by sending return url with request data. Of course there must be an API on the airline booking site to handle such url.\nThis is common mechanism when you do online payments, all kind of reservations, etc.\nNot sure about your idea to use ajax calls. Simple html form is enough here. Note that also making ajax calls between different domains can be recognized as attempt to access the restricted url.\n" ]
[ 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0003050477_javascript_python.txt
Q: Image Gurus: Optimize my Python PNG transparency function I need to replace all the white(ish) pixels in a PNG image with alpha transparency. I'm using Python in AppEngine and so do not have access to libraries like PIL, imagemagick etc. AppEngine does have an image library, but is pitched mainly at image resizing. I found the excellent little pyPNG module and managed to knock up a little function that does what I need: make_transparent.py pseudo-code for the main loop would be something like: for each pixel: if pixel looks "quite white": set pixel values to transparent otherwise: keep existing pixel values and (assuming 8bit values) "quite white" would be: where each r,g,b value is greater than "240" AND each r,g,b value is within "20" of each other This is the first time I've worked with raw pixel data in this way, and although works, it also performs extremely poorly. It seems like there must be a more efficient way of processing the data without iterating over each pixel in this manner? (Matrices?) I was hoping someone with more experience in dealing with these things might be able to point out some of my more obvious mistakes/improvements in my algorithm. Thanks! A: Honestly, the only heuristic I could conceive is picking a few arbitrary, random points on your image and using a flood fill. This only works well if your image as large contiguous white portions (if your image is an object with no or little holes in front of a background, then you're in luck -- you actually have a heuristic for which points to flood fill from). (disclaimer: I am no image guru =/ ) A: This still visits every pixel, but may be faster: new_pixels = [] for row in pixels: new_row = array('B', row) i = 0 while i < len(new_row): r = new_row[i] g = new_row[i + 1] b = new_row[i + 2] if r>threshold and g>threshold and b>threshold: m = int((r+g+b)/3) if nearly_eq(r,m,tolerance) and nearly_eq(g,m,tolerance) and nearly_eq(b,m,tolerance): new_row[i + 3] = 0 i += 4 new_pixels.append(new_row) It avoids the slicen generator, which will be copying the entire row of pixels for every pixel (less one pixel each time). It also pre-allocates the output row by directly copying the input row, and then only writes the alpha value of pixels which have changed. Even faster would be to not allocate a new set of pixels at all, and just write directly over the pixels in the source image (assuming you don't need the source image for anything else). A: I'm quite sure there is no short cut for this. You have to visit every single pixel. A: The issue seems to have more to do with loops in Python than with images. Python loops are extremely slow, it is best to avoid them and use built-ins loop operators instead. Here, if you were willing to copy the image, you could use a list comprehension: def make_transparent(pixel): if pixel looks "quite white": return transparent else: return pixel newImage = [make_transparent(p) for p in oldImage]
Image Gurus: Optimize my Python PNG transparency function
I need to replace all the white(ish) pixels in a PNG image with alpha transparency. I'm using Python in AppEngine and so do not have access to libraries like PIL, imagemagick etc. AppEngine does have an image library, but is pitched mainly at image resizing. I found the excellent little pyPNG module and managed to knock up a little function that does what I need: make_transparent.py pseudo-code for the main loop would be something like: for each pixel: if pixel looks "quite white": set pixel values to transparent otherwise: keep existing pixel values and (assuming 8bit values) "quite white" would be: where each r,g,b value is greater than "240" AND each r,g,b value is within "20" of each other This is the first time I've worked with raw pixel data in this way, and although works, it also performs extremely poorly. It seems like there must be a more efficient way of processing the data without iterating over each pixel in this manner? (Matrices?) I was hoping someone with more experience in dealing with these things might be able to point out some of my more obvious mistakes/improvements in my algorithm. Thanks!
[ "Honestly, the only heuristic I could conceive is picking a few arbitrary, random points on your image and using a flood fill.\nThis only works well if your image as large contiguous white portions (if your image is an object with no or little holes in front of a background, then you're in luck -- you actually have a heuristic for which points to flood fill from).\n(disclaimer: I am no image guru =/ )\n", "This still visits every pixel, but may be faster:\nnew_pixels = []\nfor row in pixels:\n new_row = array('B', row)\n i = 0\n while i < len(new_row):\n r = new_row[i]\n g = new_row[i + 1]\n b = new_row[i + 2]\n if r>threshold and g>threshold and b>threshold:\n m = int((r+g+b)/3)\n if nearly_eq(r,m,tolerance) and nearly_eq(g,m,tolerance) and nearly_eq(b,m,tolerance):\n new_row[i + 3] = 0\n i += 4\n new_pixels.append(new_row)\n\nIt avoids the slicen generator, which will be copying the entire row of pixels for every pixel (less one pixel each time).\nIt also pre-allocates the output row by directly copying the input row, and then only writes the alpha value of pixels which have changed.\nEven faster would be to not allocate a new set of pixels at all, and just write directly over the pixels in the source image (assuming you don't need the source image for anything else).\n", "I'm quite sure there is no short cut for this. You have to visit every single pixel. \n", "The issue seems to have more to do with loops in Python than with images.\nPython loops are extremely slow, it is best to avoid them and use built-ins loop operators instead.\nHere, if you were willing to copy the image, you could use a list comprehension:\ndef make_transparent(pixel):\n if pixel looks \"quite white\": return transparent\n else: return pixel\n\nnewImage = [make_transparent(p) for p in oldImage]\n\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "google_app_engine", "image", "png", "python" ]
stackoverflow_0003045377_algorithm_google_app_engine_image_png_python.txt
Q: Operating on rows and then on columns of a matrix produces code duplication I have the following (Python) code to check if there are any rows or columns that contain the same value: # Test rows -> # Check each row for a win for i in range(self.height): # For each row ... firstValue = None # Initialize first value placeholder for j in range(self.width): # For each value in the row if (j == 0): # If it's the first value ... firstValue = b[i][j] # Remember it else: # Otherwise ... if b[i][j] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this row, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it # Test columns -> # Check each column for a win for i in range(self.width): # For each column ... firstValue = None # Initialize first value placeholder for j in range(self.height): # For each value in the column if (j == 0): # If it's the first value ... firstValue = b[j][i] # Remember it else: # Otherwise ... if b[j][i] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this column, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it Clearly, there is a lot of code duplication here. How do I refactor this code? Thanks! A: To check whether all elements in a row are equal, I'd suggest building a python set of the row and then check whether it has only one element. Similarly for the columns. E.g. like this def testRowWin(b): for row in b: if len(set(row)) == 1: return True return False def testColWin(b): return testRowWin(zip(*b)) A: Generally, when you want to refactor, take similar snippets of code and make them into functions. So you could have a function to test all the cells for which one index (either row or column) is the same, and another function that calls that function on all the columns (or rows). Although as Pär pointed out in the comment on your question, it'd be a lot easier to help if you gave some information about what you've tried. But... another separate (maybe slightly related) matter is that your code doesn't take advantage of Python's functional capabilities. Which is fine, but just so you know, tasks like this where you have to check a bunch of different elements of an array (list, actually) are often much more concise when written functionally. For example, your example could be done like this: f = lambda x,y: x if x == y else False # for Python <= 2.4 use this instead: # f = lambda x,y: x == y and x or False # test rows [reduce(f,r) for r in array] # test columns reduce(lambda r,s: map(f,r,s), array) although that's not so helpful if you're trying to understand how the code works. A: def test_values(self, first, second, HeightWidth): for i in range(first): firstValue = None for j in range(second): (firstDimension, secondDimension) = (i, j) if HeightWidth else (j, i) if secondDimension == 0: firstValue = b[firstDimension][secondDimension] else: if b[firstDimension][secondDimension] != firstValue: firstValue = None break return firstValue firstValue = test_values(self, self.height, self.width, true) if firstValue: return firstValue firstValue test_values(self, self.width, self.height, false) if firstValue: return firstValue
Operating on rows and then on columns of a matrix produces code duplication
I have the following (Python) code to check if there are any rows or columns that contain the same value: # Test rows -> # Check each row for a win for i in range(self.height): # For each row ... firstValue = None # Initialize first value placeholder for j in range(self.width): # For each value in the row if (j == 0): # If it's the first value ... firstValue = b[i][j] # Remember it else: # Otherwise ... if b[i][j] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this row, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it # Test columns -> # Check each column for a win for i in range(self.width): # For each column ... firstValue = None # Initialize first value placeholder for j in range(self.height): # For each value in the column if (j == 0): # If it's the first value ... firstValue = b[j][i] # Remember it else: # Otherwise ... if b[j][i] != firstValue: # If this is not the same as the first value ... firstValue = None # Reset first value break # Stop checking this column, there's no win here if (firstValue != None): # If first value has been set # First value placeholder now holds the winning player's code return firstValue # Return it Clearly, there is a lot of code duplication here. How do I refactor this code? Thanks!
[ "To check whether all elements in a row are equal, I'd suggest building a python set of the row and then check whether it has only one element. Similarly for the columns.\nE.g. like this\ndef testRowWin(b):\n for row in b:\n if len(set(row)) == 1:\n return True\n return False\n\ndef testColWin(b):\n return testRowWin(zip(*b))\n\n", "Generally, when you want to refactor, take similar snippets of code and make them into functions. So you could have a function to test all the cells for which one index (either row or column) is the same, and another function that calls that function on all the columns (or rows). Although as Pär pointed out in the comment on your question, it'd be a lot easier to help if you gave some information about what you've tried.\nBut... another separate (maybe slightly related) matter is that your code doesn't take advantage of Python's functional capabilities. Which is fine, but just so you know, tasks like this where you have to check a bunch of different elements of an array (list, actually) are often much more concise when written functionally. For example, your example could be done like this:\nf = lambda x,y: x if x == y else False\n# for Python <= 2.4 use this instead:\n# f = lambda x,y: x == y and x or False\n# test rows\n[reduce(f,r) for r in array]\n# test columns\nreduce(lambda r,s: map(f,r,s), array)\n\nalthough that's not so helpful if you're trying to understand how the code works.\n", "def test_values(self, first, second, HeightWidth):\n for i in range(first):\n firstValue = None\n for j in range(second):\n (firstDimension, secondDimension) = (i, j) if HeightWidth else (j, i)\n if secondDimension == 0:\n firstValue = b[firstDimension][secondDimension]\n else:\n if b[firstDimension][secondDimension] != firstValue:\n firstValue = None\n break\n return firstValue\n\nfirstValue = test_values(self, self.height, self.width, true)\nif firstValue:\n return firstValue\n\nfirstValue test_values(self, self.width, self.height, false)\nif firstValue:\n return firstValue\n\n" ]
[ 2, 2, 1 ]
[]
[]
[ "code_duplication", "python", "refactoring" ]
stackoverflow_0003051570_code_duplication_python_refactoring.txt
Q: can the python wave module accept StringIO object i'm trying to use the wave module to read wav files in python. whats not typical of my applications is that I'm NOT using a file or a filename to read the wav file, but instead i have the wav file in a buffer. And here's what i'm doing import StringIO buffer = StringIO.StringIO() buffer.output(wav_buffer) file = wave.open(buffer, 'r') but i'm getting a EOFError when i run it... File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 493, in open return Wave_read(f) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 163, in __init__ self.initfp(f) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 128, in initfp self._file = Chunk(file, bigendian = 0) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/chunk.py", line 63, in __init__ raise EOFError i know the StringIO stuff works for creation of wav file and i tried the following and it works import StringIO buffer = StringIO.StringIO() audio_out = wave.open(buffer, 'w') audio_out.setframerate(m.getRate()) audio_out.setsampwidth(2) audio_out.setcomptype('NONE', 'not compressed') audio_out.setnchannels(1) audio_out.writeframes(raw_audio) audio_out.close() buffer.flush() # these lines do not work... # buffer.output(wav_buffer) # file = wave.open(buffer, 'r') # this file plays out fine in VLC file = open(FILE_NAME + ".wav", 'w') file.write(buffer.getvalue()) file.close() buffer.close() A: try this: import StringIO buffer = StringIO.StringIO(wav_buffer) file = wave.open(buffer, 'r') A: buffer = StringIO.StringIO() buffer.output(wav_buffer) A StringIO doesn't work like that. It's not a pipe that's connected to itself: when you read(), you don't receive data that you previously passed to write(). (Never mind output() which I'm guessing is a mispaste as there is no such method.) Instead it acts as a separate read-pipe and write-pipe. The content that read() will return is passed in with the constructor: buffer = StringIO.StringIO(wav_buffer) file = wave.open(buffer, 'rb') And any content collected from write() is readable through getvalue(). (I used binary read mode because this is what's happening, though the wave module will silently convert r mode to rb anyway.)
can the python wave module accept StringIO object
i'm trying to use the wave module to read wav files in python. whats not typical of my applications is that I'm NOT using a file or a filename to read the wav file, but instead i have the wav file in a buffer. And here's what i'm doing import StringIO buffer = StringIO.StringIO() buffer.output(wav_buffer) file = wave.open(buffer, 'r') but i'm getting a EOFError when i run it... File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 493, in open return Wave_read(f) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 163, in __init__ self.initfp(f) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/wave.py", line 128, in initfp self._file = Chunk(file, bigendian = 0) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/chunk.py", line 63, in __init__ raise EOFError i know the StringIO stuff works for creation of wav file and i tried the following and it works import StringIO buffer = StringIO.StringIO() audio_out = wave.open(buffer, 'w') audio_out.setframerate(m.getRate()) audio_out.setsampwidth(2) audio_out.setcomptype('NONE', 'not compressed') audio_out.setnchannels(1) audio_out.writeframes(raw_audio) audio_out.close() buffer.flush() # these lines do not work... # buffer.output(wav_buffer) # file = wave.open(buffer, 'r') # this file plays out fine in VLC file = open(FILE_NAME + ".wav", 'w') file.write(buffer.getvalue()) file.close() buffer.close()
[ "try this:\nimport StringIO\n\nbuffer = StringIO.StringIO(wav_buffer)\nfile = wave.open(buffer, 'r')\n\n", "buffer = StringIO.StringIO()\nbuffer.output(wav_buffer)\n\nA StringIO doesn't work like that. It's not a pipe that's connected to itself: when you read(), you don't receive data that you previously passed to write(). (Never mind output() which I'm guessing is a mispaste as there is no such method.)\nInstead it acts as a separate read-pipe and write-pipe. The content that read() will return is passed in with the constructor:\nbuffer = StringIO.StringIO(wav_buffer)\nfile = wave.open(buffer, 'rb')\n\nAnd any content collected from write() is readable through getvalue().\n(I used binary read mode because this is what's happening, though the wave module will silently convert r mode to rb anyway.)\n" ]
[ 2, 2 ]
[]
[]
[ "audio", "python", "wave" ]
stackoverflow_0003051747_audio_python_wave.txt
Q: Generating very large XML files in Python? Does anyone know of a memory efficient way to generate very large xml files (e.g. 100-500 MiB) in Python? I've been utilizing lxml, but memory usage is through the roof. A: Perhaps you could use a templating engine instead of generating/building the xml yourself? Genshi for example is xml-based and supports streaming output. A very basic example: from genshi.template import MarkupTemplate tpl_xml = ''' <doc xmlns:py="http://genshi.edgewall.org/"> <p py:for="i in data">${i}</p> </doc> ''' tpl = MarkupTemplate(tpl_xml) stream = tpl.generate(data=xrange(10000000)) with open('output.xml', 'w') as f: stream.render(out=f) It might take a while, but memory usage remains low. The same example for the Mako templating engine (not "natively" xml), but a lot faster: from mako.template import Template from mako.runtime import Context tpl_xml = ''' <doc> % for i in data: <p>${i}</p> % endfor </doc> ''' tpl = Template(tpl_xml) with open('output.xml', 'w') as f: ctx = Context(f, data=xrange(10000000)) tpl.render_context(ctx) The last example ran on my laptop for about 20 seconds, producing a (admittedly very simple) 151 MB xml file, no memory problems at all. (according to Windows task manager it remained constant at about 10MB) Depending on your needs, this might be a friendlier and faster way of generating xml than using SAX etc... Check out the docs to see what you can do with these engines (there are others as well, I just picked out these two as examples) A: The only sane way to generate so large an XML file is line by line, which means printing while running a state machine, and lots of testing. A: Obviously, you've got to avoid having to build the entire tree ( whether DOM or etree or whatever ) in memory. But the best way depends on the source of your data and how complicated and interlinked the structure of your output is. If it's big because it's got thousands of instances of fairly independent items, then you can generate the outer wrapper, and then build trees for each item and then serialize each fragment to the output. If the fragments aren't so independent, then you'll need to do some extra bookkeeping -- like maybe manage a database of generated ids & idrefs. I would break it into 2 or 3 parts: a sax event producer, an output serializer eating sax events, and optionally, if it seems easier to work with some independent pieces as objects or trees, something to build those objects and then turn them into sax events for the serializer. Maybe you could just manage it all as direct text output, instead of dealing with sax events: that depends on how complicated it is. This may also be a good place to use python generators as a way of streaming the output without having to build large structures in memory. A: If your document is very regular (such as a bunch of database records, all in the same format) you could use my own "xe" library. http://home.avvanta.com/~steveha/xe.html The xe library was designed for generating syndication feeds (Atom, RSS, etc.) and I think it is easy to use. I need to update it for Python 2.6, and I haven't yet, sorry about that.
Generating very large XML files in Python?
Does anyone know of a memory efficient way to generate very large xml files (e.g. 100-500 MiB) in Python? I've been utilizing lxml, but memory usage is through the roof.
[ "Perhaps you could use a templating engine instead of generating/building the xml yourself? \nGenshi for example is xml-based and supports streaming output. A very basic example:\nfrom genshi.template import MarkupTemplate\n\ntpl_xml = '''\n<doc xmlns:py=\"http://genshi.edgewall.org/\">\n<p py:for=\"i in data\">${i}</p>\n</doc>\n'''\n\ntpl = MarkupTemplate(tpl_xml)\nstream = tpl.generate(data=xrange(10000000))\n\nwith open('output.xml', 'w') as f:\n stream.render(out=f)\n\nIt might take a while, but memory usage remains low.\nThe same example for the Mako templating engine (not \"natively\" xml), but a lot faster:\nfrom mako.template import Template\nfrom mako.runtime import Context\n\ntpl_xml = '''\n<doc>\n% for i in data:\n<p>${i}</p>\n% endfor\n</doc>\n'''\n\ntpl = Template(tpl_xml)\n\nwith open('output.xml', 'w') as f:\n ctx = Context(f, data=xrange(10000000))\n tpl.render_context(ctx)\n\nThe last example ran on my laptop for about 20 seconds, producing a (admittedly very simple) 151 MB xml file, no memory problems at all. (according to Windows task manager it remained constant at about 10MB)\nDepending on your needs, this might be a friendlier and faster way of generating xml than using SAX etc... Check out the docs to see what you can do with these engines (there are others as well, I just picked out these two as examples)\n", "The only sane way to generate so large an XML file is line by line, which means printing while running a state machine, and lots of testing.\n", "Obviously, you've got to avoid having to build the entire tree ( whether DOM or etree or whatever ) in memory. But the best way depends on the source of your data and how complicated and interlinked the structure of your output is.\nIf it's big because it's got thousands of instances of fairly independent items, then you can generate the outer wrapper, and then build trees for each item and then serialize each fragment to the output. \nIf the fragments aren't so independent, then you'll need to do some extra bookkeeping -- like maybe manage a database of generated ids & idrefs. \nI would break it into 2 or 3 parts: a sax event producer, an output serializer\neating sax events, and optionally, if it seems easier to work with some independent pieces as objects or trees, something to build those objects and then turn them into sax events for the serializer. \nMaybe you could just manage it all as direct text output, instead of dealing with sax events: that depends on how complicated it is. \nThis may also be a good place to use python generators as a way of streaming the output without having to build large structures in memory. \n", "If your document is very regular (such as a bunch of database records, all in the same format) you could use my own \"xe\" library.\nhttp://home.avvanta.com/~steveha/xe.html\nThe xe library was designed for generating syndication feeds (Atom, RSS, etc.) and I think it is easy to use. I need to update it for Python 2.6, and I haven't yet, sorry about that.\n" ]
[ 11, 2, 2, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003049188_lxml_python_xml.txt
Q: exeuting command in background Trying to execute shell command in background using pythons commands module >>>import commands >>>output = commands.getstatusoutput("find / > tmp.txt &") sh: Syntax error: ";" unexpected Can anyone explain what is wrong with the syntax ? How should it be executed then ? Tazim. A: According to the getstatusoutput documentation, commands.getstatusoutput(cmd) is executed as { cmd ; } 2>&1 so your command is run as if it was { find / > tmp.txt & ; } 2 >& 1 and the ; is not valid after the & in such a command. You should use the subprocess module to simulate the old-style os.spawn commands. Try subprocess.Popen("find / > tmp.txt", shell=True) A: I'm not aware of a way to directly execute a command in background like that. Particularly, it's because commands module does not run the command through bash, which is what usually parses the ampersand. You should do a fork/exec call from the os module to run things in background. A: Try to create a daemon to run your process in background.
exeuting command in background
Trying to execute shell command in background using pythons commands module >>>import commands >>>output = commands.getstatusoutput("find / > tmp.txt &") sh: Syntax error: ";" unexpected Can anyone explain what is wrong with the syntax ? How should it be executed then ? Tazim.
[ "According to the getstatusoutput documentation, commands.getstatusoutput(cmd) is executed as\n{ cmd ; } 2>&1\n\nso your command is run as if it was\n{ find / > tmp.txt & ; } 2 >& 1\n\nand the ; is not valid after the & in such a command.\nYou should use the subprocess module to simulate the old-style os.spawn commands. \nTry\nsubprocess.Popen(\"find / > tmp.txt\", shell=True)\n\n", "I'm not aware of a way to directly execute a command in background like that. Particularly, it's because commands module does not run the command through bash, which is what usually parses the ampersand.\nYou should do a fork/exec call from the os module to run things in background.\n", "Try to create a daemon to run your process in background.\n" ]
[ 7, 1, 1 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0003052466_python_shell.txt
Q: Django: Get remote IP address inside settings.py I want to enable debug (DEBUG = True) For my Django project only if it runs on localhost. How can I get user IP address inside settings.py? I would like something like this to work: #Debugging only on localhost if user_ip = '127.0.0.1': DEBUG = True else: DEBUG = False How do I put user IP address in user_ip variable inside settings.py file? A: Maybe it is enough for you to specify some INTERNAL_IPS: https://docs.djangoproject.com/en/dev/ref/settings/#internal-ips A: use this. import socket print socket.gethostbyname_ex(socket.gethostname())[2] edit: ah, i had misunderstood the topic. A: Try this in you settings.py class LazyDebugSetting(object): def __init__(self): self.value = None def __nonzero__(self): if not self.value: # as emre yilmaz say user_ip = socket.gethostbyname_ex(socket.gethostname())[2] self.value = user_ip == '127.0.0.1' return self.value __len__ = __nonzero__ DEBUG = LazyDebugSetting() But better use the INTERNAL_IPS Or use environment variables DEBUG = os.environ.get('DEVELOP_MODE', False)
Django: Get remote IP address inside settings.py
I want to enable debug (DEBUG = True) For my Django project only if it runs on localhost. How can I get user IP address inside settings.py? I would like something like this to work: #Debugging only on localhost if user_ip = '127.0.0.1': DEBUG = True else: DEBUG = False How do I put user IP address in user_ip variable inside settings.py file?
[ "Maybe it is enough for you to specify some INTERNAL_IPS:\nhttps://docs.djangoproject.com/en/dev/ref/settings/#internal-ips\n", "use this.\nimport socket\n\nprint socket.gethostbyname_ex(socket.gethostname())[2]\n\nedit: ah, i had misunderstood the topic.\n", "Try this in you settings.py\nclass LazyDebugSetting(object):\n def __init__(self):\n self.value = None\n def __nonzero__(self):\n if not self.value:\n # as emre yilmaz say\n user_ip = socket.gethostbyname_ex(socket.gethostname())[2]\n self.value = user_ip == '127.0.0.1'\n return self.value \n __len__ = __nonzero__\n\nDEBUG = LazyDebugSetting()\n\nBut better use the INTERNAL_IPS\nOr use environment variables\nDEBUG = os.environ.get('DEVELOP_MODE', False)\n\n" ]
[ 5, 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003051365_django_python.txt
Q: Server-side rendering using blender and twisted (python) The project I am working on at the moment basically takes in an image and then renders a video using blender from the command line. At the moment I am using Twisted to deal with the requests but there is certainly something that I am doing wrong as it is not working how I would like it to. You can see the jist of the program here (I have stripped out anything unnecessary). The blender render is done by spawning a subprocess (I am aware Twisted can handle processes) along with a python script to configure the render and use the image provided as a texture. The program needs to be able to handle as many connections as possible. At the moment the subprocess does one render at a time but ideally it would check CPU/number of parallel renders and adjust the number to the optimum. Each render is custom to the user so once a users render is complete they should get their render back (an avi file). My question is: Is Twisted the right choice for this? Are there any other options? If not, is my implementation of the system flawed? I would appreciate any thoughts or opinions on this! A: Is Twisted the right choice for this? - Perhaps. Are there other options? - Yes. If not, is my implementation of the system flawed? - Yes. It looks to me that your subprocess call is blocking: p.wait() It is possible to do what it sounds like you're trying to do in Twisted, but you are a very long way from it. You need a rate-controlled, asynchronous task queue with a web frontend. What you've got is single page on a single threaded 'site' that doesn't return any html until the submitted job is finished. This is possible in twisted. However it's probably easier to implement using django + celery. Django: http://www.djangoproject.com/ Celery: http://celery.github.com/celery/getting-started/introduction.html And a tutorial for a similar purpose: http://webcookies.org/blog/2009/09/10/rabbitmq-celery-and-django/
Server-side rendering using blender and twisted (python)
The project I am working on at the moment basically takes in an image and then renders a video using blender from the command line. At the moment I am using Twisted to deal with the requests but there is certainly something that I am doing wrong as it is not working how I would like it to. You can see the jist of the program here (I have stripped out anything unnecessary). The blender render is done by spawning a subprocess (I am aware Twisted can handle processes) along with a python script to configure the render and use the image provided as a texture. The program needs to be able to handle as many connections as possible. At the moment the subprocess does one render at a time but ideally it would check CPU/number of parallel renders and adjust the number to the optimum. Each render is custom to the user so once a users render is complete they should get their render back (an avi file). My question is: Is Twisted the right choice for this? Are there any other options? If not, is my implementation of the system flawed? I would appreciate any thoughts or opinions on this!
[ "Is Twisted the right choice for this? - Perhaps.\nAre there other options? - Yes.\nIf not, is my implementation of the system flawed? - Yes. It looks to me that your subprocess call is blocking: p.wait()\nIt is possible to do what it sounds like you're trying to do in Twisted, but you are a very long way from it.\nYou need a rate-controlled, asynchronous task queue with a web frontend.\nWhat you've got is single page on a single threaded 'site' that doesn't return any html until the submitted job is finished.\nThis is possible in twisted. However it's probably easier to implement using django + celery.\nDjango: http://www.djangoproject.com/\nCelery: http://celery.github.com/celery/getting-started/introduction.html\nAnd a tutorial for a similar purpose:\nhttp://webcookies.org/blog/2009/09/10/rabbitmq-celery-and-django/\n" ]
[ 3 ]
[]
[]
[ "blender", "python", "rendering", "twisted" ]
stackoverflow_0003052230_blender_python_rendering_twisted.txt
Q: Django templates tag error def _table_(request,id,has_permissions): dict = {} dict.update(get_newdata(request,rid)) return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)})) In templates the code is as, {% if has_permissions == "1" %} <input type="button" value="Edit" id="edit" onclick="javascript:edit('{{id}}')" style="display:inline;"/>&nbsp;&nbsp;&nbsp;&nbsp; {% endif %} There is a template error in has_permissions line. What is wrong here? has_permissions has the value 1 or 0. A: Versions of Django before 1.2 do not support relational operators in {% if %}. Use {% ifequal %} or a bare {% if %} instead.
Django templates tag error
def _table_(request,id,has_permissions): dict = {} dict.update(get_newdata(request,rid)) return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)})) In templates the code is as, {% if has_permissions == "1" %} <input type="button" value="Edit" id="edit" onclick="javascript:edit('{{id}}')" style="display:inline;"/>&nbsp;&nbsp;&nbsp;&nbsp; {% endif %} There is a template error in has_permissions line. What is wrong here? has_permissions has the value 1 or 0.
[ "Versions of Django before 1.2 do not support relational operators in {% if %}. Use {% ifequal %} or a bare {% if %} instead.\n" ]
[ 2 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0003052549_django_django_templates_django_views_python.txt
Q: os.environ() giving errors while setting for Hudson I want a small python script to set the HUDSON_HOME environment variable. When using the shell, I can easily do this using >>set HUDSON_HOME=http://localhost:8080 But how can I do the same directly through python?? I don't want to do it by passing the command line to os.system().. can os.environ() be of any help?? I had in my script: import os os.environ('HUDSON_HOME')='http://localhost:8080' but it's probably setting it for the subprocss and not the parent shell..any way around this?? A: os.environ is a dictionary represenation of the environment. You'd use it like this: >>> import os >>> os.environ['HUDSON_HOME'] = 'http://localhost:8080' However, it cannot modify the environment of the parent process AFAIK. A: I am unaware of any way to do this as you've requested, as modifying the environment in your Python program will simply change the environment for it, and any child processes, but not the parent process. That said, if all you need to do is have some Python program that figures out what the value of the variable is, depending on your shell, you should be able to simply assign the output of it to the environment variable: #!/usr/bin/env python # code goes here print 'http://localhost:8080' If the above was your program, you could run this on the shell, and have HUDSON_HOME set to http://localhost:8080: $ set HUDSON_HOME=`python program.py` Note: Those are backticks, which is how it knows to take the output of running the command instead of the command itself.
os.environ() giving errors while setting for Hudson
I want a small python script to set the HUDSON_HOME environment variable. When using the shell, I can easily do this using >>set HUDSON_HOME=http://localhost:8080 But how can I do the same directly through python?? I don't want to do it by passing the command line to os.system().. can os.environ() be of any help?? I had in my script: import os os.environ('HUDSON_HOME')='http://localhost:8080' but it's probably setting it for the subprocss and not the parent shell..any way around this??
[ "os.environ is a dictionary represenation of the environment. You'd use it like this:\n>>> import os\n>>> os.environ['HUDSON_HOME'] = 'http://localhost:8080'\n\nHowever, it cannot modify the environment of the parent process AFAIK.\n", "I am unaware of any way to do this as you've requested, as modifying the environment in your Python program will simply change the environment for it, and any child processes, but not the parent process.\nThat said, if all you need to do is have some Python program that figures out what the value of the variable is, depending on your shell, you should be able to simply assign the output of it to the environment variable:\n#!/usr/bin/env python\n\n# code goes here\n\nprint 'http://localhost:8080'\n\nIf the above was your program, you could run this on the shell, and have HUDSON_HOME set to http://localhost:8080:\n$ set HUDSON_HOME=`python program.py`\n\nNote: Those are backticks, which is how it knows to take the output of running the command instead of the command itself.\n" ]
[ 3, 0 ]
[]
[]
[ "environment_variables", "hudson", "python" ]
stackoverflow_0003052534_environment_variables_hudson_python.txt
Q: Multi-part template issue with Jinja2 When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single string to the web-server (CherryPy in this case). My first approach is as follows... from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('')) tmpl = env.get_template('Body.html') page_body = tmpl.render() tmpl = env.get_template('Header.html') page_header = tmpl.render() tmpl = env.get_template('Footer.html') page_footer = tmpl.render() page_code = page_header + page_body + page_footer but this contains repetitious code, so my next approach is... def render_template(html_file): from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('')) tmpl = env.get_template(html_file) return tmpl.render() page_header = render_template('Header.html') page_body = render_template('Body.html') page_footer = render_template('Footer.html) However, this means that each part is created in its own environment - can that be a problem? Are there any other downsides to this approach? I have chosen the 3-part approach over the child-template approach because I think it may be more flexible (and easier to follow), but I might be wrong. Anyone like to convince me that using header, body and footer blocks might be better? Any advice would be appreciated. Alan A: If you don't want to do template inheritance, have you considered include? {% include 'header.html' %} Body {% include 'footer.html' %}
Multi-part template issue with Jinja2
When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single string to the web-server (CherryPy in this case). My first approach is as follows... from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('')) tmpl = env.get_template('Body.html') page_body = tmpl.render() tmpl = env.get_template('Header.html') page_header = tmpl.render() tmpl = env.get_template('Footer.html') page_footer = tmpl.render() page_code = page_header + page_body + page_footer but this contains repetitious code, so my next approach is... def render_template(html_file): from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('')) tmpl = env.get_template(html_file) return tmpl.render() page_header = render_template('Header.html') page_body = render_template('Body.html') page_footer = render_template('Footer.html) However, this means that each part is created in its own environment - can that be a problem? Are there any other downsides to this approach? I have chosen the 3-part approach over the child-template approach because I think it may be more flexible (and easier to follow), but I might be wrong. Anyone like to convince me that using header, body and footer blocks might be better? Any advice would be appreciated. Alan
[ "If you don't want to do template inheritance, have you considered include?\n{% include 'header.html' %}\n Body\n{% include 'footer.html' %}\n\n" ]
[ 11 ]
[]
[]
[ "jinja2", "python", "templates" ]
stackoverflow_0003052702_jinja2_python_templates.txt
Q: AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime? If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example: class MyEntity(db.Expando): x = db.IntegerProperty() my_entity = MyEntity(x=1) my_entity.y = 2 But suppose I have the name of the dynamic property in a variable... how can I (1) read and write to it, and (2) check if the Dynamic variable exists in the entity's instance? e.g. class MyEntity(db.Expando): x = db.IntegerProperty() my_entity = MyEntity(x=1) # choose a var name: var_name = "z" # assign a value to the Dynamic variable whose name is in var_name: my_entity.property_by_name[var_name] = 2 # also, check if such a property esists if my_entity.property_exists(var_name): # read the value of the Dynamic property whose name is in var_name print my_entity.property_by_name[var_name] Thanks... A: Yes, you can. You simply have to set the attribute on the entity: some_name = 'wee' setattr(my_entity, some_name, 'value') print getattr(my_entity, some_name) my_entity.put() setattr and getattr are built-in functions of Python used to set/get attributes with arbitrary names on an object.
AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime?
If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example: class MyEntity(db.Expando): x = db.IntegerProperty() my_entity = MyEntity(x=1) my_entity.y = 2 But suppose I have the name of the dynamic property in a variable... how can I (1) read and write to it, and (2) check if the Dynamic variable exists in the entity's instance? e.g. class MyEntity(db.Expando): x = db.IntegerProperty() my_entity = MyEntity(x=1) # choose a var name: var_name = "z" # assign a value to the Dynamic variable whose name is in var_name: my_entity.property_by_name[var_name] = 2 # also, check if such a property esists if my_entity.property_exists(var_name): # read the value of the Dynamic property whose name is in var_name print my_entity.property_by_name[var_name] Thanks...
[ "Yes, you can. You simply have to set the attribute on the entity:\nsome_name = 'wee'\nsetattr(my_entity, some_name, 'value')\nprint getattr(my_entity, some_name)\nmy_entity.put()\n\nsetattr and getattr are built-in functions of Python used to set/get attributes with arbitrary names on an object.\n" ]
[ 6 ]
[]
[]
[ "entity", "google_app_engine", "google_cloud_datastore", "properties", "python" ]
stackoverflow_0003052821_entity_google_app_engine_google_cloud_datastore_properties_python.txt
Q: store/load numpy array from binary files I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix. def saveArrayToFile(data, fileName): with open(fileName, 'w') as file: a = array.array('f') nSamples, ndim = data.shape a.extend([nSamples, ndim]) # write number of elements and dimensions a.fromstring(data.tostring()) a.tofile(file) def readArrayFromFile(fileName): _featDesc = np.fromfile(fileName, 'f') _ndesc = int(_featDesc[0]) _ndim = int(_featDesc[1]) _featDesc = _featDesc[2:] _featDesc = _featDesc.reshape([_ndesc, _ndim]) return _featDesc, _ndesc, _ndim An example on how to use the functions is: myarr=np.array([[7, 4],[3, 9],[1, 3]]) saveArrayToFile(myarr,'myfile.txt') _featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt') However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed. I think the problem might be in the saveArrayToFile function. Best wishes, Javier A: Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.
store/load numpy array from binary files
I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix. def saveArrayToFile(data, fileName): with open(fileName, 'w') as file: a = array.array('f') nSamples, ndim = data.shape a.extend([nSamples, ndim]) # write number of elements and dimensions a.fromstring(data.tostring()) a.tofile(file) def readArrayFromFile(fileName): _featDesc = np.fromfile(fileName, 'f') _ndesc = int(_featDesc[0]) _ndim = int(_featDesc[1]) _featDesc = _featDesc[2:] _featDesc = _featDesc.reshape([_ndesc, _ndim]) return _featDesc, _ndesc, _ndim An example on how to use the functions is: myarr=np.array([[7, 4],[3, 9],[1, 3]]) saveArrayToFile(myarr,'myfile.txt') _featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt') However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed. I think the problem might be in the saveArrayToFile function. Best wishes, Javier
[ "Use numpy.save (and numpy.load) to dump (retrieve) numpy arrays to (from) a binary file.\n" ]
[ 2 ]
[]
[]
[ "binaryfiles", "file", "python" ]
stackoverflow_0003052669_binaryfiles_file_python.txt
Q: Fully customized login system in Django? I am currently writing an application which I plan to sell as SaaS. Without giving away "secrets," I can say that it is basically a "document editing system" in which many users will be submitting documents. The basic heirarchy is this: Institution Individual Document Sub-document So each Individual should be able to BROWSE all documents that were submitted by anybody in their institution, but should only be able to EDIT documents that they created. No individual should even be aware of the existence of another Institution--that should all be completely hidden. I have written a Django/Python class that would facilitate this, but every document regarding authentication that I have read requires that I use the User object. Is this just a limitation of Django, or is there a way to do this? If there is a way, how can I get my own "Individual" class details attached to the "request" objects so I can validate the things I should be showing the users? A: What you're looking for is authorization, not authentication. Django's built-in authorization system is fairly crude, as you've discovered. You'll need something like django-authority if you want a more complete solution. A: The auth module is typically used to cover authentication cases. Gives you groups (Institutions), Users (Individuals) and permissions. Using these features you can perform checking if a user is a member of a group or owns a doc before allowing them to see or edit the doc. http://docs.djangoproject.com/en/dev/topics/auth/ If you need to go beyond the typical use case, supporting LDAP for example, then you can look at writing your own authentication backend. http://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources A: In general, if you need to attach more information to the builtin User model, you would create new model which subclasses models.Model (not User), and identify it in settings as AUTH_PROFILE_MODULE. You can get the appropriate instance of your model from a user by calling user.get_profile(). (see http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). This is generally useful for adding extra fields to User such as address, contact information, etc. While it would be possible to use this for your authentication needs, you'd most likely be better off using the built in groups, or a more comprehensive solution like django-authority as others have mentioned. I've included this answer only because it seems to be what you were asking for (a way to attach a class to User), but not really what you need (authorization).
Fully customized login system in Django?
I am currently writing an application which I plan to sell as SaaS. Without giving away "secrets," I can say that it is basically a "document editing system" in which many users will be submitting documents. The basic heirarchy is this: Institution Individual Document Sub-document So each Individual should be able to BROWSE all documents that were submitted by anybody in their institution, but should only be able to EDIT documents that they created. No individual should even be aware of the existence of another Institution--that should all be completely hidden. I have written a Django/Python class that would facilitate this, but every document regarding authentication that I have read requires that I use the User object. Is this just a limitation of Django, or is there a way to do this? If there is a way, how can I get my own "Individual" class details attached to the "request" objects so I can validate the things I should be showing the users?
[ "What you're looking for is authorization, not authentication. Django's built-in authorization system is fairly crude, as you've discovered. You'll need something like django-authority if you want a more complete solution.\n", "The auth module is typically used to cover authentication cases.\nGives you groups (Institutions), Users (Individuals) and permissions.\nUsing these features you can perform checking if a user is a member of a group or owns a doc before allowing them to see or edit the doc.\nhttp://docs.djangoproject.com/en/dev/topics/auth/\nIf you need to go beyond the typical use case, supporting LDAP for example, then you can look at writing your own authentication backend. \nhttp://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources\n", "In general, if you need to attach more information to the builtin User model, you would create new model which subclasses models.Model (not User), and identify it in settings as AUTH_PROFILE_MODULE. You can get the appropriate instance of your model from a user by calling user.get_profile(). (see http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users).\nThis is generally useful for adding extra fields to User such as address, contact information, etc. While it would be possible to use this for your authentication needs, you'd most likely be better off using the built in groups, or a more comprehensive solution like django-authority as others have mentioned. I've included this answer only because it seems to be what you were asking for (a way to attach a class to User), but not really what you need (authorization).\n" ]
[ 3, 1, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0003050063_authentication_django_python.txt
Q: Python Attributes and Inheritance Say I have the folowing code: class Class1(object): def __init__(self): self.my_attr = 1 self.my_other_attr = 2 class Class2(Class1): def __init__(self): super(Class1,self).__init__() Why does Class2 not inherit the attributes of Class1? A: You used super wrong, change it to super(Class2, self).__init__() Basically you tell super to look above the given class, so if you give Class1 then that __init__ method is never called. A: Because you're giving super the wrong class. It should be: class Class2(Class1): def __init__(self): super(Class2,self).__init__()
Python Attributes and Inheritance
Say I have the folowing code: class Class1(object): def __init__(self): self.my_attr = 1 self.my_other_attr = 2 class Class2(Class1): def __init__(self): super(Class1,self).__init__() Why does Class2 not inherit the attributes of Class1?
[ "You used super wrong, change it to\nsuper(Class2, self).__init__()\n\nBasically you tell super to look above the given class, so if you give Class1 then that __init__ method is never called.\n", "Because you're giving super the wrong class. It should be:\nclass Class2(Class1):\n\n def __init__(self):\n super(Class2,self).__init__()\n\n" ]
[ 10, 4 ]
[]
[]
[ "attributes", "inheritance", "python" ]
stackoverflow_0003053256_attributes_inheritance_python.txt
Q: How to read watermarks with Python? Is there any way to read metadata - watermarks from image files with Python? A: If by watermark you mean some "signature" image content added to an image in order to mark it, then no. Such a watermark is merged with the original image and thus an integral part of it. If you mean meta-data info then yes, this can be read: but you don't specify whether you mean programmatically, or what language or stack you're using or would like to use.
How to read watermarks with Python?
Is there any way to read metadata - watermarks from image files with Python?
[ "If by watermark you mean some \"signature\" image content added to an image in order to mark it, then no. Such a watermark is merged with the original image and thus an integral part of it. If you mean meta-data info then yes, this can be read: but you don't specify whether you mean programmatically, or what language or stack you're using or would like to use.\n" ]
[ 3 ]
[]
[]
[ "python", "watermark" ]
stackoverflow_0003053480_python_watermark.txt
Q: multiple custom app in django I want to have two custom made app dealing with two different tasks. i have a page(template) where the data from the both app come together. how to deploy url for that, in the common urls.py so that the two app work together. how to integrate the views from both app to return data to same template simultaneously. is that possible? I found these situations in django books, but they have one custom made app and other one is built-in app. the apps are integrated in special way. can u help to solve my problem with 2 custom app. A: You'll need to be a bit more specific. There's nothing magical about an app in Django - it's just a collection of models and views. If you need access to some of the models from one app in another app, just import them and use them as normal.
multiple custom app in django
I want to have two custom made app dealing with two different tasks. i have a page(template) where the data from the both app come together. how to deploy url for that, in the common urls.py so that the two app work together. how to integrate the views from both app to return data to same template simultaneously. is that possible? I found these situations in django books, but they have one custom made app and other one is built-in app. the apps are integrated in special way. can u help to solve my problem with 2 custom app.
[ "You'll need to be a bit more specific. There's nothing magical about an app in Django - it's just a collection of models and views. If you need access to some of the models from one app in another app, just import them and use them as normal.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003053442_django_python.txt
Q: Beginner questions regarding Python classes I am new to Python so please don't flame me if I ask something too noobish :) 1. Consider I have a class: class Test: def __init__(self, x, y): self.x = x self.y = y def wow(): print 5 * 5 Now I try to create an object of the class: x = Test(3, 4) This works as expected. However, when I try to call the method wow(), it returns an error, which is fixed by changing wow() to: def wow(self) Why do I need to include self and if I don't, what does the method mean?2. In the definition of __init__: def __init__(self, x, y): self.x = x self.y = y Why do I need to declare x and y, when I can do this: def __init__(self): self.x = x self.y = y I hope I am being clear... Thanks for your time. A: If you do that : def __init__(self): self.x = x self.y = y you assign the gobal vars x and y (it they exists ) to your instance with : def __init__(self, x, y): self.x = x self.y = y you assign what you give as parameter to the constructor and that is a lot more flexible :-) A: The instance reference in Python is explicit. That way it can be manipulated by e.g. decorators before finally being passed to the method. We need to declare x and y as arguments to the function so that we can use their names within the function, bound to the arguments passed in the corresponding function call. A: Just to be clear Why do I need to declare x and y, when I can do this: def __init__(self): self.x = x self.y = y This ^ will only work if x and y can be found at runtime - if they haven't been passed in then they must have been set elsewhere (globally) or it will generate an error. >>> class c: def __init__(self): self.x = x >>> x = 1 >>> q = c() >>> q.x 1 >>> del x >>> q.x 1 >>> w = c() Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> w = c() File "<pyshell#14>", line 3, in __init__ self.x = x NameError: global name 'x' is not defined >>> >>> w = c(2) Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> w = c(2) TypeError: __init__() takes exactly 1 argument (2 given) This is why you want / need to specify them as parameters - it might work with the global lookup but it would probably violate the "principle of least astonishment" A: self is a "magic" name - it can really be anything, but self is used for consistency and clarity. To answer your question, each class method/function requires an explicit reference to the class as the first parameter. Using Ipython: In [66]: class Test: ....: def __init__(self): ....: pass ....: def wow(self): ....: print self ....: ....: In [67]: x = Test() In [68]: x.wow() <__main__.Test instance at 0x0159FDF0> Your second example won't actually work unless you already have an x and y in your namespace. For instance, if you defined your class: class Test: def __init__(self): self.x = x self.y = y and tried x = Test() it will throw a NameError. However if you write: x = 3 y = 4 test = Test() then it will work. However, it's not a good idea to do such a thing. For the reason why read line 2: In [72]: import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! A: In Python, methods should always take "one extra" argument, which is the reference to the instance the method is being called on. This is automatic in other languages such as Java, C#, etc. but Python is verbose about it. That doesn't make sense. Where are x and y in that example? If you want the constructor to take two arguments which populate the object, define it as such. Otherwise, you're doing something else. A: Python is different from languages like C++ and Java in that the object instance reference is passed explicitly. That is, if you have an object which is an instance of the class and you want to invoke a method that operates on that instance (e.g., reads its fields), you use the self references as the object. In c++ and Java, you have an implicit "this" reference that is present in the compiled version of your program but not in the source code. You use the static keyword to make it into a class method that does not have a "this".
Beginner questions regarding Python classes
I am new to Python so please don't flame me if I ask something too noobish :) 1. Consider I have a class: class Test: def __init__(self, x, y): self.x = x self.y = y def wow(): print 5 * 5 Now I try to create an object of the class: x = Test(3, 4) This works as expected. However, when I try to call the method wow(), it returns an error, which is fixed by changing wow() to: def wow(self) Why do I need to include self and if I don't, what does the method mean?2. In the definition of __init__: def __init__(self, x, y): self.x = x self.y = y Why do I need to declare x and y, when I can do this: def __init__(self): self.x = x self.y = y I hope I am being clear... Thanks for your time.
[ "If you do that :\ndef __init__(self):\n self.x = x\n self.y = y\n\nyou assign the gobal vars x and y (it they exists ) to your instance\nwith :\ndef __init__(self, x, y):\n self.x = x\n self.y = y\n\nyou assign what you give as parameter to the constructor\nand that is a lot more flexible :-)\n", "The instance reference in Python is explicit. That way it can be manipulated by e.g. decorators before finally being passed to the method.\nWe need to declare x and y as arguments to the function so that we can use their names within the function, bound to the arguments passed in the corresponding function call.\n", "Just to be clear\n\nWhy do I need to declare x and y, when\n I can do this:\n\ndef __init__(self):\n self.x = x\n self.y = y\n\nThis ^ will only work if x and y can be found at runtime - if they haven't been passed in then they must have been set elsewhere (globally) or it will generate an error.\n>>> class c:\n def __init__(self):\n self.x = x\n\n>>> x = 1\n>>> q = c()\n>>> q.x\n1\n>>> del x\n>>> q.x\n1\n>>> w = c()\n\nTraceback (most recent call last):\n File \"<pyshell#24>\", line 1, in <module>\n w = c()\n File \"<pyshell#14>\", line 3, in __init__\n self.x = x\nNameError: global name 'x' is not defined\n>>> \n>>> w = c(2)\n\nTraceback (most recent call last):\n File \"<pyshell#19>\", line 1, in <module>\n w = c(2)\nTypeError: __init__() takes exactly 1 argument (2 given)\n\nThis is why you want / need to specify them as parameters - it might work with the global lookup but it would probably violate the \"principle of least astonishment\"\n", "self is a \"magic\" name - it can really be anything, but self is used for consistency and clarity. To answer your question, each class method/function requires an explicit reference to the class as the first parameter. Using Ipython:\nIn [66]: class Test:\n ....: def __init__(self):\n ....: pass\n ....: def wow(self):\n ....: print self\n ....:\n ....:\n\nIn [67]: x = Test()\n\nIn [68]: x.wow()\n<__main__.Test instance at 0x0159FDF0>\n\nYour second example won't actually work unless you already have an x and y in your namespace.\nFor instance, if you defined your class:\nclass Test:\n def __init__(self):\n self.x = x\n self.y = y\n\nand tried\nx = Test()\n\nit will throw a NameError.\nHowever if you write:\nx = 3\ny = 4\ntest = Test()\n\nthen it will work. However, it's not a good idea to do such a thing. For the reason why read line 2:\nIn [72]: import this\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n\n", "\nIn Python, methods should always take \"one extra\" argument, which is the reference to the instance the method is being called on. This is automatic in other languages such as Java, C#, etc. but Python is verbose about it.\nThat doesn't make sense. Where are x and y in that example? If you want the constructor to take two arguments which populate the object, define it as such. Otherwise, you're doing something else.\n\n", "Python is different from languages like C++ and Java in that the object instance reference is passed explicitly.\nThat is, if you have an object which is an instance of the class and you want to invoke a method that operates on that instance (e.g., reads its fields), you use the self references as the object.\nIn c++ and Java, you have an implicit \"this\" reference that is present in the compiled version of your program but not in the source code. You use the static keyword to make it into a class method that does not have a \"this\".\n" ]
[ 4, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003053680_python.txt
Q: adding space in an output file with out having to read the entire thing first Question: How do you write data to an already existing file at the beginning of the file with out writing over what's already there and with out reading the entire file into memory? (e.g. prepend) Info: I'm working on a project right now where the program frequently dumps data into a file. this file will very quickly balloon up to 3-4gb. I'm running this simulation on a computer with only 768mb of ram. pulling all that data to the ram over and over will be a great pain and a huge waste of time. The simulation already takes long enough to run as it is. The file is structured such that the number of dumps it makes is listed at the beginning with just a simple value, like 6. each time the program makes a new dump I want that to be incremented, so now it's 7. the problem lies with the 10th, 100th, 1000th, and so dump. the program will enter the 10 just fine, but remove the first letter of the next line: "9\n580,2995,2083,028\n..." "10\n80,2995,2083,028\n..." obviously, the difference between 580 and 80 in this case is significant. I can't lose these values. so i need a way to add a little space in there so that I can add in this new data without losing my data or having to pull the entire file up and then rewrite it. Basically what I'm looking for is a kind of prepend function. something to add data to the beginning of a file instead of the end. Programmed in Python ~n A: See the answers to this question: How do I modify a text file in Python? Summary: you can't do it without reading the file in (this is due to how the operating system works, rather than a Python limitation) A: It's not addressing your original question, but here are some possible workarounds: Use SQLite (it's bundled with your Python) Use a fancier database, either RDBMS or NoSQL Just track the number of dumps in a different text file The first couple of options are a little more work up front, but provide more flexibility. The last option is the easiest solution to your current problem. A: You could quite easily create an new file, output the data you wish to prepend to that file and then copy the content of the existing file and append it to the new one, then rename. This would prevent having to read the whole file if that is the primary issue.
adding space in an output file with out having to read the entire thing first
Question: How do you write data to an already existing file at the beginning of the file with out writing over what's already there and with out reading the entire file into memory? (e.g. prepend) Info: I'm working on a project right now where the program frequently dumps data into a file. this file will very quickly balloon up to 3-4gb. I'm running this simulation on a computer with only 768mb of ram. pulling all that data to the ram over and over will be a great pain and a huge waste of time. The simulation already takes long enough to run as it is. The file is structured such that the number of dumps it makes is listed at the beginning with just a simple value, like 6. each time the program makes a new dump I want that to be incremented, so now it's 7. the problem lies with the 10th, 100th, 1000th, and so dump. the program will enter the 10 just fine, but remove the first letter of the next line: "9\n580,2995,2083,028\n..." "10\n80,2995,2083,028\n..." obviously, the difference between 580 and 80 in this case is significant. I can't lose these values. so i need a way to add a little space in there so that I can add in this new data without losing my data or having to pull the entire file up and then rewrite it. Basically what I'm looking for is a kind of prepend function. something to add data to the beginning of a file instead of the end. Programmed in Python ~n
[ "See the answers to this question:\nHow do I modify a text file in Python?\nSummary: you can't do it without reading the file in (this is due to how the operating system works, rather than a Python limitation)\n", "It's not addressing your original question, but here are some possible workarounds:\n\nUse SQLite (it's bundled with your Python)\nUse a fancier database, either RDBMS or NoSQL\nJust track the number of dumps in a different text file\n\nThe first couple of options are a little more work up front, but provide more flexibility. The last option is the easiest solution to your current problem.\n", "You could quite easily create an new file, output the data you wish to prepend to that file and then copy the content of the existing file and append it to the new one, then rename.\nThis would prevent having to read the whole file if that is the primary issue.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "append", "file", "prepend", "python" ]
stackoverflow_0003053875_append_file_prepend_python.txt
Q: Using Python: How can I telnet into a server and then from that connection telnet into a second server? I am able to establish the initial telnet session. But from this session I need to create a second. Basically I can not telnet directly to the device I need to access. Interactively this is not an issue but I am attempting to setup an automated test using python. Does anyone know who to accomplish this? A: After establishing the first connection, just write the same telnet command you use manually to that connection. A: If you log in from A to B to C, do you need the console input from A to go to C ? If not, it is fairly straightforward, as you can execute commands on the second server to connect to the third. I do something like that using SSH, where I have paramiko and scripts installed on both A and B. A logs in to B and executes a command to start a python script on B which then connects to C and does whatever.
Using Python: How can I telnet into a server and then from that connection telnet into a second server?
I am able to establish the initial telnet session. But from this session I need to create a second. Basically I can not telnet directly to the device I need to access. Interactively this is not an issue but I am attempting to setup an automated test using python. Does anyone know who to accomplish this?
[ "After establishing the first connection, just write the same telnet command you use manually to that connection.\n", "If you log in from A to B to C, do you need the console input from A to go to C ?\nIf not, it is fairly straightforward, as you can execute commands on the second server to connect to the third.\nI do something like that using SSH, where I have paramiko and scripts installed on both A and B. A logs in to B and executes a command to start a python script on B which then connects to C and does whatever.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "telnet", "telnetlib" ]
stackoverflow_0003054086_python_telnet_telnetlib.txt
Q: Python execution order using C module I'm trying to learn python and have encountered some strange behaviour. I am experimenting with ctypes and a self-made (very simple) DLL. This is Python script I'm trying to run: from ctypes import * myLib = CDLL("libDlltest") myLib.hello() myLib.goodbye() print 'I am a line' myLib.goodbye() I've configured eclipse according to build the library according to this guide, and when it didn't work I built it in cygwin with gcc. hello() and goodbye() are implemented as EXPORT void hello(void) { printf ("Hello\n"); } EXPORT void goodbye(void) { puts ("Goodbye"); } (Where EXPORT is a macro that you can read more about in the above guide) Nevertheless, it starts getting weird when the output I get from the program is: I am a line Hello Goodbye Goodbye In case you didn't notice, the printouts are not in the correct order. The text printed from the library functions appears after or right before the program finishes executing, and the text printed by the python 'print' appears first, despite being called second. I can't imagine this being the intended behaviour. I'm probably the one doing something wrong here anyway, so: What could I be doing wrong? Is there any way to explain this behaviour? A: It looks like Python's stdout is buffered independently from C's stdout. You should try calling flush() on them to force them to write their data.
Python execution order using C module
I'm trying to learn python and have encountered some strange behaviour. I am experimenting with ctypes and a self-made (very simple) DLL. This is Python script I'm trying to run: from ctypes import * myLib = CDLL("libDlltest") myLib.hello() myLib.goodbye() print 'I am a line' myLib.goodbye() I've configured eclipse according to build the library according to this guide, and when it didn't work I built it in cygwin with gcc. hello() and goodbye() are implemented as EXPORT void hello(void) { printf ("Hello\n"); } EXPORT void goodbye(void) { puts ("Goodbye"); } (Where EXPORT is a macro that you can read more about in the above guide) Nevertheless, it starts getting weird when the output I get from the program is: I am a line Hello Goodbye Goodbye In case you didn't notice, the printouts are not in the correct order. The text printed from the library functions appears after or right before the program finishes executing, and the text printed by the python 'print' appears first, despite being called second. I can't imagine this being the intended behaviour. I'm probably the one doing something wrong here anyway, so: What could I be doing wrong? Is there any way to explain this behaviour?
[ "It looks like Python's stdout is buffered independently from C's stdout. You should try calling flush() on them to force them to write their data.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003054077_ctypes_python.txt
Q: defining precision in python(2.6) division from future import division To perform a division in which I need some percision. However, it gives a long number, like: 1.876543820098765 I only need the the first two numbers after "." => 1.87 How can I do that? A: "%0.2f" % yournumber As you said you don't want a rounded number, you might want to try def twoDigits(x): return int(100*x)/100.0 A: The number are stored as binary floating point. If you need to show just two digits, you can turn the float into a string and control the number of digits displayed using printf like syntax. mystring = "%.2f" % (x/y) This will limit the string to have only 2 digits after the decimal point. if x/y = 1.876543820098765 mystring = "1.88" A: f = 1.876543820098765 print f print round(f, 2) >> 1.8765438201 >> 1.88
defining precision in python(2.6) division
from future import division To perform a division in which I need some percision. However, it gives a long number, like: 1.876543820098765 I only need the the first two numbers after "." => 1.87 How can I do that?
[ "\"%0.2f\" % yournumber\n\nAs you said you don't want a rounded number, you might want to try\ndef twoDigits(x):\n return int(100*x)/100.0\n\n", "The number are stored as binary floating point. If you need to show just two digits, you can turn the float into a string and control the number of digits displayed using printf like syntax.\nmystring = \"%.2f\" % (x/y)\n\nThis will limit the string to have only 2 digits after the decimal point.\nif x/y = 1.876543820098765\nmystring = \"1.88\"\n", "f = 1.876543820098765\nprint f\nprint round(f, 2)\n\n>> 1.8765438201\n>> 1.88\n\n" ]
[ 4, 2, 1 ]
[]
[]
[ "floating_point", "python", "string_formatting" ]
stackoverflow_0003054030_floating_point_python_string_formatting.txt
Q: Repoze.bfg or Grok I am about to take the head long plunge into Zope land and am wondering which framework would fit my needs better. I have some experience toying around with django and the primary reason I am switching to a zope-based framework is ZPT and also needing to occasionally do things with Plone. Both seem to be well run projects I am mainly wondering which would have the better learning overlap with Plone? Thanks in advance! A: BFG doesn't have very much to do with Zope, except: it uses some Zope libraries internally. it uses a variant of ZPT as its built-in templating language. it uses some concepts, such as traversal, that will be familiar to Zope people. If you know Zope 3 very well, and you like it, you'll like Grok. If you want a framework maybe a bit more like Pylons, but slightly cleaner, and which uses some Zope technologies and concepts, you'll like BFG. A: So Repoze.bfg advertises "pay for only what you eat", meaning that you can pick and choose what portions of the framework you need to include, and you don't have extra cruft in your app. It looks like you can mix Plone and Repoze.bfg: Here's a link to a Plone 2008 coference talk, and the templating language matches ZPT too. But, it's very possible that the community around Zope is bigger, and certainly has been established longer: it may just depend on your confort level. You might want to write a small app in each and see how you feel.
Repoze.bfg or Grok
I am about to take the head long plunge into Zope land and am wondering which framework would fit my needs better. I have some experience toying around with django and the primary reason I am switching to a zope-based framework is ZPT and also needing to occasionally do things with Plone. Both seem to be well run projects I am mainly wondering which would have the better learning overlap with Plone? Thanks in advance!
[ "BFG doesn't have very much to do with Zope, except:\n\nit uses some Zope libraries internally.\nit uses a variant of ZPT as its built-in templating language.\nit uses some concepts, such as traversal, that will be familiar to Zope people.\n\nIf you know Zope 3 very well, and you like it, you'll like Grok. If you want a framework maybe a bit more like Pylons, but slightly cleaner, and which uses some Zope technologies and concepts, you'll like BFG.\n", "So Repoze.bfg advertises \"pay for only what you eat\", meaning that you can pick and choose what portions of the framework you need to include, and you don't have extra cruft in your app.\nIt looks like you can mix Plone and Repoze.bfg: Here's a link to a Plone 2008 coference talk, and the templating language matches ZPT too.\nBut, it's very possible that the community around Zope is bigger, and certainly has been established longer: it may just depend on your confort level. You might want to write a small app in each and see how you feel.\n" ]
[ 3, 0 ]
[]
[]
[ "plone", "python", "zope" ]
stackoverflow_0003049431_plone_python_zope.txt
Q: Add string to another string I currently encountered a problem: I want to handle adding strings to other strings very efficiently, so I looked up many methods and techniques, and I figured the "fastest" method. But I quite can not understand how it actually works: def method6(): return ''.join([`num` for num in xrange(loop_count)]) From source (Method 6) Especially the ([`num` for num in xrange(loop_count)]) confused me totally. A: it's a list comprehension, that uses backticks for repr conversion. Don't do this. Backticks are deprecated and removed in py3k and more efficient and pythonic way is not to build intermediate list at all, but to use generator expression: ''.join(str(num) for num in xrange(loop_count)) # use range in py3k A: That bit in the brackets is a list comprehension, arguably one of the most powerful elements of Python. It produces a list from iteration. You may want to look up its documentation. The use of backticks to convert num to a string is not suggestible - try str(num) or some such instead. join() is a method of the string class. It takes a list of strings and return a single string consisting of each component string separated by "self" (aka the calling string). The trick here is that join() is being called directly from the string literal '', which is allowed in Python. What this code will to is produce a string consisting of the string form of each element of xrange(loop_count) with no separation. A: xrange() is a faster (written in C) version of range(). Backtick notation -- num, coerces a variable to a string, and is the same as str(num). [x for x in y] is called a list comprehension, and is basically an one-liner for loop that returns a list as its result. So all together, your code's semantically equivalent to the following, but faster, because list comprehensions and xrange are faster than for loops and range: z = [] for i in range(loop_count): z.append(str(i)) return "".join(z) A: First of all: while this code is still correct in the 2.x series of Python, it a bit confusing and can be written differently: def method6a(): return ''.join(str(num) for num in xrange(loop_count)) In Python 2.x, the backticks can be used instead of the repr function. The expression within the square brackets [] is a list comprehension. In case you are new to list comprehensions: they work like a combination of a loop and a list append-statement, only that you don't have to invent a name for a variable: Those two are equivalent: a = [repr(num) for num in xrange(loop_count)] # <=> a = [] for num in xrange(loop_count): a.append(repr(num)) As a result, the list comprehension will contain a list of all numbers from 0 to loop_count (exclusively). Finally, string.join(iterable) will use the contents of string concatenate all of the strings in iterable, using string as the seperator between each element. If you use the empty string as the seperator, then all elements are concatenated without anything between them - this is exactly what you wanted: a concatenation of all of the numbers from 0 to loop_count. As for my modifications: I used str instead of repr because the result is the same for all ints and it is easier to read. I am using a generator expression instead of a list comprehension because the list built by the list comprehension is unnecessary and gets garbage collected anyway. Generator expressions are iterable, but they don't need to store all elements of the list. Of course, if you already have a list of strings, then simply pass the list to the join. Generally, the ''.join(iterable) idiom is well understood by most Python programmers to mean "string concatenation of any list of strings", so understandability shouldn't be an issue.
Add string to another string
I currently encountered a problem: I want to handle adding strings to other strings very efficiently, so I looked up many methods and techniques, and I figured the "fastest" method. But I quite can not understand how it actually works: def method6(): return ''.join([`num` for num in xrange(loop_count)]) From source (Method 6) Especially the ([`num` for num in xrange(loop_count)]) confused me totally.
[ "it's a list comprehension, that uses backticks for repr conversion. Don't do this. Backticks are deprecated and removed in py3k and more efficient and pythonic way is not to build intermediate list at all, but to use generator expression:\n''.join(str(num) for num in xrange(loop_count)) # use range in py3k\n\n", "That bit in the brackets is a list comprehension, arguably one of the most powerful elements of Python. It produces a list from iteration. You may want to look up its documentation. The use of backticks to convert num to a string is not suggestible - try str(num) or some such instead.\njoin() is a method of the string class. It takes a list of strings and return a single string consisting of each component string separated by \"self\" (aka the calling string). The trick here is that join() is being called directly from the string literal '', which is allowed in Python. What this code will to is produce a string consisting of the string form of each element of xrange(loop_count) with no separation.\n", "xrange() is a faster (written in C) version of range().\nBacktick notation -- num, coerces a variable to a string, and is the same as str(num).\n[x for x in y] is called a list comprehension, and is basically an one-liner for loop that returns a list as its result. So all together, your code's semantically equivalent to the following, but faster, because list comprehensions and xrange are faster than for loops and range:\nz = []\nfor i in range(loop_count):\n z.append(str(i))\nreturn \"\".join(z)\n\n", "First of all: while this code is still correct in the 2.x series of Python, it a bit confusing and can be written differently:\ndef method6a():\n return ''.join(str(num) for num in xrange(loop_count))\n\nIn Python 2.x, the backticks can be used instead of the repr function. The expression within the square brackets [] is a list comprehension. In case you are new to list comprehensions: they work like a combination of a loop and a list append-statement, only that you don't have to invent a name for a variable:\nThose two are equivalent:\na = [repr(num) for num in xrange(loop_count)]\n# <=>\na = []\nfor num in xrange(loop_count):\n a.append(repr(num))\n\nAs a result, the list comprehension will contain a list of all numbers from 0 to loop_count (exclusively).\nFinally, string.join(iterable) will use the contents of string concatenate all of the strings in iterable, using string as the seperator between each element. If you use the empty string as the seperator, then all elements are concatenated without anything between them - this is exactly what you wanted: a concatenation of all of the numbers from 0 to loop_count.\nAs for my modifications:\n\nI used str instead of repr because the result is the same for all ints and it is easier to read.\nI am using a generator expression instead of a list comprehension because the list built by the list comprehension is unnecessary and gets garbage collected anyway. Generator expressions are iterable, but they don't need to store all elements of the list. Of course, if you already have a list of strings, then simply pass the list to the join.\n\nGenerally, the ''.join(iterable) idiom is well understood by most Python programmers to mean \"string concatenation of any list of strings\", so understandability shouldn't be an issue.\n" ]
[ 6, 2, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003054215_python_string.txt
Q: Best strategy for dealing with incomplete lines of data from a file I use the following block of code to read lines out of a file 'f' into a nested list: for data in f: clean_data = data.rstrip() data = clean_data.split('\t') t += [data[0]] strmat += [data[1:]] Sometimes, however, the data is incomplete and a row may look like this: ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0'] It puts a spanner in the works because I would like Python to implicitly cast my list as floats but the empty fields '' cause it to be cast as an array of strings (dtype: s12). I could start a second 'if' statement and convert all empty fields into NULL (since 0 is wrong in this instance) but I was unsure whether this was best. Is this the best strategy of dealing with incomplete data? Should I edit the stream or do it post-hoc? A: The way how you should deal with incomplete values depends on the context of your application (which you haven't mentioned yet). For example, you can simply ignore missing values >>> l = ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0'] >>> filter(bool, l) # remove empty values ['955.159', '62.8168', '29', '30', '0', '0'] >>> map(float, filter(bool, l)) # remove empty values and convert the rest to floats [955.15899999999999, 62.816800000000001, 29.0, 30.0, 0.0, 0.0] Or alternatively, you might want to replace them with NULL as you mentioned: >>> map(lambda x: x or 'NULL', l) ['955.159', '62.8168', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', '29', '30', '0', '0'] As you can see, there are many different strategies of dealing with incomplete data. Anyway, the example snippets here might help you to choose the right one for your task. And as you can see, I prefer the functional programming like build-ins for doing stuff like this, because it's often the shortest and easiest way to do it (and I don't think there will be any noticeable differences in the execution time).
Best strategy for dealing with incomplete lines of data from a file
I use the following block of code to read lines out of a file 'f' into a nested list: for data in f: clean_data = data.rstrip() data = clean_data.split('\t') t += [data[0]] strmat += [data[1:]] Sometimes, however, the data is incomplete and a row may look like this: ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0'] It puts a spanner in the works because I would like Python to implicitly cast my list as floats but the empty fields '' cause it to be cast as an array of strings (dtype: s12). I could start a second 'if' statement and convert all empty fields into NULL (since 0 is wrong in this instance) but I was unsure whether this was best. Is this the best strategy of dealing with incomplete data? Should I edit the stream or do it post-hoc?
[ "The way how you should deal with incomplete values depends on the context of your application (which you haven't mentioned yet).\nFor example, you can simply ignore missing values\n>>> l = ['955.159', '62.8168', '', '', '', '', '', '', '', '', '', '', '', '', '', '29', '30', '0', '0']\n>>> filter(bool, l) # remove empty values\n['955.159', '62.8168', '29', '30', '0', '0']\n>>> map(float, filter(bool, l)) # remove empty values and convert the rest to floats\n[955.15899999999999, 62.816800000000001, 29.0, 30.0, 0.0, 0.0]\n\nOr alternatively, you might want to replace them with NULL as you mentioned:\n>>> map(lambda x: x or 'NULL', l)\n['955.159', '62.8168', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', '29', '30', '0', '0']\n\nAs you can see, there are many different strategies of dealing with incomplete data. Anyway, the example snippets here might help you to choose the right one for your task. And as you can see, I prefer the functional programming like build-ins for doing stuff like this, because it's often the shortest and easiest way to do it (and I don't think there will be any noticeable differences in the execution time).\n" ]
[ 1 ]
[]
[]
[ "arrays", "file", "list", "nested", "python" ]
stackoverflow_0003054013_arrays_file_list_nested_python.txt
Q: Django : In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response? In case of views that contain login or logout, this sessionid is different from the one submitted in request's Coockie header. I need to retrieve it before returning response for some purpose. How can I do this ? A: I think you should be able to access this via request.session.session_key
Django : In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response?
In case of views that contain login or logout, this sessionid is different from the one submitted in request's Coockie header. I need to retrieve it before returning response for some purpose. How can I do this ?
[ "I think you should be able to access this via request.session.session_key\n" ]
[ 1 ]
[]
[]
[ "cookies", "django", "django_authentication", "python" ]
stackoverflow_0003053923_cookies_django_django_authentication_python.txt
Q: How do I implement a dictionary "with a Python tuple" as key in C++? I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on earth do I write something similar in C++? Maybe my algorithm is horrendous and there is some way I can make it faster without resorting to C++? The whole algorithm below for clarity's sake. The dictionary "post_score" is the issue. def get_best_match_best(search_text, posts): """ Find the best matches between a search query "search_text" and any of the strings in "posts". @param search_text: Query to find an appropriate match with in posts. @type search_text: string @param posts: List of candidates to match with target text. @type posts: [cl_post.Post] @return: Best matches of the candidates found in posts. The posts are ordered according to their rank. First post in list has best match and so on. @returntype: [cl_post.Post] """ from math import log search_words = separate_words(search_text) total_number_of_hits = {} post_score = {} post_size = {} for search_word in search_words: total_number_of_hits[search_word] = 0.0 for post in posts: post_score[(post, search_word)] = 0.0 post_words = separate_words(post.text) post_size[post] = len(post_words) for post_word in post_words: possible_match = abs(len(post_word) - len(search_word)) <= 2 if possible_match: score = calculate_score(search_word, post_word) post_score[(post, search_word)] += score if score >= 1.0: total_number_of_hits[search_word] += 1.0 log_of_number_of_posts = log(len(posts)) matches = [] for post in posts: rank = 0.0 for search_word in search_words: rank += post_score[(post, search_word)] * \ (log_of_number_of_posts - log(1.0 + total_number_of_hits[search_word])) matches.append((rank / post_size[post], post)) matches.sort(reverse=True) return [post[1] for post in matches] A: map<pair<..., string>, ...> if you're hellbent on using C++ for this. A: for once, you're calling separate_words(post.text) for every search_word in search_words. You should call separate_words only once for each post in posts. That is, rather than: for search_word in search_words: for post in posts: # do heavy work you should instead have: for post in posts: # do the heavy works for search_word in search_words: ... If, as I suspected, that separate_words do a lot of string manipulations, don't forget that string manipulations is relatively expensive in python since string is immutable. Another improvement you can do, is that you don't have to compare every word in search_words with every word in post_words. If you keep the search_words and post_words array sorted by word length, then you can use a sliding window technique. Basically, since search_word will only match a post_word if the difference in their length is less than 2, then you need only to check among the window of two lengths differences, thereby cutting down the number of words to check, e.g.: search_words = sorted(search_words, key=len) g_post_words = collections.defaultdict(list) # this can probably use list of list for post_word in post_words: g_post_words[len(post_word)].append(post_word) for search_word in search_words: l = len(search_word) # candidates = itertools.chain.from_iterable(g_post_words.get(m, []) for m in range(l - 2, l + 3)) candidates = itertools.chain(g_post_words.get(l - 2, []), g_post_words.get(l - 1, []), g_post_words.get(l , []), g_post_words.get(l + 1, []), g_post_words.get(l + 2, []) ) for post_word in candidates: score = calculate_score(search_word, post_word) # ... and the rest ... (this code probably won't work as is, it's just to illustrate the idea)
How do I implement a dictionary "with a Python tuple" as key in C++?
I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on earth do I write something similar in C++? Maybe my algorithm is horrendous and there is some way I can make it faster without resorting to C++? The whole algorithm below for clarity's sake. The dictionary "post_score" is the issue. def get_best_match_best(search_text, posts): """ Find the best matches between a search query "search_text" and any of the strings in "posts". @param search_text: Query to find an appropriate match with in posts. @type search_text: string @param posts: List of candidates to match with target text. @type posts: [cl_post.Post] @return: Best matches of the candidates found in posts. The posts are ordered according to their rank. First post in list has best match and so on. @returntype: [cl_post.Post] """ from math import log search_words = separate_words(search_text) total_number_of_hits = {} post_score = {} post_size = {} for search_word in search_words: total_number_of_hits[search_word] = 0.0 for post in posts: post_score[(post, search_word)] = 0.0 post_words = separate_words(post.text) post_size[post] = len(post_words) for post_word in post_words: possible_match = abs(len(post_word) - len(search_word)) <= 2 if possible_match: score = calculate_score(search_word, post_word) post_score[(post, search_word)] += score if score >= 1.0: total_number_of_hits[search_word] += 1.0 log_of_number_of_posts = log(len(posts)) matches = [] for post in posts: rank = 0.0 for search_word in search_words: rank += post_score[(post, search_word)] * \ (log_of_number_of_posts - log(1.0 + total_number_of_hits[search_word])) matches.append((rank / post_size[post], post)) matches.sort(reverse=True) return [post[1] for post in matches]
[ "map<pair<..., string>, ...> if you're hellbent on using C++ for this.\n", "for once, you're calling separate_words(post.text) for every search_word in search_words. You should call separate_words only once for each post in posts.\nThat is, rather than:\nfor search_word in search_words:\n for post in posts:\n # do heavy work\n\nyou should instead have:\nfor post in posts:\n # do the heavy works\n for search_word in search_words:\n ...\n\nIf, as I suspected, that separate_words do a lot of string manipulations, don't forget that string manipulations is relatively expensive in python since string is immutable.\nAnother improvement you can do, is that you don't have to compare every word in search_words with every word in post_words. If you keep the search_words and post_words array sorted by word length, then you can use a sliding window technique. Basically, since search_word will only match a post_word if the difference in their length is less than 2, then you need only to check among the window of two lengths differences, thereby cutting down the number of words to check, e.g.:\nsearch_words = sorted(search_words, key=len)\ng_post_words = collections.defaultdict(list) # this can probably use list of list\nfor post_word in post_words:\n g_post_words[len(post_word)].append(post_word)\n\nfor search_word in search_words:\n l = len(search_word)\n # candidates = itertools.chain.from_iterable(g_post_words.get(m, []) for m in range(l - 2, l + 3))\n candidates = itertools.chain(g_post_words.get(l - 2, []), \n g_post_words.get(l - 1, []), \n g_post_words.get(l , []),\n g_post_words.get(l + 1, []),\n g_post_words.get(l + 2, [])\n )\n for post_word in candidates:\n score = calculate_score(search_word, post_word)\n # ... and the rest ...\n\n(this code probably won't work as is, it's just to illustrate the idea)\n" ]
[ 3, 2 ]
[]
[]
[ "c++", "dictionary", "python" ]
stackoverflow_0003053956_c++_dictionary_python.txt
Q: Tkinter using a non-saved picture as an image I'm trying to grab a screenshot every 30 seconds and display it on my GUI, heres what I've got so far. Code: from Tkinter import * from PIL import ImageGrab window = Tk() box = (100,100,400,400) MyImage = ImageGrab.grab(box) MyPhotoImage = PhotoImage(file=MyImage) #I know this is where its going wrong, just not sure how to fix it PictureLabel = Label(window, image=MyPhotoImage) PictureLabel.pack() window.mainloop() Python doesnt like the fact I haven't saved the image, is there a possible way to do this without saving the image (not much point since its being renewed every 30 seconds) Its also not saving every 30 seconds yet, is there a simple way to do this without the program hanging? As I could just use a time.sleep(30) but the program would just freeze up for 30 seconds take a picture then freeze again. Thanks :) A: You should be able to use StringIO for this: import cStringIO fp = cStringIO.StringIO() MyImage.save(fp,'GIF') MyPhotoImage = PhotoImage(data=fp.getvalue()) EDITS Looks like I should read the docs a little closer. The PhotoImage data must be encoded to base64 from Tkinter import * from PIL import ImageGrab import cStringIO, base64 window = Tk() box = (100,100,500,500) MyImage = ImageGrab.grab(box) fp = cStringIO.StringIO() MyImage.save(fp,'GIF') MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) PictureLabel = Label(image=MyPhotoImage) PictureLabel.pack() PictureLabel.image = MyPhotoImage window.mainloop() A: tk images accept a "data" option, which allows you to specify image data encoded in base64. Also, PIL gives you ways to copy and paste image data. It should be possible to copy the data from MyImage to MyPhotoImage. Have you tried that?
Tkinter using a non-saved picture as an image
I'm trying to grab a screenshot every 30 seconds and display it on my GUI, heres what I've got so far. Code: from Tkinter import * from PIL import ImageGrab window = Tk() box = (100,100,400,400) MyImage = ImageGrab.grab(box) MyPhotoImage = PhotoImage(file=MyImage) #I know this is where its going wrong, just not sure how to fix it PictureLabel = Label(window, image=MyPhotoImage) PictureLabel.pack() window.mainloop() Python doesnt like the fact I haven't saved the image, is there a possible way to do this without saving the image (not much point since its being renewed every 30 seconds) Its also not saving every 30 seconds yet, is there a simple way to do this without the program hanging? As I could just use a time.sleep(30) but the program would just freeze up for 30 seconds take a picture then freeze again. Thanks :)
[ "You should be able to use StringIO for this:\nimport cStringIO\nfp = cStringIO.StringIO()\nMyImage.save(fp,'GIF')\nMyPhotoImage = PhotoImage(data=fp.getvalue())\n\nEDITS\nLooks like I should read the docs a little closer. The PhotoImage data must be encoded to base64\nfrom Tkinter import *\nfrom PIL import ImageGrab\nimport cStringIO, base64\n\nwindow = Tk()\n\nbox = (100,100,500,500)\nMyImage = ImageGrab.grab(box)\n\nfp = cStringIO.StringIO()\nMyImage.save(fp,'GIF') \n\nMyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) \nPictureLabel = Label(image=MyPhotoImage)\nPictureLabel.pack()\nPictureLabel.image = MyPhotoImage\n\nwindow.mainloop()\n\n", "tk images accept a \"data\" option, which allows you to specify image data encoded in base64. Also, PIL gives you ways to copy and paste image data. It should be possible to copy the data from MyImage to MyPhotoImage. Have you tried that?\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_imaging_library", "tkinter" ]
stackoverflow_0003052236_python_python_imaging_library_tkinter.txt
Q: Improving Python readability? I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects. However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read. For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing): if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this: if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me. A: Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python. A: I like to put blank lines around blocks to make control flow more obvious. For example: if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() A: You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea. A: Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more. If you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes. A: Perhaps the best thing would be to turn on "show whitespace" in your editor. Then you would have a visual indication of how far in each line is tabbed (usually a bunch of dots), and it will be more apparent when that changes. A: from __future__ import braces Need I say more? :) Seriously, PEP 8, 'Blank lines', §4 is the official way to do it.
Improving Python readability?
I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects. However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read. For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing): if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this: if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.
[ "Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.\n", "I like to put blank lines around blocks to make control flow more obvious. For example:\nif foo:\n bar = baz\n\n while bar not biz:\n bar = i_am_going_to_find_you_biz_i_swear_on_my_life()\n\ndid_i_not_warn_you_biz()\nmy_father_is_avenged()\n\n", "You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea.\n", "Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more.\nIf you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes.\n", "Perhaps the best thing would be to turn on \"show whitespace\" in your editor. Then you would have a visual indication of how far in each line is tabbed (usually a bunch of dots), and it will be more apparent when that changes.\n", "from __future__ import braces\n\nNeed I say more? :)\nSeriously, PEP 8, 'Blank lines', §4 is the official way to do it.\n" ]
[ 24, 15, 8, 7, 3, 0 ]
[ "I would look in to understanding more details about Python syntax. Often times if a piece of code looks odd, there usually is a better way to write it. For example, in the above example:\nbar = foo if baz else None\nwhile bar not biz:\n bar = i_am_going_to_find_you_biz_i_swear_on_my_life()\n\ndid_i_not_warn_you_biz()\nmy_father_is_avenged()\n\nWhile it is a small change, it might help the readability. Also, in all honesty, I've never used a while loop, so there is a good change you would end up with a nice concise list comprehension or for loop instead. ;)\n" ]
[ -1 ]
[ "python", "readability" ]
stackoverflow_0000051502_python_readability.txt
Q: Load globally accessible singleton on app start in Google App Engine using Python Using Google app engine, is it possible to initialize a globally accessible singleton on app startup? I have a large static tree structure that I need to use on every request and want to initialize it beforehand. The tree structure is too large (20+MB) to be put into Memcache and I am trying to figure out what other alternatives I have. EDIT: Just to add some clarity based on the answers I've received so far. I'm loading a dictionary of words into a trie/prefix tree structure. The trie is immutable as the dictionary of words is fixed. I'm generating anagrams based on an input string of characters, so one request may access a fair amount of the trie on a single request, possibly more the 1MB, however I'm not certain. Here's is the python structure that I'm loading the dictionary of words into as well. class Node(object): def __init__(self, letter='', final=False): self.letter = letter self.final = final self.children = {} def add(self, letters): node = self for index, letter in enumerate(letters): if letter not in node.children: node.children[letter] = Node(letter, index==len(letters)-1) node = node.children[letter] A: Each request might be served from a completely different process, on a different server, which might even be on a separate datacenter (hey, maybe in a different continent). There is nothing that's guaranteed to be "globally accessible" to the handlers of different requests to the same app except the datastore (even memcache's entries might disappear at any time if things get too busy: it's a cache, after all!-). Perhaps you can keep your "static tree structure" in a data file that you upload together with the application's code, and access it from disk in lieu of "initializing". Edit: as requested, here's a rough and ready example of the "lightweight class mapping tree into array" approach which I mentioned in a comment -- not tuned nor finely tested. I'm taking as the example a binary search tree with integer payloads and assuming that for some reason it's important to keep the exact structure in the "light" tree as in the "heavy" tree it represents. Even with these simplifications it's still a lot of code, but, here comes: import array import random def _doinsert(tree, payload): if tree is None: return HeavyTree(payload) tree.insert(payload) return tree class HeavyTree(object): def __init__(self, payload): self.payload = payload self.left = self.right = None def insert(self, other): if other <= self.payload: self.left = _doinsert(self.left, other) else: self.right = _doinsert(self.right, other) def walk(self): if self.left: for x in self.left.walk(): yield x yield self.payload if self.right: for x in self.right.walk(): yield x def walknodes(self): yield self if self.left: for x in self.left.walknodes(): yield x if self.right: for x in self.right.walknodes(): yield x data = [random.randint(0, 99) for _ in range(9)] print 'data: ', for x in data: print x, print theiter = iter(data) thetree = HeavyTree(next(theiter)) for x in theiter: thetree.insert(x) print print 'Heavy tree:' print 'nodes:', for x in thetree.walknodes(): print x.payload, print print 'inord:', for x in thetree.walk(): print x, print class LightTree(HeavyTree): def __init__(self, base, offset): self.base = base self.offset = offset @property def payload(self): return self.base[self.offset] @property def left(self): return self._astree(self.offset+1) @property def right(self): return self._astree(self.offset+2) def _astree(self, i): offset = self.base[i] if offset < 0: return None return LightTree(self.base, offset) def heavy_to_light(heavy): for i, node in enumerate(heavy.walknodes()): node.id = i * 3 base = array.array('l', (i+1) * 3 * [-1]) for node in heavy.walknodes(): base[node.id] = node.payload if node.left: base[node.id+1] = node.left.id if node.right: base[node.id+2] = node.right.id return LightTree(base, 0) print print 'Light tree:' light = heavy_to_light(thetree) print 'nodes:', for x in light.walknodes(): print x.payload, print print 'base :', for x in light.base: print x, print print 'inord:', for x in light.walk(): print x, print A typical run would show: data: 27 79 90 60 82 80 3 94 76 Heavy tree: nodes: 27 3 79 60 76 90 82 80 94 inord: 3 27 60 76 79 80 82 90 94 Light tree: nodes: 27 3 79 60 76 90 82 80 94 base : 27 3 6 3 -1 -1 79 9 15 60 -1 12 76 -1 -1 90 18 24 82 21 -1 80 -1 -1 94 -1 -1 inord: 3 27 60 76 79 80 82 90 94 variable in details every time, of course, since the data are being generated randomly. Maybe this sort of thing is just too cumbersome for anybody who didn't start with good old Fortran (and thus inevitably learned how to represent logical pointers as indices into an array), as I did back in EE school many decades ago;-). But loading such arrays from a file straight into memory is blazingly fast (compared to unpickling and the like)...!-) A: I think Google gives you 300MB of local memory for each instance that is running your project. So all you have to do is store the tree structure into a variable in some module. Whenever Google spins up a new process for your app, it will run the code to build your tree once, and then you can access it for future requests that are handled by that process. Just make sure that building the tree takes less than 30 seconds, because it has to happen within the time frame of whatever random request makes Google decide to spin up a new process. A: How much of this tree do you need to access on a single request? In what manner do you query it? Does it ever change? If it's immutable, you don't really need a 'singleton' - which implies mutability - just a way to access the data on each instance. Depending on how you need to access it, you could store it as a data file, a blob, or as data in the datastore. A: Memcache and the datastore are your best bets for truly global access across all your instances. However, a global variable can still be used to cache your data structure within each instance. Wouldn't a trie structure be pretty easy to break up into chunks such that each chunk will fit into memcache? Once you get your trie into memcache, anytime you access a chunk of the trie from memcache, you could store it in a global variable on that instance. Over the course of a few requests, you will build up a full copy of the trie on each instance that you have running. This is a bit complicated, but could ultimately give you the best performance.
Load globally accessible singleton on app start in Google App Engine using Python
Using Google app engine, is it possible to initialize a globally accessible singleton on app startup? I have a large static tree structure that I need to use on every request and want to initialize it beforehand. The tree structure is too large (20+MB) to be put into Memcache and I am trying to figure out what other alternatives I have. EDIT: Just to add some clarity based on the answers I've received so far. I'm loading a dictionary of words into a trie/prefix tree structure. The trie is immutable as the dictionary of words is fixed. I'm generating anagrams based on an input string of characters, so one request may access a fair amount of the trie on a single request, possibly more the 1MB, however I'm not certain. Here's is the python structure that I'm loading the dictionary of words into as well. class Node(object): def __init__(self, letter='', final=False): self.letter = letter self.final = final self.children = {} def add(self, letters): node = self for index, letter in enumerate(letters): if letter not in node.children: node.children[letter] = Node(letter, index==len(letters)-1) node = node.children[letter]
[ "Each request might be served from a completely different process, on a different server, which might even be on a separate datacenter (hey, maybe in a different continent). There is nothing that's guaranteed to be \"globally accessible\" to the handlers of different requests to the same app except the datastore (even memcache's entries might disappear at any time if things get too busy: it's a cache, after all!-).\nPerhaps you can keep your \"static tree structure\" in a data file that you upload together with the application's code, and access it from disk in lieu of \"initializing\".\nEdit: as requested, here's a rough and ready example of the \"lightweight class mapping tree into array\" approach which I mentioned in a comment -- not tuned nor finely tested. I'm taking as the example a binary search tree with integer payloads and assuming that for some reason it's important to keep the exact structure in the \"light\" tree as in the \"heavy\" tree it represents. Even with these simplifications it's still a lot of code, but, here comes:\nimport array\nimport random\n\ndef _doinsert(tree, payload):\n if tree is None: return HeavyTree(payload)\n tree.insert(payload)\n return tree\n\nclass HeavyTree(object):\n def __init__(self, payload):\n self.payload = payload\n self.left = self.right = None\n def insert(self, other):\n if other <= self.payload:\n self.left = _doinsert(self.left, other)\n else:\n self.right = _doinsert(self.right, other)\n def walk(self):\n if self.left:\n for x in self.left.walk(): yield x\n yield self.payload\n if self.right:\n for x in self.right.walk(): yield x\n def walknodes(self):\n yield self\n if self.left:\n for x in self.left.walknodes(): yield x\n if self.right:\n for x in self.right.walknodes(): yield x\n\ndata = [random.randint(0, 99) for _ in range(9)]\nprint 'data: ',\nfor x in data: print x,\nprint\ntheiter = iter(data)\nthetree = HeavyTree(next(theiter))\nfor x in theiter: thetree.insert(x)\n\nprint\nprint 'Heavy tree:'\nprint 'nodes:',\nfor x in thetree.walknodes(): print x.payload,\nprint\nprint 'inord:',\nfor x in thetree.walk(): print x,\nprint\n\nclass LightTree(HeavyTree):\n def __init__(self, base, offset):\n self.base = base\n self.offset = offset\n @property\n def payload(self):\n return self.base[self.offset]\n @property\n def left(self):\n return self._astree(self.offset+1)\n @property\n def right(self):\n return self._astree(self.offset+2)\n def _astree(self, i):\n offset = self.base[i]\n if offset < 0: return None\n return LightTree(self.base, offset)\n\ndef heavy_to_light(heavy):\n for i, node in enumerate(heavy.walknodes()):\n node.id = i * 3\n base = array.array('l', (i+1) * 3 * [-1])\n for node in heavy.walknodes():\n base[node.id] = node.payload\n if node.left: base[node.id+1] = node.left.id\n if node.right: base[node.id+2] = node.right.id\n return LightTree(base, 0)\n\nprint\nprint 'Light tree:'\nlight = heavy_to_light(thetree)\nprint 'nodes:',\nfor x in light.walknodes(): print x.payload,\nprint\nprint 'base :',\nfor x in light.base: print x,\nprint\nprint 'inord:',\nfor x in light.walk(): print x,\nprint\n\nA typical run would show:\ndata: 27 79 90 60 82 80 3 94 76\n\nHeavy tree:\nnodes: 27 3 79 60 76 90 82 80 94\ninord: 3 27 60 76 79 80 82 90 94\n\nLight tree:\nnodes: 27 3 79 60 76 90 82 80 94\nbase : 27 3 6 3 -1 -1 79 9 15 60 -1 12 76 -1 -1 90 18 24 82 21 -1 80 -1 -1 94 -1 -1\ninord: 3 27 60 76 79 80 82 90 94\n\nvariable in details every time, of course, since the data are being generated randomly.\nMaybe this sort of thing is just too cumbersome for anybody who didn't start with good old Fortran (and thus inevitably learned how to represent logical pointers as indices into an array), as I did back in EE school many decades ago;-). But loading such arrays from a file straight into memory is blazingly fast (compared to unpickling and the like)...!-)\n", "I think Google gives you 300MB of local memory for each instance that is running your project. So all you have to do is store the tree structure into a variable in some module.\nWhenever Google spins up a new process for your app, it will run the code to build your tree once, and then you can access it for future requests that are handled by that process. Just make sure that building the tree takes less than 30 seconds, because it has to happen within the time frame of whatever random request makes Google decide to spin up a new process.\n", "How much of this tree do you need to access on a single request? In what manner do you query it? Does it ever change?\nIf it's immutable, you don't really need a 'singleton' - which implies mutability - just a way to access the data on each instance. Depending on how you need to access it, you could store it as a data file, a blob, or as data in the datastore.\n", "Memcache and the datastore are your best bets for truly global access across all your instances. However, a global variable can still be used to cache your data structure within each instance. Wouldn't a trie structure be pretty easy to break up into chunks such that each chunk will fit into memcache? Once you get your trie into memcache, anytime you access a chunk of the trie from memcache, you could store it in a global variable on that instance. Over the course of a few requests, you will build up a full copy of the trie on each instance that you have running. This is a bit complicated, but could ultimately give you the best performance.\n" ]
[ 4, 3, 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003050463_google_app_engine_python.txt
Q: Django access data passed to form I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ChoiceField( choices = [ [group.node_id, group.name] for group in Objtree.objects.filter( type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), parent_id = 50 ).distinct()] + [[0, 'Add a new one'] ], widget = forms.Select( attrs = { 'id': 'group_select' } ) ) I would like to change the parent_id that is passed into the Objtree.objects.filter. As you can see I tried in the init function, as well with kwargs['initial']['parent_id'] and then calling it with self, but that doesnt work, since its out of scope... it was pretty much my last effort. I need to acccess it either trough the initial parameter or directly trough parent_id field, since it already holds its value (passed trough initial). Any help is appreciated, as I am running out of ideas. A: OK a couple of minor points here before I answer your question. Firstly, your field should probably be a ModelChoiceField - this takes a queryset parameter, rather than a list of choices, which avoids the need for the list comprehension to get id and value. Secondly, your query to get the Objtree objects is much better written using the double-underscore notation to traverse relations: Objtree.objects.filter(type__name='group', parent_id=50) Now, the actual question. As you note, you can't access local or instance variables within the field declarations. These are class-level attributes, which are processed (via the metaclass) when the class is defined, not when it is instantiated. So you need to do the whole thing in __init__. Like this: class GroupAdd(forms.Form): parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) self.fields['choices'].queryset = Objtree.objects.filter( type__name='group', parent_id=pid )
Django access data passed to form
I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ChoiceField( choices = [ [group.node_id, group.name] for group in Objtree.objects.filter( type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), parent_id = 50 ).distinct()] + [[0, 'Add a new one'] ], widget = forms.Select( attrs = { 'id': 'group_select' } ) ) I would like to change the parent_id that is passed into the Objtree.objects.filter. As you can see I tried in the init function, as well with kwargs['initial']['parent_id'] and then calling it with self, but that doesnt work, since its out of scope... it was pretty much my last effort. I need to acccess it either trough the initial parameter or directly trough parent_id field, since it already holds its value (passed trough initial). Any help is appreciated, as I am running out of ideas.
[ "OK a couple of minor points here before I answer your question. \nFirstly, your field should probably be a ModelChoiceField - this takes a queryset parameter, rather than a list of choices, which avoids the need for the list comprehension to get id and value.\nSecondly, your query to get the Objtree objects is much better written using the double-underscore notation to traverse relations:\nObjtree.objects.filter(type__name='group', parent_id=50)\n\nNow, the actual question. As you note, you can't access local or instance variables within the field declarations. These are class-level attributes, which are processed (via the metaclass) when the class is defined, not when it is instantiated. So you need to do the whole thing in __init__.\nLike this:\nclass GroupAdd(forms.Form):\n parent_id = forms.IntegerField(widget=forms.HiddenInput)\n choices = forms.ModelChoiceField(queryset=None)\n\n def __init__(self, *args, **kwargs):\n pid = kwargs.pop('parent_id', None)\n super(GroupAdd, self).__init__(*args, **kwargs)\n self.fields['choices'].queryset = Objtree.objects.filter(\n type__name='group', parent_id=pid\n )\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "django_models", "forms", "python" ]
stackoverflow_0003054683_django_django_forms_django_models_forms_python.txt
Q: PythonMagickWand Shepards Distortion (ctypes LP_c_double problem) I am trying to use PythonMagickWand to use a Shepards distortion on an image. You can also see the source of distort.c that is used by ImageMagick. PythonMagickWand does not by default support Shepards distortion. To fix this, I added in: ShepardsDistortion = DistortImageMethod(15) to line 544 of PythonMagickWand (See here for my modified PythonMagicWand). The 15 pointer is in reference to distort.h (line 51) of the MagickWand source in which ShepardsDistortion is the 15th item on the list. This fits with all of the other supported distortion methods. Now, something that I may be doing wrong is presuming that the existing distortion methods that are supported by PythonMagickWand use the same type of arguments as the Shepards. They might not but I do not know how I can tell. I know that distort.c is doing the work, but I can't work out if the arguments it takes in are the same or different. I have the following code (snippet): from PythonMagickWand import * from ctypes import * arrayType = c_double * 8 pointsNew = arrayType() pointsNew[0] = c_double(eyeLeft[0]) pointsNew[1] = c_double(eyeLeft[1]) pointsNew[2] = c_double(eyeLeftDest[0]) pointsNew[3] = c_double(eyeLeftDest[1]) pointsNew[4] = c_double(eyeRight[0]) pointsNew[5] = c_double(eyeRight[1]) pointsNew[6] = c_double(eyeRightDest[0]) pointsNew[7] = c_double(eyeRightDest[1]) MagickWandGenesis() wand = NewMagickWand() MagickReadImage(wand,path_to_image+'image_mod.jpg') MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) MagickWriteImage(wand,path_to_image+'image_mod22.jpg') I get the following error: MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) ctypes.ArgumentError: argument 4: <type 'exceptions.TypeError'>: expected LP_c_double instance instead of list I am aware that pointsNew is the wrong way of providing the arguments.. But I just don't know what is the right format. This is an example distort command that works when run in Terminal: convert image.jpg -virtual-pixel Black -distort Shepards 121.523809524,317.79638009 141,275 346.158730159,312.628959276 319,275 239.365079365,421.14479638 232,376 158.349206349,483.153846154 165,455 313.015873016,483.153846154 300,455 0,0 0,0 0,571.0 0,571.0 464.0,571.0 464.0,571.0 0,571.0 0,571.0 image_out.jpg So I guess the question is: How do I create a list of c_doubles that will be accepted by PythonMagickWand? Or is my hack to add Shepards Distortion into PythonMagickWand completely wrong? I basically need to re-create the terminal command. I have got it working by using subprocess to run the command from Python but that is not how I want to do it. A: From NeedMoreBeer on Reddit.com: from PythonMagickWand import * from ctypes import * arrayType = c_double * 8 pointsNew = arrayType() pointsNew[0] = c_double(121.523809524) pointsNew[1] = c_double(317.79638009) pointsNew[2] = c_double(141) pointsNew[3] = c_double(275) pointsNew[4] = c_double(346.158730159) pointsNew[5] = c_double(312.628959276) pointsNew[6] = c_double(319) pointsNew[7] = c_double(275) ShepardsDistortion = DistortImageMethod(14) MagickWandGenesis() wand = NewMagickWand() MagickReadImage(wand,'/home/user/image.png') MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) MagickWriteImage(wand,'/home/user/image_mod22.jpg') More specifically for me, it was the following line: ShepardsDistortion = DistortImageMethod(14) That fixed it for me! Thanks again to NeedMoreBeer from Reddit. A: As the error message indicates, the function is expecting a pointer (LP_c_double), but all you have is an array. You'll need to explicitly cast your array to a pointer, for the purposes of passing it as a pointer to the external function: >>> arr = (c_double * 8)() >>> arr # just an array... <__main__.c_double_Array_8 object at 0x1004ad050> >>> arr[0] = 5 # ... >>> cast(arr, POINTER(c_double)) # now it's the right type <__main__.LP_c_double object at 0x1004ad0e0> >>> cast(arr, POINTER(c_double))[0] 5.0 A: This is OT, but: I really liked python magick wand, but when I used it on 600+ images there was a memory leak somewhere, which ate all the memory in the (32 bit) machine. I was inclined to think possibly in ImageMagick itself, but I might've been wrong. In the end I found out that: GraphicsMagick is a port of an earlier version of ImageMagick; but because ImageMagick changes their API a lot, PythonMagickWant won't work with GraphicsMagick. GraphicsMagick, also seems to be faster than ImageMagick (using better multitasking). In order to get my script working quickly, in a few days I changed it so that instead of using ImageMagick, the script loaded the gimp, which then ran my script using python-scriptfu. Everything seemed to work OK. If it works for you, then use it; also the PythonMagickWand guy is really helpful + the bindings are nice.
PythonMagickWand Shepards Distortion (ctypes LP_c_double problem)
I am trying to use PythonMagickWand to use a Shepards distortion on an image. You can also see the source of distort.c that is used by ImageMagick. PythonMagickWand does not by default support Shepards distortion. To fix this, I added in: ShepardsDistortion = DistortImageMethod(15) to line 544 of PythonMagickWand (See here for my modified PythonMagicWand). The 15 pointer is in reference to distort.h (line 51) of the MagickWand source in which ShepardsDistortion is the 15th item on the list. This fits with all of the other supported distortion methods. Now, something that I may be doing wrong is presuming that the existing distortion methods that are supported by PythonMagickWand use the same type of arguments as the Shepards. They might not but I do not know how I can tell. I know that distort.c is doing the work, but I can't work out if the arguments it takes in are the same or different. I have the following code (snippet): from PythonMagickWand import * from ctypes import * arrayType = c_double * 8 pointsNew = arrayType() pointsNew[0] = c_double(eyeLeft[0]) pointsNew[1] = c_double(eyeLeft[1]) pointsNew[2] = c_double(eyeLeftDest[0]) pointsNew[3] = c_double(eyeLeftDest[1]) pointsNew[4] = c_double(eyeRight[0]) pointsNew[5] = c_double(eyeRight[1]) pointsNew[6] = c_double(eyeRightDest[0]) pointsNew[7] = c_double(eyeRightDest[1]) MagickWandGenesis() wand = NewMagickWand() MagickReadImage(wand,path_to_image+'image_mod.jpg') MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) MagickWriteImage(wand,path_to_image+'image_mod22.jpg') I get the following error: MagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False) ctypes.ArgumentError: argument 4: <type 'exceptions.TypeError'>: expected LP_c_double instance instead of list I am aware that pointsNew is the wrong way of providing the arguments.. But I just don't know what is the right format. This is an example distort command that works when run in Terminal: convert image.jpg -virtual-pixel Black -distort Shepards 121.523809524,317.79638009 141,275 346.158730159,312.628959276 319,275 239.365079365,421.14479638 232,376 158.349206349,483.153846154 165,455 313.015873016,483.153846154 300,455 0,0 0,0 0,571.0 0,571.0 464.0,571.0 464.0,571.0 0,571.0 0,571.0 image_out.jpg So I guess the question is: How do I create a list of c_doubles that will be accepted by PythonMagickWand? Or is my hack to add Shepards Distortion into PythonMagickWand completely wrong? I basically need to re-create the terminal command. I have got it working by using subprocess to run the command from Python but that is not how I want to do it.
[ "From NeedMoreBeer on Reddit.com:\nfrom PythonMagickWand import *\nfrom ctypes import *\n\narrayType = c_double * 8 \npointsNew = arrayType()\npointsNew[0] = c_double(121.523809524)\npointsNew[1] = c_double(317.79638009)\npointsNew[2] = c_double(141)\npointsNew[3] = c_double(275) \npointsNew[4] = c_double(346.158730159)\npointsNew[5] = c_double(312.628959276)\npointsNew[6] = c_double(319)\npointsNew[7] = c_double(275)\n\nShepardsDistortion = DistortImageMethod(14)\n\nMagickWandGenesis()\nwand = NewMagickWand()\nMagickReadImage(wand,'/home/user/image.png')\nMagickDistortImage(wand,ShepardsDistortion, 8, pointsNew, False)\nMagickWriteImage(wand,'/home/user/image_mod22.jpg')\n\nMore specifically for me, it was the following line:\nShepardsDistortion = DistortImageMethod(14)\n\nThat fixed it for me! Thanks again to NeedMoreBeer from Reddit.\n", "As the error message indicates, the function is expecting a pointer (LP_c_double), but all you have is an array. \nYou'll need to explicitly cast your array to a pointer, for the purposes of passing it as a pointer to the external function:\n\n>>> arr = (c_double * 8)()\n>>> arr # just an array...\n<__main__.c_double_Array_8 object at 0x1004ad050>\n>>> arr[0] = 5\n# ...\n>>> cast(arr, POINTER(c_double)) # now it's the right type\n<__main__.LP_c_double object at 0x1004ad0e0>\n>>> cast(arr, POINTER(c_double))[0]\n5.0\n\n", "This is OT, but:\nI really liked python magick wand, but when I used it on 600+ images there was a memory leak somewhere, which ate all the memory in the (32 bit) machine. I was inclined to think possibly in ImageMagick itself, but I might've been wrong.\nIn the end I found out that:\nGraphicsMagick is a port of an earlier version of ImageMagick; but because ImageMagick changes their API a lot, PythonMagickWant won't work with GraphicsMagick.\nGraphicsMagick, also seems to be faster than ImageMagick (using better multitasking).\nIn order to get my script working quickly, in a few days I changed it so that instead of using ImageMagick, the script loaded the gimp, which then ran my script using python-scriptfu.\nEverything seemed to work OK.\nIf it works for you, then use it; also the PythonMagickWand guy is really helpful + the bindings are nice.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "ctypes", "imagemagick", "magickwand", "python" ]
stackoverflow_0002989543_ctypes_imagemagick_magickwand_python.txt
Q: Graphing a line and scatter points using Matplotlib? I'm using matplotlib at the moment to try and visualise some data I am working on. I'm trying to plot around 6500 points and the line y = x on the same graph but am having some trouble in doing so. I can only seem to get the points to render and not the line itself. I know matplotlib doesn't plot equations as such rather just a set of points so I'm trying to use and identical set of points for x and y co-ordinates to produce the line. The following is my code from matplotlib import pyplot import numpy from pymongo import * class Store(object): """docstring for Store""" def __init__(self): super(Store, self).__init__() c = Connection() ucd = c.ucd self.tweets = ucd.tweets def fetch(self): x = [] y = [] for t in self.tweets.find(): x.append(t['positive']) y.append(t['negative']) return [x,y] if __name__ == '__main__': c = Store() array = c.fetch() t = numpy.arange(0., 0.03, 1) pyplot.plot(array[0], array[1], 'ro', t, t, 'b--') pyplot.show() Any suggestions would be appreciated, Patrick A: Correct me if I'm wrong (I'm not a pro at matplotlib), but 't' will simply get the value [0.]. t = numpy.arange(0.,0.03,1) That means start at 0 and go to 0.03 (not inclusive) with a step size of 1. Resulting in an array containing just 0. In that case you are simply plotting one point. It takes two to make a line.
Graphing a line and scatter points using Matplotlib?
I'm using matplotlib at the moment to try and visualise some data I am working on. I'm trying to plot around 6500 points and the line y = x on the same graph but am having some trouble in doing so. I can only seem to get the points to render and not the line itself. I know matplotlib doesn't plot equations as such rather just a set of points so I'm trying to use and identical set of points for x and y co-ordinates to produce the line. The following is my code from matplotlib import pyplot import numpy from pymongo import * class Store(object): """docstring for Store""" def __init__(self): super(Store, self).__init__() c = Connection() ucd = c.ucd self.tweets = ucd.tweets def fetch(self): x = [] y = [] for t in self.tweets.find(): x.append(t['positive']) y.append(t['negative']) return [x,y] if __name__ == '__main__': c = Store() array = c.fetch() t = numpy.arange(0., 0.03, 1) pyplot.plot(array[0], array[1], 'ro', t, t, 'b--') pyplot.show() Any suggestions would be appreciated, Patrick
[ "Correct me if I'm wrong (I'm not a pro at matplotlib), but 't' will simply get the value [0.].\nt = numpy.arange(0.,0.03,1)\n\nThat means start at 0 and go to 0.03 (not inclusive) with a step size of 1. Resulting in an array containing just 0.\nIn that case you are simply plotting one point. It takes two to make a line. \n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003055085_matplotlib_python.txt
Q: Trimming lists using a loop I have few lists like: a = [1, 2, 3, 4, 5] b = [4, 6, 5, 9, 2] c = [4, 7, 9, 1, 2] I want to trim all of them using a loop, instead of doing as below: a[-2:] b[-2:] c[-2:] I tried but got confused with pass by value or pass by reference fundamentals, looked into other questions as well but no help. Thanks A: for l in [a, b, c]: del l[-2:] This removes the last two elements from each list. If you want to remove all but the last two elements only, do this: for l in [a, b, c]: del l[:-2] There's no need to worry about references here; the list over which the for loop iterates contains references to a, b and c, and each list is mutated in-place by deleting a list slice. A: x = [a, b, c] x = map(lambda lst: lst[-2:], x) A: Deleting the unwanted items from the existing lists, using a loop: for list in [a, b, c]: del a[:-2] Or, creating new lists containing only the correct items, using a list comprehension: (a, b, c) = [x[-2:] for x in (a, b, c)]
Trimming lists using a loop
I have few lists like: a = [1, 2, 3, 4, 5] b = [4, 6, 5, 9, 2] c = [4, 7, 9, 1, 2] I want to trim all of them using a loop, instead of doing as below: a[-2:] b[-2:] c[-2:] I tried but got confused with pass by value or pass by reference fundamentals, looked into other questions as well but no help. Thanks
[ "for l in [a, b, c]:\n del l[-2:]\n\nThis removes the last two elements from each list. If you want to remove all but the last two elements only, do this:\nfor l in [a, b, c]:\n del l[:-2]\n\nThere's no need to worry about references here; the list over which the for loop iterates contains references to a, b and c, and each list is mutated in-place by deleting a list slice.\n", "x = [a, b, c]\nx = map(lambda lst: lst[-2:], x) \n\n", "Deleting the unwanted items from the existing lists, using a loop:\nfor list in [a, b, c]:\n del a[:-2]\n\nOr, creating new lists containing only the correct items, using a list comprehension:\n(a, b, c) = [x[-2:] for x in (a, b, c)]\n\n" ]
[ 4, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003055330_list_python.txt
Q: Plotting and Animating 2D points with 'headings' I will have a set of data (x, y, heading), and I need to animate it in real-time. I am currently using matplotlib to animate (x, y) and it works fine, but I would really like to have some way to indicate heading, ie what direction the object is facing. What would be the best library for this? It seems like PyGame might be able to help me out, but would I have to roll out my own graphing library for it? Thanks A: How about quiver? The examples all use a mesh grid, but of course you can simply give the coordinates of arbitrary points: quiver([1,2,3],[3,1,4],[.5,.4,-.6],[.5,-.7,.3]) xlim(0,4) ylim(0,5) show() The xlim and ylim calls are because quiver doesn't do a very good job of setting the limits automatically.
Plotting and Animating 2D points with 'headings'
I will have a set of data (x, y, heading), and I need to animate it in real-time. I am currently using matplotlib to animate (x, y) and it works fine, but I would really like to have some way to indicate heading, ie what direction the object is facing. What would be the best library for this? It seems like PyGame might be able to help me out, but would I have to roll out my own graphing library for it? Thanks
[ "How about quiver? The examples all use a mesh grid, but of course you can simply give the coordinates of arbitrary points:\nquiver([1,2,3],[3,1,4],[.5,.4,-.6],[.5,-.7,.3])\nxlim(0,4)\nylim(0,5)\nshow()\n\nThe xlim and ylim calls are because quiver doesn't do a very good job of setting the limits automatically.\n" ]
[ 1 ]
[]
[]
[ "animation", "matplotlib", "python" ]
stackoverflow_0003055199_animation_matplotlib_python.txt
Q: Getting a string from Python list? I have a List object like this ['tag1', 'tag2', 'tag3 tag3', ...] How I can skip [, ], ' characters and get a string "tag1, tag2, tag3 tag3, ..."? A: if you have a list of strings you could do: >>> lst = ['tag1', 'tag2', 'tag3 tag3'] >>> ', '.join(lst) 'tag1, tag2, tag3 tag3' Note: you do not remove characters [, ], '. You're concatenating elements of a list into a string. Original list will remain untouched. These characters serve for representing relevant types in python: lists and string, specifically. A: One simple way, for your example, would be to take the substring that excludes the first and last character. myStr = myStr[1:-1] A: > import re >>> s = "[test, test2]" >>> s = re.sub("\[|\]", "", s) >>> s 'test, test2' A: If the '[' and ']' will always be at the front and end of the string, you can use the string strip function. s = '[tag1, tag2, tag3]' s.strip('[]') This should remove the brackets.
Getting a string from Python list?
I have a List object like this ['tag1', 'tag2', 'tag3 tag3', ...] How I can skip [, ], ' characters and get a string "tag1, tag2, tag3 tag3, ..."?
[ "if you have a list of strings you could do:\n>>> lst = ['tag1', 'tag2', 'tag3 tag3']\n>>> ', '.join(lst)\n'tag1, tag2, tag3 tag3'\n\nNote: you do not remove characters [, ], '. You're concatenating elements of a list into a string. Original list will remain untouched. These characters serve for representing relevant types in python: lists and string, specifically.\n", "One simple way, for your example, would be to take the substring that excludes the first and last character.\nmyStr = myStr[1:-1]\n\n", "> import re\n>>> s = \"[test, test2]\"\n>>> s = re.sub(\"\\[|\\]\", \"\", s)\n>>> s\n'test, test2'\n\n", "If the '[' and ']' will always be at the front and end of the string, you can use the string strip function. \ns = '[tag1, tag2, tag3]'\ns.strip('[]')\n\nThis should remove the brackets. \n" ]
[ 5, 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003055644_list_python.txt
Q: Installing Python 3.1.2 from source, how do you resolve the sqlite3-dev dependency? Running ubuntu 9.04 "jaunty". When I run make I get the following error: Python build finished, but the necessary bits to build these modules were not found: _sqlite3 So the easy solution is to just install the missing dependency using apt-get, "sudo apt-get -f install libsqlite3-dev" but I get the following error: The following packages have unmet dependencies: libsqlite3-dev: Depends: libsqlite3-0 (= 3.6.10-1) but 3.6.10-1ubuntu0.2 is to be installed E: Broken packages I tried uninstalling "libsqlite3-0" but synaptic said many things needed it (50+). So now I am stuck. I can't install the missing dependency. And therefore I can not install python 3.1.2. Any ideas on how to fix the missing libsqlite3-dev dependency? A: The dependency mismatch in that error message doesn't agree with the official ubuntu repository. (The official version of libsqlite3-dev in Jaunty depends on libsqlite3-0 (= 3.6.10-1ubuntu0.2).) Perhaps your last apt-get update was done while the repo was still being updated and only some of the latest packages were available. Try again after running sudo apt-get update, perhaps first switching to a different apt server. (You can do this in the Ubuntu GUI using the Software Sources system administration tool.) Or, if you don't want to mess with building and installing Python manually, you could upgrade Ubuntu to the latest release. Lucid has Python 3.1.2 in the repositories already, as python3.
Installing Python 3.1.2 from source, how do you resolve the sqlite3-dev dependency?
Running ubuntu 9.04 "jaunty". When I run make I get the following error: Python build finished, but the necessary bits to build these modules were not found: _sqlite3 So the easy solution is to just install the missing dependency using apt-get, "sudo apt-get -f install libsqlite3-dev" but I get the following error: The following packages have unmet dependencies: libsqlite3-dev: Depends: libsqlite3-0 (= 3.6.10-1) but 3.6.10-1ubuntu0.2 is to be installed E: Broken packages I tried uninstalling "libsqlite3-0" but synaptic said many things needed it (50+). So now I am stuck. I can't install the missing dependency. And therefore I can not install python 3.1.2. Any ideas on how to fix the missing libsqlite3-dev dependency?
[ "The dependency mismatch in that error message doesn't agree with the official ubuntu repository. (The official version of libsqlite3-dev in Jaunty depends on libsqlite3-0 (= 3.6.10-1ubuntu0.2).) Perhaps your last apt-get update was done while the repo was still being updated and only some of the latest packages were available.\nTry again after running sudo apt-get update, perhaps first switching to a different apt server. (You can do this in the Ubuntu GUI using the Software Sources system administration tool.)\nOr, if you don't want to mess with building and installing Python manually, you could upgrade Ubuntu to the latest release. Lucid has Python 3.1.2 in the repositories already, as python3.\n" ]
[ 1 ]
[]
[]
[ "gnu", "makefile", "python", "sqlite", "ubuntu_9.04" ]
stackoverflow_0003055675_gnu_makefile_python_sqlite_ubuntu_9.04.txt