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: string mask and offset with regex I have a string on which I try to create a regex mask that will show N number of words, given an offset. Let's say I have the following string: "The quick, brown fox jumps over the lazy dog." I want to show 3 words at the time: offset 0: "The quick, brown" offset 1: "quick, brown fox" offset 2: "brown fox jumps" offset 3: "fox jumps over" offset 4: "jumps over the" offset 5: "over the lazy" offset 6: "the lazy dog." I'm using Python and I've been using the following simple regex to detect 3 words: >>> import re >>> s = "The quick, brown fox jumps over the lazy dog." >>> re.search(r'(\w+\W*){3}', s).group() 'The quick, brown ' But I can't figure out how to have a kind of mask to show the next 3 words and not the beginning ones. I need to keep punctuation. A: The prefix-matching option You can make this work by having a variable-prefix regex to skip the first offset words, and capturing the word triplet into a group. So something like this: import re s = "The quick, brown fox jumps over the lazy dog." print re.search(r'(?:\w+\W*){0}((?:\w+\W*){3})', s).group(1) # The quick, brown print re.search(r'(?:\w+\W*){1}((?:\w+\W*){3})', s).group(1) # quick, brown fox print re.search(r'(?:\w+\W*){2}((?:\w+\W*){3})', s).group(1) # brown fox jumps Let's take a look at the pattern: _"word"_ _"word"_ / \ / \ (?:\w+\W*){2}((?:\w+\W*){3}) \_____________/ group 1 This does what it says: match 2 words, then capturing into group 1, match 3 words. The (?:...) constructs are used for grouping for the repetition, but they're non-capturing. References regular-expressions.info/Capturing Groups, Non-capturing Groups Repeating a Capturing Group vs Capturing a Repeated Group Note on "word" pattern It should be said that \w+\W* is a poor choice for a "word" pattern, as exhibited by the following example: import re s = "nothing" print re.search(r'(\w+\W*){3}', s).group() # nothing There are no 3 words, but the regex was able to match anyway, because \W* allows for an empty string match. Perhaps a better pattern is something like: \w+(?:\W+|$) That is, a \w+ that is followed by either a \W+ or the end of the string $. The capturing lookahead option As suggested by Kobi in a comment, this option is simpler in that you only have one static pattern. It uses findall to capture all matches (see on ideone.com): import re s = "The quick, brown fox jumps over the lazy dog." triplets = re.findall(r"\b(?=((?:\w+(?:\W+|$)){3}))", s) print triplets # ['The quick, brown ', 'quick, brown fox ', 'brown fox jumps ', # 'fox jumps over ', 'jumps over the ', 'over the lazy ', 'the lazy dog.'] print triplets[3] # fox jumps over How this works is that it matches on zero-width word boundary \b, using lookahead to capture 3 "words" in group 1. ______lookahead______ / ___"word"__ \ / / \ \ \b(?=((?:\w+(?:\W+|$)){3})) \___________________/ group 1 References regular-expressions.info/Lookarounds A: One slant would be to split the string and select slices: words = re.split(r"\s+", s) for i in range(len(words) - 2): print ' '.join(words[i:i+3]) This does, of course, assume that you either have only single spaces between words, or don't care if all whitespace sequences are folded into single spaces. A: No need for regex >>> s = "The quick, brown fox jumps over the lazy dog." >>> for offset in range(7): ... print 'offset {0}: "{1}"'.format(offset, ' '.join(s.split()[offset:][:3])) ... offset 0: "The quick, brown" offset 1: "quick, brown fox" offset 2: "brown fox jumps" offset 3: "fox jumps over" offset 4: "jumps over the" offset 5: "over the lazy" offset 6: "the lazy dog." A: We have two orthogonal issues here: How to split the string. How to build groups of 3 consecutive elements. For 1 you could use regular expressions or -as others have pointed out- a simple str.split should suffice. For 2, note that you want looks very similar to the pairwise abstraction in itertools's recipes: http://docs.python.org/library/itertools.html#recipes So we write our generalized n-wise function: import itertools def nwise(iterable, n): """nwise(iter([1,2,3,4,5]), 3) -> (1,2,3), (2,3,4), (4,5,6)""" iterables = itertools.tee(iterable, n) slices = (itertools.islice(it, idx, None) for (idx, it) in enumerate(iterables)) return itertools.izip(*slices) And we end up with a simple and modularized code: >>> s = "The quick, brown fox jumps over the lazy dog." >>> list(nwise(s.split(), 3)) [('The', 'quick,', 'brown'), ('quick,', 'brown', 'fox'), ('brown', 'fox', 'jumps'), ('fox', 'jumps', 'over'), ('jumps', 'over', 'the'), ('over', 'the', 'lazy'), ('the', 'lazy', 'dog.')] Or as you requested: >>> # also: map(" ".join, nwise(s.split(), 3)) >>> [" ".join(words) for words in nwise(s.split(), 3)] ['The quick, brown', 'quick, brown fox', 'brown fox jumps', 'fox jumps over', 'jumps over the', 'over the lazy', 'the lazy dog.']
string mask and offset with regex
I have a string on which I try to create a regex mask that will show N number of words, given an offset. Let's say I have the following string: "The quick, brown fox jumps over the lazy dog." I want to show 3 words at the time: offset 0: "The quick, brown" offset 1: "quick, brown fox" offset 2: "brown fox jumps" offset 3: "fox jumps over" offset 4: "jumps over the" offset 5: "over the lazy" offset 6: "the lazy dog." I'm using Python and I've been using the following simple regex to detect 3 words: >>> import re >>> s = "The quick, brown fox jumps over the lazy dog." >>> re.search(r'(\w+\W*){3}', s).group() 'The quick, brown ' But I can't figure out how to have a kind of mask to show the next 3 words and not the beginning ones. I need to keep punctuation.
[ "The prefix-matching option\nYou can make this work by having a variable-prefix regex to skip the first offset words, and capturing the word triplet into a group.\nSo something like this:\nimport re\ns = \"The quick, brown fox jumps over the lazy dog.\"\n\nprint re.search(r'(?:\\w+\\W*){0}((?:\\w+\\W*){3})', s).gro...
[ 5, 2, 1, 1 ]
[]
[]
[ "python", "regex", "regex_negation" ]
stackoverflow_0003275324_python_regex_regex_negation.txt
Q: Processing High-Volume Streaming Data with Twisted or using Threads, Queue in Python I am getting at extremely fast rate, tweets from a long-lived connection to the Twitter API Streaming Server. I proceed by doing some heavy text processing and save the tweets in my database. I am using PyCurl for the connection and callback function that care of text processing and saving in the db. See below my approach who is not working properly. I am not familiar with network programming, so would like to know: How can use Threads, Queue or Twisted frameworks to solve this problem ? def process_tweet(): # do some heaving text processing def open_stream_connection(): connect = pycurl.Curl() connect.setopt(pycurl.URL, STREAMURL) connect.setopt(pycurl.WRITEFUNCTION, process_tweet) connect.setopt(pycurl.USERPWD, "%s:%s" % (TWITTER_USER, TWITTER_PASS)) connect.perform() A: You should have a number of threads receiving the messages as they come in. That number should probably be 1 if you are using pycurl, but should be higher if you are using httplib - the idea being you want to be able to have more than one query on the Twitter API at a time, so there is a steady amount of work to process. When each Tweet arrives, it is pushed onto a Queue.Queue. The Queue ensures that there is thread-safety in the communications - each tweet will only be handled by one worker thread. A pool of worker threads is responsible for reading from the Queue and dealing with the Tweet. Only the interesting tweets should be added to the database. As the database is probably the bottleneck, there is a limit to the number of threads in the pool that are worth adding - more threads won't make it process faster, it'll just mean more threads are waiting in the queue to access the database. This is a fairly common Python idiom. This architecture will scale only to a certain degree - i.e. what one machine can process. A: I suggest this organization: one process reads Twitter, stuffs tweets into database one or more processes reads database, processes each, inserts into new database. Original tweets either deleted or marked processed. That is, you have two more more processes/threads. The tweet database could be seen as a queue of work. Multiple worker processes take jobs (tweets) off the queue, and create data in the second database. A: Here's simple setup if you are OK with using a single machine. 1 thread accepts connections. After a connection is accepted, it passes the accepted connection to another thread for processing. You can, of course, use processes (e.g, using multiprocessing) instead of threads, but I'm not familiar with multiprocessing to give advice. The setup would be the same: 1 process accepts connections, then passes them to subprocesses. If you need to shard the processing across multiple machines, then the simple thing to do would be to stuff the message into the database, then notify the workers about the new record (this will require some sort of coordination/locking between the workers). If you want to avoid hitting the database, then you'll have to pipe messages from your network process to the workers (and I'm not well versed enough in low level networking to tell you how to do that :))
Processing High-Volume Streaming Data with Twisted or using Threads, Queue in Python
I am getting at extremely fast rate, tweets from a long-lived connection to the Twitter API Streaming Server. I proceed by doing some heavy text processing and save the tweets in my database. I am using PyCurl for the connection and callback function that care of text processing and saving in the db. See below my approach who is not working properly. I am not familiar with network programming, so would like to know: How can use Threads, Queue or Twisted frameworks to solve this problem ? def process_tweet(): # do some heaving text processing def open_stream_connection(): connect = pycurl.Curl() connect.setopt(pycurl.URL, STREAMURL) connect.setopt(pycurl.WRITEFUNCTION, process_tweet) connect.setopt(pycurl.USERPWD, "%s:%s" % (TWITTER_USER, TWITTER_PASS)) connect.perform()
[ "You should have a number of threads receiving the messages as they come in. That number should probably be 1 if you are using pycurl, but should be higher if you are using httplib - the idea being you want to be able to have more than one query on the Twitter API at a time, so there is a steady amount of work to p...
[ 2, 1, 1 ]
[]
[]
[ "python", "stream", "twisted", "twitter" ]
stackoverflow_0003180597_python_stream_twisted_twitter.txt
Q: Adding options which both change behaviour and store an argument Using the argparse module, is it possible to perform multiple actions for a given argument? Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving information about all possibilities in a set or about one particular possibility. Normally there will be a namespace attribute that contains a function to be called after parsing; I would like the -l option to both change this attribute and optionally store its argument in a different attribute. Is this possible? A: Simply implement your own Action subclass. This basically looks like this: class ListAction(argparse.Action): def __call__(parser, namespace, values, option_string=None): setattr(namespace, 'list', values[0]) do_something_completely_different() The argparse documentation has more details.
Adding options which both change behaviour and store an argument
Using the argparse module, is it possible to perform multiple actions for a given argument? Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving information about all possibilities in a set or about one particular possibility. Normally there will be a namespace attribute that contains a function to be called after parsing; I would like the -l option to both change this attribute and optionally store its argument in a different attribute. Is this possible?
[ "Simply implement your own Action subclass. This basically looks like this:\nclass ListAction(argparse.Action):\n def __call__(parser, namespace, values, option_string=None):\n setattr(namespace, 'list', values[0])\n do_something_completely_different()\n\nThe argparse documentation has more detail...
[ 1 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0003276137_argparse_python.txt
Q: Execute Python program using PHP Can I simply execute Python program using PHP like this? (in a browser) exec("python myProgram /Applications/MAMP/htdocs/somefile.xml"); or like this: exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml"); Is any of this method correct? If not, what should be the right way to do it? Thanks A: if you want to capture output as well, use proc_open (full fd connectivity, i.e. input and output) or popen (either in- or output) A: I would prefer using proc_open() as suggested by mvds as you can't write to STDIN nor read from STDOUT with exec()/shell_exec(), as well as providing your own set of environment variable -$_ENV. A sample snippet extracted from my code: $process = proc_open( "{$command}", array( array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w') ), $pipes, NULL, $_ENV ); if(is_resource($process)){ fwrite($pipes[0], $string); fclose($pipes[0]); $rt = stream_get_contents($pipes[1]); fclose($pipes[1]); $rtErr = stream_get_contents($pipes[2]); fclose($pipes[2]); $exitCode = proc_close($process); } Read more: http://php.net/manual/en/function.proc-open.php A: Yeah, why not? Note that you are not executing this "in the browser" but rather on the server side, while the page is being pre-processed. Consider that the page will not return until the exec has finished, so it really depends on what exactly you are trying to do.
Execute Python program using PHP
Can I simply execute Python program using PHP like this? (in a browser) exec("python myProgram /Applications/MAMP/htdocs/somefile.xml"); or like this: exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml"); Is any of this method correct? If not, what should be the right way to do it? Thanks
[ "if you want to capture output as well, use proc_open (full fd connectivity, i.e. input and output) or popen (either in- or output)\n", "I would prefer using proc_open() as suggested by mvds as you can't write to STDIN nor read from STDOUT with exec()/shell_exec(), as well as providing your own set of environment...
[ 1, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003276491_php_python.txt
Q: execute functions in a queue i have a example who should show what i'd like to do queue = 2 def function(): print 'abcd' time.sleep(3) def exec_times(times): #do something function() def exec_queue(queue): #do something function() exec_times(3) #things need be working while it waiting for the function finish time.sleep(10) the result should be abcd abcd #after finish the first two function executions abcd so, there is a way to do that without use thread? i mean some glib function to do this job. A: If you want to avoid threads, one option is to use multiple processes. If you're on python 2.6, take a look at the multiprocessing module. If python 2.5, look at pyprocessing. Note "Process Pools" in the docs for multiprocessing, which seem to handle your requirements: One can create a pool of processes which will carry out tasks submitted to it with the Pool class. class multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]]) A process pool object which controls a pool of worker processes to which jobs can be submitted. It supports asynchronous results with timeouts and callbacks and has a parallel map implementation.
execute functions in a queue
i have a example who should show what i'd like to do queue = 2 def function(): print 'abcd' time.sleep(3) def exec_times(times): #do something function() def exec_queue(queue): #do something function() exec_times(3) #things need be working while it waiting for the function finish time.sleep(10) the result should be abcd abcd #after finish the first two function executions abcd so, there is a way to do that without use thread? i mean some glib function to do this job.
[ "If you want to avoid threads, one option is to use multiple processes. If you're on python 2.6, take a look at the multiprocessing module. If python 2.5, look at pyprocessing.\nNote \"Process Pools\" in the docs for multiprocessing, which seem to handle your requirements:\n\nOne can create a pool of processes wh...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003276595_python.txt
Q: Optimize a list comprehension Here is a code snippet that shows the code I would like to optimize: result = [(item, foo(item)) for item in item_list if cond1(item) and cond2(foo(item))] In the above snippet I call foo(item) twice. I can't think of a way to iterate over the list only once maintain both item and foo(item) for the conditional and the result list. That is, I would like to keep item and foo(item) without having to loop over the list twice and without having to call foo(item) twice. I know I can do it with a second nested list comprehension: result = [(item, foo_item) for item, foo_item in [(i, foo(i)) for i in item_list] if cond1(item) and cond2(foo_item)] but that appears to loop through item_list twice which I would like to avoid. So the first example calls foo twice per list item. The second example loops through the list twice (or appears to). I'd like to loop one time and call foo once for each item. A: It doesn't, but here: result = [(item, foo_item) for item, foo_item in ((i, foo(i)) for i in item_list) if cond1(item) and cond2(foo_item)] Turning the inner list comprehension into a generator expression makes sure that we don't use an unnecessary temporary list. A: Like I've been repeatedly told here, the best thing in such cases is not to use a list comprehension at all: result = [] for item in item_list: if cond1(item): value = foo(item) if cond2(value): result.append((item, value)) But I am stubbborn, so let's see what I can come up with (and keep the comprehension) (oh, wait -- I got your code all wrong. Still - unwrapping and having intermediate variables is the straight way for not to repeat the call) A: How does this look? result = [ (i, fi) for i in item_list if cond1(i) for fi in (foo(i),) if cond2(fi) ] A: Use generator expressions. result = [(item, foo_item) for item, foo_item in ((i, foo(i)) for i in item_list) if cond1(item) and cond2(foo_item)] The interpreter will go through every element exactly once, because generator expression will calculate (i, foo(i)) only when it is required by the outer loop. Assuming that foo is expensive and has no side effects, I'd even try to do this: result = [(item, foo_item) for item, foo_item in ((i, foo(i)) for i in item_list if cond1(i)) if cond2(foo_item)] so that foo will not be called for elements which do not pass the first condition. Actually this looks better for me when written functionally: from itertools import imap, ifilter result = filter((lambda i,f:cond2(f)), imap((lambda i:(i, foo(i))), ifilter(cond1, item_list))) ...but I might be subjective. A: This is one of the many reasons that we have generators: def generator( items ): for item in items: if cond1(item): food = foo(item) if food: yield item, food result = list(generator(item_list)) LCs are only good when they look good - if you have to spread them over 3 lines just to make them readable it's a bad idea.
Optimize a list comprehension
Here is a code snippet that shows the code I would like to optimize: result = [(item, foo(item)) for item in item_list if cond1(item) and cond2(foo(item))] In the above snippet I call foo(item) twice. I can't think of a way to iterate over the list only once maintain both item and foo(item) for the conditional and the result list. That is, I would like to keep item and foo(item) without having to loop over the list twice and without having to call foo(item) twice. I know I can do it with a second nested list comprehension: result = [(item, foo_item) for item, foo_item in [(i, foo(i)) for i in item_list] if cond1(item) and cond2(foo_item)] but that appears to loop through item_list twice which I would like to avoid. So the first example calls foo twice per list item. The second example loops through the list twice (or appears to). I'd like to loop one time and call foo once for each item.
[ "It doesn't, but here:\nresult = [(item, foo_item)\n for item, foo_item in ((i, foo(i)) for i in item_list)\n if cond1(item) and cond2(foo_item)]\n\nTurning the inner list comprehension into a generator expression makes sure that we don't use an unnecessary temporary list.\n", "Like I've been repeatedly tol...
[ 4, 4, 3, 3, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003251480_list_comprehension_python.txt
Q: Find an element and return the XPath to it using Python I'm using Python 2.4/2.5, with libxm2dom. I can import an HTML document, and build the DOM. Is there a way to programmatically "search" for a given term, and be able to craft the XPath function to extract the href for the term? For example, given this chunk of HTML from the document: ... <a href="dog">bigdog</a> ... I'd like to have an XPath function that would find bigdog, and return the XPath to get the href link. A: This XPATH will select the @href of the a element who's text is "bigdog". //a[text()='bigdog']/@href
Find an element and return the XPath to it using Python
I'm using Python 2.4/2.5, with libxm2dom. I can import an HTML document, and build the DOM. Is there a way to programmatically "search" for a given term, and be able to craft the XPath function to extract the href for the term? For example, given this chunk of HTML from the document: ... <a href="dog">bigdog</a> ... I'd like to have an XPath function that would find bigdog, and return the XPath to get the href link.
[ "This XPATH will select the @href of the a element who's text is \"bigdog\".\n//a[text()='bigdog']/@href\n\n" ]
[ 0 ]
[]
[]
[ "libxml2", "python", "python_2.x", "xpath" ]
stackoverflow_0003275794_libxml2_python_python_2.x_xpath.txt
Q: why model has the key_name don't has the key().id() on google-app-engine if i use this : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A() a.a='sss' a.put() raise Exception(a.key().id()) i can get the a.key().id() is 961 but if i add key_name="aaa" , the a.key().id() will be None : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A(key_name="aaa") a.a='sss' a.put() raise Exception(a.key().id()) so how can i get the key().id() when i set a key_name thanks A: You can't, because they're the same thing. The fact that entities have an encoded string key plus either an integer ID or a string name can give the misleading impression that the various ways to refer to an entity are overlapping or redundant. They're not. A key name is like a filename within a filesystem. An ID is like a filename that the system has picked automatically. The key itself is like the full path to the file, including directories. Consider the Key.from_path method: k = Key.from_path('User', 'Boris', 'Address', 9876) kind=User&name=Boris is like a directory, and kind=Address&name=9876 is like a file containing your entity. The key returned is just an encoded version that path. App Engine relies on each entity have one fixed, immutable path, ergo one key. If an entity could be represented by both a user-assigned name and a system-assigned ID, this would mean that a single entity with n ancestors could have 2^(n+1) different paths and keys.
why model has the key_name don't has the key().id() on google-app-engine
if i use this : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A() a.a='sss' a.put() raise Exception(a.key().id()) i can get the a.key().id() is 961 but if i add key_name="aaa" , the a.key().id() will be None : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A(key_name="aaa") a.a='sss' a.put() raise Exception(a.key().id()) so how can i get the key().id() when i set a key_name thanks
[ "You can't, because they're the same thing.\nThe fact that entities have an encoded string key plus either an integer ID or a string name can give the misleading impression that the various ways to refer to an entity are overlapping or redundant. They're not.\nA key name is like a filename within a filesystem. An I...
[ 6 ]
[]
[]
[ "google_app_engine", "key", "python" ]
stackoverflow_0003276558_google_app_engine_key_python.txt
Q: how to Reference the variable via db.run_in_transaction on google-app-engine this is my code: class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a='' def fn(): global a a=A(a='www') a.put() db.run_in_transaction(fn) raise Exception(a.key()) and the error is : raise Exception(a.key()) AttributeError: 'str' object has no attribute 'key' so how to get the right 'a' , thanks A: Try this: class demo(BaseRequestHandler): def get(self): def fn(): a=A(a='www') a.put() return a a = db.run_in_transaction(fn) raise Exception(a.key())
how to Reference the variable via db.run_in_transaction on google-app-engine
this is my code: class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a='' def fn(): global a a=A(a='www') a.put() db.run_in_transaction(fn) raise Exception(a.key()) and the error is : raise Exception(a.key()) AttributeError: 'str' object has no attribute 'key' so how to get the right 'a' , thanks
[ "Try this:\nclass demo(BaseRequestHandler):\n def get(self):\n def fn():\n a=A(a='www')\n a.put()\n return a\n a = db.run_in_transaction(fn)\n raise Exception(a.key())\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "transactions" ]
stackoverflow_0003276736_google_app_engine_python_transactions.txt
Q: MySQL: conduct a basic search I have a names table in my database and I would wish to conduct a fuzzy search on it for example my database contains: Name ID John Smith 1 Edward Smith 2 Gabriel Gray 3 Paul Roberts 4 At the moment when I search the database via python I can only do exact match searching. But I would like to be able to do fuzzy searching where by I can search for the name "smith" and bring back John Smith and Edward Smith. A: In simplest form, you'd use the LIKE comparison: SELECT * FROM table WHERE name LIKE '%smith%'; More elaborate searches can de done with FULLTEXT index (large amounts of text), SOUNDEX() (works on words in the english language, matching on other languages is everything from 'somewhat workable' to 'terrible'), levenshtein distance of words etc. A: import MySQLdb search_str = 'smith' conn = MySQLdb.connect(host="localhost", user="me",passwd="pw",db="mydb") c = conn.cursor() c.execute("SELECT name FROM mytable WHERE name LIKE %s", '%' + search_str + '%') c.fetchall() c.close() conn.close()
MySQL: conduct a basic search
I have a names table in my database and I would wish to conduct a fuzzy search on it for example my database contains: Name ID John Smith 1 Edward Smith 2 Gabriel Gray 3 Paul Roberts 4 At the moment when I search the database via python I can only do exact match searching. But I would like to be able to do fuzzy searching where by I can search for the name "smith" and bring back John Smith and Edward Smith.
[ "In simplest form, you'd use the LIKE comparison:\nSELECT * FROM table WHERE name LIKE '%smith%';\n\nMore elaborate searches can de done with FULLTEXT index (large amounts of text), SOUNDEX() (works on words in the english language, matching on other languages is everything from 'somewhat workable' to 'terrible'), ...
[ 5, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003276904_mysql_python.txt
Q: Fabric auto-login in Windows Relevant question: fabric password I configured Putty to login with private-public keys (no password) using this guide: http://www.codelathe.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/ It works. Now I want to run Fabric with no password prompt. This does not work and I get prompted for a password. I'm assuming Paramiko (or some other Fabric dependency) does not find the ppk file. Where do I place the private key file and how do I tell fabric / paramiko about it? Running on Vista, using Python 2.6.5 and latest Fabric (0.91) / Putty (0.60). A: Adding the following to your fabfile.py should work: env.user = "your_username" env.key_filename = ["/path/to/keyfile"] See the fabric docs.
Fabric auto-login in Windows
Relevant question: fabric password I configured Putty to login with private-public keys (no password) using this guide: http://www.codelathe.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/ It works. Now I want to run Fabric with no password prompt. This does not work and I get prompted for a password. I'm assuming Paramiko (or some other Fabric dependency) does not find the ppk file. Where do I place the private key file and how do I tell fabric / paramiko about it? Running on Vista, using Python 2.6.5 and latest Fabric (0.91) / Putty (0.60).
[ "Adding the following to your fabfile.py should work:\nenv.user = \"your_username\"\nenv.key_filename = [\"/path/to/keyfile\"]\n\nSee the fabric docs.\n" ]
[ 9 ]
[]
[]
[ "fabric", "paramiko", "python", "ssh", "windows" ]
stackoverflow_0003277022_fabric_paramiko_python_ssh_windows.txt
Q: Python: is it possible to mix generator and a recursive function? Is there a way to make the something like the following code work? add = lambda n: (yield n) or add(n+1) (answers don't need to be in functional style) A: I'm not sure of the intent of "yield(n) or add(n+1)", but recursive generators are certainly possible. You might want to read the link below to get a grip on what's possible, in particular the section titled "Recursive Generators". Python Generator Tricks A: def add(n): yield n for m in add(n+1): yield m With recursive generators it's easy to build elaborate backtrackers: def resolve(db, goals, cut_parent=0): try: head, tail = goals[0], goals[1:] except IndexError: yield {} return try: predicate = ( deepcopy(clause) for clause in db[head.name] if len(clause) == len(head) ) except KeyError: return trail = [] for clause in predicate: try: unify(head, clause, trail) for each in resolve(db, clause.body, cut_parent + 1): for each in resolve(db, tail, cut_parent): yield head.subst except UnificationFailed: continue except Cut, cut: if cut.parent == cut_parent: raise break finally: restore(trail) else: if is_cut(head): raise Cut(cut_parent) ... for substitutions in resolve(db, query): print substitutions This is a Prolog engine implemented by a recursive generator. db is a dict representing a Prolog database of facts and rules. unify() is the unification function that creates all substitutions for the current goal and appends the changes to the trail, so they can be undone later. restore() does the undoing, and is_cut() tests if the current goal is a '!', so that we can do branch pruning. A: Your function seems to me just to be other expression for unbound sequence: n, n+1, n+2,.... def add(x): while True: yield x x+=1 for index in add(5): if not index<100: break ## do equivalent of range(5,100) print(index) This is not recursive, but I see no need for recursive style here. The recursive version based on the other answers link, which had generators calling generators, but not recursively: from __future__ import generators def range_from(n): yield n for i in range_from(n+1): yield i for i in range_from(5): if not i<100: break ## until 100 (not including) print i
Python: is it possible to mix generator and a recursive function?
Is there a way to make the something like the following code work? add = lambda n: (yield n) or add(n+1) (answers don't need to be in functional style)
[ "I'm not sure of the intent of \"yield(n) or add(n+1)\", but recursive generators are certainly possible. You might want to read the link below to get a grip on what's possible, in particular the section titled \"Recursive Generators\".\n\nPython Generator Tricks\n\n", "def add(n):\n yield n\n for m in add...
[ 3, 3, 0 ]
[]
[]
[ "generator", "python", "recursion" ]
stackoverflow_0003276956_generator_python_recursion.txt
Q: extend/append list I would like to either extend or append a list to the content of another list: I've got the following: l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] m = ['first', 'second', 'third'] for i in range(len(l)): result = [] for n in m: if n == "first": r=[] for word, number in ls[i]: temp = [word, number] r.append(temp) for t in r: result.extend(t) print result I would like to see the following result when the 'result' is printed out in the above code (each in newline): ['AA', 1.11, 'XX', 7.77] ['BB', 2.22, 'YY', 8.88] ['CC', 3.33, 'ZZ', 9.99] Many thanks in advance. A: All you need is zip: l = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] for x,y in zip(l,ls): print(list(x+y)) # ['AA', 1.1100000000000001, 'XX', 7.7699999999999996] # ['BB', 2.2200000000000002, 'YY', 8.8800000000000008] # ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002] A: You want the zip function: >>> for x in zip(l, ls): >>> list1, list2 = x >>> print list1 + list2 >>> ['AA', 1.1100000000000001, 'XX', 7.7699999999999996] >>> ['BB', 2.2200000000000002, 'YY', 8.8800000000000008] >>> ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002] 1: http://docs.python.org/library/functions.html#zip "zip A: Here's one way: import itertools for a, b, c in itertools.izip(l, ls, m): result = list(a) + list(b) + [c] print result The output: ['AA', 1.1100000000000001, 'XX', 7.7699999999999996, 'first'] ['BB', 2.2200000000000002, 'YY', 8.8800000000000008, 'second'] ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002, 'third']
extend/append list
I would like to either extend or append a list to the content of another list: I've got the following: l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] m = ['first', 'second', 'third'] for i in range(len(l)): result = [] for n in m: if n == "first": r=[] for word, number in ls[i]: temp = [word, number] r.append(temp) for t in r: result.extend(t) print result I would like to see the following result when the 'result' is printed out in the above code (each in newline): ['AA', 1.11, 'XX', 7.77] ['BB', 2.22, 'YY', 8.88] ['CC', 3.33, 'ZZ', 9.99] Many thanks in advance.
[ "All you need is zip:\nl = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33))\nls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]\n\nfor x,y in zip(l,ls):\n print(list(x+y))\n\n# ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]\n# ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]\n# ['CC', 3.3300000000000001, 'ZZ', ...
[ 11, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003277216_python.txt
Q: how to parse the remainder: [0] on google-app-engine my code is : class demo(BaseRequestHandler): def get(self): a=[[1,2,3],[3,6,9]] self.render_template('map/a.html',{'geo':a}) and the html is : {% for i in geo %} <p><a href="{{ i[0] }}">{{ i[0]}}</a></p> {% endfor%} and the error is : raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] TemplateSyntaxError: Could not parse the remainder: [0] so what should i do . thanks A: If you want the page to show the first item of each list: {% for i in geo %} <p><a href="{{ i.0 }}">{{ i.0 }}</a></p> {% endfor%} A: It doesn't mean you need to parse the remainder; it's saying the template engine tried to parse your i[0], understood i, but was unable to parse the remainder of the string, [0]. It looks like you can't index arrays that way; you may need to do something like this: {% for i,j,k in geo %} <p><a href="{{ i }}">{{ i}}</a></p> {% endfor%}
how to parse the remainder: [0] on google-app-engine
my code is : class demo(BaseRequestHandler): def get(self): a=[[1,2,3],[3,6,9]] self.render_template('map/a.html',{'geo':a}) and the html is : {% for i in geo %} <p><a href="{{ i[0] }}">{{ i[0]}}</a></p> {% endfor%} and the error is : raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:] TemplateSyntaxError: Could not parse the remainder: [0] so what should i do . thanks
[ "If you want the page to show the first item of each list:\n{% for i in geo %}\n <p><a href=\"{{ i.0 }}\">{{ i.0 }}</a></p>\n{% endfor%}\n\n", "It doesn't mean you need to parse the remainder; it's saying the template engine tried to parse your i[0], understood i, but was unable to parse the remainder of the str...
[ 8, 1 ]
[]
[]
[ "arrays", "google_app_engine", "python" ]
stackoverflow_0003277108_arrays_google_app_engine_python.txt
Q: Implementing class descriptors by subclassing the `type` class I'd like to have some data descriptors as part of a class. Meaning that I'd like class attributes to actually be properties, whose access is handled by class methods. It seems that Python doesn't directly support this, but that it can be implemented by subclassing the type class. So adding a property to a subclass of type will cause its instances to have descriptors for that property. Its instances are classes. Thus, class descriptors. Is this advisable? Are there any gotchas I should watch out for? A: Is this what you mean by "class attributes to actually be properties, whose access is handled by class methods"? You can use a decorator property to make an accessor appear to be an actual data member. Then, you can use the x.setter decorator to make a setter for that attribute. Be sure to inherit from object, or this won't work. class Foo(object): def __init__(self): self._hiddenx = 3 @property def x(self): return self._hiddenx + 10 @x.setter def x(self, value): self._hiddenx = value p = Foo() p.x #13 p.x = 4 p.x #14 A: It is convention (usually), for a descriptor, when accessed on a class, to return the descriptor object itself. This is what property does; if you access a property object on a class, you get the property object back (because that's what it's __get__ method chooses to do). But that's a convention; you don't have to do it that way. So, if you only need to have a getter descriptor on your class, and you don't mind that a an attempt to set will overwrite the descriptor, you can do something like this with no metaclass programming: def classproperty_getter_only(f): class NonDataDescriptor(object): def __get__(self, instance, icls): return f(icls) return NonDataDescriptor() class Foo(object): @classproperty_getter_only def flup(cls): return 'hello from', cls print Foo.flup print Foo().flup for ('hello from', <class '__main__.Foo'>) ('hello from', <class '__main__.Foo'>) If you want a full fledged data descriptor, or want to use the built-in property object, then you're right you can use a metaclass and put it there (realizing that this attribute will be totally invisible from instances of your class; metaclasses are not examined when doing attribute lookup on an instance of a class). Is it advisable? I don't think so. I wouldn't do what you're describing casually in production code; I would only consider it if I had a very compelling reason to do so (and I can't think of such a scenario off the top of my head). Metaclasses are very powerful, but they aren't well understood by all programmers, and are somewhat harder to reason about, so their use makes your code harder to maintain. I think this sort of design would be frowned upon by the python community at large.
Implementing class descriptors by subclassing the `type` class
I'd like to have some data descriptors as part of a class. Meaning that I'd like class attributes to actually be properties, whose access is handled by class methods. It seems that Python doesn't directly support this, but that it can be implemented by subclassing the type class. So adding a property to a subclass of type will cause its instances to have descriptors for that property. Its instances are classes. Thus, class descriptors. Is this advisable? Are there any gotchas I should watch out for?
[ "Is this what you mean by \"class attributes to actually be properties, whose access is handled by class methods\"?\nYou can use a decorator property to make an accessor appear to be an actual data member. Then, you can use the x.setter decorator to make a setter for that attribute.\nBe sure to inherit from object,...
[ 1, 1 ]
[]
[]
[ "class", "class_attributes", "descriptor", "properties", "python" ]
stackoverflow_0003277047_class_class_attributes_descriptor_properties_python.txt
Q: Is Python-based software considered less-professional than C++/compiled software? I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK. The C++ SDK documentation appears incomplete in certain areas and isn't documented that well. The Python SDK docs appear more complete and in general are much easier to work with. So I'm trying to decide if I want to go through the potential trouble of building a C++ plugin instead of a Python plugin to sell. About the only thing that makes me want to do a C++ plugin is that in my mind, a "C++ plugin" might be an easier sell than a "Python plugin". A lot of programmers out there don't even considered writing Python to be real "programming". Do you think that potential customers might say "Why would I pay money for a measly little Python script?"? As opposed to "Oh it was written in C++ so the guy must be a decent programmer"? Writing the Python plugin would be faster. Both plugins would look and behave exactly the same. The C++ plugin might be faster in certain spots, but for the type of plugin this is, that's not a huge deal. So my question is, would a Python plugin be considered not as professional/sellable as a C++ plugin, even if it looks and acts EXACTLY the same as a C++ plugin? A: A lot of programmers out there don't even considered writing Python to be real "programming". A lot of "programmers" out there are incompetent, too. Do you think that potential customers might say "Why would I pay money for a measly little Python script?"? I'm sure it depends on the type of software, but I can tell you that my program's customers have little interest in what we use to develop our product, and I doubt most of them know that the software is written in C++. They just care that it works. So my question is, would a Python plugin be considered not as professional/sellable as a C++ plugin, even if it looks and acts EXACTLY the same as a C++ plugin? No. A: I think it doesn't matter. It all come down to 'use the right tool for the right job'. Your primary goal should be to make the best plugin you can. So if you feel more at ease with Python use that. It will probably take you less time to write. The client probably doesn't mind it and just want the most stable, reliable, cheapest, easiest to use plugin. So concentrate on that not on the tool. A: I'm not sure what kind of answer is appropriate for this question, it seems to deserve more of a marketing answer than a technical answer. If your customer is not someone who would be knowledgeable about the differences between languages, or even what a programming language is, then why mention it? But if your customer is knowledgeable, and if your plugin delivers real value and does something useful, I don't see why it should matter. I will admit that there is something to what you're saying: years ago I had the option of buying a license for a Javascript widget toolkit, and I had the same reaction you are describing: why would I pay this? That wasn't the right reason to reject that toolkit: the right reason was to reject it because of the number of freely available and well-supported alternatives. So, to repeat myself: if your plugin does something new, valuable and not otherwise available (or not easily available), then push it on those merits instead of which language you've written it in. Some very complex software is written in Python, from the Listen media player to YouTube. Finally, if you didn't know, there are ways of distributing compiled PYC files. A: Python will also have the advantage/disadvantage (depending on what you want) that the source code must be open. (I think delivering only the .pyc file is not really an option as the Python bytecode format is changing in every release.) Otherwise, let's say you are selling to people who don't really know what the difference is between Python/C++: The outcome is the important thing. If your Python plugin runs and feels stable and fast, it is fine. If they have heard about both languages, there really may be a difference. I must admit, if I had a choice between two plugins which do exactly the same and which are perfectly stable from all user reports, I probably would prefer the C++ plugin. It would be my intuition which would tell me that the C++ code is probably slightly more stable and faster. This is also for Unix tools and other stuff.
Is Python-based software considered less-professional than C++/compiled software?
I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK. The C++ SDK documentation appears incomplete in certain areas and isn't documented that well. The Python SDK docs appear more complete and in general are much easier to work with. So I'm trying to decide if I want to go through the potential trouble of building a C++ plugin instead of a Python plugin to sell. About the only thing that makes me want to do a C++ plugin is that in my mind, a "C++ plugin" might be an easier sell than a "Python plugin". A lot of programmers out there don't even considered writing Python to be real "programming". Do you think that potential customers might say "Why would I pay money for a measly little Python script?"? As opposed to "Oh it was written in C++ so the guy must be a decent programmer"? Writing the Python plugin would be faster. Both plugins would look and behave exactly the same. The C++ plugin might be faster in certain spots, but for the type of plugin this is, that's not a huge deal. So my question is, would a Python plugin be considered not as professional/sellable as a C++ plugin, even if it looks and acts EXACTLY the same as a C++ plugin?
[ "\nA lot of programmers out there don't even considered writing Python to be real \"programming\".\n\nA lot of \"programmers\" out there are incompetent, too.\n\nDo you think that potential customers might say \"Why would I pay money for a measly little Python script?\"?\n\nI'm sure it depends on the type of softwa...
[ 6, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0003277376_c++_python.txt
Q: Set Django ModelForm visible fields at runtime? I have a Django model: class Customer(models.Model): first_name=models.CharField(max_length=20,null=True, blank=True) last_name=models.CharField(max_length=25,null=True, blank=True) address=models.CharField(max_length=60,null=True, blank=True) address2=models.CharField(max_length=60,null=True, blank=True) city=models.CharField(max_length=40,null=True, blank=True) state=models.CharField(max_length=2,null=True, blank=True) From there, I created a ModelForm: class CustomerForm(forms.ModelForm): class Meta: model=Customer I'd like to be able to show pieces of the form in my template corresponding to specific information the users can change. For example, if I want to let the customers change their name, I'd like to be able to show a form that only has the fields 'first_name' and 'last_name'. One way to do this would be to create a ModelForm for each of the various field snippets... for the name example, it would look something like: class CustomerFormName(forms.ModelForm): class Meta: model=Customer fields=('first_name','last_name') This seems pretty inelegant, and inflexible. What I'd like to do is be able to specify the fields at runtime, so when I pass the dictionary from the view to the template, I can just set which fields I'd like to show. How can I set it up so that I set the fields for a form at runtime? I'd ideally like the final dictionary passed to look something like this: {'name_change_form':CustomerFormName(<form with only first_name and last_name>), 'address_change_form':CustomerFormName(<form with only address fields>)} Then, I know that whenever I output name_change_form.as_p, it'll have exactly the form fields that I'm looking for. Thoughts? Also feel free to recommend a better way to do it. A: from django.forms import ModelForm from wherever import Customer def formClassFactory(model,fields): ff = fields mm = model class formClass(ModelForm): class Meta: model = mm fields = ff return formClass form_class = formClassFactory( ('first_name','last_name') )
Set Django ModelForm visible fields at runtime?
I have a Django model: class Customer(models.Model): first_name=models.CharField(max_length=20,null=True, blank=True) last_name=models.CharField(max_length=25,null=True, blank=True) address=models.CharField(max_length=60,null=True, blank=True) address2=models.CharField(max_length=60,null=True, blank=True) city=models.CharField(max_length=40,null=True, blank=True) state=models.CharField(max_length=2,null=True, blank=True) From there, I created a ModelForm: class CustomerForm(forms.ModelForm): class Meta: model=Customer I'd like to be able to show pieces of the form in my template corresponding to specific information the users can change. For example, if I want to let the customers change their name, I'd like to be able to show a form that only has the fields 'first_name' and 'last_name'. One way to do this would be to create a ModelForm for each of the various field snippets... for the name example, it would look something like: class CustomerFormName(forms.ModelForm): class Meta: model=Customer fields=('first_name','last_name') This seems pretty inelegant, and inflexible. What I'd like to do is be able to specify the fields at runtime, so when I pass the dictionary from the view to the template, I can just set which fields I'd like to show. How can I set it up so that I set the fields for a form at runtime? I'd ideally like the final dictionary passed to look something like this: {'name_change_form':CustomerFormName(<form with only first_name and last_name>), 'address_change_form':CustomerFormName(<form with only address fields>)} Then, I know that whenever I output name_change_form.as_p, it'll have exactly the form fields that I'm looking for. Thoughts? Also feel free to recommend a better way to do it.
[ "from django.forms import ModelForm\nfrom wherever import Customer\ndef formClassFactory(model,fields):\n ff = fields\n mm = model\n class formClass(ModelForm):\n class Meta:\n model = mm\n fields = ff\n return formClass\nform_class = formClassFactory( ('first_name','last_name') )\n\n" ]
[ 4 ]
[]
[]
[ "django", "modelform", "models", "python", "runtime" ]
stackoverflow_0003276896_django_modelform_models_python_runtime.txt
Q: Python object oriented model I have something like the follwing. A person having many colors of cars of the same model belonging to some state. I have designed a person class as having attributes person name, car model, car year, car state, and car color as attributes. And color should be a list as a person can have many cars of different colors but of the same model. Now how do I find and print 2 different people who have same model of car and same color of car but belong to different states in object oriented terms? I am new to Python. While inserting color into the person object how do I insert into the list and how do I retrieve from the list? I know how to do it for an attribute, but I am a little confused about list operations. The data can be like this: person1 ford [red,blue,yellow] new-york person2 honda [red,blue] new-york person3 ford [red,grey] california person4 ford [red] california person5 honda [red] new-york Now my result should only be: [(person1,person5)] (same model car,same color, different state) A: You might want to model state and car separately from person. Then, each person can have a list of cars, and live in a state (or even a list of states, depending on your model). These are has-a relationships. It will also allow you to subclass car later and make sportsCar later, if you want. A: You wanted to know a little about list manipulation: $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l=[] >>> l.append("honda") >>> l.append("ford") >>> l ['honda', 'ford'] >>> l[0] 'honda' >>> l.pop(0) 'honda' >>> l.pop(0) 'ford' >>> l.pop(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop from empty list If you want to find several persons with matching attributes, you could do some iteration (represented here in some psuedo-code, because I think focussing on the algorithm is more useful than focussing on the python to make it happen): results = [] foreach p1 in [list of people] foreach p2 in [list of people] next if p1 == p2 next if p1.state == p2.state next unless p1.car == p2.car foreach c1 in p1.colors foreach c2 in p2.colors results.append((p1,p2)) if c1 == c2 This code compares pairs of people. It doesn't compare a person against themself. It doesn't compare people who live in the same state because you asked for ".. but belong to different states". So let's filter those same-state people out. It compares only people who own the identical kind of car. (If people owned different types of cars, then you'd just add two more nested for loops.) Then it notes the pairs of people that have the same color of car. There's a potential bug in this algorithm: it'll report [(person1, person2), (person2, person1)]. So entries are duplicated. It's possible to amend the algorithm to search just the upper or lower triangle of people if you don't want this duplication: results = [] for i=0; i<people.last_index-1; i++ for j=i+1; j<people.last_index ; j++ p1 = people[i] ; p2 = people[j] next if p1.state == p2.state next unless p1.car == p2.car foreach c1 in p1.colors foreach c2 in p2.colors results.append((p1,p2)) if c1 == c2 Note we can remove the next if p1 == p2 check because we explicitly cannot get i == j. j is defined to start with i+1. A: There are a bunch of ways to do this. If you have a lot of data then I'd recommend that you go ahead and tackle a database based implementation using python's built-in sqlite support (which is actually not that hard). A database engine is purpose built for searching. You would need two tables since you can have multiple colors per person. The person table would have the following columns: id, name, model, state. The colors table would have: personid, color. The personid column would contain the id number that the row in the color table corresponds to. You can then have multiple rows in the color table with the same personid value (which is the database version of a list). sqlAlchemy is a library to help implement a database using python objects which you may find more appropriate with what you are trying to do. The sqlAlchemy ORM Tutorial walks you through working with an sqlite database with two tables (users, addresses) that are very similar to what you would need. Now if you want stick with python classes alone you are going to have to have a list of people instances and iterate through them all looking for matches. A handy simplification for your color matching is to convert the color lists to sets and do an intersection. >>> s1 = set(['red','blue','yellow']) >>> s2 = set(['red','blue']) >>> s1.intersection(s2) set(['blue', 'red']) A shortcut for your iteration through the list of people instances is to use python's itertools library and use the permutations generator. from itertools import permutations people = ['p1', 'p2', 'p3'] for p1, p2 in itertools.permutations(people,2): print p1, p2 p1 p2 p1 p3 p2 p1 p2 p3 p3 p1 p3 p2 Hopefully this is enough to help you along your way. Rereading your question it looks like you may need to do more reading on programming in python. But to address your question about lists here is a little bit of code that may help you out. class Person(object): def __init__(self, name, model, colors, state): self.name = name self.model = model self.colors = colors self.state = state p1 = Person('p1', 'ford', ['red', 'blue'], 'new-york') p2 = Person('p2', 'honda', ['red', 'blue'], 'new-york') persons = [p1, p2] # or persons = [] persons.append(p1) persons.append(p2) p1.color.append('yellow') # or persons[0].color.append('yellow')
Python object oriented model
I have something like the follwing. A person having many colors of cars of the same model belonging to some state. I have designed a person class as having attributes person name, car model, car year, car state, and car color as attributes. And color should be a list as a person can have many cars of different colors but of the same model. Now how do I find and print 2 different people who have same model of car and same color of car but belong to different states in object oriented terms? I am new to Python. While inserting color into the person object how do I insert into the list and how do I retrieve from the list? I know how to do it for an attribute, but I am a little confused about list operations. The data can be like this: person1 ford [red,blue,yellow] new-york person2 honda [red,blue] new-york person3 ford [red,grey] california person4 ford [red] california person5 honda [red] new-york Now my result should only be: [(person1,person5)] (same model car,same color, different state)
[ "You might want to model state and car separately from person. Then, each person can have a list of cars, and live in a state (or even a list of states, depending on your model). These are has-a relationships. It will also allow you to subclass car later and make sportsCar later, if you want.\n", "You wanted to k...
[ 2, 2, 2 ]
[]
[]
[ "class_design", "oop", "python" ]
stackoverflow_0003277404_class_design_oop_python.txt
Q: Error using redirect in pylons Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simpleform.html') def submit(self): # Code to perform some action based on the form data # ... h.redirect_to(controller='formtest', action='result') def result(self): return 'Your data was successfully submitted.' First I noticed that in the book the author indicates to import redirect_to you executing the following import: from pylons.controllers.util import redirect_to This seems to be incorrect, as redirect_to lives in the routes module so I changed it to this: from routes import redirect_to everything works fine, no more import error, but when I execute a form submit, i see the following traceback h.redirect_to(controller='formtest', action='result') target = url_for(*args, **kargs) encoding = config.mapper.encoding return getattr(self.__shared_state, name) AttributeError: 'thread._local' object has no attribute 'mapper' can anyone help me? A: Try: from pylons import url from pylons.controllers.util import redirect # ... redirect(url(controller='formtest', action='result')) You might be better off using the current Pylons 1.0 documentation and the QuickWiki tutorial updated for 1.0, among other references on the site.
Error using redirect in pylons
Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simpleform.html') def submit(self): # Code to perform some action based on the form data # ... h.redirect_to(controller='formtest', action='result') def result(self): return 'Your data was successfully submitted.' First I noticed that in the book the author indicates to import redirect_to you executing the following import: from pylons.controllers.util import redirect_to This seems to be incorrect, as redirect_to lives in the routes module so I changed it to this: from routes import redirect_to everything works fine, no more import error, but when I execute a form submit, i see the following traceback h.redirect_to(controller='formtest', action='result') target = url_for(*args, **kargs) encoding = config.mapper.encoding return getattr(self.__shared_state, name) AttributeError: 'thread._local' object has no attribute 'mapper' can anyone help me?
[ "Try:\nfrom pylons import url\nfrom pylons.controllers.util import redirect\n\n# ...\nredirect(url(controller='formtest', action='result'))\n\nYou might be better off using the current Pylons 1.0 documentation and the QuickWiki tutorial updated for 1.0, among other references on the site.\n" ]
[ 6 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003277765_pylons_python.txt
Q: Possible to pass more than 1 argument to a context processor in Django? Is it possible to pass more than 1 argument to a context processor in Django? In other words, in addition to the HttpRequest object, I would like to pass 1 or more additional argument? A: Store whatever variables you would want in the session. Then you can access it through the request. A: You might want to look into custom tags: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags Make sure that your template tags module is in a templatetags subdir of a loaded module. I.e. if you have a "foo" module in your INSTALLED_APPS, make sure that, wherever foo is located, there is a: foo/templatetags/blurf.py that contains the tags and filters you want. Then you can: {% load blurf %} in your template, and if blurf has a grok tag with two arguments defined, then you can: {% grok 1 2 %} in that template.
Possible to pass more than 1 argument to a context processor in Django?
Is it possible to pass more than 1 argument to a context processor in Django? In other words, in addition to the HttpRequest object, I would like to pass 1 or more additional argument?
[ "Store whatever variables you would want in the session. Then you can access it through the request.\n", "You might want to look into custom tags:\nhttp://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags\nMake sure that your template tags module is in a templatetags subdir of a...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003277307_django_python.txt
Q: Using Lambdas to build executable functions from string expressions I'm using python, and I want a function that takes a string containing a mathematical expression of one variable (x) and returns a function that evaluates that expression using lambdas. Syntax should be such: f = f_of_x("sin(pi*x)/(1+x**2)") print f(0.5) 0.8 syntax should allow ( ) as well as [ ] and use standard operator precedence. Trig functions should have precedence lower than multiplication and higher than addition. Hence the string 'sin 2x + 1' would be equivalent to sin(2x)+1, though both are valid. This is for evaluating user input of algebraic and trigonometric expressions, so think math syntax not programming syntax. The list of supported functions should be easily extensible and the code should be clear and easy to understand. It's OK not to collapse constant expressions. The sample function here is incomplete. It takes a nested list representing the expression and generates an appropriate function. While somewhat easy to understand, even this seems ugly for python. import math def f_of_x(op): if (isinstance((op[0]), (int, long, float, complex)) ): return (lambda x:op[0]) elif op[0]=="pi": return lambda x: 3.14159265358979 elif op[0]=="e": return lambda x: 2.718281828459 elif op[0]=="x": return lambda x: x elif op[0]=="sin": return lambda x: math.sin(f_of_x(op[1])(x)) elif op[0]=="cos": return lambda x: math.cos(f_of_x(op[1])(x)) elif op[0]=="tan": return lambda x: math.tan(f_of_x(op[1])(x)) elif op[0]=="sqrt": return lambda x: math.sqrt(f_of_x(op[1])(x)) elif op[0]=="+": return lambda x: (f_of_x(op[1])(x))+(f_of_x(op[2])(x)) elif op[0]=="-": return lambda x: (f_of_x(op[1])(x))-(f_of_x(op[2])(x)) elif op[0]=="*": return lambda x: (f_of_x(op[1])(x))*(f_of_x(op[2])(x)) elif op[0]=="/": return lambda x: (f_of_x(op[1])(x))/(f_of_x(op[2])(x)) elif op[0]=="**": return lambda x: (f_of_x(op[1])(x))**(f_of_x(op[2])(x)) # should never get here with well formed input return def test(): # test function f(x) = sin(pi*x)/(1+x**2) s = ['/',['sin',['*',['pi'],['x']]],['+',[1],['**',['x'],[2]]]] f = f_of_x(s) for x in range(30): print " "*int(f(x*0.2)*30+10)+"x" As a general guideline, think of your solution as a tutorial on lambdas and parsers - not code golf. The sample code is just that, so write what you feel is clearest. A: How about this: import math def f_of_x(op): return eval("lambda x:" + op, math.__dict__) It can easily be made to support [] as well as () and uses standard operator precedence. It does not let you use trig functions without parens, though, nor does it let you imply multiplication by juxtaposition (like 2x). The list of supported functions is easily extensible, however, and the code is probably as clear and easy to understand as you can get. If you absolutely need the extra features, look at http://christophe.delord.free.fr/tpg/. The example given on that page can be easily modified to do everything you want. A: If you insist on using, for your expressions, a language drastically different from Python (in which all functions are always called with parentheses, while you want to allow several functions to be called without -- allow 2x to stand for 2 * x -- and so forth), you'll first need to parse the string, e.g. with pyparsing (a self-contained solution), or ply (the "python lexx and yacc") if you want a more traditional approach based on a lexical analyzer and a separate "compiler's compiler" (that's what the two "c"s in yacc stand for: Yet Another Compiler's Compiler). From this parser's output, you then might generate Python syntax to be compiled -- however, there is no real reason to generate a lambda rather than a plain def, since you'll have to compile either of them anyway. So, thinking of the approach as a "tutorial on lambdas" would be really weird, since the decision to use lambda would be arbitrary and very debatable. We're talking about a few hours' worth of programming, and probably well over 100 lines of resulting Python code if you hope for any clarity whatsoever. I consider this definitely out of scope for what's intended as the normal scope for a SO question and answer. Substantially less work would be to generate a private kind of bytecode (and have a simple interpreter in Python for that private code) -- but then lambda (which is even in the title of your question, clarifying that you're all-consumed with the importance of using that keyword in the solution) would be even crazier to use (since the obvious approach to implement this variant would be to return, as the "function", the bound method of an instance of an appropriate custom class instead -- so the "bytecode" data and the simple interpreter in python could be appropriately bound together). lambda survived in Python (and reluctantly, because Guido was originally keen to remove it in the transition to Python 3, and subsided only when faced with a "mass rebellion" invoking the following point...;-) for a single reason: because there's a large number of trivially simple tasks (a function returning a constant, one returning exactly its argument, and so forth) that a very short lambda, with all the limitations connected with its body being just an expression, is handy to perform. Stretching lambdas in Python anywhere beyond this extremely limited role (as you're apparently super-keen to do) is therefore a pretty bad idea. A: The example fourFn.py code will give you a pretty good lead on writing this with pyparsing. Adapting that code to meet the OP's specific requirements is left as an exercise for the OP. -- Paul
Using Lambdas to build executable functions from string expressions
I'm using python, and I want a function that takes a string containing a mathematical expression of one variable (x) and returns a function that evaluates that expression using lambdas. Syntax should be such: f = f_of_x("sin(pi*x)/(1+x**2)") print f(0.5) 0.8 syntax should allow ( ) as well as [ ] and use standard operator precedence. Trig functions should have precedence lower than multiplication and higher than addition. Hence the string 'sin 2x + 1' would be equivalent to sin(2x)+1, though both are valid. This is for evaluating user input of algebraic and trigonometric expressions, so think math syntax not programming syntax. The list of supported functions should be easily extensible and the code should be clear and easy to understand. It's OK not to collapse constant expressions. The sample function here is incomplete. It takes a nested list representing the expression and generates an appropriate function. While somewhat easy to understand, even this seems ugly for python. import math def f_of_x(op): if (isinstance((op[0]), (int, long, float, complex)) ): return (lambda x:op[0]) elif op[0]=="pi": return lambda x: 3.14159265358979 elif op[0]=="e": return lambda x: 2.718281828459 elif op[0]=="x": return lambda x: x elif op[0]=="sin": return lambda x: math.sin(f_of_x(op[1])(x)) elif op[0]=="cos": return lambda x: math.cos(f_of_x(op[1])(x)) elif op[0]=="tan": return lambda x: math.tan(f_of_x(op[1])(x)) elif op[0]=="sqrt": return lambda x: math.sqrt(f_of_x(op[1])(x)) elif op[0]=="+": return lambda x: (f_of_x(op[1])(x))+(f_of_x(op[2])(x)) elif op[0]=="-": return lambda x: (f_of_x(op[1])(x))-(f_of_x(op[2])(x)) elif op[0]=="*": return lambda x: (f_of_x(op[1])(x))*(f_of_x(op[2])(x)) elif op[0]=="/": return lambda x: (f_of_x(op[1])(x))/(f_of_x(op[2])(x)) elif op[0]=="**": return lambda x: (f_of_x(op[1])(x))**(f_of_x(op[2])(x)) # should never get here with well formed input return def test(): # test function f(x) = sin(pi*x)/(1+x**2) s = ['/',['sin',['*',['pi'],['x']]],['+',[1],['**',['x'],[2]]]] f = f_of_x(s) for x in range(30): print " "*int(f(x*0.2)*30+10)+"x" As a general guideline, think of your solution as a tutorial on lambdas and parsers - not code golf. The sample code is just that, so write what you feel is clearest.
[ "How about this:\nimport math\ndef f_of_x(op):\n return eval(\"lambda x:\" + op, math.__dict__)\n\nIt can easily be made to support [] as well as () and uses standard operator precedence. It does not let you use trig functions without parens, though, nor does it let you imply multiplication by juxtaposition (lik...
[ 5, 0, 0 ]
[]
[]
[ "lambda", "math", "parsing", "python" ]
stackoverflow_0003278151_lambda_math_parsing_python.txt
Q: gdata python analytics metrics and dimensions error I am using the gdata module in python, when using this query I get an 'Illegal combination of dimensions and metrics' error. I have looked at documentation but not found the reason. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': tid, 'start-date': '2010-04-20', 'end-date': '2010-04-21', 'dimensions': 'ga:date,ga:hour,ga:medium,ga:source,ga:keyword', 'metrics': 'ga:visits', 'sort': 'ga:date,ga:hour', 'filters': 'ga:exitPagePath=@/blabla', 'max-results': '10000'}) Dirk A: I would suggest using the data explorer to manually construct the uri first.
gdata python analytics metrics and dimensions error
I am using the gdata module in python, when using this query I get an 'Illegal combination of dimensions and metrics' error. I have looked at documentation but not found the reason. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': tid, 'start-date': '2010-04-20', 'end-date': '2010-04-21', 'dimensions': 'ga:date,ga:hour,ga:medium,ga:source,ga:keyword', 'metrics': 'ga:visits', 'sort': 'ga:date,ga:hour', 'filters': 'ga:exitPagePath=@/blabla', 'max-results': '10000'}) Dirk
[ "I would suggest using the data explorer to manually construct the uri first.\n" ]
[ 1 ]
[]
[]
[ "gdata_api", "python" ]
stackoverflow_0002692126_gdata_api_python.txt
Q: No IDLE Subprocess connection I'm new to python programming, and want to try to edit scripts in IDLE instead of the OSX command line. However, when I try to start it, it gives me the error "Idle Subprocess didn't make a connection. Either Idle can't start a subprocess or personal firewall software is blocking the connection." I don't have a firewall configured, so what could the problem be? A: You can try running IDLE with the "-n" option. From the IDLE help: Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. A: You don't say which version of Python or OS X you are using but, if you are trying to use the IDLE installed by the recent python.org 64-bit installer for Python 2.7, you are almost certainly running into a known issue. As noted in the bug report, until the problem with the 2.7 installer is resolved, the simplest workaround for 2.7 is to install the 32-bit-only version of 2.7 using the '10.3 and up' installer. UPDATE: This problem existed with the python.org 64-bit/32-bit installer for Python 2.7. It has been corrected with subsequent releases of Python 2.7; as of this writing, Python 2.7.2 is current. However, the root cause of the original problem remains the version of Tcl/Tk 8.5 supplied by Apple with Mac OS X 10.6. To use IDLE or Tkinter with the current 64-bit Python installers for OS X, you need to install the more stable Tcl/Tk 8.5 from ActiveState. Updated details are maintained here which is also linked from the current installer download pages.
No IDLE Subprocess connection
I'm new to python programming, and want to try to edit scripts in IDLE instead of the OSX command line. However, when I try to start it, it gives me the error "Idle Subprocess didn't make a connection. Either Idle can't start a subprocess or personal firewall software is blocking the connection." I don't have a firewall configured, so what could the problem be?
[ "You can try running IDLE with the \"-n\" option. From the IDLE help:\n\nRunning without a subprocess:\n\n If IDLE is started with the -n command line switch it will run in a\n single process and will not create the subprocess which runs the RPC\n Python execution server. This can be useful if Python can...
[ 2, 2 ]
[]
[]
[ "macos", "python", "subprocess" ]
stackoverflow_0003277946_macos_python_subprocess.txt
Q: Move cursor upon right click in TextView? At the moment, when one right clicks in a TextView, a popup menu is brought up, but the cursor doesn't actually change position to where one is right clicking, it just leaves the cursor alone. For me, whom is trying to implement a spell checking menu, this isn't good since I have to click THEN right click in order to get the cursor in the right spot. So, my question is if there is any way to modify this behavior somehow so that it actually does this somehow? A: Well, I stumbled across gtk.TextView.get_iter_at_location, which lead me to gtk.TextView.get_pointer and gtk.TextView.window_to_buffer_coords. Basically, to get this working, I did this: x, y = self.textView.get_pointer() x, y = self.textView.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET, x, y) if self.textView.get_iter_at_location(x, y).has_tag(self.errTag): # Code here Basically, it gets the pointer's position (relative to the window), transforms it to buffer coordinates (I find that gtk.TEXT_WINDOW_TEXT gives the same coordinates as gtk.TEXT_WINDOW_WIDGET, but I thought I'd err on the side of caution and use the widget's window), and then gets an iter at that location. Works wonderfully.
Move cursor upon right click in TextView?
At the moment, when one right clicks in a TextView, a popup menu is brought up, but the cursor doesn't actually change position to where one is right clicking, it just leaves the cursor alone. For me, whom is trying to implement a spell checking menu, this isn't good since I have to click THEN right click in order to get the cursor in the right spot. So, my question is if there is any way to modify this behavior somehow so that it actually does this somehow?
[ "Well, I stumbled across gtk.TextView.get_iter_at_location, which lead me to gtk.TextView.get_pointer and gtk.TextView.window_to_buffer_coords. Basically, to get this working, I did this:\n x, y = self.textView.get_pointer()\n x, y = self.textView.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET, x, y)\n if ...
[ 3 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003278215_pygtk_python.txt
Q: comparison between the elements of list with keys of dictionary I need to check if a particular key is present in some dictionary. I can use has_key ?? Is there any other method to compare the items of the list to the key of dictionary. I have a list like...[(3,4),(4,5)..] I need to check if the (3,4) is there in the dictionary. A: Something like this? >>> d = { (1,3):"foo", (2,6):"bar" } >>> print (1,3) in d True >>> print (1,4) in d False >>> L = [ (1,3), (1,4), (15) ] >>> print [ x in d for x in L ] [True, False, False] If you want to add missing entries you'll need an explicit loop for x in L: if x not in d: d[x]="something" A: The "right" way is using the in operator like what the other answers have mentioned. This works for anything iterable and you get some speed gains when you can look things up by hashing (like for dictionaries and sets). There's also an older way which works only for dictionaries which is the has_key method. I don't usually see it around these days and it's slower as well (though not by much). >>> timeit.timeit('f = {(1,2) : "Foo"}; f.has_key((1,2))') 0.27945899963378906 >>> timeit.timeit('f = {(1,2) : "Foo"}; (1,2) in f') 0.22165989875793457 A: dictionary.keys() returns a list of keys you can then use if (3,4) in d.keys()
comparison between the elements of list with keys of dictionary
I need to check if a particular key is present in some dictionary. I can use has_key ?? Is there any other method to compare the items of the list to the key of dictionary. I have a list like...[(3,4),(4,5)..] I need to check if the (3,4) is there in the dictionary.
[ "Something like this?\n>>> d = { (1,3):\"foo\", (2,6):\"bar\" }\n>>> print (1,3) in d\nTrue\n>>> print (1,4) in d\nFalse\n>>> L = [ (1,3), (1,4), (15) ]\n>>> print [ x in d for x in L ]\n[True, False, False]\n\nIf you want to add missing entries you'll need an explicit loop\nfor x in L:\n if x not in d:\n d[x]=...
[ 4, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003278831_dictionary_python.txt
Q: In Python - a way to choose which dictionary to iterate over (and manipulate values in) Here's my problem: Lets say I have two dictionaries, dict_a and dict_b. Each of them have similar keys and values that I can manipulate in the same way, and in fact that's what I'm doing in a large piece of code. Only I don't want to have to write it twice. However, I can't do something like this: if choose_a == 1: for x and y in dict_a.iteritems(): # goto line 20 if choose_b == 1: for x and y in dict_b.iteritems(): # goto line 20 # line 20 # do stuff with x and y. Except I have no idea what to do in a situation like this. If there is a like thread, please point me to it, and forgive me if I have violated anything (first post). Thanks in advance, I appreciate any help. A: Perhaps do something like this: if choose_a == 1: the_dict=dict_a elif choose_b == 1: the_dict=dict_b for x,y in the_dict.iteritems(): # do stuff with x and y. A: def do_stuff( d ): for x and y in d.iteritems(): whatever with x and y if choose_a == 1: do_stuff( dict_a ) if choose_b == 1: do_stuff( dict_b ) A: What do you want to happen if both choose_a and choose_b are true? What if neither of them is true? Is either of these conditions at all possible...? Can you afford to move all the "stuff" to a separate function as a couple of answers have suggested, or would the resulting scope change be a problem? As you see, you've left many things underspecified (or totally unspecified). Assuming the worst...: both the choose_... variables could be true, in which case you need to use both dicts both the choose_... variables could be false, in which case you want to do nothing you need the "stuff" to happen within the current function due to scoping issues, then...: thedicts = [] if choose_a == 1: thedicts.append(dict_a) if choose_b == 1: thedicts.append(dict_b) for d in thedicts: for x, y in d.iteritems(): ...do stuff _locally_ with x and y... You could express the building of the thedicts list more concisely, but, I think, not as clearly, by rolling it up in the for statement, e.g. as follows...: for d in [d for d, c in zip((dict_a, dict_b), (choose_a, choose_b)) if c]: A: Just define a function. def do_stuff(x, y): # Do stuff pass if choose_a == 1: for x and y in dict_a.iteritems(): do_stuff(x, y) if choose_b == 1: for x and y in dict_b.iteritems(): do_stuff(x, y) A: How about this: d = dict_a if choose_a else dict_b for x, y in d.items(): # do stuff with x and y Obviously that assumes that you're going to use one or the other; pretty simple to add an if statement if that's not the case though. Also, your x and y syntax is invalid, but I guess you'll figure that out :) A: You can put the two dictionaries in a dict and then select them with a key for example: choice = 'A' # or choice = 'B' working_dict = {'A': dict_a, 'B': dict_b}[choice] for x,y in working_dict.iteritems(): # do stuff with x and y This is slightly different from your approach using two flags. If you are stuck with that scheme you could use something like this to set the value of choice if choose_a == 1: choice = 'A' elif choose_b == 1: choice = 'B' else: pass # maybe this should raise an exception? Perhaps it is just easier to write it this way: if choose_a == 1: working_dict = dict_a elif choose_b == 1: working_dict = dict_b else: pass # maybe this should raise an exception? for x,y in working_dict.iteritems(): # do stuff with x and y
In Python - a way to choose which dictionary to iterate over (and manipulate values in)
Here's my problem: Lets say I have two dictionaries, dict_a and dict_b. Each of them have similar keys and values that I can manipulate in the same way, and in fact that's what I'm doing in a large piece of code. Only I don't want to have to write it twice. However, I can't do something like this: if choose_a == 1: for x and y in dict_a.iteritems(): # goto line 20 if choose_b == 1: for x and y in dict_b.iteritems(): # goto line 20 # line 20 # do stuff with x and y. Except I have no idea what to do in a situation like this. If there is a like thread, please point me to it, and forgive me if I have violated anything (first post). Thanks in advance, I appreciate any help.
[ "Perhaps do something like this:\nif choose_a == 1: the_dict=dict_a\nelif choose_b == 1: the_dict=dict_b\n\nfor x,y in the_dict.iteritems():\n # do stuff with x and y.\n\n", "def do_stuff( d ):\n for x and y in d.iteritems():\n whatever with x and y\nif choose_a == 1: do_stuff( dict_a ) \nif choose_b ==...
[ 4, 3, 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003278263_dictionary_python.txt
Q: python dictionary key Vs object attribute suppose i have object has key 'dlist0' with attribute 'row_id' the i can access as getattr(dlist0,'row_id') then it return value but if i have a dictionary ddict0 = {'row_id':4, 'name':'account_balance'} getattr(ddict0,'row_id') it is not work my question is how can i access ddict0 and dlist0 same way any one can help me? A: Dictionaries have items, and thus use whatever is defined as __getitem__() to retrieve the value of a key. Objects have attributes, and thus use __getattr__() to retrieve the value of an attribute. You can theoretically override one to point at the other, if you need to - but why do you need to? Why not just write a helper function instead: Python 2.x: def get_value(some_thing, some_key): if type(some_thing) in ('dict','tuple','list'): return some_thing[some_key] else: return getattr(some_thing, some_key) Python 3.x: def get_value(some_thing, some_key): if type(some_thing) in (dict,tuple,list): return some_thing[some_key] else: return getattr(some_thing, some_key) A: Perhaps a namedtuple is more suitable for your purpose >>> from collections import namedtuple >>> AccountBalance=namedtuple('account_balance','row_id name') >>> ddict0=AccountBalance(**{'row_id':4, 'name':'account_balance'}) >>> getattr(ddict0,'row_id') 4 >>> ddict0._asdict() {'row_id': 4, 'name': 'account_balance'}
python dictionary key Vs object attribute
suppose i have object has key 'dlist0' with attribute 'row_id' the i can access as getattr(dlist0,'row_id') then it return value but if i have a dictionary ddict0 = {'row_id':4, 'name':'account_balance'} getattr(ddict0,'row_id') it is not work my question is how can i access ddict0 and dlist0 same way any one can help me?
[ "Dictionaries have items, and thus use whatever is defined as __getitem__() to retrieve the value of a key.\nObjects have attributes, and thus use __getattr__() to retrieve the value of an attribute.\nYou can theoretically override one to point at the other, if you need to - but why do you need to? Why not just wri...
[ 7, 1 ]
[]
[]
[ "dictionary", "object", "python" ]
stackoverflow_0003279011_dictionary_object_python.txt
Q: Python pack arguments? is to possible to "pack" arguments in python? I have the following functions in the library, that I can't change (simplified): def g(a,b=2): print a,b def f(arg): g(arg) I can do o={'a':10,'b':20} g(**o) 10 20 but can I/how do I pass this through f? That's what I don't want: f(**o) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() got an unexpected keyword argument 'a' f(o) {'a': 10, 'b': 20} 2 A: f has to accept arbitrary (positional and) keyword arguments: def f(*args, **kwargs): g(*args, **kwargs) If you don't want f to accept positional arguments, leave out the *args part.
Python pack arguments?
is to possible to "pack" arguments in python? I have the following functions in the library, that I can't change (simplified): def g(a,b=2): print a,b def f(arg): g(arg) I can do o={'a':10,'b':20} g(**o) 10 20 but can I/how do I pass this through f? That's what I don't want: f(**o) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() got an unexpected keyword argument 'a' f(o) {'a': 10, 'b': 20} 2
[ "f has to accept arbitrary (positional and) keyword arguments:\ndef f(*args, **kwargs):\n g(*args, **kwargs)\n\nIf you don't want f to accept positional arguments, leave out the *args part.\n" ]
[ 2 ]
[]
[]
[ "arguments", "iterable_unpacking", "python" ]
stackoverflow_0003279449_arguments_iterable_unpacking_python.txt
Q: Python: How do i manipulate the list to get the string starting with '+'? I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here): result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ..., ' qcleaner\n', '+ extraFile\n', ' rc.d\n', '+ extraFile2\n', ..., ' resolv.conf\n', ' wu-ftpd\n'] I want to be able to take the strings with the '+' sign out to do something else. how do i manipulate the list? in the example above, i want to be able to get this string "extraFile" and "extraFile2". Thanks to all the people who posted solutions. It helps a lot and I am grateful :) Here's what I did to get the string I wanted: newresult = [file[2:-1] for file in result if file.startswith('+')] to print out the strings: for i in range (len(newresult)): print newresult[i] THANKS~!!! :) A: You can use list comprehension: newlist = [file[1:] for file in result if file.startswith('+')] # ^-- gets rid of `+` at the beginning See the string methods documentation. And if you want to get rid of the newline character and whitespaces just do: newlist = [file[1:].strip() for file in result if file.startswith('+')] Another way would be to use filter(), but you cannot manipulate the string then (just want to mention it for completeness): newlist = filter(lambda s: s.startswith('+'), result) A: >>> [x.strip('+').strip() for x in result if x.startswith("+")] ['extraFile', 'extraFile2'] Improved version with stripping out '+' and whitespace/linebreaks A: Try a list comprehension : [x for x in result if x[0]=='+']
Python: How do i manipulate the list to get the string starting with '+'?
I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here): result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ..., ' qcleaner\n', '+ extraFile\n', ' rc.d\n', '+ extraFile2\n', ..., ' resolv.conf\n', ' wu-ftpd\n'] I want to be able to take the strings with the '+' sign out to do something else. how do i manipulate the list? in the example above, i want to be able to get this string "extraFile" and "extraFile2". Thanks to all the people who posted solutions. It helps a lot and I am grateful :) Here's what I did to get the string I wanted: newresult = [file[2:-1] for file in result if file.startswith('+')] to print out the strings: for i in range (len(newresult)): print newresult[i] THANKS~!!! :)
[ "You can use list comprehension:\nnewlist = [file[1:] for file in result if file.startswith('+')]\n# ^-- gets rid of `+` at the beginning\n\nSee the string methods documentation.\nAnd if you want to get rid of the newline character and whitespaces just do:\nnewlist = [file[1:].strip() for file in result ...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003279700_python.txt
Q: How do I convert a python string to ucs2 hex? I've been searching for this one and couldn't find it, although it seems simple. I need to send in a ucs2 hex string in the url, and I don't know how to convert a python string to be ucs2 hex. Any thoughts? A: >>> 'åéîøü'.encode('utf16') b'\xff\xfe\xe5\x00\xe9\x00\xee\x00\xf8\x00\xfc\x00' (Note that there's a BOM in the beginning. Use the encoding 'utf_16_be' or 'utf_16_le' if the endian is fixed.) If you need hex digits, use binascii.hexlify. >>> import binascii >>> binascii.hexlify('åéîøü'.encode('utf16')) b'fffee500e900ee00f800fc00'
How do I convert a python string to ucs2 hex?
I've been searching for this one and couldn't find it, although it seems simple. I need to send in a ucs2 hex string in the url, and I don't know how to convert a python string to be ucs2 hex. Any thoughts?
[ ">>> 'åéîøü'.encode('utf16')\nb'\\xff\\xfe\\xe5\\x00\\xe9\\x00\\xee\\x00\\xf8\\x00\\xfc\\x00'\n\n(Note that there's a BOM in the beginning. Use the encoding 'utf_16_be' or 'utf_16_le' if the endian is fixed.)\nIf you need hex digits, use binascii.hexlify.\n>>> import binascii\n>>> binascii.hexlify('åéîøü'.encode('u...
[ 5 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003279830_encoding_python.txt
Q: Python: How do i split the file? I have this txt file which is ls -R of etc directory in a linux system. Example file: etc: ArchiveSEL xinetd.d etc/cmm: CMM_5085.bin cmm_sel storage.cfg etc/crontabs: root etc/pam.d: ftp rsh etc/rc.d: eth.set.sh rc.sysinit etc/rc.d/init.d: cmm functions userScripts etc/security: access.conf console.apps time.conf etc/security/console.apps: kbdrate etc/ssh: ssh_host_dsa_key sshd_config etc/var: setUser snmpd.conf etc/xinetd.d: irsh wu-ftpd I would like to split it by subdirectories into several files. example files would be like this: etc.txt, etcCmm.txt, etcCrontabs.txt, etcPamd.txt, ... Can someone give me a python code that can do that? Notice that the subdirectory lines end with ':', but i'm just not smart enough to write the code. some examples would be appreciated. thank you :) A: Maybe something like this? re.M generates a multiline regular expression which can match several lines, and the last part just iterates over the matches and creates the files... import re data = '<your input data as above>' # or open('data.txt').read() results = map(lambda m: (m[0], m[1].strip().splitlines()), re.findall('^([^\n]+):\n((?:[^\n]+\n)*)\n', data, re.M)) for dirname, files in results: f = open(dirname.replace('/', '')+'.txt', 'w') for line in files: f.write(line + '\n') f.close() A: You will need to do it line-by-line. if a line.endswith(":") then you are in a new subdirectory. From then on, each line is a new entry into your subdirectory, until another line ends with :. From my understanding, you just want to split one textfile into several, ambiguously named, text files. So you'd see if a line ends with :. then you open a new text file, like etcCmm.txt, and every line that you read from the source text, from that point on, you write intoetcCmm.txt. When you encounter another line that ends in :, you close the previously opened file, create a new one, and continue. I'm leaving a few things for you to do yourself, such as figuring out what to call the text file, reading a file line-by-line, etc. A: use regexp like '.*:'. use file.readline(). use loops. A: If Python is not a must, you can use this one liner awk '/:$/{gsub(/:|\//,"");fn=$0}{print $0 > fn".txt"}' file A: Here's what I would do: Read the file into memory (myfile = open(filename).read() should do). Then split the file along the delimiters: import re myregex = re.compile(r"^(.*):[ \t]*$", re.MULTILINE) arr = myregex.split(myfile)[1:] # dropping everything before the first directory entry Then convert the array to a dict, removing unwanted characters along the way: mydict = dict([(re.sub(r"\W+","",k), v.strip()) for (k,v) in zip(arr[::2], arr[1::2])]) Then write the files: for name,content in mydict.iteritems(): output = open(name+".txt","w") output.write(content) output.close()
Python: How do i split the file?
I have this txt file which is ls -R of etc directory in a linux system. Example file: etc: ArchiveSEL xinetd.d etc/cmm: CMM_5085.bin cmm_sel storage.cfg etc/crontabs: root etc/pam.d: ftp rsh etc/rc.d: eth.set.sh rc.sysinit etc/rc.d/init.d: cmm functions userScripts etc/security: access.conf console.apps time.conf etc/security/console.apps: kbdrate etc/ssh: ssh_host_dsa_key sshd_config etc/var: setUser snmpd.conf etc/xinetd.d: irsh wu-ftpd I would like to split it by subdirectories into several files. example files would be like this: etc.txt, etcCmm.txt, etcCrontabs.txt, etcPamd.txt, ... Can someone give me a python code that can do that? Notice that the subdirectory lines end with ':', but i'm just not smart enough to write the code. some examples would be appreciated. thank you :)
[ "Maybe something like this? re.M generates a multiline regular expression which can match several lines, and the last part just iterates over the matches and creates the files...\nimport re\n\ndata = '<your input data as above>' # or open('data.txt').read()\nresults = map(lambda m: (m[0], m[1].strip().splitlines())...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003279843_python.txt
Q: How to use a custom __init__ of an app engine Python model class properly? I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying Are you sure?, you get a 2 minute time frame to cancel deletion. I want to track What will be deleted When with a db.Model class (DeleteQueueItem), as I found no way to delete a task from the queue and suspect I can query what's there. Creating a DeleteQueueItem entity should automatically set a delete_when property and add a task to the queue. I use the relative path of blog posts as their key_name and want to use that as key_name here, too. This led me to a custom init: class DeleteQueueItem(db.Model): """Model to keep track of items that will be deleted via task queue.""" # URL path to the blog post is handled as key_name delete_when = db.DateTimeProperty() def __init__(self, **kwargs): delay = 120 # Seconds t = datetime.timedelta(seconds=delay) deadline = datetime.datetime.now() - t key_name = kwargs.get('key_name') db.Model.__init__(self, **kwargs) self.delete_when = deadline taskqueue.add(url='/admin/task/delete_page', countdown=delay, params={'path': key_name}) This seems to work, until I try to delete the entity: fetched_item = models.DeleteQueueItem.get_by_key_name(path) This fails with: TypeError: __init__() takes exactly 1 non-keyword argument (2 given) What am I doing wrong? A: Generally, you shouldn't try and override the init method of Model classes. While it's possible to get right, the correct constructor behaviour is fairly complex, and may even change between releases, breaking your code (though we try to avoid doing so!). Part of the reason for this is that the constructor has to be used both by your own code, to construct new models, and by the framework, to reconstitute models loaded from the datastore. A better approach is to use a factory method, which you call instead of the constructor. Also, you probably want to add the task at the same time as you write the entity, rather than at creation time. If you don't, you end up with a race condition: the task may execute before you've stored the new entity to the datastore! Here's a suggested refactoring: class DeleteQueueItem(db.Model): """Model to keep track of items that will be deleted via task queue.""" # URL path to the blog post is handled as key_name delete_when = db.DateTimeProperty() @classmethod def new(cls, key_name): delay = 120 # Seconds t = datetime.timedelta(seconds=delay) deadline = datetime.datetime.now() - t return cls(key_name=key_name, delete_when=deadline) def put(self, **kwargs): def _tx(): taskqueue.add(url='/admin/task/delete_page', countdown=delay, params={'path': key_name}, transactional=True) return super(DeleteQueueItem, self).put(**kwargs) if not self.is_saved(): return db.run_in_transaction(_tx) else: return super(DeleteQueueItem, self).put(**kwargs)
How to use a custom __init__ of an app engine Python model class properly?
I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying Are you sure?, you get a 2 minute time frame to cancel deletion. I want to track What will be deleted When with a db.Model class (DeleteQueueItem), as I found no way to delete a task from the queue and suspect I can query what's there. Creating a DeleteQueueItem entity should automatically set a delete_when property and add a task to the queue. I use the relative path of blog posts as their key_name and want to use that as key_name here, too. This led me to a custom init: class DeleteQueueItem(db.Model): """Model to keep track of items that will be deleted via task queue.""" # URL path to the blog post is handled as key_name delete_when = db.DateTimeProperty() def __init__(self, **kwargs): delay = 120 # Seconds t = datetime.timedelta(seconds=delay) deadline = datetime.datetime.now() - t key_name = kwargs.get('key_name') db.Model.__init__(self, **kwargs) self.delete_when = deadline taskqueue.add(url='/admin/task/delete_page', countdown=delay, params={'path': key_name}) This seems to work, until I try to delete the entity: fetched_item = models.DeleteQueueItem.get_by_key_name(path) This fails with: TypeError: __init__() takes exactly 1 non-keyword argument (2 given) What am I doing wrong?
[ "Generally, you shouldn't try and override the init method of Model classes. While it's possible to get right, the correct constructor behaviour is fairly complex, and may even change between releases, breaking your code (though we try to avoid doing so!). Part of the reason for this is that the constructor has to ...
[ 15 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003279833_google_app_engine_python.txt
Q: Does anyone have a code example of AES encryption in python on Google App Engine? I have a query string I need to encrypt using AES in CBC mode with zero padding, before finally encoding it to base64 and I need to run this on Google App Engine in Python. I've had a look around and can't be sure what works in GAE and what doesn't, I'm also finding it hard to get example code of some of those I believe should work, such as (http://code.google.com/p/slowaes/). Does anyone have a code example or link to one for AES encryption in python on Google App Engine? Thanks, Denis A: PyCrypto is supported on App Engine. I would recommend checking out examples and docs for PyCrypto - they should function the same on App Engine as everywhere else. A: Appengine has a limit on source files ( less than 1000) and doesn't run python modules with C extensions. Given this limitations I would recommend you SlowAES (http://code.google.com/p/slowaes/) which is ( for Python) only one source file and is written in pure python.
Does anyone have a code example of AES encryption in python on Google App Engine?
I have a query string I need to encrypt using AES in CBC mode with zero padding, before finally encoding it to base64 and I need to run this on Google App Engine in Python. I've had a look around and can't be sure what works in GAE and what doesn't, I'm also finding it hard to get example code of some of those I believe should work, such as (http://code.google.com/p/slowaes/). Does anyone have a code example or link to one for AES encryption in python on Google App Engine? Thanks, Denis
[ "PyCrypto is supported on App Engine. I would recommend checking out examples and docs for PyCrypto - they should function the same on App Engine as everywhere else.\n", "Appengine has a limit on source files ( less than 1000) and doesn't run python modules with C extensions. Given this limitations I would recomm...
[ 2, 1 ]
[]
[]
[ "aes", "cryptography", "encryption", "google_app_engine", "python" ]
stackoverflow_0003276685_aes_cryptography_encryption_google_app_engine_python.txt
Q: Best way to check new-line-independent-identity of 2 files with python I tried filecmp.cmp(file1,file2) but it doesn't work since files are identically except for new line characters. Is there an option for that in filecmp or some other convenience function/library or do I have to read both files line by line and compare those? A: I think a simple convenience function like this should do the job: from itertools import izip def areFilesIdentical(filename1, filename2): with open(filename1, "rtU") as a: with open(filename2, "rtU") as b: # Note that "all" and "izip" are lazy # (will stop at the first line that's not identical) return all(myprint() and lineA == lineB for lineA, lineB in izip(a.xreadlines(), b.xreadlines())) A: Try the difflib module - it provides classes and functions for comparing sequences. For your needs, the difflib.Differ class looks interesting. class difflib.Differ This is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. See the differ example, that compares two texts. The sequences being compared can also be obtained from the readlines() method of file-like objects. A: Looks like you just need to check if files are same or not ignoring whitespace/newlines. You can use a function like this def do_cmp(f1, f2): bufsize = 8*1024 fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') while True: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if not is_same(b1, b2): return False if not b1: return True def is_same(text1, text2): return text1.replace("\n","") == text2.replace("\n","") you can improve is_same so that it matches according to your requirements e.g. you may ignore case too.
Best way to check new-line-independent-identity of 2 files with python
I tried filecmp.cmp(file1,file2) but it doesn't work since files are identically except for new line characters. Is there an option for that in filecmp or some other convenience function/library or do I have to read both files line by line and compare those?
[ "I think a simple convenience function like this should do the job:\nfrom itertools import izip\n\ndef areFilesIdentical(filename1, filename2):\n with open(filename1, \"rtU\") as a:\n with open(filename2, \"rtU\") as b:\n # Note that \"all\" and \"izip\" are lazy\n # (will stop at th...
[ 5, 1, 0 ]
[]
[]
[ "compare", "file", "python" ]
stackoverflow_0003280317_compare_file_python.txt
Q: Using trellis as a framework for managing UI interaction rules Does anyone have experience with trellis? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens. A: It seems this project has died. No new stuff to the page has been added to it since your question. Also I think that new language features in Python 2.6 and Python 3 are removing the need of some of the offered constructs.
Using trellis as a framework for managing UI interaction rules
Does anyone have experience with trellis? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens.
[ "It seems this project has died. No new stuff to the page has been added to it since your question. Also I think that new language features in Python 2.6 and Python 3 are removing the need of some of the offered constructs.\n" ]
[ 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0000214430_python_user_interface.txt
Q: Django - Custom dashboard view authentication issues Django version 1.1.1 I have a custom dashboard view set up to override the django admin default like: (r'^admin/$', 'dashboard.views.dashboard'), (r'^admin/', include(admin.site.urls)), dashboard view authenticates with the @staff_member_required decorator This has been working fine with all users having superuser permissions but when trying to login a user with just staff member status (have tried different permission settings) I am throwing a 500 server error: [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] mod_wsgi (pid=13815): Exception occurred processing WSGI script '/home/......../ _site.wsgi'. [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] Traceback (most recent call last): [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/...../lib/python2.5/django/core/handlers/wsgi.py", line 245, in __call__ [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] response = middleware_method(request, response) [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/....../lib/python2.5/django/contrib/sessions/middleware.py", line 26, in process_response [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] patch_vary_headers(response, ('Cookie',)) [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/....../lib/python2.5/django/utils/cache.py", line 130, in patch_vary_headers [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] if response.has_header('Vary'): [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] AttributeError: 'QuerySet' object has no attribute 'has_header' I get the same error when user @login_required as well. Any ideas on this? Thanks A: Maybe you should clean your browser cookies and logout properly, both in your public logout url and in the admin logout url. I think normal users opens a session and staff users opens another, so is not a good idea to mix both in the same app.
Django - Custom dashboard view authentication issues
Django version 1.1.1 I have a custom dashboard view set up to override the django admin default like: (r'^admin/$', 'dashboard.views.dashboard'), (r'^admin/', include(admin.site.urls)), dashboard view authenticates with the @staff_member_required decorator This has been working fine with all users having superuser permissions but when trying to login a user with just staff member status (have tried different permission settings) I am throwing a 500 server error: [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] mod_wsgi (pid=13815): Exception occurred processing WSGI script '/home/......../ _site.wsgi'. [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] Traceback (most recent call last): [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/...../lib/python2.5/django/core/handlers/wsgi.py", line 245, in __call__ [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] response = middleware_method(request, response) [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/....../lib/python2.5/django/contrib/sessions/middleware.py", line 26, in process_response [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] patch_vary_headers(response, ('Cookie',)) [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] File "/ home/....../lib/python2.5/django/utils/cache.py", line 130, in patch_vary_headers [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] if response.has_header('Vary'): [Sun Jul 18 12:36:59 2010] [error] [client 127.0.0.1] AttributeError: 'QuerySet' object has no attribute 'has_header' I get the same error when user @login_required as well. Any ideas on this? Thanks
[ "Maybe you should clean your browser cookies and logout properly, both in your public logout url and in the admin logout url. I think normal users opens a session and staff users opens another, so is not a good idea to mix both in the same app.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003277065_django_django_admin_python.txt
Q: twitter request limit Regarding the twitter API request limit, how does one counts as a request? I'm using python-twitter, so if I have client = twitter.Api(username='acc',password='pw') self.client.GetFriends(result[0]) Does this count as 1 request? Or as many as the number of friends I have? I asked this because I have the following code: for user in friends: name = user.GetScreenName() print 'username is ' + name try: messages = self.client.GetUserTimeline(user= name,count = 15) for message in messages: print 'message: ' + message.getText() And I already got a bad request error code without even displaying a single status message. A: That's 1 request. For that request Twitter will return a json file representing the list of friends. Also the twitter.API call also produce a request, but this one is not counted for the limit stuff. You can read about it in apiwiki You can also request your limit status.
twitter request limit
Regarding the twitter API request limit, how does one counts as a request? I'm using python-twitter, so if I have client = twitter.Api(username='acc',password='pw') self.client.GetFriends(result[0]) Does this count as 1 request? Or as many as the number of friends I have? I asked this because I have the following code: for user in friends: name = user.GetScreenName() print 'username is ' + name try: messages = self.client.GetUserTimeline(user= name,count = 15) for message in messages: print 'message: ' + message.getText() And I already got a bad request error code without even displaying a single status message.
[ "That's 1 request. For that request Twitter will return a json file representing the list of friends.\nAlso the twitter.API call also produce a request, but this one is not counted for the limit stuff.\nYou can read about it in apiwiki\nYou can also request your limit status.\n" ]
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003278788_python_twitter.txt
Q: terminate script of another user On a linux box I've got a python script that's always started from predefined user. It may take a while for it to finish so I want to allow other users to stop it from the web. Using kill fails with Operation not permitted. Can I somehow modify my long running python script so that it'll recive a signal from another user? Obviously, that another user is the one that starts a web server. May be there's entirely different way to approach this problem I can't think of right now. A: If you do not want to execute the kill command with the correct permissions, you can send any other signal to the other script. It is then the other scripts' responsibility to terminate. You cannot force it, unless you have the permissions to do so. This can happen with a network connection, or a 'kill' file whose existence is checked by the other script, or anything else the script is able to listen to. A: Off the top of my head, one solution would be threading the script and waiting for a kill signal via some form or another. Or rather than threading, you could have a file that the script checks every N times through a loop - then you just write a kill signal to that file (which of course has write permissions by the web user). I'm not terribly familiar with kill, other than killing my own scripts, so there may be a better solution. A: If you set up your python script to run as a deamon (bottom of page under Unix Daemon) on your server (which sounds appropriate), and you give the apache user permissions to execute the init.d script for the service, then you can control the service with php code similar to this (from here - the service script name in this case is 'otto2'): <? $otto = "/usr/etc/init.d/otto2 "; if( $_GET["action"] ) { $ret = shell_exec( $otto.$_GET["action"] ); //Check your ret value } else { ?> <a href="<?=$PHP_SELF?>?action=start">Start </a> <a href="<?=$PHP_SELF?>?action=stop">Stop </a> <? } ?> The note on that is 'really basic untested code' :) A: You could use sudo to perform the kill command as root, but that is horrible practice. How about having the long-running script check some condition every x seconds, for example the existence of a file like /tmp/stop-xyz.txt? If that file is found, the script terminates itself immediately. (Or any other means of inter-process communication - it doesn't matter.)
terminate script of another user
On a linux box I've got a python script that's always started from predefined user. It may take a while for it to finish so I want to allow other users to stop it from the web. Using kill fails with Operation not permitted. Can I somehow modify my long running python script so that it'll recive a signal from another user? Obviously, that another user is the one that starts a web server. May be there's entirely different way to approach this problem I can't think of right now.
[ "If you do not want to execute the kill command with the correct permissions, you can send any other signal to the other script. It is then the other scripts' responsibility to terminate. You cannot force it, unless you have the permissions to do so. \nThis can happen with a network connection, or a 'kill' file wh...
[ 1, 1, 1, 0 ]
[]
[]
[ "kill", "linux", "python", "signals" ]
stackoverflow_0003281107_kill_linux_python_signals.txt
Q: Automatically call all functions matching a certain pattern in python In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this in python? def setup_1(): .... def setup_2(): .... def setup_3(): ... ... if __name__ == '__main__': setup_*() A: def setup_1(): print('1') def setup_2(): print('2') def setup_3(): print('3') if __name__ == '__main__': for func in (val for key,val in vars().items() if key.startswith('setup_')): func() yields # 1 # 3 # 2 A: Here is one possible solution: import types def setup_1(): print "setup_1" def setup_2(): print "setup_2" def setup_3(): print "setup_3" if __name__ == '__main__': for name, member in globals().items(): # NB: not iteritems() if isinstance(member, types.FunctionType) and name.startswith("setup_"): member() A: This does not get function objects directly but must use eval, I am checking solution with vars() to get rid of eval: def setup_1(): print('setup_1') def setup_2(): print('setup_2') def setup_3(): print('setup_3') if __name__ == '__main__': [eval(func+'()') for func in dir() if func.startswith('setup_')] Ok, here the version with vars(): def setup_1(): print('setup_1') def setup_2(): print('setup_2') def setup_3(): print('setup_3') if __name__ == '__main__': [vars()[func]() for func in dir() if func.startswith('setup_')] A: You can use locals() L = locals() for k in L: if hasattr(L[k], '__call__') and k.startswith('setup'): L[k]() Of course you'll want to make sure that your function names don't appear elsewhere in locals. In addition, you could also do something like this because functions are first class objects (note the function names are not strings): setupfunctions = [setup_1, setup_2, setup_3, myotherfunciton] for f in setupfunctions: f()
Automatically call all functions matching a certain pattern in python
In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this in python? def setup_1(): .... def setup_2(): .... def setup_3(): ... ... if __name__ == '__main__': setup_*()
[ "def setup_1():\n print('1')\n\ndef setup_2():\n print('2')\n\ndef setup_3():\n print('3')\n\nif __name__ == '__main__': \n for func in (val for key,val in vars().items()\n if key.startswith('setup_')):\n func()\n\nyields\n# 1\n# 3\n# 2\n\n", "Here is one possible solution:\n...
[ 8, 4, 1, 0 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0003281300_automation_python.txt
Q: How to preload model for ReferenceProperty? I have a models in different files (blog/models.py, forum/models.py, article/models.py). In each of this files I have defined model classes with application prefix (BlobPost, BlogTag, ForumPost, ForumThread, Article, ArticleCategory). Also I have appliation - comment, for adding comment attached to any model object. For example, I want to comment BlogPost, or add comment referenced to ForumPost. For this I use property with type ReferenceProperty() - without specify type of references. Any model can attached to comment. What a problem? If I have show all comments in administration section, I see a problem with autoloading models for ReferenceProperty. I don't know, what type of model used for current comment. I need to autoload package with model, if this need. Yes, exists simple solution - include all models from all applications. But, this is not good solution. I need load only need models. How to do this autoloading? My idea is based on detect kind of property, and by first part of this name detect application name for load all models in this application. For example, I have comment with Reference to BlogPost model. I get name of application - Blog and load all models from blog.models import * For implement my idea I need to understand - how to intercept creating property instances. In my case, if I loop over comments, I see that App Engine automatically (thanks, but not in my case) create instances for properties. How to inject my logic for loading my models before creating property instance? Thank you! A: This isn't possible in the standard db framework, as there's not enough information present to find your models. The only information the framework has to work with is the kind name, which doesn't include the fully qualified package - so it has no way to figure out what package your model definition might be in. If you're writing an admin interface, though, you probably want to use the low-level google.appengine.api.datastore interface, instead, which operates on dicts instead of model classes, and doesn't require a model definition.
How to preload model for ReferenceProperty?
I have a models in different files (blog/models.py, forum/models.py, article/models.py). In each of this files I have defined model classes with application prefix (BlobPost, BlogTag, ForumPost, ForumThread, Article, ArticleCategory). Also I have appliation - comment, for adding comment attached to any model object. For example, I want to comment BlogPost, or add comment referenced to ForumPost. For this I use property with type ReferenceProperty() - without specify type of references. Any model can attached to comment. What a problem? If I have show all comments in administration section, I see a problem with autoloading models for ReferenceProperty. I don't know, what type of model used for current comment. I need to autoload package with model, if this need. Yes, exists simple solution - include all models from all applications. But, this is not good solution. I need load only need models. How to do this autoloading? My idea is based on detect kind of property, and by first part of this name detect application name for load all models in this application. For example, I have comment with Reference to BlogPost model. I get name of application - Blog and load all models from blog.models import * For implement my idea I need to understand - how to intercept creating property instances. In my case, if I loop over comments, I see that App Engine automatically (thanks, but not in my case) create instances for properties. How to inject my logic for loading my models before creating property instance? Thank you!
[ "This isn't possible in the standard db framework, as there's not enough information present to find your models. The only information the framework has to work with is the kind name, which doesn't include the fully qualified package - so it has no way to figure out what package your model definition might be in.\n...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003247971_google_app_engine_python.txt
Q: Really awkward (seemingly simple) bug with python integer comparisons I have the following piece of code which is not working the way I expect it to at all... current_frame = 15 # just for showcasing purposes g_ch = 7 if (current_frame != int(row[0])) and (int(row[1]) != g_ch): current_frame = int(row[0]) print "curious=================================" print current_frame print row print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0]) print "========================================" which prints for any specific case: curious================================= 15 ['15', '1', 'more data'] 15 != 15 , False ======================================== This should obviously never even enter the if statement, as the equality is showing false. Why is this happening? edit: I have also tried this with != instead of 'is not', and gotten the same results. A: Value comparisons are done with the != operator, not with is not, which compares object identity. Apart from that, I think it's an indentation problem. A: In short, you need to use == and !=, and not is. is compares object identity, not equality. A: You assign current_frame = int(row[0]) inside the if, which changes the value of the boolean expression.
Really awkward (seemingly simple) bug with python integer comparisons
I have the following piece of code which is not working the way I expect it to at all... current_frame = 15 # just for showcasing purposes g_ch = 7 if (current_frame != int(row[0])) and (int(row[1]) != g_ch): current_frame = int(row[0]) print "curious=================================" print current_frame print row print current_frame, " != ", int(row[0]), ", ", current_frame != int(row[0]) print "========================================" which prints for any specific case: curious================================= 15 ['15', '1', 'more data'] 15 != 15 , False ======================================== This should obviously never even enter the if statement, as the equality is showing false. Why is this happening? edit: I have also tried this with != instead of 'is not', and gotten the same results.
[ "Value comparisons are done with the != operator, not with is not, which compares object identity.\nApart from that, I think it's an indentation problem.\n", "In short, you need to use == and !=, and not is. is compares object identity, not equality.\n", "You assign current_frame = int(row[0]) inside the if, wh...
[ 6, 1, 0 ]
[]
[]
[ "equality", "identity", "python" ]
stackoverflow_0003281550_equality_identity_python.txt
Q: best python lib to clean the tag (not safe), and keep the tag that i think safe ex: i want to clean the "script" tag , but i want to keep the 'a' tag , so what lib you using to do this . and i use jquery cleditor for WYSIWYG HTML editor , can it do this for me automatically ? thanks A: I have to do this automatically for a project of mine. The solution I have found is to use the Beautiful Soup module to extract the script tag (I also do this for style and form). soup = BeautifulSoup(html_string, convertEntities=BeautifulSoup.HTML_ENTITIES) scripts = soup.findAll('script') # find and return a list of 'script' entities for s in scripts: s.extract() # remove it from the DOM completely Then, you can have BeautifulSoup print out or save the html. A: I suppose that BeautifulSoup should do the trick, here. Actually, here's a question + answers that's exactly about that : Python HTML sanitizer / scrubber / filter A: Another option, designed for sanitization, is html5lib. Whatever you do, do not rely on an editor component to do it for you: That runs on the client, so could easily be manipulated to submit invalid or malicious HTML!
best python lib to clean the tag (not safe), and keep the tag that i think safe
ex: i want to clean the "script" tag , but i want to keep the 'a' tag , so what lib you using to do this . and i use jquery cleditor for WYSIWYG HTML editor , can it do this for me automatically ? thanks
[ "I have to do this automatically for a project of mine. The solution I have found is to use the Beautiful Soup module to extract the script tag (I also do this for style and form).\nsoup = BeautifulSoup(html_string, convertEntities=BeautifulSoup.HTML_ENTITIES)\n\nscripts = soup.findAll('script') # find and return...
[ 3, 2, 0 ]
[]
[]
[ "google_app_engine", "jquery", "python", "tags" ]
stackoverflow_0003240009_google_app_engine_jquery_python_tags.txt
Q: Format date based on locale in python I have a date output like >>> import time >>> print time.strftime("%d %B") 19 July Is there a way to format the date based on the locale, but still have control of what is shown (in some cases I don't want the year). For example, on a en_US machine, I want it to output: July 19'th A: The strftime methods always use the current locale. For example: from datetime import date d = date.today() print d.format("%B %d") will output "July 19" (no "'th", sorry...) if your locale is en_US, but "juillet 19" if the locale uses French. If you want to make the order of the different parts also dependent on the locale, or other more advanced things, I suggest you have a look at the babel library, which uses data from the Common Locale Data Repository and allows you to do things like: from babel.dates import dateformat format_date(d, format="long", locale="en_US") which would output "July 19, 2010", but "19 juillet 2010" for French, etc... Note that you have to explicitly request a specific locale though (or rather the language code) Alas, this doesn't allow leaving off the year. If you delve further into babel however, there are ways to get the patterns for a specific locale (babel.dates.get_date_format("long", locale="en_US").pattern would give you "EEEE, MMMM d, yyyy" for example, which you could use for the format argument instead of "long"). This still leaves you with the task of stripping "yyyy" out of the format, along with the comma's etc... that might come before or after. Other than that, I'm afraid you would have to make your own patterns for each locale.
Format date based on locale in python
I have a date output like >>> import time >>> print time.strftime("%d %B") 19 July Is there a way to format the date based on the locale, but still have control of what is shown (in some cases I don't want the year). For example, on a en_US machine, I want it to output: July 19'th
[ "The strftime methods always use the current locale. For example:\nfrom datetime import date\nd = date.today()\nprint d.format(\"%B %d\")\n\nwill output \"July 19\" (no \"'th\", sorry...) if your locale is en_US, but \"juillet 19\" if the locale uses French.\nIf you want to make the order of the different parts als...
[ 2 ]
[]
[]
[ "formatting", "locale", "python", "time" ]
stackoverflow_0003280818_formatting_locale_python_time.txt
Q: how to change page selection in wxNotebook or wxChoicebook? Is there any way to change the page of a wxNotebook or wxChoicebook programmatically? Looking at the documentation I would have thought that wxChoicebook::ChangeSelection was the way to go, or wxChoicebook::SetSelection if I want the page changing/changed events to be sent. However, I don't know what these functions expect as input. The seem to require a size_t type input, but all I get from a GetSelection is an integer. I'm working in wxPython if that helps. A: I think you should be using wxNotebook::ChangeSelection, and in that function the size_t parameter refers to the integer index of the notebook page you would like to switch to. ChangeSelection(0) would change to the first notebook page, ChangeSelection(1) to the second, and so on. I did test this in code, and it works. I use wxWidgets with C++ though, I didn't test wxPython. Hope that helps!
how to change page selection in wxNotebook or wxChoicebook?
Is there any way to change the page of a wxNotebook or wxChoicebook programmatically? Looking at the documentation I would have thought that wxChoicebook::ChangeSelection was the way to go, or wxChoicebook::SetSelection if I want the page changing/changed events to be sent. However, I don't know what these functions expect as input. The seem to require a size_t type input, but all I get from a GetSelection is an integer. I'm working in wxPython if that helps.
[ "I think you should be using wxNotebook::ChangeSelection, and in that function the size_t parameter refers to the integer index of the notebook page you would like to switch to. ChangeSelection(0) would change to the first notebook page, ChangeSelection(1) to the second, and so on. \nI did test this in code, and it...
[ 0 ]
[]
[]
[ "python", "user_interface", "wxwidgets" ]
stackoverflow_0003250175_python_user_interface_wxwidgets.txt
Q: python - list operations Given a list of unsorted numbers, I want to find the smallest number larger than N (if any). In C#, I'd do something like this (checks omitted) : var x = list.Where(i => i > N).Min(); What's a short, READABLE way to do this in Python? A: >>> l = [4, 5, 12, 0, 3, 7] >>> min(x for x in l if x > 5) 7 A: min(x for x in mylist if x > N) A: Other people have given list comprehension answers. As an alternative filter is useful for 'filtering' out elements of a list. min(filter(lambda t: t > N, mylist)) A: x = min(i for i in mylist if i > N)
python - list operations
Given a list of unsorted numbers, I want to find the smallest number larger than N (if any). In C#, I'd do something like this (checks omitted) : var x = list.Where(i => i > N).Min(); What's a short, READABLE way to do this in Python?
[ ">>> l = [4, 5, 12, 0, 3, 7]\n>>> min(x for x in l if x > 5)\n7\n\n", "min(x for x in mylist if x > N)\n\n", "Other people have given list comprehension answers. As an alternative filter is useful for 'filtering' out elements of a list.\nmin(filter(lambda t: t > N, mylist))\n\n", "x = min(i for i in mylist if...
[ 19, 4, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003281898_list_python.txt
Q: please expain wx.grid.Grid.create() can any one please expain me the functionality of this function wx.grid.Grid.create() i created a frame and inside that i create a grid using this function every thing is fine but while closing that frame my whole application is closing while closing i just need to distroy the frame only not the whole application thankz in advance A: Are you using self.Destroy()? If so, try self.Close() instead. or bind wx.EVT_CLOSE to your custom close function self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) def OnCloseWindow(self,event): //do anything here A: If the frame with the grid in it is the only top-level window, then closing it will close your application. If you close the only frame in any program, how would you open another? There's nothing left to click on. Mike Driscoll Blog: http://blog.pythonlibrary.org
please expain wx.grid.Grid.create()
can any one please expain me the functionality of this function wx.grid.Grid.create() i created a frame and inside that i create a grid using this function every thing is fine but while closing that frame my whole application is closing while closing i just need to distroy the frame only not the whole application thankz in advance
[ "Are you using self.Destroy()? If so, try self.Close() instead.\nor bind wx.EVT_CLOSE to your custom close function\nself.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\ndef OnCloseWindow(self,event):\n //do anything here\n\n", "If the frame with the grid in it is the only top-level window, then closing it will clo...
[ 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002415854_python_wxpython.txt
Q: Python Threading with Timer I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this? threading.Timer only starts after the previous one has been completed. A: import threading import time class A(threading.Thread): def run(self): print "here", time.time() time.sleep(10) print "there", time.time() if __name__=="__main__": for i in range(3): a = A() a.start() prints: here 1279553593.49 here 1279553593.49 here 1279553593.49 there 1279553603.5 there 1279553603.5 there 1279553603.5
Python Threading with Timer
I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this? threading.Timer only starts after the previous one has been completed.
[ "import threading \nimport time\n\nclass A(threading.Thread):\n def run(self):\n print \"here\", time.time()\n time.sleep(10)\n print \"there\", time.time()\n\n\nif __name__==\"__main__\":\n for i in range(3):\n a = A()\n a.start()\n\nprints:\nhere 1279553593.49\nhere 1279553593.49\nhere 12795...
[ 4 ]
[]
[]
[ "multithreading", "python", "timer" ]
stackoverflow_0003282469_multithreading_python_timer.txt
Q: wxPython validator not called for grandchild of dialogue I have something like this: class ADialog(wx.Dialog): def __init__(self, parent, *args, **kwargs): ... self.editor = APanel(parent=self) ... ... class APanel(wx.Panel): def CreatePanel(self, *args, **kwargs): ... self.textCtrls = [] for (key, val) in zip(foo, bar): ... box = wx.TextCtrl(parent=self, value=val, validator=Validator()) .... Now, I need to have APanel seperate, because the text controls have to be changed dynamically. Problem is, the Validate() method of Validator never gets called. I've tried passing the flag wx.WS_EX_VALIDATE_RECURSIVELY to wx.Dialog.__init__, and also tried overriding the Validate() method of ADialog to call Validate() on APanel, and then overridden the Validate() method of APanel to call the validators of each text control, but that didn't work either. os: Windows 7 python version: 2.5.4 wxPython version: 2.8.10 A: wx.WS_EX_VALIDATE_RECURSIVELY is an extended style, so you need to set it with SetExtraStyle, not by passing it to the base class' __init__
wxPython validator not called for grandchild of dialogue
I have something like this: class ADialog(wx.Dialog): def __init__(self, parent, *args, **kwargs): ... self.editor = APanel(parent=self) ... ... class APanel(wx.Panel): def CreatePanel(self, *args, **kwargs): ... self.textCtrls = [] for (key, val) in zip(foo, bar): ... box = wx.TextCtrl(parent=self, value=val, validator=Validator()) .... Now, I need to have APanel seperate, because the text controls have to be changed dynamically. Problem is, the Validate() method of Validator never gets called. I've tried passing the flag wx.WS_EX_VALIDATE_RECURSIVELY to wx.Dialog.__init__, and also tried overriding the Validate() method of ADialog to call Validate() on APanel, and then overridden the Validate() method of APanel to call the validators of each text control, but that didn't work either. os: Windows 7 python version: 2.5.4 wxPython version: 2.8.10
[ "wx.WS_EX_VALIDATE_RECURSIVELY is an extended style, so you need to set it with SetExtraStyle, not by passing it to the base class' __init__\n" ]
[ 3 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003244084_python_user_interface_wxpython.txt
Q: wxPython: Can a wx.PyControl contain a wx.Sizer? Can a wx.PyControl contain a wx.Sizer? Note that what I am ultimately trying to do here (spinner with float values) is already answered in another question. I am particularly interested in layouting widgets within a wx.PyControl, a skill which might prove useful if I come across a need to make my own custom widgets. I already read through CreatingCustomControls, but it didn't use sizers within the wx.PyControl subclass. Using my code below, my CustomWidget just doesn't look right. I'm not yet doing a DoGetBestSize because I think that applies to a wx.Sizer acting on a widget. I am actually having a wx.Sizer doing its thing inside a CustomWidget. Here is my code (without the event bindings between sub-widgets): EDIT: Here is my corrected class code, thanks to Steven Sproat: import wx class CustomWidget(wx.PyControl): def __init__(self, parent): wx.PyControl.__init__(self, parent=parent, style=wx.NO_BORDER) # Style added. text = wx.TextCtrl(parent=self) spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL) sizer = wx.GridBagSizer() self.layout(text, spin, sizer) self.OnInit(text, sizer) def OnInit(self, text, sizer): text.SetValue(u"0.000") def layout(self, text, spin, sizer): self.SetSizer(sizer) sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER) sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER) self.Fit() self.Layout() # This is what I lacked. I needed to call .Layout() self.CenterOnParent() A: Yes, it can. You just need to call Layout() to tell the sizer to recalculate/layout its children. import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) blah = CustomWidget(self) self.Show(True) class CustomWidget(wx.PyControl): def __init__(self, parent): wx.PyControl.__init__(self, parent=parent) text = wx.TextCtrl(parent=self) spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL) sizer = wx.GridBagSizer() self.layout(text, spin, sizer) self.OnInit(text, sizer) def OnInit(self, text, sizer): text.SetValue(u"0.000") def layout(self, text, spin, sizer): self.SetSizer(sizer) sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER) sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER) self.Fit() self.Layout() self.CenterOnParent() app = wx.App() f = Frame() app.MainLoop() By the way, it would be nice in the future if you could attach a runnable sample as above :) A: Since classes derived from wxControl are not normally used for containing other widgets the auto-layout code is not present and so it will not call Layout() when it gets the EVT_SIZE event. You can easily add that ability to your class by Bind()ing a handler for EVT_SIZE and calling self.Layout() from there. Then it will act just like a panel does when it gets the size event and has children and a sizer.
wxPython: Can a wx.PyControl contain a wx.Sizer?
Can a wx.PyControl contain a wx.Sizer? Note that what I am ultimately trying to do here (spinner with float values) is already answered in another question. I am particularly interested in layouting widgets within a wx.PyControl, a skill which might prove useful if I come across a need to make my own custom widgets. I already read through CreatingCustomControls, but it didn't use sizers within the wx.PyControl subclass. Using my code below, my CustomWidget just doesn't look right. I'm not yet doing a DoGetBestSize because I think that applies to a wx.Sizer acting on a widget. I am actually having a wx.Sizer doing its thing inside a CustomWidget. Here is my code (without the event bindings between sub-widgets): EDIT: Here is my corrected class code, thanks to Steven Sproat: import wx class CustomWidget(wx.PyControl): def __init__(self, parent): wx.PyControl.__init__(self, parent=parent, style=wx.NO_BORDER) # Style added. text = wx.TextCtrl(parent=self) spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL) sizer = wx.GridBagSizer() self.layout(text, spin, sizer) self.OnInit(text, sizer) def OnInit(self, text, sizer): text.SetValue(u"0.000") def layout(self, text, spin, sizer): self.SetSizer(sizer) sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER) sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER) self.Fit() self.Layout() # This is what I lacked. I needed to call .Layout() self.CenterOnParent()
[ "Yes, it can. You just need to call Layout() to tell the sizer to recalculate/layout its children.\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n blah = CustomWidget(self)\n self.Show(True)\n\nclass CustomWidget(wx.PyControl):\n def __init__(self, parent):\n...
[ 3, 1 ]
[]
[]
[ "custom_controls", "python", "sizer", "widget", "wxpython" ]
stackoverflow_0003271639_custom_controls_python_sizer_widget_wxpython.txt
Q: Getting parameters from a file via shell script into python script in the right format I have the following shell script: #! /bin/sh while read page_section page=${page_section%%\ *} section=${page_section#* } #NOTE: `%* }` is NOT a comment wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tmp & wait # echo ${page_section%%\ *} # verify correct string chopping # echo ${page_section#* } # verify correct string chopping ./DokuWikiHtml2Latex.py html.tmp $section & wait done < inputfile And an input file like this: doku.php?id=ndewet:tools:tramonitor TraMonitor doku.php?id=ndewet:description Implementation -1 doku.php?id=ndewet:description Research\ Areas -1 The script downloads a number of webpages spesified in inputfile and must then pass the rest of line (eg. "Implementation -1" or "Research\ Areas -1") to the python script. Now for the sticky bit. When the third line of this example file is processed it passes "Research\ Areas" to the python script as two separate arguments, as confirmed by: >>> print sys.argv ['./DokuWikiHtml2Latex.py', 'html.tmp', 'Research', 'Areas', '-1'] How can I get a multi word section, like "Research Areas" from the input file into a single argument for the python script? I've tried escaping the '\', and also doing ./DokuWikiHtml2Latex.py html.tmp `echo ${section#* }` among other things, but to no avail. The number at the end of an input line is another argument, but optional. A: Put quotes around $section: ./DokuWikiHtml2Latex.py html.tmp "$section" & wait A: Just let read do the parsing stuff: while read page section rest do echo "Page: $page" echo "Section: $section" done < inputfile For handling the optional argument elegantly, use an array: while read -a fields do wget --quiet --no-proxy "www.cs.sun.ac.za/hons/${fields[0]}" -O html.tmp unset "fields[0]" ./DokuWikiHtml2Latex.py html.tmp "${fields[@]}" done < inputfile Always quote your variables! A: Normally multi-word arguments can be passed as one by using quotes, so: doku.php?id=ndewet:description "Research Areas" -1
Getting parameters from a file via shell script into python script in the right format
I have the following shell script: #! /bin/sh while read page_section page=${page_section%%\ *} section=${page_section#* } #NOTE: `%* }` is NOT a comment wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tmp & wait # echo ${page_section%%\ *} # verify correct string chopping # echo ${page_section#* } # verify correct string chopping ./DokuWikiHtml2Latex.py html.tmp $section & wait done < inputfile And an input file like this: doku.php?id=ndewet:tools:tramonitor TraMonitor doku.php?id=ndewet:description Implementation -1 doku.php?id=ndewet:description Research\ Areas -1 The script downloads a number of webpages spesified in inputfile and must then pass the rest of line (eg. "Implementation -1" or "Research\ Areas -1") to the python script. Now for the sticky bit. When the third line of this example file is processed it passes "Research\ Areas" to the python script as two separate arguments, as confirmed by: >>> print sys.argv ['./DokuWikiHtml2Latex.py', 'html.tmp', 'Research', 'Areas', '-1'] How can I get a multi word section, like "Research Areas" from the input file into a single argument for the python script? I've tried escaping the '\', and also doing ./DokuWikiHtml2Latex.py html.tmp `echo ${section#* }` among other things, but to no avail. The number at the end of an input line is another argument, but optional.
[ "Put quotes around $section:\n./DokuWikiHtml2Latex.py html.tmp \"$section\" & wait\n\n", "Just let read do the parsing stuff:\nwhile read page section rest\ndo\n echo \"Page: $page\"\n echo \"Section: $section\"\ndone < inputfile\n\nFor handling the optional argument elegantly, use an array:\nwhile read -a ...
[ 2, 1, 0 ]
[]
[]
[ "argument_passing", "bash", "python" ]
stackoverflow_0003282769_argument_passing_bash_python.txt
Q: Python interface to PayPal - urllib.urlencode non-ASCII characters failing I am trying to implement PayPal IPN functionality. The basic protocol is as such: The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc. I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. When I try to urllib.urlencode the params which PayPal has sent to me, I get a: While calling send_response_to_paypal. Traceback (most recent call last): File "<snip>/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "<snip>/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method) Details: I read the params in PayPal's original request as follows (the GET is for testing): def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() The code I use for sending back the request to PayPal from the processing page is: def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range. A: Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode: params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) Of course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to unicode first, then encode it: params['foo'] = my_raw_input.decode('iso-8859-1') params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) A: Instead of encoding to utf-8, one should encode to what ever the paypal is using for the post. It is available under key 'charset' in the form paypal sends. So the following code worked for me: data = dict([(k, v.encode(data['charset'])) for k, v in data.items()]) A: I know it's a bit late to chime in here, but the best solution I found was to not even parse what they were giving back. In django (don't know what you're using) I was able to get the raw request they sent, which I passed back verbatim. Then it was just a matter of putting the cmd key onto that. This way it never matters what encoding they send you, you're just sending it right back.
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
I am trying to implement PayPal IPN functionality. The basic protocol is as such: The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc. I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. When I try to urllib.urlencode the params which PayPal has sent to me, I get a: While calling send_response_to_paypal. Traceback (most recent call last): File "<snip>/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "<snip>/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method) Details: I read the params in PayPal's original request as follows (the GET is for testing): def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() The code I use for sending back the request to PayPal from the processing page is: def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range.
[ "Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode:\nparams = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))\n\nOf course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to u...
[ 41, 6, 3 ]
[]
[]
[ "paypal", "python", "unicode", "urllib", "urllib2" ]
stackoverflow_0000787935_paypal_python_unicode_urllib_urllib2.txt
Q: Speeding up regular expressions in Python I need to quickly extract text from HTML files. I am using the following regular expressions instead of a full-fledged parser since I need to be fast rather than accurate (I have more than a terabyte of text). The profiler shows that most of the time in my script is spent in the re.sub procedure. What are good ways of speeding up my process? I can implement some portions in C, but I wonder whether that will help given that the time is spent inside re.sub, which I think would be efficiently implemented. # Remove scripts, styles, tags, entities, and extraneous spaces: scriptRx = re.compile("<script.*?/script>", re.I) styleRx = re.compile("<style.*?/style>", re.I) tagsRx = re.compile("<[!/]?[a-zA-Z-]+[^<>]*>") entitiesRx = re.compile("&[0-9a-zA-Z]+;") spacesRx = re.compile("\s{2,}") .... text = scriptRx.sub(" ", text) text = styleRx.sub(" ", text) .... Thanks! A: First, use an HTML parser built for this, like BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Then, you can identify remaining particular slow spots with the profiler: http://docs.python.org/library/profile.html And for learning about regular expressions, I've found Mastering Regular Expressions very valuable, no matter what the programming language: http://oreilly.com/catalog/9781565922570 Also: How can I debug a regular expression in python? Due to the reclarification of the use-case, then for this request, I would say the above is not what you want. My alternate recommendation would be: Speeding up regular expressions in Python A: You're processing each file five times, so the first thing you should do (as Paul Sanwald said) is try to reduce that number by combining your regexes together. I would also avoid using reluctant quantifiers, which are designed for convenience at the expense of efficiency. Consider this regex: <script.*?</script> Each time the . goes to consume another character, it first has to make sure </script> won't match at that spot. It's almost like doing a negative lookahead at every position: <script(?:(?!</script>).)*</script> But we know there's no point doing the lookahead if the next character is anything but <, and we can tailor the regex accordingly: <script[^<]*(?:<(?!/script>)[^<]*)*</script> When I test them in RegexBuddy with this target string: <script type="text/javascript">var imagePath='http://sstatic.net/stackoverflow/img/';</script> ...the reluctant regex takes 173 steps to make the match, while the tailored regex takes only 28. Combining your first three regexes into one yields this beast: <(?:(script|style)[^<]*(?:<(?!/\1)[^<]*)*</\1>|[!/]?[a-zA-Z-]+[^<>]*>) You might want to zap the <HEAD> element while you're at it (i.e., (script|style|head)). I don't know what you're doing with the fourth regex, for character entities--are you just deleting those, too? I'm guessing the fifth regex has to be run separately, since some of the whitespace it's cleaning up is generated by the earlier steps. But try it with the first three regexes combined and see how much difference it makes. That should tell you if it's worth going forward with this approach. A: one thing you can do is combine the script/style regexes using backreferences. here's some sample data: $ cat sample <script>some stuff</script> <html>whatever </html> <style>some other stuff</style> using perl: perl -ne "if (/<(script|style)>.*?<\/\1>/) { print $1; } " sample it will match either script or style. I second the recommendation for "mastering regular expressions", it's an excellent book. A: If your use-case is indeed to parse a few things for each of millions of documents, then my above answer won't help. I recommend some heuristics, like doing a couple "straight text" regexes on them to begin with - like just plain /script/ and /style/ to throw things out quickly if you can. In fact, do you really need to do the end-tag check at all? Isn't <style good enough? Leave validation for someone else. If the quick ones succeed, then put the rest into a single regex, like /<script|<style|\s{2,}|etc.../ so that it doesn't have to go through so much text once for each regex. A: The suggestion to use an HTML parser is a good one, since it'll quite possibly be faster than regular expressions. But I'm not sure BeautifulSoup is the right tool for the job, since it constructs a parse tree from the entire file and stores the whole thing in memory. For a terabyte of HTML, you'd need an obscene amount of RAM to do that ;-) I'd suggest you look at HTMLParser, which is written at a lower level than BeautifulSoup, but I believe it's a stream parser, so it will only load a bit of the text at a time. A: I would use simple program with regular Python partition something like, this, but it is tested only with one style example file: ## simple filtering when not hierarchical tags inside other discarded tags start_tags=('<style','<script') end_tags=('</style>','</script>') ##print("input:\n %s" % open('giant.html').read()) out=open('cleaned.html','w') end_tag='' for line in open('giant.html'): line=' '.join(line.split()) if end_tag: if end_tag in line: _,tag,end = line.partition(end_tags[index]) if end.strip(): out.write(end) end_tag='' continue ## discard rest of line if no end tag found in line found=( index for index in (start_tags.index(start_tag) if start_tag in line else '' for start_tag in start_tags) if index is not '') for index in found: start,tag,end = line.partition(start_tags[index]) # drop until closing angle bracket of start tag tag,_ ,end = end.partition('>') # check if closing tag already in same line if end_tags[index] in end: _,tag,end = end.partition(end_tags[index]) if end.strip(): out.write(end) end_tag = '' # end tag reset after found else: end_tag=end_tags[index] out.write(end) # no end tag at same line if not end_tag: out.write(line+'\n') out.close() ## print 'result:\n%s' % open('cleaned.html').read()
Speeding up regular expressions in Python
I need to quickly extract text from HTML files. I am using the following regular expressions instead of a full-fledged parser since I need to be fast rather than accurate (I have more than a terabyte of text). The profiler shows that most of the time in my script is spent in the re.sub procedure. What are good ways of speeding up my process? I can implement some portions in C, but I wonder whether that will help given that the time is spent inside re.sub, which I think would be efficiently implemented. # Remove scripts, styles, tags, entities, and extraneous spaces: scriptRx = re.compile("<script.*?/script>", re.I) styleRx = re.compile("<style.*?/style>", re.I) tagsRx = re.compile("<[!/]?[a-zA-Z-]+[^<>]*>") entitiesRx = re.compile("&[0-9a-zA-Z]+;") spacesRx = re.compile("\s{2,}") .... text = scriptRx.sub(" ", text) text = styleRx.sub(" ", text) .... Thanks!
[ "First, use an HTML parser built for this, like BeautifulSoup:\nhttp://www.crummy.com/software/BeautifulSoup/\nThen, you can identify remaining particular slow spots with the profiler:\nhttp://docs.python.org/library/profile.html\nAnd for learning about regular expressions, I've found Mastering Regular Expressions ...
[ 8, 5, 1, 1, 0, 0 ]
[]
[]
[ "optimization", "python", "regex" ]
stackoverflow_0003277239_optimization_python_regex.txt
Q: Looking for a PHP's str_split() replacement Let's say I have this little piece of code: <?php $tmp = str_split('hello world!',2); // $tmp will now be: array('he','ll','o ','wo','rl','d!'); foreach($tmp AS &$a) { // some processing } unset($tmp); ?> How can I do this in Python v2.7? I thought this would do it: the_string = 'hello world!' tmp = the_string.split('',2) for a in tmp: # some processing del tmp but it returns an "empty separator" error. Any thoughts on this? A: for i in range(0, len(the_string), 2): print(the_string[i:i+2]) A: tmp = the_string[::2] gives a copy of the_string with every second element. ...[::1] would return a copy with every element, ...[::3] would give every third element, etc. Note that this is a slice and the full form is list[start:stop:step], though any of these three can be omitted (as well as step can be omitted since it defaults to 1). A: In [24]: s = 'hello, world' In [25]: tmp = [''.join(t) for t in zip(s[::2], s[1::2])] In [26]: print tmp ['he', 'll', 'o,', ' w', 'or', 'ld'] A: def str_split_like_php(s, n): """Split `s` into chunks `n` chars long.""" ret = [] for i in range(0, len(s), n): ret.append(s[i:i+n]) return ret
Looking for a PHP's str_split() replacement
Let's say I have this little piece of code: <?php $tmp = str_split('hello world!',2); // $tmp will now be: array('he','ll','o ','wo','rl','d!'); foreach($tmp AS &$a) { // some processing } unset($tmp); ?> How can I do this in Python v2.7? I thought this would do it: the_string = 'hello world!' tmp = the_string.split('',2) for a in tmp: # some processing del tmp but it returns an "empty separator" error. Any thoughts on this?
[ "for i in range(0, len(the_string), 2):\n print(the_string[i:i+2])\n\n", "tmp = the_string[::2] gives a copy of the_string with every second element. ...[::1] would return a copy with every element, ...[::3] would give every third element, etc.\nNote that this is a slice and the full form is list[start:stop:st...
[ 6, 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003282929_python_string.txt
Q: Python Chain getattr as a string import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom doc = amara.parse("sample.xml") print chain_attribute_call(doc, "X.Y.Z") In oder to execute chain attribute calls for an object as a string, I had to develop the clumsy snippet above. I am curious if there would be a more clever / efficient solution to this. A: you could also use: from operator import attrgetter attrgetter('x.y.z')(doc) A: Just copying from Useful code which uses reduce() in Python: from functools import reduce reduce(getattr, "X.Y.Z".split('.'), doc)
Python Chain getattr as a string
import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom doc = amara.parse("sample.xml") print chain_attribute_call(doc, "X.Y.Z") In oder to execute chain attribute calls for an object as a string, I had to develop the clumsy snippet above. I am curious if there would be a more clever / efficient solution to this.
[ "you could also use:\nfrom operator import attrgetter\nattrgetter('x.y.z')(doc)\n\n", "Just copying from Useful code which uses reduce() in Python:\nfrom functools import reduce\nreduce(getattr, \"X.Y.Z\".split('.'), doc)\n\n" ]
[ 31, 13 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0003279082_getattr_python.txt
Q: python and using 'self' in methods From what I read/understand, the 'self' parameter is similiar to 'this'. Is that true? If its optional, what would you do if self wasnt' passed into the method? A: Yes, it's used in similar ways. Note that it's a positional parameter and you can call it what you want; however there is a strong convention to call it self (not this or anything else). Some positional parameter must be there for a usable instance method; it is not optional. A: The joy of Python That is true to some extend. Methods are bound to the object instance they are a part of. When you see def some_func(self, foo, bar) The passing of self is sometimes implicit when you call, for example: obj.some_func(foo_val, bar_val) Which is equal (presuming obj is of class MyClass) to MyClass.some_func(obj, foo_val, bar_val) Because the method is bound to obj, the self argument gets populated. This is part of Python being explicit with what it means. In other languages, this just pops into scope, with Python there is some exposure of how this happens. You can also pass methods around, and manually pass them self when not calling from a bound context. The Python docs do a good Job: xf = x.f while True: print xf() will continue to print hello world until the end of time. What exactly happens when a method is called? You may have noticed that x.f() was called >without an argument above, even though the function definition for f() specified an >argument. What happened to the argument? Surely Python raises an exception when a function >that requires an argument is called without any — even if the argument isn’t actually >used... Actually, you may have guessed the answer: the special thing about methods is that the >object is passed as the first argument of the function. In our example, the call x.f() is >exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments >is equivalent to calling the corresponding function with an argument list that is created >by inserting the method’s object before the first argument. A: self is this, just you have to explicitly pass it and explicitly use it to refer to class methods/properties. It isn't optional in class methods. You will get a TypeError if you try to define a classmethod without at least one argument (i.e., the self parameter). However, you can call it something other than self, but I have never seen otherwise. A: In classes a self variable (or cls for classmethods) is required. What you want to call it is your decision though. If you prefer you could call it this instead. A classmethod is a method that gets the class as a first argument instead of a instance. It can be called without passing an instance. i.e. with a classmethod you can do: SomeObject.some_class_method() while a normal method would require you to do SomeObject().some_normal_method() or SomeObject.some_normal_method(instance) A: self refers to the object on which the method was called, much like this in C++. But it is important that self is merely a convention, you can name it as you like and pass instances of subclasses. A: self is definitely similar to this, however, in Python, the name self is just a convention, and could be named anything else. The variable is named after whatever you call it in the function's prototype (def function(whatever, params...):). For instance methods, self IS actually required. For class or static methods, you need to specify that they should be treated as such, and then self is not required. For example: def type_to_display(type): """Converts a pass type to the full written pass type.""" return list((pair[1] for pair in Pass.TYPE_CHOICES if pair[0] == type[0:1].upper()))[0] type_to_display = staticmethod(type_to_display) You will never be able to use an instance method in such a way that self is not passed in. For example, if I have an instance my_car of a Car class, and I use the Car class's drive instance method, the my_car instance will be implicitly passed into the drive method as the first parameter (self). class Car: def drive(self): self.do_some_stuff() my_car = Car() my_car.drive() # actually calls Car.drive(my_car)
python and using 'self' in methods
From what I read/understand, the 'self' parameter is similiar to 'this'. Is that true? If its optional, what would you do if self wasnt' passed into the method?
[ "Yes, it's used in similar ways. Note that it's a positional parameter and you can call it what you want; however there is a strong convention to call it self (not this or anything else). Some positional parameter must be there for a usable instance method; it is not optional.\n", "The joy of Python\nThat is tr...
[ 5, 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "self" ]
stackoverflow_0003283178_python_self.txt
Q: 2 digit years using strptime() is not able to parse birthdays very well Consider the following birthdays (as dob): 1-Jun-68 1-Jun-69 When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield: datetime.datetime(2068, 6, 1, 0, 0) datetime.datetime(1969, 6, 1, 0, 0) Well of course they’re supposed to be born in the same decade but now it’s not even in the same century! According to the docs this is perfectly valid behaviour: When 2-digit years are accepted, they are converted according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and values 0–68 are mapped to 2000–2068. I understand why the function is set up like this but is there a way to work around this? Perhaps with defining your own ranges for 2-digit years? A: If you're always using it for birthdays, just subtract 100 if the year is after now: if d > datetime.now(): d = datetime(d.year - 100, d.month, d.day) A: This function shifts the year to 1950: def millenium(year, shift=1950): return (year-shift)%100 + shift A: If you're expecting a birthday, you could always just manually massage the data - any date in the future is automatically set back a century, or some such.
2 digit years using strptime() is not able to parse birthdays very well
Consider the following birthdays (as dob): 1-Jun-68 1-Jun-69 When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield: datetime.datetime(2068, 6, 1, 0, 0) datetime.datetime(1969, 6, 1, 0, 0) Well of course they’re supposed to be born in the same decade but now it’s not even in the same century! According to the docs this is perfectly valid behaviour: When 2-digit years are accepted, they are converted according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and values 0–68 are mapped to 2000–2068. I understand why the function is set up like this but is there a way to work around this? Perhaps with defining your own ranges for 2-digit years?
[ "If you're always using it for birthdays, just subtract 100 if the year is after now:\nif d > datetime.now():\n d = datetime(d.year - 100, d.month, d.day)\n\n", "This function shifts the year to 1950:\ndef millenium(year, shift=1950):\n return (year-shift)%100 + shift\n\n", "If you're expecting a birthday...
[ 12, 2, 0 ]
[]
[]
[ "2_digit_year", "python", "strptime" ]
stackoverflow_0003283209_2_digit_year_python_strptime.txt
Q: Python, suds, Error When I'm trying get method from remote webservice it gives me error. My code is: portion=10 start=0 print self.stamp.datetime client=self.client while 1: print 'getting ids...........' fresh_ids=client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) #this line makes exception if len(fresh_ids) is not 0: for id in fresh_ids: yield id start=+portion else: print 'No updated topics anymore' sys.exit() There is trace-back: /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/client.py in invoke(self, args, kwargs) 469 binding = self.method.binding.input 470 binding.options = self.options --> 471 msg = binding.get_message(self.method, args, kwargs) 472 timer.stop() 473 metrics.log.debug( /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/bindings/binding.py in get_message(self, method, args, kwargs) 96 content = self.headercontent(method) 97 header = self.header(content) ---> 98 content = self.bodycontent(method, args, kwargs) 99 body = self.body(content) 100 env = self.envelope(header, body) /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/bindings/rpc.py in bodycontent(self, method, args, kwargs) 61 p = self.mkparam(method, pd, value) 62 if p is not None: ---> 63 root.append(p) 64 n += 1 65 return root /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/sax/element.py in append(self, objects) 329 child.parent = self 330 continue --> 331 raise Exception('append %s not-valid' % child.__class__.__name__) 332 return self 333 <type 'exceptions.Exception'>: append list not-valid There is the method in suds module which raises an Exception: def insert(self, objects, index=0): """ Insert an L{Element} content at the specified index. @param objects: A (single|collection) of attribute(s) or element(s) to be added as children. @type objects: (L{Element}|L{Attribute}) @param index: The position in the list of children to insert. @type index: int @return: self @rtype: L{Element} """ objects = (objects,) for child in objects: if isinstance(child, Element): self.children.insert(index, child) child.parent = self else: raise Exception('append %s not-valid' % child.__class__.__name__) return self In the console everything is going well. I'm stuck. Ok, I tried to make an experiment: def YieldID(self): portion=10 start=0 print self.stamp.datetime fresh_ids=self.client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) #This work while 1: print 'getting ids...........' fresh_ids=self.client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) # This raise exception if len(fresh_ids)!=0: for id in fresh_ids: yield id start=+portion else: print 'No updated topics anymore' sys.exit() I add calling of the same method before WHILE end it work. But when it go inside while gives me exception. How it can work before loop, and don't work inside loop? That is the main question. What changed? I even tried changing while to for. A: Edit: On another look at the code, I noticed that this line: start=+portion needs to be changed to start += portion That might make the following analysis unnecessary... but I think there might still be an issue in your suds source, as explained below. The first question I'd ask is: Are you sure that nothing is changing inside your self.client object between calls to YieldID? The other concern I have -- which may well be indicative of nothing at all -- is that you may have posted the wrong source for the function where the Exception is raised. The traceback shows that the Exception is raised during a call to append, but the code you included is for insert. It looks as if insert's Exception message identifies it as "append" due to a copy and paste error. And there's more. Assuming that I've identified the right source location, here's the full source for append, which starts with line number 313: def append(self, objects): """ Append the specified child based on whether it is an element or an attrbuite. @param objects: A (single|collection) of attribute(s) or element(s) to be added as children. @type objects: (L{Element}|L{Attribute}) @return: self @rtype: L{Element} """ if not isinstance(objects, (list, tuple)): objects = (objects,) for child in objects: if isinstance(child, Element): self.children.append(child) child.parent = self continue if isinstance(child, Attribute): self.attributes.append(child) child.parent = self continue raise Exception('append %s not-valid' % child.__class__.__name__) return self Here, the Exception is raised on line 334, not 331 as your traceback shows. Are you sure that you're using the original version of suds 0.3.5, and not a modified version? Because the original version of append has an interesting difference with insert: insert always creates a tuple out of its input argument, which seems redundant at best: def insert(self, objects, index=0): // line 337 # ... snip to line 348 objects = (objects,) whereas the original append does this conditionally (see above): if not isinstance(objects, (list, tuple)): objects = (objects,) Now look at the message in the exception: : append list not-valid This means that the child that it tried to append was itself a list. But how could this be? If a list had been passed in as input, then we should be iterating through the children of that list... which should not themselves be lists. Hmm. Perhaps a doubly-nested list had been passed into append as the object parameter, which would seem to indicate some pretty bad corruption of data structures. (See my first question.) Or... What follows is sheer speculation, and can't possibly be right ... unless it is... Or, maybe, you're using a modified version of Suds in which that conditional conversion to a list has been removed, along with the iteration through the list? That would explain the 3-line difference (331 vs. 334) between the code you posted and the source that I found online. Could you double-check the source file that you're using, and let us know for sure?
Python, suds, Error
When I'm trying get method from remote webservice it gives me error. My code is: portion=10 start=0 print self.stamp.datetime client=self.client while 1: print 'getting ids...........' fresh_ids=client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) #this line makes exception if len(fresh_ids) is not 0: for id in fresh_ids: yield id start=+portion else: print 'No updated topics anymore' sys.exit() There is trace-back: /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/client.py in invoke(self, args, kwargs) 469 binding = self.method.binding.input 470 binding.options = self.options --> 471 msg = binding.get_message(self.method, args, kwargs) 472 timer.stop() 473 metrics.log.debug( /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/bindings/binding.py in get_message(self, method, args, kwargs) 96 content = self.headercontent(method) 97 header = self.header(content) ---> 98 content = self.bodycontent(method, args, kwargs) 99 body = self.body(content) 100 env = self.envelope(header, body) /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/bindings/rpc.py in bodycontent(self, method, args, kwargs) 61 p = self.mkparam(method, pd, value) 62 if p is not None: ---> 63 root.append(p) 64 n += 1 65 return root /usr/lib/python2.5/site-packages/suds-0.3.5-py2.5.egg/suds/sax/element.py in append(self, objects) 329 child.parent = self 330 continue --> 331 raise Exception('append %s not-valid' % child.__class__.__name__) 332 return self 333 <type 'exceptions.Exception'>: append list not-valid There is the method in suds module which raises an Exception: def insert(self, objects, index=0): """ Insert an L{Element} content at the specified index. @param objects: A (single|collection) of attribute(s) or element(s) to be added as children. @type objects: (L{Element}|L{Attribute}) @param index: The position in the list of children to insert. @type index: int @return: self @rtype: L{Element} """ objects = (objects,) for child in objects: if isinstance(child, Element): self.children.insert(index, child) child.parent = self else: raise Exception('append %s not-valid' % child.__class__.__name__) return self In the console everything is going well. I'm stuck. Ok, I tried to make an experiment: def YieldID(self): portion=10 start=0 print self.stamp.datetime fresh_ids=self.client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) #This work while 1: print 'getting ids...........' fresh_ids=self.client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.datetime,start,portion) # This raise exception if len(fresh_ids)!=0: for id in fresh_ids: yield id start=+portion else: print 'No updated topics anymore' sys.exit() I add calling of the same method before WHILE end it work. But when it go inside while gives me exception. How it can work before loop, and don't work inside loop? That is the main question. What changed? I even tried changing while to for.
[ "Edit: On another look at the code, I noticed that this line:\n start=+portion\n\nneeds to be changed to\n start += portion\n\nThat might make the following analysis unnecessary... but I think there might still be an issue in your suds source, as explained below.\n\nThe first question I'd ask ...
[ 2 ]
[]
[]
[ "python", "suds" ]
stackoverflow_0003282150_python_suds.txt
Q: finding out absolute path to a file from python If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo, os.curdir will return foo but not the path of test.py. thanks. A: Here's how to get the directory of the current file: import os os.path.abspath(os.path.dirname(__file__)) A: the answer is to use: __file__ which returns a relative path. os.path.abspath(__file__) can be used to get the full path. A: The answers so far have correctly pointed you to os.path.abspath, which does exactly the job you requested. However don't forget that os.path.normpath and os.path.realpath can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these "many" is impossible to tell from the scant info we have, of course;-). A: import os dirname, filename = os.path.split(os.path.abspath(__file__)) A: os.path has lots of tools for dealing with paths and getting information about paths. Particularly, you want: os.path.abspath
finding out absolute path to a file from python
If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo, os.curdir will return foo but not the path of test.py. thanks.
[ "Here's how to get the directory of the current file:\nimport os\nos.path.abspath(os.path.dirname(__file__))\n\n", "the answer is to use:\n __file__\n\nwhich returns a relative path. \nos.path.abspath(__file__) \n\ncan be used to get the full path.\n", "The answers so far have correctly pointed you to os.path.a...
[ 53, 25, 5, 2, 0 ]
[]
[]
[ "filesystems", "io", "python" ]
stackoverflow_0003283306_filesystems_io_python.txt
Q: Python "NoneType is not callable" error I have a function that looks like the following, with a whole lot of optional parameters. One of these parameters, somewhere amidst all the others, is text. I handle text specially because if it is a boolean, then I want to run to do something based on that. If it's not (which means it's just a string), then I do something else. The code looks roughly like this: def foo(self, arg1=None, arg2=None, arg3=None, ..., text=None, argN=None, ...): ... if text is not None: if type(text)==bool: if text: # Do something else: # Do something else else: # Do something else I get the following error on the type(text)==bool line: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...", line 79, in foo if type(text)==bool: TypeError: 'NoneType' object is not callable Not sure what the problem is. Should I be testing the type differently? Experimenting on the python command line seems to confirm that my way of doing it should work. A: I guess you have an argument called type somewhere, I can easily reproduce your error with the following code: >>> type('abc') <class 'str'> >>> type = None >>> type('abc') Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> type('abc') TypeError: 'NoneType' object is not callable A: I bet you have a type=None among your arguments. Just a special case of the general rule: "don't hide built-in identifiers with your own -- it may or may not bite in any specific give case, but it will bite you nastily in some cases in the future unless you develop the right habit about it"!-)
Python "NoneType is not callable" error
I have a function that looks like the following, with a whole lot of optional parameters. One of these parameters, somewhere amidst all the others, is text. I handle text specially because if it is a boolean, then I want to run to do something based on that. If it's not (which means it's just a string), then I do something else. The code looks roughly like this: def foo(self, arg1=None, arg2=None, arg3=None, ..., text=None, argN=None, ...): ... if text is not None: if type(text)==bool: if text: # Do something else: # Do something else else: # Do something else I get the following error on the type(text)==bool line: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "...", line 79, in foo if type(text)==bool: TypeError: 'NoneType' object is not callable Not sure what the problem is. Should I be testing the type differently? Experimenting on the python command line seems to confirm that my way of doing it should work.
[ "I guess you have an argument called type somewhere, I can easily reproduce your error with the following code:\n>>> type('abc')\n<class 'str'>\n>>> type = None\n>>> type('abc')\nTraceback (most recent call last):\n File \"<pyshell#62>\", line 1, in <module>\n type('abc')\nTypeError: 'NoneType' object is not ca...
[ 8, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0003283441_python_types.txt
Q: Is this an acceptable pythonic idiom? I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an acceptable idiom? I've just started using Python. class FileParser: """ uses an open filehandle to do stuff """ class BatchImporter: def __init__(self, files): self.files=files def parsers(self): for file in self.files: try: fh = open(file, "rb") parser = FileParser(fh) yield parser finally: fh.close() def verifyfiles( def cleanup( --- importer = BatchImporter(filelist) for p in BatchImporter.parsers(): p.method1() ... A: You could make one thing a little simpler: Instead of try...finally, use a with block: with open(file, "rb") as fh: yield FileParser(fh) This will close the file for you automatically as soon as the with block is left. A: It's absolutely fine to have a method that's a generator, as you do. I would recommend making all your classes new-style (if you're on Python 2, either set __metaclass__ = type at the start of your module, or add (object) to all your base-less class statements), because legacy classes are "evil";-); and, for clarity and conciseness, I would also recomment coding the generator differently...: def parsers(self): for afile in self.files: with open(afile, "rb") as fh: yield FileParser(fh) but neither of these bits of advice condemns in any way the use of generator methods!-) Note the use of afile in lieu of file: the latter is a built-in identifier, and as a general rule it's better to get used to not "hide" built-in identifiers with your own (it doesn't bite you here, but it will in many nasty ways in the future unless you get into the right habit!-). A: The design is fine if you ask me, though using finally the way you use it isn't exactly idiomatic. Use catch and maybe re-raise the exception (using the raise keyword alone, otherwise you mess the stacktrace up), and for bonus points, don't catch: but catch Exception: (otherwise, you catch SystemExit and KeyboardInterrupt). Or simply use the with-statement as shown by Tim Pietzcker. A: In general, it isn't safe to close the file after you yield a parser object that will try to read it. Consider this code: parsers = list(BatchImporter.parsers()) for p in parsers: # the file object that p holds will already be closed! If you're not writing a long-running daemon process, most of the time you don't need to worry about closing files -- they will all get closed when your program exits, or when the file objects are garbage-collected. (And if you use CPython, that will happen as soon as all references to them are lost, since CPython uses reference counting.) Nevertheless, taking care to free resources is a good habit to acquire, so I would probably write the FileParser class this way: class FileParser: def __init__(self, file_or_filename, closing=False): if hasattr(file_or_filename, 'read'): self.f = file_or_filename self._need_to_close = closing else: self.f = open(file_or_filename, 'rb') self._need_to_close = True def close(self): if self._need_to_close: self.f.close() self._need_to_close = False and then BatchImporter.parsers would become def parsers(self): for file in self.files: yield FileParser(file) or, if you love functional programming def parsers(self): return itertools.imap(FileParser, self.files) An aside: if you're new to Python, I recommend you take a look at the Python style guide (also known as PEP 8). Two-space indents look weird.
Is this an acceptable pythonic idiom?
I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an acceptable idiom? I've just started using Python. class FileParser: """ uses an open filehandle to do stuff """ class BatchImporter: def __init__(self, files): self.files=files def parsers(self): for file in self.files: try: fh = open(file, "rb") parser = FileParser(fh) yield parser finally: fh.close() def verifyfiles( def cleanup( --- importer = BatchImporter(filelist) for p in BatchImporter.parsers(): p.method1() ...
[ "You could make one thing a little simpler: Instead of try...finally, use a with block:\nwith open(file, \"rb\") as fh:\n yield FileParser(fh)\n\nThis will close the file for you automatically as soon as the with block is left.\n", "It's absolutely fine to have a method that's a generator, as you do. I would ...
[ 12, 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003283479_python.txt
Q: Can I format a variable in python? Is there a way of formating a variable? For example, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution? A: The best solution for this kind of problem is to use dictionaries: color_of = {} M = "bingo" color_of[M] = "red" print(color_of[M]) A: If the 'variable' can be an attribute of an object, you could use setattr() class Color(object): pass color = Color() attr_name = '{foo}_color'.format(foo='bingo') setattr(color, attr_name, 'red') Beyond that, you're looking at using eval()
Can I format a variable in python?
Is there a way of formating a variable? For example, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution?
[ "The best solution for this kind of problem is to use dictionaries:\ncolor_of = {}\nM = \"bingo\"\ncolor_of[M] = \"red\"\nprint(color_of[M])\n\n", "If the 'variable' can be an attribute of an object, you could use setattr()\nclass Color(object):\n pass\n\ncolor = Color()\n\nattr_name = '{foo}_color'.format(foo...
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003283621_python.txt
Q: How to convert a Python string representing bytes into actual bytes? I have a string like: "01030009" and I want to get another string (because in Python 2.x we use strings for bytes) newString which will produce this result: for a in newString: print ord(a) 0 1 0 3 0 0 0 9 Thanks A: ''.join(chr(int(x)) for x in oldString) chr is the inverse of ord. A: All the "deeply builtin" ways interpret characters as bytes in a different way than the one you want, because the way you appear to desire seems limited to represent bytes worth less than 10 (or less than 16 if you meant to use hex and just completely forgot to mention it). In other words, your desired code can represent a truly miniscule fraction of byte strings, and therefore would be absurd to "officialize" in any way (such as supporting it in builtin ways)! For example, considering strings of length 8 (your example's short length), the total number of byte strings of that length which exist is 256 ** 8, while the number your chosen notation can represent is 10 ** 8. I.e....: >>> exist = 256 ** 8 >>> repre = 10 ** 8 >>> print exist, repre 18446744073709551616 100000000 >>> print (repre / float(exist)) 5.42101086243e-12 >>> So why would you expect any kind of "built-in" official support for a representation which, even for such really short strings, can only represent about five thousandths of one billionth of the possible byte strings?! The words "special case" were invented for things that happen far more frequently than this (if you got a random 8-byte string every second, it would be many centuries before you finally got one representable in your scheme), and longer byte strings keep exacerbating this effect exponentially, of course. There are many "official" schemes for representation of byte strings, such as base64 and friends as specified in RFC 3548... your desired scheme is very signally not among them;-). Those are the schemes that get "official", built-in support in Python, of course. A: For variety: import string newString = oldString.translate(string.maketrans('0123456789', '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09'))
How to convert a Python string representing bytes into actual bytes?
I have a string like: "01030009" and I want to get another string (because in Python 2.x we use strings for bytes) newString which will produce this result: for a in newString: print ord(a) 0 1 0 3 0 0 0 9 Thanks
[ "''.join(chr(int(x)) for x in oldString)\n\nchr is the inverse of ord.\n", "All the \"deeply builtin\" ways interpret characters as bytes in a different way than the one you want, because the way you appear to desire seems limited to represent bytes worth less than 10 (or less than 16 if you meant to use hex and ...
[ 8, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003282678_python.txt
Q: What python virtual environment and deployment solution should I use? I'm looking for a virtual environment solution for Python applications and I would like something that respects these requirements: Windows and Linux works with x86/x64 Python versions easy to use/maintain Python 2.6-2.7 compatible and preferably even 3.x source control friendly - I want to keep the packages in SCM. So far I identified virtual-python and zc.buildout, but at least buildout does not supports py3. I'm not looking for a list of solutions, only one you recommend, preferably after you used more than one. A: Either virtualenv or zc.buildout will work. Virtualenv is easier to learn and use; buildout is more powerful. I personally use buildout for development/deployment of packages I develop, and virtualenv for deployment of 3rd-party applications (like Trac). Disclaimer: I've never attempted to use either on Windows, or on Python 3. I see that there's a version of virtualenv that works in Python 3, and there's a branch of zc.buildout that attempts to add Python 3 support (but it seems to be abandoned).
What python virtual environment and deployment solution should I use?
I'm looking for a virtual environment solution for Python applications and I would like something that respects these requirements: Windows and Linux works with x86/x64 Python versions easy to use/maintain Python 2.6-2.7 compatible and preferably even 3.x source control friendly - I want to keep the packages in SCM. So far I identified virtual-python and zc.buildout, but at least buildout does not supports py3. I'm not looking for a list of solutions, only one you recommend, preferably after you used more than one.
[ "Either virtualenv or zc.buildout will work. Virtualenv is easier to learn and use; buildout is more powerful. I personally use buildout for development/deployment of packages I develop, and virtualenv for deployment of 3rd-party applications (like Trac).\nDisclaimer: I've never attempted to use either on Windows...
[ 2 ]
[]
[]
[ "buildout", "python", "virtualenv" ]
stackoverflow_0003282451_buildout_python_virtualenv.txt
Q: Sorting a list pairs by frequency of the pair elements I'm completely new to Python and while trying various random bits and pieces I've struck upon a problem that I believe I've "solved", but the code doesn't feel right - I strongly suspect there is going to be a better way to get the desired result. FYI - I'm using whatever the latest version of Python 3 is, on Windows. Problem definition Briefly, what I'm doing is sorting a list of pairs, such that the pairs containing the elements that appears in the fewest pairs are sorted to the front. The pairs are in the form [i,j] with 0 <= i <= j < n, where n is a known maximum value for the elements. There are no duplicate pairs within the list. The count of an element i is a simple count of the number of pairs (not pair elements) in the forms [i,j],[j,i] and [i,i] where j is any value that results in a valid pair. In the sorted result, a pair [i,j] should appear before a pair [k,l] if count(i) < count(k) or count(i) == count(k) and count(j) < count(l) (If count(j) == count(l) the two can be in either order - I'm not bothered about the sort being stable, would be a bonus though). In the sorted result, a pair [i,j] should appear before a pair [k,l] if min(count(i),count(j)) < min(count(k),count(l)) or min(count(i),count(j)) == min(count(k),count(l)) and max(count(i),count(j)) < max(count(k),count(l)). In otherwords, if the pair is [0,1] and 1 has a count of one, but 0 has a count of four hundred, the pair should still be at (or at least very near) the front of the list - they need sorting by the least frequent element in the pair. Here's a contrived example I've built: input [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]] Here's the individual element counts and the source pairs they come from: 0: 1 [0,0] 1: 2 [1,2],[1,4] 2: 3 [1,2],[2,2],[2,3] 3: 3 [2,3],[3,3],[3,4] 4: 2 [1,4],[3,4] And here's the result, along with the pair scores: output: [[0,0],[1,4],[1,2],[3,4],[2,2],[2,3],[3,3]] scores: 1 1-2 1-3 2-3 3 3 3 Here, 0 has a count of one (it appears in one pair, albeit twice) so comes first. 1 has a count of two, so appears second - with [1,4] before [1,2] because 4 has a count of two and 2 has a count of three, et cetera. My current solution As said, I believe this implimentation works accurately, but it just feels that there must be a better way to go about doing this. Anyway, here's what I've got so far: #my implementation uncommented to reduce post size, see history for comments def sortPairList( data , n ): count = [] for i in range(0,n): count.append( 0 ) #count up the data for p in data: count[p[0]] += 1 if p[1] != p[0]: count[p[1]] += 1 maxcount = 0 for i in range(0,n): if count[i] > maxcount: maxcount = count[i] def elementFrequency(p): if count[ p[0] ] < count[ p[1] ]: return count[ p[0] ] + float(count[ p[1] ]) / (maxcount+1) else: return count[ p[1] ] + float(count[ p[0] ]) / (maxcount+1) data.sort( key=elementFrequency ) Any suggestions on a more "Python" way of doing this? Or anything that's wrong with my current attempt? New Test Case (see answer's comments) input: [[0,0],[0,3],[0,5],[0,7],[1,1],[1,2],[1,8],[2,4],[2,5],[3,4],[3,5],[3,9],[4,4],[4,7],[4,8],[6,8],[7,7],[7,9],[8,9]] expected: [[6,8],[1,1],[1,2],[2,5],[0,5],[1,8],[3,5],[3,9],[7,9],[8,9],[2,4],[0,0],[0,3],[0,7],[7,7],[3,4],[4,7],[4,8],[4,4]] A: I would probably use a Counter (needs Python ≥2.7 or ≥3.1) for tallying. from collections import Counter from itertools import chain def sortPairList2(data): tally = Counter(chain(*map(set, data))) data.sort(key=lambda x: sorted(tally[i] for i in x)) Note that: You can create an anonymous function with lambda. For example, >>> c = 4 >>> a = lambda p: p - c >>> a(7) 3 The sort key need not be a number. Anything comparable can be used as the return value of the key function. In my code, a list is used for ordering. There are many simpler idioms in Python for your original code. The count can be initialized using count = [0] * n instead of that loop. The maxcount can be obtained with the max function. maxcount = max(count) List comprehension is used a lot in Python. If your target is to transform an iterable into another iterable, prefer comprehension over loops. A: >>> n = 4 >>> freqs = {i: sum(i in j for j in inp) for i in range(n+1)} >>> def key(x): a, b = x return min(freqs[a], freqs[b]), max(freqs[a], freqs[b]) >>> sorted(inp, key=key) P.S. Please note that input is a bad name for a variable as it shadows built-in. A: While KennyTM solution works I tried to do it myself. My solution precomputes frequencies and stores it in dictionary where str(n) is key. I had some trouble with changing compare function known from Python2 to key used with Python3, but I found recipe at ActiveState code item_cnt = {} def icount(n): return item_cnt[str(n)] def add_item(n): sn = str(n) try: item_cnt[sn] += 1 except KeyError: item_cnt[sn] = 1 # sort callback def cmp_items(ij, kl): i, j = ij k, l = kl if icount(i) < icount(k) or icount(i) == icount(k) and icount(j) < icount(l): return -1 return 1 input = [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]] # count all items for (i, j) in input: add_item(i) add_item(j) # works with Python 2.x #input.sort(cmp_items) # works with Python2.6 and Python 3.x # to convert compare function to key look at: # http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/ input.sort(key=cmp_to_key(cmp_items)) print(input) A: Similar to KennyTM's solution, but for Python 2.5 or greater: import collections def sort_by_occurence(sequences): tally = collections.defaultdict(int) for sequence in sequences: for item in sequence: tally[item] += 1 sequences.sort(key=lambda x:map(tally.get, x)) pair_list = [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]] sort_by_occurence(pair_list) print pair_list
Sorting a list pairs by frequency of the pair elements
I'm completely new to Python and while trying various random bits and pieces I've struck upon a problem that I believe I've "solved", but the code doesn't feel right - I strongly suspect there is going to be a better way to get the desired result. FYI - I'm using whatever the latest version of Python 3 is, on Windows. Problem definition Briefly, what I'm doing is sorting a list of pairs, such that the pairs containing the elements that appears in the fewest pairs are sorted to the front. The pairs are in the form [i,j] with 0 <= i <= j < n, where n is a known maximum value for the elements. There are no duplicate pairs within the list. The count of an element i is a simple count of the number of pairs (not pair elements) in the forms [i,j],[j,i] and [i,i] where j is any value that results in a valid pair. In the sorted result, a pair [i,j] should appear before a pair [k,l] if count(i) < count(k) or count(i) == count(k) and count(j) < count(l) (If count(j) == count(l) the two can be in either order - I'm not bothered about the sort being stable, would be a bonus though). In the sorted result, a pair [i,j] should appear before a pair [k,l] if min(count(i),count(j)) < min(count(k),count(l)) or min(count(i),count(j)) == min(count(k),count(l)) and max(count(i),count(j)) < max(count(k),count(l)). In otherwords, if the pair is [0,1] and 1 has a count of one, but 0 has a count of four hundred, the pair should still be at (or at least very near) the front of the list - they need sorting by the least frequent element in the pair. Here's a contrived example I've built: input [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]] Here's the individual element counts and the source pairs they come from: 0: 1 [0,0] 1: 2 [1,2],[1,4] 2: 3 [1,2],[2,2],[2,3] 3: 3 [2,3],[3,3],[3,4] 4: 2 [1,4],[3,4] And here's the result, along with the pair scores: output: [[0,0],[1,4],[1,2],[3,4],[2,2],[2,3],[3,3]] scores: 1 1-2 1-3 2-3 3 3 3 Here, 0 has a count of one (it appears in one pair, albeit twice) so comes first. 1 has a count of two, so appears second - with [1,4] before [1,2] because 4 has a count of two and 2 has a count of three, et cetera. My current solution As said, I believe this implimentation works accurately, but it just feels that there must be a better way to go about doing this. Anyway, here's what I've got so far: #my implementation uncommented to reduce post size, see history for comments def sortPairList( data , n ): count = [] for i in range(0,n): count.append( 0 ) #count up the data for p in data: count[p[0]] += 1 if p[1] != p[0]: count[p[1]] += 1 maxcount = 0 for i in range(0,n): if count[i] > maxcount: maxcount = count[i] def elementFrequency(p): if count[ p[0] ] < count[ p[1] ]: return count[ p[0] ] + float(count[ p[1] ]) / (maxcount+1) else: return count[ p[1] ] + float(count[ p[0] ]) / (maxcount+1) data.sort( key=elementFrequency ) Any suggestions on a more "Python" way of doing this? Or anything that's wrong with my current attempt? New Test Case (see answer's comments) input: [[0,0],[0,3],[0,5],[0,7],[1,1],[1,2],[1,8],[2,4],[2,5],[3,4],[3,5],[3,9],[4,4],[4,7],[4,8],[6,8],[7,7],[7,9],[8,9]] expected: [[6,8],[1,1],[1,2],[2,5],[0,5],[1,8],[3,5],[3,9],[7,9],[8,9],[2,4],[0,0],[0,3],[0,7],[7,7],[3,4],[4,7],[4,8],[4,4]]
[ "I would probably use a Counter (needs Python ≥2.7 or ≥3.1) for tallying.\nfrom collections import Counter\nfrom itertools import chain\ndef sortPairList2(data):\n tally = Counter(chain(*map(set, data)))\n data.sort(key=lambda x: sorted(tally[i] for i in x))\n\nNote that:\n\nYou can create an anonymous functi...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003280098_python_sorting.txt
Q: python dictionary, keeping a count of integers I am trying to count a list of say, integers. I have a list of numbers in a csv file I am able to read in, that looks something like 4,245,34,99,340,... What I am doing is trying to return is a dictionary with key:value pairs where the key is an integer value from the csv file, and the value is the number of times it appears in the list. I'm not sure what I am doing wrong here, any help would be appreciated allCounts = dict() rows = csv.reader(open('...csv'), delimiter=',') for intValue in rows: intVal = intValue[0] for intVal, numAppearances in allCounts: if intVal in allCounts: allCounts[numAppearances] = allCounts[numAppearances]+1 else: allCounts[numAppearances] = 1 A: Sounds like what you want is a Counter object: http://docs.python.org/library/collections.html#counter-objects Also I think you may want to use the CSV module: http://docs.python.org/library/csv.html Using the built-in modules should make it a lot easier :) To get the rows something like this should work: csvfile = open("example.csv") dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) Then you should be able to do this: c = Counter(reader) A: What you're doing is iterating through the entire dict for every cell, which is kind of weird and probably not what you want to do. What you really want to do is just look in the dict and increment the key in question. So: # first part stays mostly the same rows = csv.reader(open("...csv") ) allCounts = {} for row in rows: for field in row: allCounts[field] = allCounts.get(field, 0) + 1 That last line uses a nice little feature of dict, which returns a default value if the key isn't found. In your own code, there are some noteworth defects. The most significant one is the fourth and fifth lines. you extract the first field from the selected row and assign it to intVal but then you completely mask intVal by using it as the key when iterating over your dict. what that means is that assignment did no work at all. The if clause is doomed. You are checking to see if a key is in a dict, but you came up with that key by iterating over the keys from the same dict. Of course that key is in the dict. The next issue is that your else clause is modifying a collection over which you are iterating. Python makes no guarantees about how this will work for dicts, so don't do it For that matter, there's no reason at all to be iterating over the dict. You can just grab whichever key-value pair you are interested in directly. What you should be iterating over is the list of integers from the file. A CSV file is always structured as a list of values (normally separated by commas) that form rows, and the rows are separated by newlines. the CSV module preserves this view, by returning a list of lists. To drill down to the actual values, you need to iterate over each row, and then each field in that row. Your code iterates over each row, and then each key in the dict for each row, ignoring the fields. A: Get rid of intVal = intValue[0] Since intValue is a string, you'll be the first character in the string representation of th e number. What you really want is intValue = int(intValue). Then you've got your logic all wrong - currently allCounts is initialized to an empty dictionary which you cannot iterate over. What you want to do is iterate over the values returned by the csv.reader, which you already are. From there your logic is close -- unfortunately this is neither horseshoes nor hand grenades. What you want is this: # Checks to see if intValue is a key in the dictionary if intValue in allCounts: # If it is then we want to increment the current value # += 1 is the idiomatic way to do this allCounts[intValue] += 1 else: # If it is not a key, then make it a key with a value of 1 allCounts[intValue] = 1
python dictionary, keeping a count of integers
I am trying to count a list of say, integers. I have a list of numbers in a csv file I am able to read in, that looks something like 4,245,34,99,340,... What I am doing is trying to return is a dictionary with key:value pairs where the key is an integer value from the csv file, and the value is the number of times it appears in the list. I'm not sure what I am doing wrong here, any help would be appreciated allCounts = dict() rows = csv.reader(open('...csv'), delimiter=',') for intValue in rows: intVal = intValue[0] for intVal, numAppearances in allCounts: if intVal in allCounts: allCounts[numAppearances] = allCounts[numAppearances]+1 else: allCounts[numAppearances] = 1
[ "Sounds like what you want is a Counter object:\nhttp://docs.python.org/library/collections.html#counter-objects\nAlso I think you may want to use the CSV module:\nhttp://docs.python.org/library/csv.html\nUsing the built-in modules should make it a lot easier :)\nTo get the rows something like this should work: \n...
[ 8, 5, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003283990_dictionary_python.txt
Q: Python in Windows I am new to Python and need some help. i need to write a script that will look for file in c:\script\test\ directory with ext ".dat" and find "^" in there and replace with "|" i am not sure how to write this. There will only be one file for a day in the directory with the current date as the file name. Please help. I am not a good programmer obviously thanks A: Start here: http://diveintopython3.ep.io/table-of-contents.html You'll be interested in endswith, open, and replace. splitext could be good if you're extra-careful. A: Example: Check if file exists or not? import os.path # os.path - The key to File I/O os.path.exists("foo.txt") To learn more details : os.path Resources to learn more: Use this excellent resource if you want to learn the basics in organized way :Google's Python Class - should clear your doubts about how to do string operations. @Chris's answer has a very good link in it, so use that one to learn more. note: Anyone here can give you exact code but you won't learn that way. A: import glob for filename in glob.glob(r"C:\script\test\*.dat"): with open(filename, 'rb') as inputfile: data = inputfile.read() with open(filename, 'wb') as outputfile: outputfile.write(data.replace("^", "|")) should work in Python 2.6 and 2.7. Make sure you make a backup of your file first.
Python in Windows
I am new to Python and need some help. i need to write a script that will look for file in c:\script\test\ directory with ext ".dat" and find "^" in there and replace with "|" i am not sure how to write this. There will only be one file for a day in the directory with the current date as the file name. Please help. I am not a good programmer obviously thanks
[ "Start here: http://diveintopython3.ep.io/table-of-contents.html\nYou'll be interested in endswith, open, and replace. splitext could be good if you're extra-careful.\n", "Example: Check if file exists or not?\nimport os.path\n# os.path - The key to File I/O\nos.path.exists(\"foo.txt\")\n\nTo learn more details ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003283955_python.txt
Q: How do I get the concrete name (e.g. "".") of a class reference in Python? This is what I have so far: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. """ # TODO: How do I check that klass is actually a class? # even better would be determine if it's old style vs new style # at the same time and handle things differently below. # The str of a newstyle class is "<class 'django.forms.CharField'>" # so we search for the single quotes, and grab everything inside it, # giving us "django.forms.CharField" matches = re.search(r"'(.+)'", str(klass)) if matches: return matches.group(1) # Old style's classes' str is the concrete class name. return str(klass) So this works just fine, but it seems pretty hackish to have to do a regex search on the string of the class. Note that I cannot just do klass().__class__.__name__ (can't deal with args, etc.). Also, does anyone know how to accomplish the TODO (check if klass is a class and whether its oldstyle vs new style)? Any suggestions would be greatly appreciated. Based on the comments here's what I ended up with: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. Raises a `TypeError` if klass is not a class. """ if not isinstance(klass, (type, ClassType)): raise TypeError('The klass argument must be a class. Got type %s; %s' % (type(klass), klass)) return '%s.%s' % (klass.__module__, klass.__name__) A: How about just using klass.__name__, or to get the fully qualified name, klass.__module__+'.'+klass.__name__? A: You can just say klass.__module__ + "." + klass.__name__ As for how to determine whether something is an old class or new class, I recommend saying something like from types import ClassType # old style class type if not isinstance(klass, (type, ClassType)): # not a class elif isinstance(klass, type): # new-style class else: # old-style class A: >>> class X: ... pass ... >>> class Y( object ): ... pass ... The type function tells you if a name is a class and old-style vs. new style. >>> type(X) <type 'classobj'> >>> type(Y) <type 'type'> It also tells you what an object is. >>> x= X() >>> type(x) <type 'instance'> >>> y= Y() >>> type(y) <class '__main__.Y'> You can test old-stye vs. new style by simply asking what it's a subclass of. >>> issubclass(y.__class__,object) True >>> issubclass(x.__class__,object) False >>>
How do I get the concrete name (e.g. "".") of a class reference in Python?
This is what I have so far: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. """ # TODO: How do I check that klass is actually a class? # even better would be determine if it's old style vs new style # at the same time and handle things differently below. # The str of a newstyle class is "<class 'django.forms.CharField'>" # so we search for the single quotes, and grab everything inside it, # giving us "django.forms.CharField" matches = re.search(r"'(.+)'", str(klass)) if matches: return matches.group(1) # Old style's classes' str is the concrete class name. return str(klass) So this works just fine, but it seems pretty hackish to have to do a regex search on the string of the class. Note that I cannot just do klass().__class__.__name__ (can't deal with args, etc.). Also, does anyone know how to accomplish the TODO (check if klass is a class and whether its oldstyle vs new style)? Any suggestions would be greatly appreciated. Based on the comments here's what I ended up with: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. Raises a `TypeError` if klass is not a class. """ if not isinstance(klass, (type, ClassType)): raise TypeError('The klass argument must be a class. Got type %s; %s' % (type(klass), klass)) return '%s.%s' % (klass.__module__, klass.__name__)
[ "How about just using klass.__name__, or to get the fully qualified name, klass.__module__+'.'+klass.__name__?\n", "You can just say\nklass.__module__ + \".\" + klass.__name__\n\nAs for how to determine whether something is an old class or new class, I recommend saying something like\nfrom types import ClassType ...
[ 2, 2, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003284089_class_python.txt
Q: Checking duplicate while inserting in SQLite I am trying to insert a data into SQLite database using Python. INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK") WHERE "UK" NOT EXISTS IN (SELECT LABEL FROM DATA_TABLE); This query is dynamically generated from Python and I am checking whether the date is already exist in the table before inserting and its not working in SQLite database. Getting this near "WHERE": syntax error error. Am I doing something wrong ? Thanks for your help. A: I'm pretty sure that INSERT doesn't have a WHERE clause (the documentation doesn't mention any). What you can do: create a unique index on LABEL use INSERT OR FAIL if that triggers an error, the row already exists. A: It is giving you a syntax error because it is not allowed syntax. From your example I presume the schema is probably: create table data_table (uid integer primary key autoincrement. label string); in which case primary key implies unique. But, since you allow auto-generation of uid then you don't care what it's value is, you just don't want duplicate labels in which case you actually care that label be unique so tell it so: create table data_table (uid integer primary key autoincrement, label string unique on conflict fail); which then works as expected: sqlite> insert into data_table (label) values ("uk"); sqlite> insert into data_table (label) values ("uk"); Error: column label is not unique sqlite> select * from data_table; 1|uk Incidentally, if the names data_table, uid, and label aren't example names for the purposes of this question then you should use more meaningful names as these are horribly uninformative. A: INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK") WHERE NOT EXISTS(SELECT 1 FROM DATA_TABLE WHERE LABEL="UK"); you can use this instead of INSERT OR FAIL.
Checking duplicate while inserting in SQLite
I am trying to insert a data into SQLite database using Python. INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK") WHERE "UK" NOT EXISTS IN (SELECT LABEL FROM DATA_TABLE); This query is dynamically generated from Python and I am checking whether the date is already exist in the table before inserting and its not working in SQLite database. Getting this near "WHERE": syntax error error. Am I doing something wrong ? Thanks for your help.
[ "I'm pretty sure that INSERT doesn't have a WHERE clause (the documentation doesn't mention any). What you can do:\n\ncreate a unique index on LABEL \nuse INSERT OR FAIL\nif that triggers an error, the row already exists.\n\n", "It is giving you a syntax error because it is not allowed syntax. From your example I...
[ 2, 2, 1 ]
[]
[]
[ "pysqlite", "python", "sqlite", "windows" ]
stackoverflow_0003281800_pysqlite_python_sqlite_windows.txt
Q: Building a graph of the structure of an XML document I'd like to build a graph showing which tags are used as children of which other tags in a given XML document. I've written this function to get the unique set of child tags for a given tag in an lxml.etree tree: def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of tag. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t Is there a general-purpose graph builder that I could use with this function to build a dotfile or a graph in some other format? I'm also getting the sneaking suspicion that there is a tool somewhere explicitly designed for this purpose; what might that be? A: I ended up using python-graph. I also ended up using argparse to build a command line interface that pulls some basic bits of info from XML documents and builds graph images in formats supported by pydot. It's called xmlearn and is sort of useful: usage: xmlearn [-h] [-i INFILE] [-p PATH] {graph,dump,tags} ... optional arguments: -h, --help show this help message and exit -i INFILE, --infile INFILE The XML file to learn about. Defaults to stdin. -p PATH, --path PATH An XPath to be applied to various actions. Defaults to the root node. subcommands: {graph,dump,tags} dump Dump xml data according to a set of rules. tags Show information about tags. graph Build a graph from the XML tags relationships.
Building a graph of the structure of an XML document
I'd like to build a graph showing which tags are used as children of which other tags in a given XML document. I've written this function to get the unique set of child tags for a given tag in an lxml.etree tree: def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of tag. Iteration starts at `root`. """ found_child_tags = set() instances = root.iterdescendants(tag) from itertools import chain child_nodes = chain.from_iterable(i.getchildren() for i in instances) child_tags = (n.tag for n in child_nodes) for t in child_tags: if t not in found_child_tags: found_child_tags.add(t) yield t Is there a general-purpose graph builder that I could use with this function to build a dotfile or a graph in some other format? I'm also getting the sneaking suspicion that there is a tool somewhere explicitly designed for this purpose; what might that be?
[ "I ended up using python-graph. I also ended up using argparse to build a command line interface that pulls some basic bits of info from XML documents and builds graph images in formats supported by pydot. It's called xmlearn and is sort of useful:\nusage: xmlearn [-h] [-i INFILE] [-p PATH] {graph,dump,tags} ...\...
[ 3 ]
[]
[]
[ "dotfiles", "graph", "lxml", "python", "xml" ]
stackoverflow_0003273158_dotfiles_graph_lxml_python_xml.txt
Q: Print PDF document with python's win32print module? I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? If so, is there a module available to convert a PDF document into PCL? I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default printer. I need to print to a variety of printers on servers across various networks. Thanks for your help, Pete A: I ended up using Ghostscript to accomplish this task. There is a command line tool that relies on Ghostscript called gsprint. You don't even need Acrobat installed to print PDFs in this fashion which is quite nice. Here is an example: on the command line: gsprint -printer \\server\printer "test.pdf" from python: win32api.ShellExecute(0, 'open', 'gsprint.exe', '-printer "\\\\' + self.server + '\\' + self.printer_name + '" ' + file, '.', 0) Note that I've added to my PATH variable in these examples, so I don't have to include the entire path when calling the executable. There is one downside, however. The code is licensed under the GPL, so it's no very useful in commercial software. Hope this helps someone, Pete A: I was already using the win32api.ShellExecute approach and needed to print to a non-default printer. The best way I could work out was to temporarily change the default printer. So right before I do the print I store what the current default printer is, change it, and then set it back after printing. Something like: tempprinter = "\\\\server01\\printer01" currentprinter = win32print.GetDefaultPrinter() win32print.SetDefaultPrinter(tempprinter) win32api.ShellExecute(0, "print", filename, None, ".", 0) win32print.SetDefaultPrinter(currentprinter) I'm not going to claim it's pretty, but it worked and it allowed me to leave my other code untouched.
Print PDF document with python's win32print module?
I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? If so, is there a module available to convert a PDF document into PCL? I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default printer. I need to print to a variety of printers on servers across various networks. Thanks for your help, Pete
[ "I ended up using Ghostscript to accomplish this task. There is a command line tool that relies on Ghostscript called gsprint.\nYou don't even need Acrobat installed to print PDFs in this fashion which is quite nice. \nHere is an example:\non the command line:\ngsprint -printer \\\\server\\printer \"test.pdf\"\n\nf...
[ 10, 3 ]
[ "I am not sure how to specifically get win32print to work, but there might be a couple of other options. Reportlab is often mentioned when creating PDFs from Python. If you are already invested in your approach, maybe using PyX or pypsg to generate the Postscript files and then feeding that into win32print would ...
[ -1 ]
[ "pdf", "postscript", "python", "winapi", "windows" ]
stackoverflow_0001462842_pdf_postscript_python_winapi_windows.txt
Q: Regex match words and end of string 2 Regex question How can I match a word or 2 words in a subpattern ()? How can i match a word or 2 words that's either followed by a specific word like "with" OR the end of the string $ I tried (\w+\W*\w*\b)(\W*\bwith\b|$) but it's definitely not working edit: I'm thinking of matching both "go to mall" and "go to", in a way that i can group "go to" in python. A: Perhaps something like this? >>> import re >>> r = re.compile(r'(\w+(\W+\w+)?)(\W+with\b|\Z)') >>> r.search('bar baz baf bag').group(1) 'baf bag' >>> r.search('bar baz baf with bag').group(1) 'baz baf' >>> r.search('bar baz baf without bag').group(1) 'without bag' >>> r.search('bar with bag').group(1) 'bar' >>> r.search('bar with baz baf with bag').group(1) 'bar' A: Here's what I came up with: import re class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) match = re.compile( flags = re.VERBOSE, pattern = r""" ( (?!with) (?P<first> [a-zA-Z_]+ ) ) ( \s+ (?!with) (?P<second> [a-zA-Z_]+ ) )? ( \s+ (?P<awith> with ) )? (?![a-zA-Z_\s]+) | (?P<error> .* ) """ ).match s = 'john doe with' b = Bunch(**match(s).groupdict()) print 's:', s if b.error: print 'error:', b.error else: print 'first:', b.first print 'second:', b.second print 'with:', b.awith Output: s: john doe with first: john second: doe with: with Tried it also with: s: john first: john second: None with: None s: john doe first: john second: doe with: None s: john with first: john second: None with: with s: john doe width error: john doe width s: with error: with BTW: re.VERBOSE and re.DEBUG are your friends. Regards, Mick.
Regex match words and end of string
2 Regex question How can I match a word or 2 words in a subpattern ()? How can i match a word or 2 words that's either followed by a specific word like "with" OR the end of the string $ I tried (\w+\W*\w*\b)(\W*\bwith\b|$) but it's definitely not working edit: I'm thinking of matching both "go to mall" and "go to", in a way that i can group "go to" in python.
[ "Perhaps something like this?\n>>> import re\n>>> r = re.compile(r'(\\w+(\\W+\\w+)?)(\\W+with\\b|\\Z)')\n>>> r.search('bar baz baf bag').group(1)\n'baf bag'\n>>> r.search('bar baz baf with bag').group(1)\n'baz baf'\n>>> r.search('bar baz baf without bag').group(1)\n'without bag'\n>>> r.search('bar with bag').group(...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003284608_python_regex.txt
Q: Using select_related and extra clause I'm trying to achieve some extra select on a queryset and wants to add the needed table to the pool of tables in the query using the select_related method in order to benefit for the '__' syntax. Here is an example with simple models : from django.db import models # Create your models here. class testA(models.Model): code = models.TextField(unique = True) date = models.DateTimeField(auto_now_add = True) class testB(models.Model): text = models.TextField() a = models.ForeignKey(testA) And here is the query I want to build : SELECT (extract(hour from testa.date)) AS hour, testb.text FROM testb INNER JOIN testa ON (testb.a_id = testa.id) So here is how i build it in python : testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour','text') but django removes the select_related when he sees that I'm not using the "testa" table (because of the 'values' statement). So the resulting SQL query fails : SELECT (extract(hour from testa.date)) AS "hour", "testb"."text" FROM "testb" If I remove the "values" statement it works fine : SELECT (extract(hour from testa.date)) AS "hour", "testb"."id", "testb"."text", "testb"."a_id", "testa"."id", "testa"."code", "testa"."date" FROM "testb" INNER JOIN "testa" ON ("testb"."a_id" = "testa"."id") but I must put the values statement as I want to make aggregates as in "count the b objects grouped by the hour of the date in the a object" : testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour').annotate(count = Count('pk')) So what is the good way to achive this ? "Count objects grouped by something in another object" ? Or is there a way to "force" django to keep the "select_related" tables even if he thinks they are useless ? PS : I know I could use the "tables" argument of the extra statement but in that case I would have to rewrite the join by myself and I want to benefit from the django ORM A: I have developped a Django app to solve this kind of problems : django-cube. The base idea is to emulate a multi-dimensional DB, in order to easily calculate aggregations. The functionnality you require ('__hour' : a field-lookup for 'hour') is not implemented, but implementing it would take probably 15 minutes. So read what's next, how it works, etc ... and if it fits your need, write to me, and I'll implement it. The examples on the main page and the api doc are not up-to-date (they will be in a few days), but these snippets are. If you want to give it a try, here is how you would solve this problem with django-cube : #install the app first ... from cube.models import Dimension, Cube class MyCube(Cube): #declare a dimension called 'hour_a', #that is related to the field 'a__date__hour'. hour_a = Dimension(field='a__date__hour') #declare how to calculate the aggregation on a queryset @staticmethod def aggregation(queryset): return queryset.count() And then, there are various methods to calculate the results, check in the snippets... You can for example use : cube(testB.objects.all()).measure_dict('hour_a', full=False) Which would return something like : { 12: {measure: 889}, 13: {measure: 6654}, 14: {measure: 77}, #<hour>: <count> } Also, don't take the featured download, rather check-out from source (branch 0.3). I don't know what are your real needs, it might be a little heavy for the use you will have (it was initially made for data visualization purposes). A: I can't answer your main query, but it's worth noting that select_related has nothing to do with the __ syntax. select_related is simply an optimisation that will return extra related objects, adding joins to the query if necessary. But the double-underscore syntax for querying related tables works with or without select_related. A: I get the same error locally: everything works until "values" is appended and then django fails to place the appropriate FROM clause. I would post this example to the django-users group and see if someone in the know can verify if this is a bug or if there's a quick was to fix it.
Using select_related and extra clause
I'm trying to achieve some extra select on a queryset and wants to add the needed table to the pool of tables in the query using the select_related method in order to benefit for the '__' syntax. Here is an example with simple models : from django.db import models # Create your models here. class testA(models.Model): code = models.TextField(unique = True) date = models.DateTimeField(auto_now_add = True) class testB(models.Model): text = models.TextField() a = models.ForeignKey(testA) And here is the query I want to build : SELECT (extract(hour from testa.date)) AS hour, testb.text FROM testb INNER JOIN testa ON (testb.a_id = testa.id) So here is how i build it in python : testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour','text') but django removes the select_related when he sees that I'm not using the "testa" table (because of the 'values' statement). So the resulting SQL query fails : SELECT (extract(hour from testa.date)) AS "hour", "testb"."text" FROM "testb" If I remove the "values" statement it works fine : SELECT (extract(hour from testa.date)) AS "hour", "testb"."id", "testb"."text", "testb"."a_id", "testa"."id", "testa"."code", "testa"."date" FROM "testb" INNER JOIN "testa" ON ("testb"."a_id" = "testa"."id") but I must put the values statement as I want to make aggregates as in "count the b objects grouped by the hour of the date in the a object" : testB.objects.all().select_related('a').extra(select = {'hour' : 'extract(hour from testa.date)'}).values('hour').annotate(count = Count('pk')) So what is the good way to achive this ? "Count objects grouped by something in another object" ? Or is there a way to "force" django to keep the "select_related" tables even if he thinks they are useless ? PS : I know I could use the "tables" argument of the extra statement but in that case I would have to rewrite the join by myself and I want to benefit from the django ORM
[ "I have developped a Django app to solve this kind of problems : django-cube. The base idea is to emulate a multi-dimensional DB, in order to easily calculate aggregations.\nThe functionnality you require ('__hour' : a field-lookup for 'hour') is not implemented, but implementing it would take probably 15 minutes. ...
[ 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003280165_django_python.txt
Q: Remove items with checkboxes in Django forms I'm writing a form with Django. The form is a model form for a certain model, Experiment. Each Experiment has several TimeSlot models associated with it, defined with a ForeignKey('Experiment'). I'd like to have a form with the option to remove one or more TimeSlot instances from the EditExperimentForm by checking boxes. Currently, I define all of the Checkboxes in the model by a loop in the init function in EditExperimentForm: def __init__(self, *args, **kwargs): super(EditExperimentForm,self).__init__(*args,**kwargs) experiment = self.instance for timeslot in experiment.timeslot_set.all(): self.fields['timeslot-'+str(timeslot.id)] = BooleanField(label="Remove Timeslot at "+str(timeslot.start),required=False) And then I process them upon submission with a regular expression: timeslot_re = re.compile(r'^timeslot-([\d]+)$') for key in form.data.keys(): match = timeslot_re.match(key) if match: timeslot = TimeSlot.objects.get(id=match.expand(r'\1')) timeslot.delete() This is far from an elegant solution (for one thing, it makes anything but the most generic template a straight up nightmare to work with. Can anyone think of an easier way to do this? A: It may be a cleaner solution if you used a model formset for your TimeSlot objects. Have you looked at that at all? http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1 A: This code isn't tested, but something like this should do it: class MyForm(forms.Form): # You can change the queryset in the __init__ method, but this should be a nice basis timeslots = forms.ModelMultipleChoiceFieldqueryset=Timeslot.objects.all(), widget=forms.CheckboxSelectMultiple) def save(self): # make sure you do a form.is_valid() before trying to save() for timeslot in self.cleaned_data['timeslots']: timeslot.delete()
Remove items with checkboxes in Django forms
I'm writing a form with Django. The form is a model form for a certain model, Experiment. Each Experiment has several TimeSlot models associated with it, defined with a ForeignKey('Experiment'). I'd like to have a form with the option to remove one or more TimeSlot instances from the EditExperimentForm by checking boxes. Currently, I define all of the Checkboxes in the model by a loop in the init function in EditExperimentForm: def __init__(self, *args, **kwargs): super(EditExperimentForm,self).__init__(*args,**kwargs) experiment = self.instance for timeslot in experiment.timeslot_set.all(): self.fields['timeslot-'+str(timeslot.id)] = BooleanField(label="Remove Timeslot at "+str(timeslot.start),required=False) And then I process them upon submission with a regular expression: timeslot_re = re.compile(r'^timeslot-([\d]+)$') for key in form.data.keys(): match = timeslot_re.match(key) if match: timeslot = TimeSlot.objects.get(id=match.expand(r'\1')) timeslot.delete() This is far from an elegant solution (for one thing, it makes anything but the most generic template a straight up nightmare to work with. Can anyone think of an easier way to do this?
[ "It may be a cleaner solution if you used a model formset for your TimeSlot objects. Have you looked at that at all?\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1\n", "This code isn't tested, but something like this should do it:\nclass MyForm(forms.Form):\n # You can change the queryset ...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003285387_django_django_forms_python.txt
Q: CSV, DictWriter, unicode and utf-8 I am having problems with the DictWriter and non-ascii characters. A short version of my problem: #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import csv f = codecs.open("test.csv", 'w', 'utf-8') writer = csv.DictWriter(f, ['field1'], delimiter='\t') writer.writerow({'field1':u'å'.encode('utf-8')}) f.close() Gives this Traceback: Traceback (most recent call last): File "test.py", line 10, in <module>writer.writerow({'field1':u'å'.encode('utf-8')}) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/csv.py", line 124, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py", line 638, in write return self.writer.write(data) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) I am bit lost as the DictWriter ought to be able to work with UTF-8 from what I have read in the documentation. A: The object you obtain with codecs.open wants a unicode string in its write method -- that's the whole point. csv.DictWriter of course is calling that method with a utf8-encoded byte string instead, whence the exception. Change f's creation to f = open("test.csv", 'wb') (taking codecs out of the picture) and things should work just fine.
CSV, DictWriter, unicode and utf-8
I am having problems with the DictWriter and non-ascii characters. A short version of my problem: #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import csv f = codecs.open("test.csv", 'w', 'utf-8') writer = csv.DictWriter(f, ['field1'], delimiter='\t') writer.writerow({'field1':u'å'.encode('utf-8')}) f.close() Gives this Traceback: Traceback (most recent call last): File "test.py", line 10, in <module>writer.writerow({'field1':u'å'.encode('utf-8')}) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/csv.py", line 124, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py", line 638, in write return self.writer.write(data) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py", line 303, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) I am bit lost as the DictWriter ought to be able to work with UTF-8 from what I have read in the documentation.
[ "The object you obtain with codecs.open wants a unicode string in its write method -- that's the whole point. csv.DictWriter of course is calling that method with a utf8-encoded byte string instead, whence the exception.\nChange f's creation to f = open(\"test.csv\", 'wb') (taking codecs out of the picture) and th...
[ 9 ]
[]
[]
[ "csv", "python", "unicode", "utf_8" ]
stackoverflow_0003285578_csv_python_unicode_utf_8.txt
Q: Python 3 chokes on CP-1252/ANSI reading I'm working on a series of parsers where I get a bunch of tracebacks from my unit tests like: File "c:\Python31\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined> The files are opened with open() with no extra arguemnts. Can I pass extra arguments to open() or use something in the codec module to open these differently? This came up with code that was written in Python 2 and converted to 3 with the 2to3 tool. UPDATE: it turns out this is a result of feeding a zipfile into the parser. The unit test actually expects this to happen. The parser should recognize it as something that can't be parsed. So, I need to change my exception handling. In the process of doing that now. A: Position 0x81 is unassigned in Windows-1252 (aka cp1252). It is assigned to U+0081 HIGH OCTET PRESET (HOP) control character in Latin-1 (aka ISO 8859-1). I can reproduce your error in Python 3.1 like this: >>> b'\x81'.decode('cp1252') Traceback (most recent call last): ... UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 0: character maps to <undefined> or with an actual file: >>> open('test.txt', 'wb').write(b'\x81\n') 2 >>> open('test.txt').read() Traceback (most recent call last): ... UnicodeDecodeError: 'utf8' codec can't decode byte 0x81 in position 0: unexpected code byte Now to treat this file as Latin-1 you pass the encoding argument, like codeape suggested: >>> open('test.txt', encoding='latin-1').read() '\x81\n' Beware that there are differences between Windows-1257 and Latin-1 encodings, e.g. Latin-1 doesn't have “smart quotes”. If the file you're processing is a text file, ask yourself what that \x81 is doing in it. A: You can relax the error handling. For instance: f = open(filename, encoding="...", errors="replace") Or: f = open(filename, encoding="...", errors="ignore") See the docs. EDIT: But are you certain that the problem is in reading the file? Could it be that the exception happens when something is written to the console? Check http://wiki.python.org/moin/PrintFails A: All files are "not Unicode". Unicode is an internal representation which must be encoded. You need to determine for each file what encoding has been used, and specify that where necessary when the file is opened. As the traceback and error message indicate, the file in question is NOT encoded in cp1252. If it is encoded in latin1, the "\x81" that it is complaining about is a C1 control character that doesn't even have a name (in Unicode). Consider latin1 extremely unlikely to be valid. You say "some of the files are parsed with xml.dom.minidom" -- parsed successfully or unsuccessfully? A valid XML file should declare its encoding (default is UTF-8) in the first line, and you should not need to specify an encoding in your code. Show us the code that you are using to do the xml.dom.minidom parsing. "others read directly as iterables" -- sample code please. Suggestion: try opening some of each type of file in your browser. Then click View and click Character Encoding (Firefox) or Encoding (Internet Explorer). What encoding has the browser guessed [usually reliably]? Other possible encoding clues: What languages are used in the text in the files? Where did you get the files from? Note: please edit your question with clarifying information; don't answer in the comments.
Python 3 chokes on CP-1252/ANSI reading
I'm working on a series of parsers where I get a bunch of tracebacks from my unit tests like: File "c:\Python31\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined> The files are opened with open() with no extra arguemnts. Can I pass extra arguments to open() or use something in the codec module to open these differently? This came up with code that was written in Python 2 and converted to 3 with the 2to3 tool. UPDATE: it turns out this is a result of feeding a zipfile into the parser. The unit test actually expects this to happen. The parser should recognize it as something that can't be parsed. So, I need to change my exception handling. In the process of doing that now.
[ "Position 0x81 is unassigned in Windows-1252 (aka cp1252). It is assigned to U+0081 HIGH OCTET PRESET (HOP) control character in Latin-1 (aka ISO 8859-1). I can reproduce your error in Python 3.1 like this:\n>>> b'\\x81'.decode('cp1252')\nTraceback (most recent call last):\n ...\nUnicodeDecodeError: 'charmap' co...
[ 15, 4, 2 ]
[]
[]
[ "cp1252", "latin1", "python", "python_3.x", "unicode" ]
stackoverflow_0003284827_cp1252_latin1_python_python_3.x_unicode.txt
Q: Python: How to Capture WebPage as Image File? I want to cache a webpage as an image upon a user request, but I don't know where to start with this. I'm developing on App Engine with python. A: Here's a good library for capturing a webpage as a png image: http://github.com/AdamN/python-webkit2png A: One way is to use a web service such as thumbalizr since a lot of the programs for this type of thing aren't always install-able on appengine (because they use C++, etc). Other options include girafa and browsershots. A: There are websites that to this for you. Google is your friend. If you build a script around them, you have what you need. As a demonstration, see http://webshots.velocitysc.com/sandbox/. There are also downloadable programs that do it, such as the one at http://download.cnet.com/Advanced-Website-to-Image-JPG-BMP-Converter-Free/3000-2094_4-10900902.html. These are just examples; google a while and you'll find better implementations. If you want to do it yourself, you basically need to duplicate a web browser (the HTML rendering part, anyway), which is unrealistic, or use a preexisting rendering engine like webkit as Zach suggests. If I were you, I would forget about doing it myself and use a preexisting web service, unless this is going to be the core of your application.
Python: How to Capture WebPage as Image File?
I want to cache a webpage as an image upon a user request, but I don't know where to start with this. I'm developing on App Engine with python.
[ "Here's a good library for capturing a webpage as a png image:\nhttp://github.com/AdamN/python-webkit2png\n", "One way is to use a web service such as thumbalizr since a lot of the programs for this type of thing aren't always install-able on appengine (because they use C++, etc). Other options include girafa an...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "image_processing", "python" ]
stackoverflow_0003285724_google_app_engine_image_processing_python.txt
Q: How to make a fancy shortcut on the desktop to my python app? I've made this nice python app that runs when i use "python main.py" in terminal, but going thru the terminal each time is boring :-) how can i make a nice shortcut button with a img to have on my desktop? A: From here: http://www.themaemo.com/howto-launch-a-terminal-app-from-a-shortcut/ Basically, you need to create a .desktop file with the execution of the script in the EXEC line
How to make a fancy shortcut on the desktop to my python app?
I've made this nice python app that runs when i use "python main.py" in terminal, but going thru the terminal each time is boring :-) how can i make a nice shortcut button with a img to have on my desktop?
[ "From here:\nhttp://www.themaemo.com/howto-launch-a-terminal-app-from-a-shortcut/\nBasically, you need to create a .desktop file with the execution of the script in the EXEC line\n" ]
[ 2 ]
[]
[]
[ "maemo", "n900", "nokia", "python" ]
stackoverflow_0003149722_maemo_n900_nokia_python.txt
Q: Any way to run python TK scripts on web page? Is there any way to run a python script that utilizes TKinter on a web page such that a user could run the script and interact with the TK windows without having to download the script or have the appropriate python interpreter? A: No. There is no way to do this. A: The only approach I can think of, is to use some virtual screen protocol such as VNC, run your Tkinter script on a server for that protocol (e.g., a VNC server), and use a viewer browser plug-in for that protocol in the user's browser (e.g., maybe this one -- haven't tried it myself, though). A similar approach could use the NX protocol (e.g., cfr here). Note that such solutions will most likely not scale well: they're mostly meant to let one user connect to "their desktop" from a browser. Performance, robustness and scalability of web-native approaches will all run rapid circles around any such "compatibility hack"!
Any way to run python TK scripts on web page?
Is there any way to run a python script that utilizes TKinter on a web page such that a user could run the script and interact with the TK windows without having to download the script or have the appropriate python interpreter?
[ "No. There is no way to do this.\n", "The only approach I can think of, is to use some virtual screen protocol such as VNC, run your Tkinter script on a server for that protocol (e.g., a VNC server), and use a viewer browser plug-in for that protocol in the user's browser (e.g., maybe this one -- haven't tried it...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003284779_python_tkinter.txt
Q: wxPython threaded UDP server I am trying to put together a UDP server with a wxPython GUI. Here is a link to the code: UDP Server pastie.org I have linked it as its pretty lengthy. I have successfully got the UDP server running on the thread but I can not figure out how to close the socket when the stopping the thread. At the moment it will kick up a new thread each time you click start but I will be removing this. Is it possible to close the socket from running when the thread is stopped? If I am doing this the complete wrong way any advice is appreciated. Cheers Eef A: Use Python Twisted. It has wxPython integration with twisted.internet.wxreactor and makes networking easy and threadless. from twisted.internet import wxreactor from twisted.internet.protocol import DatagramProtocol wxreactor.install() class MyProtocol(DatagramProtocol): def datagramReceived(self, data, (host, port)): print "received %r from %s:%d" % (data, host, port) self.transport.write(data, (host, port)) # <GUI code> # to start listening do port = reactor.listenUDP(<port>, MyProtocol()) # to stop do self.transport.stopListening() in MyProtocol # or port.stopListening() from outside from twisted.internet import reactor reactor.registerWxApp(app) reactor.run()
wxPython threaded UDP server
I am trying to put together a UDP server with a wxPython GUI. Here is a link to the code: UDP Server pastie.org I have linked it as its pretty lengthy. I have successfully got the UDP server running on the thread but I can not figure out how to close the socket when the stopping the thread. At the moment it will kick up a new thread each time you click start but I will be removing this. Is it possible to close the socket from running when the thread is stopped? If I am doing this the complete wrong way any advice is appreciated. Cheers Eef
[ "Use Python Twisted. It has wxPython integration with twisted.internet.wxreactor and makes networking easy and threadless.\nfrom twisted.internet import wxreactor\nfrom twisted.internet.protocol import DatagramProtocol\n\nwxreactor.install()\n\nclass MyProtocol(DatagramProtocol):\n def datagramReceived(self, dat...
[ 2 ]
[]
[]
[ "multithreading", "python", "sockets", "udp", "wxpython" ]
stackoverflow_0003285907_multithreading_python_sockets_udp_wxpython.txt
Q: Embedding a 3-D editor (such as Blender) in a wxPython application Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.) My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other. Possible? How? A: Blender has python plugins, you can write a plugin to interract with your program. A: I second Luper Rouch's idea of Blender plugins. But if you must have your own window you need to fork Blender. Take a look at makehuman project. It used to have Blender as a platform. (I'm not sure but I think they have a different infrastructure now) A: For Blender specifically, I doubt it. Blender uses a custom UI based on OpenGL, and I'm not sure you can force it to use a pre-existing window. I suggest browsing the code of "Ghost", which is Blender's custom adaption layer (responsible for interacting with the OS for UI purposes). A: Perhaps this script might provide some context for your project. It integrates Blender, ActiveX, and wxPython. Caveat: Windows only. A: For Blender2.5 on linux you can use gtk.Socket, code example is here on pastebin
Embedding a 3-D editor (such as Blender) in a wxPython application
Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.) My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other. Possible? How?
[ "Blender has python plugins, you can write a plugin to interract with your program.\n", "I second Luper Rouch's idea of Blender plugins. But if you must have your own window you need to fork Blender. Take a look at makehuman project. It used to have Blender as a platform. (I'm not sure but I think they have a dif...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "3d", "blender", "embedding", "python", "wxpython" ]
stackoverflow_0000950145_3d_blender_embedding_python_wxpython.txt
Q: How to get an attribute just from the current class and not from possible parent classes? How to get an attribute just from the current class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is not defined in the current class (even if it is defined in some parent class). A: This is not a 100% proof answer (e.g. it will not work for classes that use __slots__), but it will work in most cases: >>> class A(object): ... x = 42 ... y = 43 ... >>> class B(A): ... x = 11 ... >>> b = B() You can check if the attribute is defined in the class directly like this: >>> 'x' in b.__class__.__dict__ True >>> 'y' in b.__class__.__dict__ False Now to answer your question: # comment explaining why this unusual check is necessary if 'attribute' in instance.__class__.__dict__: value = instance.attribute else: value = None A: You kind of painted yourself into a corner with your own rules. Sounds more like like a design shortcoming than a language or class issue with Python, as the beuty of python is to remove and hide the complexity of class inheritance. You will likely need to settle for an "alternative" solution like this: class Parent(object): property_on_parent = 'default value' @property def property_accessor(self): return self.property_on_parent class Child(Parent): property_on_child = None @property def property_accessor(self): return self.property_on_child c = Child() assert c.property_accessor == None However, i feel that you are better off rethinking the approach. A: Nothing prevents you from "resetting" that attrib in the init setting it to None after you init the super (in Python classes inherited and inheriting are super and sub btw, not parent and child). Unless that attrib is created elsewhere and its presence isn't guaranteed, only in that case walking up the inheritance tree, at which point you might have some serious design issues going on :) All that said, these are poor man solutions to the problem, and I agree you might have some design issues to address instead.
How to get an attribute just from the current class and not from possible parent classes?
How to get an attribute just from the current class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is not defined in the current class (even if it is defined in some parent class).
[ "This is not a 100% proof answer (e.g. it will not work for classes that use __slots__), but it will work in most cases:\n>>> class A(object):\n... x = 42\n... y = 43\n... \n>>> class B(A):\n... x = 11\n... \n>>> b = B()\n\nYou can check if the attribute is defined in the class directly like this:\n>>> 'x'...
[ 4, 0, 0 ]
[]
[]
[ "django", "object", "python" ]
stackoverflow_0003285237_django_object_python.txt
Q: Exception Value field is blank when throwing custom exceptions in django I have custom exceptions in my django project that look like this: class CustomFooError(Exception): def __init__(self, msg="Something went wrong with Foo."): self.msg = msg def __str__(self): return repr(self.msg) At various points in my code I will raise exceptions like this: raise CustomFooError("Things are going badly") When Django catches these errors, in debug mode I get django's standard pretty stack-trace page. But I never see my error messages -- "Things are going badly" never shows up in the debug error page. It seems they should show up as the Exception Value on the error page. I walked back through the django source far enough to find out that this is the value field from sys.exc_info() which is consistently tersely documented as "[the exception's] associated value or the second argument to raise, which is always a class instance if the exception type is a class object." Unfortunately, I don't know what to do with this information. So my question is: How should I be writing and raising my custom exceptions to get more useful data to show up in places like the django error screen? A: I would just use super and let the constructor of Exception handle assigning the msg attribute: class CustomFooError(Exception): def __init__(self, msg=None): if msg is None: msg = 'Something went wrong with Foo.' super(CustomFooError, self).__init__(msg) I just tested this from within a Django environment and it correctly displayed the message I passed to the exception constructor or the default one if None was passed. A: @AdmiralNemo is right: let the base class do the work. But to dig into your code a little deeper, the problem is that you don't tie into the Exception implementation at all. Exception(s) stores s in the .message attribute, not .msg. It also stores it as (s,) in the .args attribute. Your code doesn't set either of these attributes, which is probably why Django can't find a message to display. Also, your __str__ method is odd. It should return self.msg, not repr(self.msg), which would add quotes around the string, and potentially escapes inside the text.
Exception Value field is blank when throwing custom exceptions in django
I have custom exceptions in my django project that look like this: class CustomFooError(Exception): def __init__(self, msg="Something went wrong with Foo."): self.msg = msg def __str__(self): return repr(self.msg) At various points in my code I will raise exceptions like this: raise CustomFooError("Things are going badly") When Django catches these errors, in debug mode I get django's standard pretty stack-trace page. But I never see my error messages -- "Things are going badly" never shows up in the debug error page. It seems they should show up as the Exception Value on the error page. I walked back through the django source far enough to find out that this is the value field from sys.exc_info() which is consistently tersely documented as "[the exception's] associated value or the second argument to raise, which is always a class instance if the exception type is a class object." Unfortunately, I don't know what to do with this information. So my question is: How should I be writing and raising my custom exceptions to get more useful data to show up in places like the django error screen?
[ "I would just use super and let the constructor of Exception handle assigning the msg attribute:\nclass CustomFooError(Exception):\n\n def __init__(self, msg=None):\n if msg is None:\n msg = 'Something went wrong with Foo.'\n super(CustomFooError, self).__init__(msg)\n\nI just tested thi...
[ 3, 1 ]
[]
[]
[ "django", "exception_handling", "python" ]
stackoverflow_0003286204_django_exception_handling_python.txt
Q: How does one do the equivalent of "import * from module" with Python's __import__ function? Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to perform as expected (as it doesn't import anything). A: Please reconsider. The only thing worse than import * is magic import *. If you really want to: m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr) A: Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The __name__ global was being overwritten with the module name of the local settings file, which caused setup_environ(), used in manage.py, to have problems. try: import socket HOSTNAME = socket.gethostname().replace('.','_') # See http://docs.python.org/library/functions.html#__import__ m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*") try: attrlist = m.__all__ except AttributeError: attrlist = dir(m) for attr in [a for a in attrlist if '__' not in a]: globals()[attr] = getattr(m, attr) except ImportError, e: sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME) sys.exit(1) A: The underlying problem is that I am developing some Django, but on more than one host (with colleagues), all with different settings. I was hoping to do something like this in the project/settings.py file: from platform import node settings_files = { 'BMH.lan': 'settings_bmh.py", ... } __import__( settings_files[ node() ] ) It seemed a simple solution (thus elegant), but I would agree that it has a smell to it and the simplicity goes out the loop when you have to use logic like what John Millikin posted (thanks). Here's essentially the solution I went with: from platform import node from settings_global import * n = node() if n == 'BMH.lan': from settings_bmh import * # add your own, here... else: raise Exception("No host settings for '%s'. See settings.py." % node()) Which works fine for our purposes. A: It appears that you can also use dict.update() on module's dictionaries in your case: config = [__import__(name) for name in names_list] options = {} for conf in config: options.update(conf.__dict__) Update: I think there's a short "functional" version of it: options = reduce(dict.update, map(__import__, names_list))
How does one do the equivalent of "import * from module" with Python's __import__ function?
Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to perform as expected (as it doesn't import anything).
[ "Please reconsider. The only thing worse than import * is magic import *.\nIf you really want to:\nm = __import__ (S)\ntry:\n attrlist = m.__all__\nexcept AttributeError:\n attrlist = dir (m)\nfor attr in attrlist:\n globals()[attr] = getattr (m, attr)\n\n", "Here's my solution for dynamic naming of loca...
[ 36, 6, 0, 0 ]
[ "I didn't find a good way to do it so I took a simpler but ugly way from http://www.djangosnippets.org/snippets/600/\ntry:\n import socket\n hostname = socket.gethostname().replace('.','_')\n exec \"from host_settings.%s import *\" % hostname\nexcept ImportError, e:\n raise e\n\n" ]
[ -1 ]
[ "python", "python_import" ]
stackoverflow_0000147507_python_python_import.txt
Q: Import multiple files from a folder in Python I have a folder in my Application directory called Commands.folder. What I want to do is import all the modules in that folder, regardless of the name, into the python file that imports. How can I do this? A: from Commands import * You should create an empty file named "__init__.py" in the "Commands" folder, and your main app script should be in the "Application" folder you've mentioned. Note however, the "from module import *" is not recommended since it may cause namespace pollution. Read this. A: If you start your program in Application, you can import all modules in /Commands using: from Commands import *
Import multiple files from a folder in Python
I have a folder in my Application directory called Commands.folder. What I want to do is import all the modules in that folder, regardless of the name, into the python file that imports. How can I do this?
[ "from Commands import *\n\nYou should create an empty file named \"__init__.py\" in the \"Commands\" folder, and your main app script should be in the \"Application\" folder you've mentioned.\nNote however, the \"from module import *\" is not recommended since it may cause namespace pollution. \nRead this.\n", "I...
[ 4, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003286856_import_python.txt
Q: Validate Email Header in Python I have a RegEx for validating email addresses, but I'm really looking to validate a whole From header. Any of these would be valid: name@domain.com <name@domain.com> My Name <name@domain.com> Is there anything out there that would validate these as valid from headers? I'm going to look in the smtp library :) A: Be aware that there are plenty of other valid cases of e-mail addresses beyond what you've posted. See here for a recipe that may help. Also read this for a great discussion of parsing email addresses with a regex. There are any number of good regexes in there that will match the uses you're looking for, imho :-) A: I couldn't get the posted response to work, so I've been working on this and finally got this one, which seems to work so far. I'm sure it'll miss/catch something, but it's working for now. [a-zA-Z0-9+_\-\.\ ]*[ ]*<?[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+>?
Validate Email Header in Python
I have a RegEx for validating email addresses, but I'm really looking to validate a whole From header. Any of these would be valid: name@domain.com <name@domain.com> My Name <name@domain.com> Is there anything out there that would validate these as valid from headers? I'm going to look in the smtp library :)
[ "Be aware that there are plenty of other valid cases of e-mail addresses beyond what you've posted.\nSee here for a recipe that may help. Also read this for a great discussion of parsing email addresses with a regex. There are any number of good regexes in there that will match the uses you're looking for, imho :...
[ 1, 1 ]
[]
[]
[ "email", "python", "regex" ]
stackoverflow_0003268198_email_python_regex.txt
Q: Django-models. Complex request to database I need to make special request to database through django. For example: class Model(models.Model): name=models.CharField() date=models.DateTimeField() other=models.TextField() How do I ask for row which name containe word 'Hello' (it shoul ignor register of first letter) end it is must be in diapason of date, for example between 2005.08.09 and 2005.08.11? A: Try the following: start_date = datetime.date(2005, 8, 9) end_date = datetime.date(2005, 8, 11) Model.objects.filter(name__icontains="hello").filter(date__range(start_date,end_date)) You can stack as many filters as you like and it will be built into a single SQL Query (or whatever database system you use)
Django-models. Complex request to database
I need to make special request to database through django. For example: class Model(models.Model): name=models.CharField() date=models.DateTimeField() other=models.TextField() How do I ask for row which name containe word 'Hello' (it shoul ignor register of first letter) end it is must be in diapason of date, for example between 2005.08.09 and 2005.08.11?
[ "Try the following:\nstart_date = datetime.date(2005, 8, 9)\nend_date = datetime.date(2005, 8, 11)\nModel.objects.filter(name__icontains=\"hello\").filter(date__range(start_date,end_date))\n\nYou can stack as many filters as you like and it will be built into a single SQL Query (or whatever database system you use)...
[ 1 ]
[]
[]
[ "django_models", "filter", "python" ]
stackoverflow_0003286999_django_models_filter_python.txt
Q: Numpy records in the c api I'm playing with writing some C code to speed up an inner loop in my python code. This loop operates on a numpy record, e.g. soemthing like this: a = numpy.zeros((10,), dtype=[("myfvalue" ,"float"), ("myc", "int8"), ("anotheri", "uint64")]) which is then passed into c code like so: myCFunc(a, "blah") I was wondering if someone had an example of how to access particular columns of "a" in the C func. Clearly, this is going to involve a PyArray_Descr.fields somewhere, but an example would really help make things clearer for me. A: There are a number of examples on the Scipy Wiki: C Extensions to NumPy and Python
Numpy records in the c api
I'm playing with writing some C code to speed up an inner loop in my python code. This loop operates on a numpy record, e.g. soemthing like this: a = numpy.zeros((10,), dtype=[("myfvalue" ,"float"), ("myc", "int8"), ("anotheri", "uint64")]) which is then passed into c code like so: myCFunc(a, "blah") I was wondering if someone had an example of how to access particular columns of "a" in the C func. Clearly, this is going to involve a PyArray_Descr.fields somewhere, but an example would really help make things clearer for me.
[ "There are a number of examples on the Scipy Wiki:\n\nC Extensions to NumPy and Python\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003285572_numpy_python.txt
Q: Issue with PPT conversion using python-Django I was just trying to convert a PPT using the following URL http://code.google.com/p/qifei/wiki/PDFConverter python code I could see the same thing happening with the command line option too python documentconverter.py /home/rajeev/Desktop/Downloads/Industry2.ppt /home/rajeev/Desktop/test.pdf It appears that the image overlaps on some text in some cases.Are there any work arounds for this. A: Mangled images are probably a function of the pdf converter (in this case, Open Office). Try using a different library like pyPDF.
Issue with PPT conversion using python-Django
I was just trying to convert a PPT using the following URL http://code.google.com/p/qifei/wiki/PDFConverter python code I could see the same thing happening with the command line option too python documentconverter.py /home/rajeev/Desktop/Downloads/Industry2.ppt /home/rajeev/Desktop/test.pdf It appears that the image overlaps on some text in some cases.Are there any work arounds for this.
[ "Mangled images are probably a function of the pdf converter (in this case, Open Office). Try using a different library like pyPDF.\n" ]
[ 0 ]
[]
[]
[ "django", "django_views", "document_conversion", "python" ]
stackoverflow_0003287317_django_django_views_document_conversion_python.txt
Q: Reading from a plain text file Say I have the following in a text file: car apple bike book How can I read it and put them into a dictionary or a list? A: Reading them into a list is trivially done with readlines(): f = open('your-file.dat') yourList = f.readlines() If you need the newlines stripped out you can use ars' method, or do: yourList = [line.rstrip('\n') for line in f] If you want a dictionary with keys from 1 to the length of the list, the first way that comes to mind is to make the list as above and then do: yourDict = dict(zip(xrange(1, len(yourList)+1), yourList)) A: words = [] for word in open('words.txt'): words.append(word.rstrip('\n')) The words list will contain the words in your file. strip removes the newline characters. A: You can use the file with with like this. This is called a context manager and automatically closes the file at the end of the indented block with open('data.txt') as f: words = f.readlines() If you want to do it without a context manager, you should close the file yourself f = open('data.txt') words = f.readlines() f.close() Otherwise the file remains open at least as long as f is still in scope A: This is covered pretty thoroughly in the Python tutorial. lines = open('filename.txt', 'r').readlines()
Reading from a plain text file
Say I have the following in a text file: car apple bike book How can I read it and put them into a dictionary or a list?
[ "Reading them into a list is trivially done with readlines():\nf = open('your-file.dat')\nyourList = f.readlines()\n\nIf you need the newlines stripped out you can use ars' method, or do:\nyourList = [line.rstrip('\\n') for line in f]\n\nIf you want a dictionary with keys from 1 to the length of the list, the first...
[ 10, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003287179_python.txt
Q: SingPath Python Help - cosine problem Any help? I have the following: import math def cosine (a): x = (a * math.pi) / 180 return math.cos(x) The problem: Create a function that calculates the cosine of an angle (in degrees). The math module contains a function math.cos that uses radians to calculate the cosine. You will need to convert the angle to radians first, then use the cos function to calculate cosine. Remember, you have to multiply the degrees by pi/180 to convert to radians. Let me know! Am I using the cosine function wrong by using x as a parameter? A: Your code as listed seems to work fine to me. If you want, you can omit the intermediate variable by just combining: return math.cos((a * math.pi) / 180)
SingPath Python Help - cosine problem
Any help? I have the following: import math def cosine (a): x = (a * math.pi) / 180 return math.cos(x) The problem: Create a function that calculates the cosine of an angle (in degrees). The math module contains a function math.cos that uses radians to calculate the cosine. You will need to convert the angle to radians first, then use the cos function to calculate cosine. Remember, you have to multiply the degrees by pi/180 to convert to radians. Let me know! Am I using the cosine function wrong by using x as a parameter?
[ "Your code as listed seems to work fine to me. If you want, you can omit the intermediate variable by just combining:\nreturn math.cos((a * math.pi) / 180)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003287627_python.txt
Q: Django migrations--is it possible to use South in the middle of the project? I already started a project, and the models are all synced and everything. A: Yes. I think it is not too late. I've moved to south in a middle of a project and I am happy with that choice. I think it is a big help for deployment. The initialization of the south app can be done at any moment. A: It's even mentioned in docs: http://south.aeracode.org/wiki/QuickStartGuide#a1.SetupeveryapplicationtobetrackablebySouth A: It's quite straight forward to start using South. Just follow the installation instructions (don't forget to run syncdb at the end). Then you can convert the app to south: ./manage.py convert_to_south myapp Then you can make modifications to your model and do schemamigrations or even do datamigrations.
Django migrations--is it possible to use South in the middle of the project?
I already started a project, and the models are all synced and everything.
[ "Yes. I think it is not too late. I've moved to south in a middle of a project and I am happy with that choice. I think it is a big help for deployment.\nThe initialization of the south app can be done at any moment.\n", "It's even mentioned in docs:\nhttp://south.aeracode.org/wiki/QuickStartGuide#a1.Setupeveryap...
[ 4, 4, 2 ]
[]
[]
[ "database", "django", "django_south", "mysql", "python" ]
stackoverflow_0002445761_database_django_django_south_mysql_python.txt
Q: Data structure to store key-value pairs and retrive the key for the lowest value quickly I'm implementing something like a cache, which works like this: If a new value for the given key arrives from some external process, store that value, and remember the time when this value arrived. If we are idle, find the oldest entry in the cache, fetch the new value for the key from external source and update the cache. Return the value for the given key when asked. I need a data structure to store key-value pairs which would allow to perform the following operations as fast as possible (in the order of speed priority): Find the key with the lowest (unknown) value. Update a value for the given key or add a new key-value pair if the key does not exist. Other regular hash-table operations, like delete a key, check if a key exists, etc. Are there any data-structures which allow this? The problem here is that to perform the first query quickly I need something value-ordered and to update the values for the given key quickly I need something key-ordered. The best solution I have so far is something like this: Store values an a regular hashtable, and pairs of (value, key) as a value-ordered heap. Finding the key for the lowest value goes like this: Find the key for the lowest value on the heap. Find the value for that key from the hashtable. If the values don't match pop the value from the heap and repeat from step 1. Updating the values goes like this: Store the value in the hashtable. Push the new (value, key) pair to the heap. Deleting a key is more tricky and requires searching for the value in the heap. This gives something like O(log n) performance, but this solution seems to be cumbersome to me. Are there any data structures which combine the properties of a hashtable for keys and a heap for the associated values? I'm programming in Python, so if there are existing implementations in Python, it is a big plus. A: Most heap implementations will get you the lowest key in your collection in O(1) time, but there's no guarantees regarding the speed of random lookups or removal. I'd recommend pairing up two data structures: any simple heap implementation and any out-of-the-box hashtable. Of course, any balanced binary tree can be used as a heap, since the smallest and largest values are on the left-most and right-most leaves respectively. Red-black tree or AVL tree should give you O(lg n) heap and dictionary operations. A: I'd try: import heapq myheap = [] mydict = {} ... def push(key, val): heapq.heappush(myheap, (val, key)) mydict[key] = val def pop(): ... More info here A: You're looking for a Map, or an associative array. To get more specific, we'd need to know what language you're trying to use.
Data structure to store key-value pairs and retrive the key for the lowest value quickly
I'm implementing something like a cache, which works like this: If a new value for the given key arrives from some external process, store that value, and remember the time when this value arrived. If we are idle, find the oldest entry in the cache, fetch the new value for the key from external source and update the cache. Return the value for the given key when asked. I need a data structure to store key-value pairs which would allow to perform the following operations as fast as possible (in the order of speed priority): Find the key with the lowest (unknown) value. Update a value for the given key or add a new key-value pair if the key does not exist. Other regular hash-table operations, like delete a key, check if a key exists, etc. Are there any data-structures which allow this? The problem here is that to perform the first query quickly I need something value-ordered and to update the values for the given key quickly I need something key-ordered. The best solution I have so far is something like this: Store values an a regular hashtable, and pairs of (value, key) as a value-ordered heap. Finding the key for the lowest value goes like this: Find the key for the lowest value on the heap. Find the value for that key from the hashtable. If the values don't match pop the value from the heap and repeat from step 1. Updating the values goes like this: Store the value in the hashtable. Push the new (value, key) pair to the heap. Deleting a key is more tricky and requires searching for the value in the heap. This gives something like O(log n) performance, but this solution seems to be cumbersome to me. Are there any data structures which combine the properties of a hashtable for keys and a heap for the associated values? I'm programming in Python, so if there are existing implementations in Python, it is a big plus.
[ "Most heap implementations will get you the lowest key in your collection in O(1) time, but there's no guarantees regarding the speed of random lookups or removal. I'd recommend pairing up two data structures: any simple heap implementation and any out-of-the-box hashtable.\nOf course, any balanced binary tree can ...
[ 3, 1, 0 ]
[]
[]
[ "caching", "data_structures", "python" ]
stackoverflow_0003285168_caching_data_structures_python.txt
Q: How can I exclude a declared field in ModelForm in form's subclass? In Django, I am trying to derive (subclass) a new form from ModelForm form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.forms): class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): fields = ('first_name', 'last_name', 'email') But this does not work as it adds/keeps also an username field in the resulting form. This field was declared explicitly in UserChangeForm. Even adding username to exclude attribute does not help. Is there some proper way to exclude it and I am missing something? Is this a bug? Is there some workaround? A: Try this: class MyUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(MyUserChangeForm, self).__init__(*args, **kwargs) self.fields.pop('username') class Meta(UserChangeForm.Meta): fields = ('first_name', 'last_name', 'email') This dynamically removes a field from the form when it is created. A: It seems the (generic) workaround (still missing taking exclude into the account) is: def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) for field in list(self.fields): if field not in self._meta.fields: del self.fields[field] But this smells like a bug to me.
How can I exclude a declared field in ModelForm in form's subclass?
In Django, I am trying to derive (subclass) a new form from ModelForm form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.forms): class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): fields = ('first_name', 'last_name', 'email') But this does not work as it adds/keeps also an username field in the resulting form. This field was declared explicitly in UserChangeForm. Even adding username to exclude attribute does not help. Is there some proper way to exclude it and I am missing something? Is this a bug? Is there some workaround?
[ "Try this:\nclass MyUserChangeForm(UserChangeForm):\n\n def __init__(self, *args, **kwargs):\n super(MyUserChangeForm, self).__init__(*args, **kwargs)\n self.fields.pop('username')\n\n class Meta(UserChangeForm.Meta):\n fields = ('first_name', 'last_name', 'email')\n\nThis dynamically removes a field fro...
[ 3, 1 ]
[]
[]
[ "django", "django_forms", "modelform", "python" ]
stackoverflow_0003287974_django_django_forms_modelform_python.txt
Q: How to create an .app file in mac os x from binaries? I have a project in the form of binaries which can be distributed to other mac pcs. How to create an .app file for that project? Thanks in advance A: Take a look at py2app, it might solve your problem. py2app is a Python setuptools command which will allow you to make standalone application bundles and plugins from Python scripts. py2app is similar in purpose and design to py2exe for Windows.
How to create an .app file in mac os x from binaries?
I have a project in the form of binaries which can be distributed to other mac pcs. How to create an .app file for that project? Thanks in advance
[ "Take a look at py2app, it might solve your problem.\n\npy2app is a Python setuptools command which will allow you to make standalone application bundles and plugins from Python scripts. py2app is similar in purpose and design to py2exe for Windows.\n\n" ]
[ 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003287727_macos_python.txt
Q: Why does this keep going around in a never ending loop? def get_houseid_list(): """Returns a list of all house ids from db""" print 'Building list of all HouseIDs...' houseid_list = [] houseids = session.query(Episode.HouseID).all() for i in houseids: houseid_list.append(i[0]) return houseid_list def walkDir(top, ignore=[]): """Returns a complete list of files from a directory, recursing through subfolders""" print 'Building list of files...' fflist = [] for root, dirs, files in os.walk(top): dirs[:] = [ dn for dn in dirs if dn not in ignore ] file_list = [name for name in files if name[0] != '.'] if len(file_list): for f in file_list: try: houseid_parse(f) print 'adding...', f [fflist.append(join(root, f)) for f in file_list] except HouseIdException: print 'skipping...', f print 'Found', len(file_list), 'files in', root return fflist def get_nonmatches(houseid_list, finallist): print 'Comparing files to HouseIDs...' nonmatches = [] for id in houseid_list: print 'Searching for files to match', id for f in finallist: if re.search(id, f, re.IGNORECASE): nonmatches.append(f) return nonmatches def writeCSV(nonmatch): print 'Writing nonmatches to CSV...' csv.write('%s' % nonmatch) if __name__ == "__main__": houseid_list = get_houseid_list() print len(houseid_list), 'HouseIDs found' wdirs = ['/Volumes/Assets/Projects'] finallist = [] for d in wdirs: fflist = walkDir(d) for f in fflist: nonmatches = get_nonmatches(houseid_list,f) print 'nonmatches', nonmatches A: Just some comments on this code, while we wait for you to give us enough information to solve your problem.. It's pretty horrible depending on a side effect like this [fflist.append(join(root, f)) for f in file_list] when you can just say fflist.extend(join(root, f) for f in file_list) But that looks like a bug to me, do you mean to iterate over file_list again there? Perhaps you just need fflist.append(join(root, f)) This part seems to remove the condition from it's effect if len(file_list): for f in file_list: try: houseid_parse(f) print 'adding...', f [fflist.append(join(root, f)) for f in file_list] except HouseIdException: print 'skipping...', f print 'Found', len(file_list), 'files in', root Why not write it like this? for f in file_list: try: houseid_parse(f) print 'adding...', f fflist.append(join(root, f)) except HouseIdException: print 'skipping...', f if file_list: print 'Found', len(file_list), 'files in', root If you are just going to iterate over fflist, maybe you can turn walkDir into a generator def walkDir(top, ignore=[]): """Returns a generator for a complete list of files from a directory, recursing through subfolders""" for root, dirs, files in os.walk(top): dirs[:] = [ dn for dn in dirs if dn not in ignore ] file_list = [name for name in files if name[0] != '.'] for f in file_list: try: houseid_parse(f) print 'yielding...', f yield join(root, f) except HouseIdException: print 'skipping...', f if file_list: print 'Found', len(file_list), 'files in', root Now perhaps you tell us what the output of the program is and why you are sure it's an infinite loop and not just taking a long time to run. For all we can tell this line houseids = session.query(Episode.HouseID).all() could just be taking a very long time to execute
Why does this keep going around in a never ending loop?
def get_houseid_list(): """Returns a list of all house ids from db""" print 'Building list of all HouseIDs...' houseid_list = [] houseids = session.query(Episode.HouseID).all() for i in houseids: houseid_list.append(i[0]) return houseid_list def walkDir(top, ignore=[]): """Returns a complete list of files from a directory, recursing through subfolders""" print 'Building list of files...' fflist = [] for root, dirs, files in os.walk(top): dirs[:] = [ dn for dn in dirs if dn not in ignore ] file_list = [name for name in files if name[0] != '.'] if len(file_list): for f in file_list: try: houseid_parse(f) print 'adding...', f [fflist.append(join(root, f)) for f in file_list] except HouseIdException: print 'skipping...', f print 'Found', len(file_list), 'files in', root return fflist def get_nonmatches(houseid_list, finallist): print 'Comparing files to HouseIDs...' nonmatches = [] for id in houseid_list: print 'Searching for files to match', id for f in finallist: if re.search(id, f, re.IGNORECASE): nonmatches.append(f) return nonmatches def writeCSV(nonmatch): print 'Writing nonmatches to CSV...' csv.write('%s' % nonmatch) if __name__ == "__main__": houseid_list = get_houseid_list() print len(houseid_list), 'HouseIDs found' wdirs = ['/Volumes/Assets/Projects'] finallist = [] for d in wdirs: fflist = walkDir(d) for f in fflist: nonmatches = get_nonmatches(houseid_list,f) print 'nonmatches', nonmatches
[ "Just some comments on this code, while we wait for you to give us enough information to solve your problem..\nIt's pretty horrible depending on a side effect like this\n[fflist.append(join(root, f)) for f in file_list]\n\nwhen you can just say\nfflist.extend(join(root, f) for f in file_list)\n\nBut that looks like...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003287578_python.txt
Q: Python: How to Sort SQL statements in a text file? The output below is from Oracle; where it generates "create table" statements using a supplied package. I feed them into the python diff tool HtmlDiff which uses difflib under the covers. Each table is followed by a number of "alter table add constraint" commands that add the various constraints. The problem is that there is no explicit ordering of the "alter table" commands, and I have to re-order them after generating the output file, before I run the comparison. I need help doing this; ideally using python, sed or awk. The rules would be After each line containing "CREATE TABLE" until the next line containing "CREATE TABLE" sort each line containing " ADD CONSTRAINT " This is a sample of my output: CREATE TABLE T1 ( BOOK_ID NUMBER NOT NULL ENABLE, LOCATION_ID NUMBER NOT NULL ENABLE, NAME VARCHAR2(255) NOT NULL ENABLE, LEGAL_ENTITY VARCHAR2(255) NOT NULL ENABLE, STATUS CHAR(1) NOT NULL ENABLE ) ; ALTER TABLE T1 ADD CONSTRAINT T1_CHK_1 CHECK ( status IN ( 'A', 'I' , 'T' ) ) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY (BOOK_ID) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_AK_1 UNIQUE (NAME) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_FK_1 FOREIGN KEY (LOCATION_ID) REFERENCES T6 (LOCATION_ID) ENABLE; CREATE TABLE T2 ( BUCKET_ID NUMBER NOT NULL ENABLE, DATA_LOAD_SESSION_ID NUMBER, IS_LOCKED CHAR(1) NOT NULL ENABLE, LOCK_DATE_TIME DATE ) ; ALTER TABLE T2 ADD CONSTRAINT CKC_IS_LOCKED_BUCKET CHECK (IS_LOCKED in ('T','F')) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_PK PRIMARY KEY (BUCKET_ID) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_FK_2 FOREIGN KEY (RRDB_STAGING_TABLE_ID) REFERENCES T4 (RRDB_STAGING_TABLE_ID) ENABLE; CREATE TABLE T3 ( VALUE_DATE DATE, NODE_ID NUMBER, RESULT_UID VARCHAR2(255), LATEST_EOD_SING_VAL_RESULT_ID NUMBER NOT NULL ENABLE ) ALTER TABLE T3 ADD CONSTRAINT T3_PK PRIMARY KEY (VALUE_DATE, NODE_ID, RESULT_UID) ENABLE; Desired output: the only difference is the ordering of the " ADD CONSTRAINT " lines CREATE TABLE T1 ( BOOK_ID NUMBER NOT NULL ENABLE, LOCATION_ID NUMBER NOT NULL ENABLE, NAME VARCHAR2(255) NOT NULL ENABLE, LEGAL_ENTITY VARCHAR2(255) NOT NULL ENABLE, STATUS CHAR(1) NOT NULL ENABLE ) ; ALTER TABLE T1 ADD CONSTRAINT T1_AK_1 UNIQUE (NAME) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_CHK_1 CHECK ( status IN ( 'A', 'I' , 'T' ) ) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_FK_1 FOREIGN KEY (LOCATION_ID) REFERENCES T6 (LOCATION_ID) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY (BOOK_ID) ENABLE; CREATE TABLE T2 ( BUCKET_ID NUMBER NOT NULL ENABLE, DATA_LOAD_SESSION_ID NUMBER, IS_LOCKED CHAR(1) NOT NULL ENABLE, LOCK_DATE_TIME DATE ) ; ALTER TABLE T2 ADD CONSTRAINT CKC_IS_LOCKED_BUCKET CHECK (IS_LOCKED in ('T','F')) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_FK_2 FOREIGN KEY (RRDB_STAGING_TABLE_ID) REFERENCES T4 (RRDB_STAGING_TABLE_ID) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_PK PRIMARY KEY (BUCKET_ID) ENABLE; CREATE TABLE T3 ( VALUE_DATE DATE, NODE_ID NUMBER, RESULT_UID VARCHAR2(255), LATEST_EOD_SING_VAL_RESULT_ID NUMBER NOT NULL ENABLE ) ALTER TABLE T3 ADD CONSTRAINT T3_PK PRIMARY KEY (VALUE_DATE, NODE_ID, RESULT_UID) ENABLE; A: Load it all in to a string, then split on ";" to build an array of SQL commands. Loop the array and build a new sorted array. Pass along the CREATE TABLE bits and slice out the ALTER TABLE statements in to a separate list. sort() the alter list and extend it to the result array. When you're done, ';\n'.join(result_array) + ';'. A: Quick-and-dirty, but i think this will do it for your case (worked on the example for sure): conList = [] for ln in f: if ' ADD CONSTRAINT ' in ln: conList.append(ln) else: for it in sorted(conList): print it conList = [] print ln # finish any unfinished business for it in sorted(conList): print it
Python: How to Sort SQL statements in a text file?
The output below is from Oracle; where it generates "create table" statements using a supplied package. I feed them into the python diff tool HtmlDiff which uses difflib under the covers. Each table is followed by a number of "alter table add constraint" commands that add the various constraints. The problem is that there is no explicit ordering of the "alter table" commands, and I have to re-order them after generating the output file, before I run the comparison. I need help doing this; ideally using python, sed or awk. The rules would be After each line containing "CREATE TABLE" until the next line containing "CREATE TABLE" sort each line containing " ADD CONSTRAINT " This is a sample of my output: CREATE TABLE T1 ( BOOK_ID NUMBER NOT NULL ENABLE, LOCATION_ID NUMBER NOT NULL ENABLE, NAME VARCHAR2(255) NOT NULL ENABLE, LEGAL_ENTITY VARCHAR2(255) NOT NULL ENABLE, STATUS CHAR(1) NOT NULL ENABLE ) ; ALTER TABLE T1 ADD CONSTRAINT T1_CHK_1 CHECK ( status IN ( 'A', 'I' , 'T' ) ) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY (BOOK_ID) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_AK_1 UNIQUE (NAME) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_FK_1 FOREIGN KEY (LOCATION_ID) REFERENCES T6 (LOCATION_ID) ENABLE; CREATE TABLE T2 ( BUCKET_ID NUMBER NOT NULL ENABLE, DATA_LOAD_SESSION_ID NUMBER, IS_LOCKED CHAR(1) NOT NULL ENABLE, LOCK_DATE_TIME DATE ) ; ALTER TABLE T2 ADD CONSTRAINT CKC_IS_LOCKED_BUCKET CHECK (IS_LOCKED in ('T','F')) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_PK PRIMARY KEY (BUCKET_ID) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_FK_2 FOREIGN KEY (RRDB_STAGING_TABLE_ID) REFERENCES T4 (RRDB_STAGING_TABLE_ID) ENABLE; CREATE TABLE T3 ( VALUE_DATE DATE, NODE_ID NUMBER, RESULT_UID VARCHAR2(255), LATEST_EOD_SING_VAL_RESULT_ID NUMBER NOT NULL ENABLE ) ALTER TABLE T3 ADD CONSTRAINT T3_PK PRIMARY KEY (VALUE_DATE, NODE_ID, RESULT_UID) ENABLE; Desired output: the only difference is the ordering of the " ADD CONSTRAINT " lines CREATE TABLE T1 ( BOOK_ID NUMBER NOT NULL ENABLE, LOCATION_ID NUMBER NOT NULL ENABLE, NAME VARCHAR2(255) NOT NULL ENABLE, LEGAL_ENTITY VARCHAR2(255) NOT NULL ENABLE, STATUS CHAR(1) NOT NULL ENABLE ) ; ALTER TABLE T1 ADD CONSTRAINT T1_AK_1 UNIQUE (NAME) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_CHK_1 CHECK ( status IN ( 'A', 'I' , 'T' ) ) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_FK_1 FOREIGN KEY (LOCATION_ID) REFERENCES T6 (LOCATION_ID) ENABLE; ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY (BOOK_ID) ENABLE; CREATE TABLE T2 ( BUCKET_ID NUMBER NOT NULL ENABLE, DATA_LOAD_SESSION_ID NUMBER, IS_LOCKED CHAR(1) NOT NULL ENABLE, LOCK_DATE_TIME DATE ) ; ALTER TABLE T2 ADD CONSTRAINT CKC_IS_LOCKED_BUCKET CHECK (IS_LOCKED in ('T','F')) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_FK_2 FOREIGN KEY (RRDB_STAGING_TABLE_ID) REFERENCES T4 (RRDB_STAGING_TABLE_ID) ENABLE; ALTER TABLE T2 ADD CONSTRAINT T2_PK PRIMARY KEY (BUCKET_ID) ENABLE; CREATE TABLE T3 ( VALUE_DATE DATE, NODE_ID NUMBER, RESULT_UID VARCHAR2(255), LATEST_EOD_SING_VAL_RESULT_ID NUMBER NOT NULL ENABLE ) ALTER TABLE T3 ADD CONSTRAINT T3_PK PRIMARY KEY (VALUE_DATE, NODE_ID, RESULT_UID) ENABLE;
[ "Load it all in to a string, then split on \";\" to build an array of SQL commands. Loop the array and build a new sorted array. Pass along the CREATE TABLE bits and slice out the ALTER TABLE statements in to a separate list. sort() the alter list and extend it to the result array. When you're done, ';\\n'.join(res...
[ 0, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003286607_python_sql.txt
Q: Google AppEngine Indexing Delay Am trying to deploy a app to Google AppEngine. But the DataStore index building seems to take forever. The contents of my index.yaml indexes: # AUTOGENERATED # This index.yaml is automatically updated whenever the dev_appserver # detects that a new type of query is run. If you want to manage the # index.yaml file manually, remove the above marker line (the line # saying "# AUTOGENERATED"). If you want to manage some indexes # manually, move them above the marker line. The index.yaml file is # automatically uploaded to the admin console when you next deploy # your application using appcfg.py. - kind: comments properties: - name: content_type_id - name: is_public - name: is_removed - name: object_pk - name: site_id - name: created - kind: comments properties: - name: content_type_id - name: object_pk - name: user_email - name: user_name - name: user_url - name: created - kind: content_type properties: - name: app_label - name: name - kind: pages properties: - name: post_status - name: created - kind: pages properties: - name: post_status - name: post_title - kind: posts properties: - name: post_status - name: created - kind: posts properties: - name: post_status - name: created direction: desc Any idea on how to speed up the process? A: The only thing you can do to speed up indexing is to create indexes when you have less data - though this will impose additional overhead on inserts. Other than that, you have to leave it up to the automated system to build the indexes as fast as it can.
Google AppEngine Indexing Delay
Am trying to deploy a app to Google AppEngine. But the DataStore index building seems to take forever. The contents of my index.yaml indexes: # AUTOGENERATED # This index.yaml is automatically updated whenever the dev_appserver # detects that a new type of query is run. If you want to manage the # index.yaml file manually, remove the above marker line (the line # saying "# AUTOGENERATED"). If you want to manage some indexes # manually, move them above the marker line. The index.yaml file is # automatically uploaded to the admin console when you next deploy # your application using appcfg.py. - kind: comments properties: - name: content_type_id - name: is_public - name: is_removed - name: object_pk - name: site_id - name: created - kind: comments properties: - name: content_type_id - name: object_pk - name: user_email - name: user_name - name: user_url - name: created - kind: content_type properties: - name: app_label - name: name - kind: pages properties: - name: post_status - name: created - kind: pages properties: - name: post_status - name: post_title - kind: posts properties: - name: post_status - name: created - kind: posts properties: - name: post_status - name: created direction: desc Any idea on how to speed up the process?
[ "The only thing you can do to speed up indexing is to create indexes when you have less data - though this will impose additional overhead on inserts. Other than that, you have to leave it up to the automated system to build the indexes as fast as it can.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003286995_google_app_engine_python.txt
Q: How do I launch a function and wait/don't wait on it depending on whether it's a GUI application? I'm looking for a Python function which behaves just like the Windows command interpreter cmd.exe when it comes to waiting for newly launched processes to finish. Right now I'm using os.system() but this function always blocks, even when launching GUI applications (which, in case they were written in C/C++, have a WinMain function and were linked with /SUBSYSTEM:WINDOWS). What code should I be using for launching external processes in case I do want the function to block when launching console applications, but I do not want it to block when launching GUI applications? A: You could write a small C wrapper/extension that checks for the subsystem (using ImageNtHeader). If all else fails, you can parse the PE headers directly. A: Python has no standard way to examine the executables you can start with the process API. How about you start the external command using cmd.exe? Or create a BAT script in %TEMP% and run that.
How do I launch a function and wait/don't wait on it depending on whether it's a GUI application?
I'm looking for a Python function which behaves just like the Windows command interpreter cmd.exe when it comes to waiting for newly launched processes to finish. Right now I'm using os.system() but this function always blocks, even when launching GUI applications (which, in case they were written in C/C++, have a WinMain function and were linked with /SUBSYSTEM:WINDOWS). What code should I be using for launching external processes in case I do want the function to block when launching console applications, but I do not want it to block when launching GUI applications?
[ "You could write a small C wrapper/extension that checks for the subsystem (using ImageNtHeader). If all else fails, you can parse the PE headers directly.\n", "Python has no standard way to examine the executables you can start with the process API.\nHow about you start the external command using cmd.exe? Or cre...
[ 2, 0 ]
[]
[]
[ "process", "python", "windows" ]
stackoverflow_0003288289_process_python_windows.txt
Q: python handle endless XML I am working on a application, and my job just is to develop a sample Python interface for the application. The application can provide XML-based document, I can get the document via HTTP Get method, but the problem is the XML-based document is endless which means there will be no end element. I know that the document should be handled by SAX, but how to deal with the endless problem? Any idea, sample code? A: This is what I use for parsing an endless xml stream which I get from a remote computer (in my case I connect over a socket and use socket.makefile('r') to create the file object) 19.12.2. IncrementalParser Objects parser = xml.sax.make_parser(['xml.sax.IncrementalParser']) handler = FooHandler() parser.setContentHandler(handler) data = sockfile.readline() while ( len(data) != 0 ): parser.feed(data) data = sockfilefile.readline() A: Take a look at the xmlstream module in jabberpy (also available from twisted): xmlstream.py provides simple functionality for implementing XML stream based network protocols. It is used as a base for jabber.py. xmlstream.py manages the network connectivity and xml parsing of the stream. When a complete 'protocol element' ( meaning a complete child of the xmlstreams root ) is parsed the dipatch method is called with a 'Node' instance of this structure. The Node class is a very simple XML DOM like class for manipulating XML documents or 'protocol elements' in this case. A: If the document never gets an close-tag for an element in the document, then it isn't correctly formed XML, which is going to play havoc with any XML parser. That said, using the Python SAX2 API would seem to be the best approach, but you're going to have to determine what exception will be thrown by the missing close-tag, catch it, and handle it yourself. Added Assume that you're receiving an XML document like this: <? xml version="1.0" ?> <foo> <bar>...</bar> <bar>...</bar> <bar>...</bar> <bar>...</bar> ... And you never receive a closing </foo>. In this case, a SAX parser that is reacting to the bar elements will issue a stream of events for startElement(bar) and endElement(bar). Presumably you'll gather up all of the data between the start and the end, and then process it all at one shot once you see the end event. The only way to stop this loop is going to be through outside action: define in advance the number of bar elements to process, or define in advance the amount of time you want to devote to receiving bar events. Run the SAX parser in a thread and then kill the thread when you hit your limit. You'll want to have your main process sleep while waiting on the sax-parser thread to finish. A: I assume your XML is basically a list of identical XML elements gathered under one container element. Something like <items> <item> <!-- content here --> </item> <item> <!-- content here --> </item> <item> <!-- content here --> </item> </items> In SAX when your parser gets and end event, you can parse the completed item, clear the stack, and pass the item on to whatever other code should be handling parsed items. def process(item) : # App logic goes here class ItemsHandler(xml.sax.handler.ContentHandler) : # Omitting __init__, startElement, and characters methods # to store data on a stack during processing def endElement(self, name) : if name == "item" : # create item from stored data on stack parsed_item = self.parse_item_from_stack() process(parsed_item) If the application logic is complicated enough, you'll want to put the SAX parsing in a separate thread so you don't miss events. A: If the document is endless why not add end tag (of main element) manually before opening it in parser? I don't know Python but why not add </endtag> to string? A: I can not provide a solution in Python right away, but will give you a hint. That kind of XML parsing is handled by StAX parsers. The problem here is that a SAX-parser pushes events, but StAX provives interface for pulling events. StAX is mainly used for partial XML parsing (parsing only headers from a SOAP message), and this seems to be your case. I have not seen a StAX-like parsers in Python standard library, but there should definetely be one. UPD: lxml (as a wrapper tp libxml2) seems to have similar functinality. A: You can use the iterparse function from the xml.etree.ElementTree (or cElementTree for speed) in the stdlib. (you could also use lxml) The trick is described here: http://effbot.org/zone/element-iterparse.htm#incremental-parsing The example describes exactly what you need. It doesn't mention anything about endless files, but it will work. (it will just keep on going). Most importantly: don't forget to clear the root element. Easy and available in the stdlib ;-)
python handle endless XML
I am working on a application, and my job just is to develop a sample Python interface for the application. The application can provide XML-based document, I can get the document via HTTP Get method, but the problem is the XML-based document is endless which means there will be no end element. I know that the document should be handled by SAX, but how to deal with the endless problem? Any idea, sample code?
[ "This is what I use for parsing an endless xml stream which I get from a remote computer (in my case I connect over a socket and use socket.makefile('r') to create the file object)\n19.12.2. IncrementalParser Objects\nparser = xml.sax.make_parser(['xml.sax.IncrementalParser'])\nhandler = FooHandler()\nparser.setCon...
[ 7, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003284289_python_xml.txt
Q: Question about nested loops I am new to programming and having some problem figuring out nested loops. I have a list of data that I want to extract from a larger file. I am able to extract one item of data from the larger file successfully but I need to extract 100 different trials from this larger file of thousands of trials. Each trial is one line of data of the larger file. This is the program I have used to extract one line of data successfully one at a time. In this example it extracts the data for trial 1. It is based off of examples I have seen in prior questions and tutorials. The problem is that I don't need trials 1-100, or any ordered pattern. I need trials 134, 274, 388, etc. It skips around. So I don't know how to do a nested loop using the for statement if it doesn't have a range that I can enter. Any help is appreciated. Thanks. completedataset = open('completedataset.txt', 'r') smallerdataset = open('smallerdataset.txt', 'w') for line in completedataset: if 'trial1' in line: smallerdataset(line) completedataset.close() smallerdataset.close() I'd really like to do it like this: trials = ('trial12', 'trial23', 'trial34') for line in completedataset: for trial in trials: if trial in line: smallerdataset(line) but this isn't working. Can anyone help me modify this program so that it works correctly? A: It seems to me that you need a list that holds all the trial numbers that you are interested in. So maybe you could try something like this: completedataset = open('completedataset.txt', 'r') smallerdataset = open('smallerdataset.txt', 'w') trials = [134, 274, 388] completedata = completedataset.readlines() for t in trials: for line in completedata: if "trial"+str(t) in line: smallerdataset.write(line) completedataset.close() smallerdataset.close() A: You could just do this: trials = ['trial1', 'trial134', 'trial274'] for line in completedataset: for trial in trials: if trial in line: smallerdataset(line) For more efficient operation you could match each line with 'trial[0-9]+' -regex and look up whether the symbol can be found from a set. A: If each trial in the complete set is a known byte size, you can use file.seek(n), where n is the byte to start reading at. For example, if each line in the file is 3 bytes long, you could do something such as: myfile = open('file.txt', 'r') myfile.seek(lineToStartAt * 3) myfile.readline()#etc If the number of bytes per line is variable or unknown, you would simply have to read in lines and discard the lines you don't care for (as in KLee1's answer) A: Assuming you know the trials ahead of time, you can do trials = ('trial12', 'trial23', 'trial34') for line in completedataset: for trial in trials: if trial in line: smallerdataset(line) A: You are going to run into some problems with the way you are specifying your trials. If you look for lines containing 'trial1', you will also get lines containing 'trial123'. If you larger dataset is structured in some way you can trying looking for the trial number in a particular field. For instance, if the data is comma delimited you can make use of the csv package. Finally, using a generator expression instead of the loop will make things a little cleaner. Assuming that the trial number was in the first column of your dataset you could do something like: import csv trials = ['trial134', 'trial1', 'trial56'] data = csv.reader(open('completedataset.txt')) with open('smalldataset.txt','w') as outf: csv.writer(outf).writerows(l for l in data if l[0] in trials) A: Assuming you had a function that, looking at a line, is able to tell you whether that line is "desired", the proper structure for your code would be very simple: with open('completedataset.txt', 'r') as completedataset: with open('smallerdataset.txt', 'w') as smallerdataset: for line in completedataset: if iwantthisone(line): smallerdataset.write(line) The with statements take care of the closing for you. In Python 2.7, you could merge the two withs into one; in Python 2.5, you need to start your module with a from __future__ import with_statement; in Python 2.6, currently the most widespread version, the above code is the right form. So, absolutely everything boils down to that iwantthisone function. You don't tell us anything about the format of your lines, making it impossible for us to help you much further. But assume for example that the first word in each line identifies the test, e.g. test432 ..., and you have the numbers of the tests you want in a set named want_these, e.g set([113, 432, 251, ...]). Then, a very simple way to write iwantthisone might be: def iwantthisone(line): firstword = line.split(None, 1)[0] testnumber = int(firstword[4:]) return testnumber in want_these The proper contents of iwantthisone entirely depend on your lines' format and how do you tell what lines you actually do want to keep, of course. But I hope this general structure still helps. Note that there are really no nested loops in this general structure I recommend!-) A: About the error message you show in in your comments: the line continuation character is a backslash, so it's telling you that you have an errant backslash character somewhere in that line. A: Assuming the lines always start with the trial identifier you can use the startswith function and filter to pull out the ones you want. completedataset = open('completedataset.txt', 'r') smallerdataset = open('smallerdataset.txt', 'w') wantedtrials = ('trial134', 'trial274', 'trial388') for line in completedataset: if filter(line.startswith, wantedtrials): smallerdataset.write(line)
Question about nested loops
I am new to programming and having some problem figuring out nested loops. I have a list of data that I want to extract from a larger file. I am able to extract one item of data from the larger file successfully but I need to extract 100 different trials from this larger file of thousands of trials. Each trial is one line of data of the larger file. This is the program I have used to extract one line of data successfully one at a time. In this example it extracts the data for trial 1. It is based off of examples I have seen in prior questions and tutorials. The problem is that I don't need trials 1-100, or any ordered pattern. I need trials 134, 274, 388, etc. It skips around. So I don't know how to do a nested loop using the for statement if it doesn't have a range that I can enter. Any help is appreciated. Thanks. completedataset = open('completedataset.txt', 'r') smallerdataset = open('smallerdataset.txt', 'w') for line in completedataset: if 'trial1' in line: smallerdataset(line) completedataset.close() smallerdataset.close() I'd really like to do it like this: trials = ('trial12', 'trial23', 'trial34') for line in completedataset: for trial in trials: if trial in line: smallerdataset(line) but this isn't working. Can anyone help me modify this program so that it works correctly?
[ "It seems to me that you need a list that holds all the trial numbers that you are interested in. So maybe you could try something like this:\ncompletedataset = open('completedataset.txt', 'r')\nsmallerdataset = open('smallerdataset.txt', 'w')\n\ntrials = [134, 274, 388]\ncompletedata = completedataset.readlines()\...
[ 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0003282785_loops_nested_python.txt