Re: Reading twice from STDIN
On 2/12/11 03:46:10, Dan Stromberg wrote: You can read piped data from sys.stdin normally. Then if you want something from the user, at least on most *ix's, you would open /dev/tty and get user input from there. 'Not sure about OS/X. Reading from /dev/tty works fine on OS/X. -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On Fri, Dec 2, 2011 at 4:34 PM, Steven D'Aprano wrote: > On Fri, 02 Dec 2011 13:07:57 +1100, Chris Angelico wrote: >> I would consider integer representations of ASCII to be code smell. It's >> not instantly obvious that 45 means '-', even if you happen to know the >> ASCII table by heart (which most people won't). Note, I'm not saying that C's way is perfect; merely that using the integer 45 to represent a hyphen is worse. > In what mad universe would you describe > 65 as a letter? I dunno, this universe looks pretty mad from where I am... wait, where am I? Oh, right. Rutledge's Private Clinic... nice soft walls they have here... > To say nothing of the fact that C's trick only works (for some definition > of works) for ASCII. Take for example one of the many EBCDIC encodings, > cp500. If you expect 'I' + 1 to equal 'J', you will be sorely > disappointed: > > py> u'I'.encode('cp500') > '\xc9' > py> u'J'.encode('cp500') > '\xd1' Nothing to do with C, this is a feature of ASCII. Anything involving arithmetic on ordinals depends on your encoding, regardless of conflation of int and char. > Anyone unfamiliar with C's model would have trouble guessing what 'A' + 1 > should mean. Should it be? > > - an error > - 'B' > - 'A1' > - the numeric value of variable A plus 1 > - 66 (assuming ascii encoding) > - 194 (assuming cp500 encoding) > - some other number > - something else? Agreed. But implicit casting is both a minefield and a source of immense amounts of clarity. Imagine if you couldn't implicitly cast int to float - it'd stop you from losing precision on large integers, but it would get in the way any time you want to work with integers and floating point together. > Note that this still doesn't work the way we might like in EBCDIC, but > the very fact that you are forced to think about explicit conversion > steps means you are less likely to make unwarranted assumptions about > what characters convert to. I don't know about that. Anyone brought up on ASCII and moving to EBCDIC will likely have trouble with this, no matter how many function calls it takes. > Better than both, I would say, would be for string objects to have > successor and predecessor methods, that skip ahead (or back) the > specified number of code points (defaulting to 1): > > 'A'.succ() => 'B' > 'A'.succ(5) => 'F' > > with appropriate exceptions if you try to go below 0 or above the largest > code point. ... and this still has that same issue. Arithmetic on codepoints depends on that. I'd be fine with a simple syntax that gives a Unicode codepoint, rather than an ASCII one; at least that's standardized. Being able to work with characters as though they're integers is a huge advantage in low-level code, but not so vital in Python. But if you're going to do it, you may as well do it without all the syntactic salt of explicit conversion functions. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Friday, December 2, 2011 1:00:10 PM UTC+8, Chris Angelico wrote: > On Fri, Dec 2, 2011 at 3:29 PM, 8 Dihedral > wrote: > > I clear my point a hash is a collection of (key, value) pairs that have > > well defined methods and behavior to be used in programming. > > > > The basic operations of a hash normally includes the following: > > > > 1. insertion of a (key, value) pair into the hash > > 2. deletion of a (key, value) from the hash > > 3. inquiring a hash by a key to retrieve the value if the (key, value) > > pair available in the hash. If no key matched, the hash will return > > a not found result. > > > > The hash can grow with (k,v) pairs accumulated in the run time. > > An auto memory management mechanism is required for a hash of a non-fixed > > size of (k,v) pairs. > > That's a hash table - think of a Python dictionary: > > On Fri, Dec 2, 2011 at 3:33 PM, Steven D'Aprano > wrote: > > Python dicts are hash tables. > > Although strictly speaking, isn't that "Python dicts are implemented > as hash tables in CPython"? Or is the hashtable implementation > mandated? Anyway, near enough. > > Cryptography and data verification use hashing too (look at the > various historic hashing algorithms - CRC, MD5, SHA, etc). The concept > of a hash is a number (usually of a fixed size) that is calculated > from a string or other large data type, such that hashing the same > input will always give the same output, but hashing different input > will usually give different output. It's then possible to identify a > large object solely by its hash, as is done in git, for instance; or > to transmit both the data and the hash, as is done in message > protection schemes (many archiving programs/formats include a hash of > the uncompressed data). These have nothing to do with (key,value) > pairs, but are important uses of hashes. > > ChrisA If one tries to insert a (k,v1) and then a (k,v2) pair into a hash with v1 not equals V2, what could happen in your understanding of a hash? A hash function is different from a hash or so called a hash table in my post. If the hash collision rate is not specified, then it is trivial to write a hash function with the conditions you specified. A hash function applied to a set of data items only is of very limited use at all. A hash stores (k,v) pairs specified in the run time with auto memory management build in is not a simple hash function to produce data signatures only clearly in my post. What I said a hash which is lifted as a basic type in python is called a dictionary in python. It is called a map in c++'s generics library. -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On Fri, 02 Dec 2011 13:07:57 +1100, Chris Angelico wrote: > On Fri, Dec 2, 2011 at 11:15 AM, Steven D'Aprano > wrote: >> Try this on for size. >> >> >> f = type(q)(c[c.index(chr(45))+1:])+type(q)(1) c >> = str.join('\n', list(map(chr, (45, 48))) + >> [c])[::2] >> c = (lambda a,b: a+b)(c[:c.index(chr(45))+1], >> type(c)(f)) > > I would consider integer representations of ASCII to be code smell. It's > not instantly obvious that 45 means '-', even if you happen to know the > ASCII table by heart (which most people won't). This is one thing that I > like about C's quote handling; double quotes for a string, or single > quotes for an integer with that character's value. It's clearer than the > Python (and other) requirement to have an actual function call: > > for (int i=0;i<10;++i) { > digit[i]='0'+i; > letter[i]='A'+i; > } I would disagree that this is clear at all. You're adding what looks like a character, but is actually an integer, with an integer. And then just to add insult to injury, you're storing integers into arrays that are named as if they were characters. In what mad universe would you describe 65 as a letter? To say nothing of the fact that C's trick only works (for some definition of works) for ASCII. Take for example one of the many EBCDIC encodings, cp500. If you expect 'I' + 1 to equal 'J', you will be sorely disappointed: py> u'I'.encode('cp500') '\xc9' py> u'J'.encode('cp500') '\xd1' Characters are not integers, and C conflates them, to the disservice of all. If fewer people learned C, fewer people would have such trouble understanding Unicode. Anyone unfamiliar with C's model would have trouble guessing what 'A' + 1 should mean. Should it be? - an error - 'B' - 'A1' - the numeric value of variable A plus 1 - 66 (assuming ascii encoding) - 194 (assuming cp500 encoding) - some other number - something else? How about 1000 + 'A'? > versus > > for i in range(10): > digit[i]=chr(ord('0')+i) > letter[i]=chr(ord('A')+i) It's a tad more verbose, but it's explicit about what is being done. Take the character '0', find out what ordinal value it encodes to, add 1 to that value, re-encode back to a character. That's exactly what C does, only it does it explicitly. Note that this still doesn't work the way we might like in EBCDIC, but the very fact that you are forced to think about explicit conversion steps means you are less likely to make unwarranted assumptions about what characters convert to. Better than both, I would say, would be for string objects to have successor and predecessor methods, that skip ahead (or back) the specified number of code points (defaulting to 1): 'A'.succ() => 'B' 'A'.succ(5) => 'F' with appropriate exceptions if you try to go below 0 or above the largest code point. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
Thank you. ಠ_ಠ On Fri, Dec 2, 2011 at 1:49 PM, Terry Reedy wrote: > On 11/30/2011 10:49 PM, Matt Joiner wrote: >> >> def possible_names(): >> yield "foo" >> for i in range(20): >> yield "foo-" + str(i) > > > This is my favorite -- crystal clear with only the variable part variable. > And it works in both 2.x and 3.x. > > -- > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Fri, Dec 2, 2011 at 3:29 PM, 8 Dihedral wrote: > I clear my point a hash is a collection of (key, value) pairs that have > well defined methods and behavior to be used in programming. > > The basic operations of a hash normally includes the following: > > 1. insertion of a (key, value) pair into the hash > 2. deletion of a (key, value) from the hash > 3. inquiring a hash by a key to retrieve the value if the (key, value) > pair available in the hash. If no key matched, the hash will return > a not found result. > > The hash can grow with (k,v) pairs accumulated in the run time. > An auto memory management mechanism is required for a hash of a non-fixed > size of (k,v) pairs. That's a hash table - think of a Python dictionary: On Fri, Dec 2, 2011 at 3:33 PM, Steven D'Aprano wrote: > Python dicts are hash tables. Although strictly speaking, isn't that "Python dicts are implemented as hash tables in CPython"? Or is the hashtable implementation mandated? Anyway, near enough. Cryptography and data verification use hashing too (look at the various historic hashing algorithms - CRC, MD5, SHA, etc). The concept of a hash is a number (usually of a fixed size) that is calculated from a string or other large data type, such that hashing the same input will always give the same output, but hashing different input will usually give different output. It's then possible to identify a large object solely by its hash, as is done in git, for instance; or to transmit both the data and the hash, as is done in message protection schemes (many archiving programs/formats include a hash of the uncompressed data). These have nothing to do with (key,value) pairs, but are important uses of hashes. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Fri, 02 Dec 2011 03:18:29 +1100, Chris Angelico wrote: > On Fri, Dec 2, 2011 at 2:52 AM, Dave Angel wrote: >> On 12/01/2011 10:35 AM, 8 Dihedral wrote: >>> I knew a hash can replace a bi-directional linked list. The value can >>> be a multi-field string to be parsed for further actions. Is this >>> what you are asking? >> >> A hash is a number, so I don't see how it can replace any kind of >> linked list. Perhaps you're thinking of some other language. > > A hashtable is a form of data structure that involves hashing values (ie > calculating hashes for them) and storing them for easier retrieval than > a simple linked list offers. That may be what you're thinking of. Python dicts are hash tables. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Friday, December 2, 2011 12:18:29 AM UTC+8, Chris Angelico wrote: > On Fri, Dec 2, 2011 at 2:52 AM, Dave Angel wrote: > > On 12/01/2011 10:35 AM, 8 Dihedral wrote: > >> I knew a hash can replace a bi-directional linked list. > >> The value can be a multi-field string to be parsed for further actions. > >> Is this what you are asking? > > > > A hash is a number, so I don't see how it can replace any kind of linked > > list. Perhaps you're thinking of some other language. > > A hashtable is a form of data structure that involves hashing values > (ie calculating hashes for them) and storing them for easier retrieval > than a simple linked list offers. That may be what you're thinking of. > > ChrisA I clear my point a hash is a collection of (key, value) pairs that have well defined methods and behavior to be used in programming. The basic operations of a hash normally includes the following: 1. insertion of a (key, value) pair into the hash 2. deletion of a (key, value) from the hash 3. inquiring a hash by a key to retrieve the value if the (key, value) pair available in the hash. If no key matched, the hash will return a not found result. The hash can grow with (k,v) pairs accumulated in the run time. An auto memory management mechanism is required for a hash of a non-fixed size of (k,v) pairs. Some implementations of a hash might pose some restrictions of k and v for some reasons. But in object programming k and v can be objects to be manipulated by the programmer. -- http://mail.python.org/mailman/listinfo/python-list
Passing along cmd.Cmd completion to contained class
I have sub-classes of cmd.Cmd in an arrangement somewhat like class Config(cmd.Cmd): def do_foo(self, line): print "Fooing %r" % line def complete_foo(self, text, line, begidx, endidx): ... class MyTUI(cmd.Cmd): def __init__(self, configger=Config, *args, **kwargs): cmd.Cmd.__init__(self, *args, **kwargs) self.config = configger() def complete_config(self, text, line, begidx, endidx): magic_here(self.config, text, line, begidx, endidx) I've been sparring with getting MyTUI.complete_config() to reach into self.config for completions so I can type things like (cmd) config (cmd) config foo and have it suggest from Config as if I had done something like def do_config(self, line) self.config.cmdloop() and then asked for completions. That would mean that the first one would act like Config.completenames() and the second one would act like Config.complete_foo(...) Is there a best way to get this pass-along behavior? Thanks, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On 11/30/2011 10:49 PM, Matt Joiner wrote: def possible_names(): yield "foo" for i in range(20): yield "foo-" + str(i) This is my favorite -- crystal clear with only the variable part variable. And it works in both 2.x and 3.x. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading twice from STDIN
On 12/1/11, janedenone wrote: > Hi, > > I would like to read from a pipe, parse the input and ask the user > what to do next: > > message = sys.stdin.read() > # message is parsed and URLs are printed as a list to choose from... > selected_index = raw_input('Which URL to open?') > > Calling raw_input() always raises in an EOFError. I tried reopening > and resetting sys.stdin, but nothing worked (at least on OX X 10.7, > see > You can read piped data from sys.stdin normally. Then if you want something from the user, at least on most *ix's, you would open /dev/tty and get user input from there. 'Not sure about OS/X. http://stackoverflow.com/questions/8034595/python-raw-input-following-sys-stdin-read-throws-eoferror). > > I am surprised to find that a seemingly trivial task cannot be > accomplished with Python 2.7 on a current Mac. Or am I missing > something simple? > > - Jan > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On Fri, Dec 2, 2011 at 11:15 AM, Steven D'Aprano wrote: > Try this on for size. > > > f = type(q)(c[c.index(chr(45))+1:])+type(q)(1) > c = str.join('\n', list(map(chr, (45, 48))) + [c])[::2] > c = (lambda a,b: a+b)(c[:c.index(chr(45))+1], type(c)(f)) I would consider integer representations of ASCII to be code smell. It's not instantly obvious that 45 means '-', even if you happen to know the ASCII table by heart (which most people won't). This is one thing that I like about C's quote handling; double quotes for a string, or single quotes for an integer with that character's value. It's clearer than the Python (and other) requirement to have an actual function call: for (int i=0;i<10;++i) { digit[i]='0'+i; letter[i]='A'+i; } versus for i in range(10): digit[i]=chr(ord('0')+i) letter[i]=chr(ord('A')+i) Ignoring the fact that you'd probably use a list comp in Python, this is imho a win for C. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the Python Interpreter as a Reference
On Fri, Dec 2, 2011 at 11:43 AM, Steven D'Aprano wrote: > Why would you want to encourage coders to write deeply indented code? > > In my opinion, if your code is indented four or more levels, you should > start to think about refactorising your code; if you reach six levels, > your code is probably a mess. So... would it be a bad thing to wrap up all my code into a single massive expression that returns a single integer for success/failure? Oh wait, the only time I ever saw code do that was in the IOCCC. Still, it WAS pretty awesome code! IOCCC is a code perfume factory. Cloying smell. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the Python Interpreter as a Reference
On Thu, 01 Dec 2011 10:03:53 -0800, DevPlayer wrote: [...] > Well, that may be a little hyperbolic. But with 2 spaces you can > encourage coders to get very deep, indentially, and still fit 80 chars. Why would you want to encourage coders to write deeply indented code? In my opinion, if your code is indented four or more levels, you should start to think about refactorising your code; if you reach six levels, your code is probably a mess. class K: def spam(): if x: for a in b: # This is about as deep as comfortable while y: # Code is starting to smell try: # Code smell is now beginning to reek with z as c: # And now more of a stench try: # A burning, painful stench if d: # Help! I can't breathe!!! for e in f: # WTF are you thinking? try: # DIE YOU M***ER!!! while g: # gibbers quietly ... The beauty of languages like Python where indentation is significant is that you can't hide from the ugliness of this code. class K: { # Code looks okay to a casual glance. def spam():{ if x: { for a in b:{ while y:{ try:{ with z as c:{ try:{ if d:{ for e in f:{ try:{ while g:{ ... Deeply indented code *is* painful, it should *look* painful. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
On 12/1/11 4:53 AM, Mark wrote: Hi there, I'm a complete beginner to Python and, aside from HTML and CSS, to coding in general. I've spent a few hours on it and think I understand most of the syntax. However, I'm wondering a bit about For Loops. I know that the basic syntax for them is to define a list, and then to use something like: for x in y However, what does "for" and "in" mean in this context? Can anyone help me to understand this? I know it's a really basic question, but hopefully it will see me on my way to coding properly :) Thanks a lot. y is some list ["help","beginner","question"] for x in y: if x=="question": print "FOUND" Clear? Cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On Thu, 01 Dec 2011 21:13:51 +, Martin P. Hellwig wrote: > On 01/12/2011 03:15, Roy Smith wrote: > Well, I have seen much worse, so the WTFs/minute(*) count won't be too > bad. > > However, as general rule for readability; If you think you have to ask, > don't bother asking, spend that time rethinking and write a more > readable solution. That's generally good advice, but in this case, I don't know why Roy Smith thought he had to ask. His initial snippet was pretty much standard vanilla Python: a for loop over a list. The list was made by adding a list containing a single element '', and a second list made from a list comprehension that converted a bunch of numbers into strings. It uses no advanced features like generators. A newbie to Python could work it out. In my opinion, if anyone thinks that's "obfuscated" (as opposed to merely "not quite idiomatic"), either their standards for readability are impossibly high, or they just can't read Python code. Try this on for size. def obfuscated_prefixes(q=20): c = str() while isinstance(type(c), type(type)): yield None or c while isinstance(c, object): try: f = type(q)(c[c.index(chr(45))+1:])+type(q)(1) except ValueError: c = str.join('\n', list(map(chr, (45, 48))) + [c])[::2] else: break if f <= q: pass else: break try: c = (lambda a,b: a+b)(c[:c.index(chr(45))+1], type(c)(f)) except IndexError: c = c[1::] -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On 01/12/2011 03:15, Roy Smith wrote: Well, I have seen much worse, so the WTFs/minute(*) count won't be too bad. However, as general rule for readability; If you think you have to ask, don't bother asking, spend that time rethinking and write a more readable solution. *) http://www.osnews.com/story/19266/WTFs_m -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: platform issues?
The curl & dig ideas were great, thanks. Turns out the machine's network was badly configured and that's probably what was causing this problem. Curiously firefox could browse these sites without any problem despite not having any proxy defined and it took the command line to reveal the issue. Thank you for your help, this had been bugging us for days! Adrian. -Original Message- From: "Redcat" [red...@catfolks.net] Date: 12/01/2011 02:05 PM To: python-list@python.org Subject: Re: platform issues? On Thu, 01 Dec 2011 13:43:38 -0500, Adrian Powell wrote: > Since I'm actually trying to write a twitter client, I was more focused > on the results from twitter. Since google and twitter are so huge and so > distributed, I'd bet neither are good tests for this, but they look > approximately right. > > Are there better ways to test if our network setup is good? At least > that would be a relatively easy thing to fix. I think I'd first try "dig www.google.com" to be sure that it is resolving, then I believe I'd try to fetch the URL from your code sample using cUrl. If both of those work then I'm not sure what I'd look at next. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
Arnaud Delobelle wrote: > On 1 December 2011 03:15, Roy Smith wrote: >> I need to try a bunch of names in sequence until I find one that works >> (definition of "works" is unimportant). The algorithm is: >> >> 1) Given a base name, "foo", first see if just plain "foo" works. >> >> 2) If not, try "foo-1", "foo-2", and so on >> >> 3) If you reach "foo-20", give up. >> >> What would you say if you saw this: >> >> for suffix in [''] + [str(i) for i in xrange(-1, -20, -1)]: >> > > It's a little obfuscated ;) I would go for the simple: > > for i in xrange(21): > suffix = "-%s" % i if i else "" > > obfuscated for obfuscated, you can merge the two ideas: for suffix in ('-%s' % i if i else '' for i in xrange(21)): ... -- By ZeD -- http://mail.python.org/mailman/listinfo/python-list
ANN: Urwid 1.0.1, Urwid 0.9.9.3 - Console UI Library
Announcing Urwid 1.0.1 and Urwid 0.9.9.3 Urwid home page: http://excess.org/urwid/ Manual: http://excess.org/urwid/wiki/UrwidManual Tarballs: http://excess.org/urwid/urwid-1.0.1.tar.gz http://excess.org/urwid/urwid-0.9.9.3.tar.gz About these releases: = These are bug-fix releases for Urwid 1.0.0 and Urwid 0.9.9.2. Release 0.9.9.3 may be the last in the 0.9.9 series. Users are strongly encouraged to upgrade to the 1.0 series. New in 1.0.1: = * Fix for Terminal widget in BSD/OSX * Fix for a Filler mouse_event() position bug * Fix support for mouse positions up to x=255, y=255 * Fixes for a number of string encoding issues under Python 3 * Fix for a LineBox border __init__() parameters * Fix input input of UTF-8 in tour.py example by converting captions to unicode * Fix tutorial examples' use of TextCanvas and switch to using unicode literals * Prevent raw_display from calling tcseattr() or tcgetattr() on non-ttys * Disable curses_display external event loop support: screen resizing and gpm events are not properly supported * Mark PollingListWalker as deprecated New in 0.9.9.3: === * ListBox now includes a get_cursor_coords() method, allowing nested ListBox widgets * Fix for a Filler mouse_event() position bug * Fix support for mouse positions up to x=255, y=255 * Fix for leaks of None object in str_util extension * Fix for WidgetWrap and AttrMap not working with fixed widgets About Urwid === Urwid is a console UI library for Python. It features fluid interface resizing, Unicode support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. -- http://mail.python.org/mailman/listinfo/python-list
Re: platform issues?
On Thu, 01 Dec 2011 13:43:38 -0500, Adrian Powell wrote: > Since I'm actually trying to write a twitter client, I was more focused > on the results from twitter. Since google and twitter are so huge and so > distributed, I'd bet neither are good tests for this, but they look > approximately right. > > Are there better ways to test if our network setup is good? At least > that would be a relatively easy thing to fix. I think I'd first try "dig www.google.com" to be sure that it is resolving, then I believe I'd try to fetch the URL from your code sample using cUrl. If both of those work then I'm not sure what I'd look at next. -- http://mail.python.org/mailman/listinfo/python-list
Re: platform issues?
to run the tests, I sit at my dev machine and SSH to the server where I can copy & paste the test case directly into the python interpreter. If there's a typo, it's going to both of them equally. I am concerned about the name lookup since our servers have had some network glitches in the past and I'm not confident in our DNS. We can browse the net on the server without a problem but to be sure, I tried this: On the server: >>> socket.gethostbyaddr(socket.gethostbyname('www.google.com')) ('yyz06s07-in-f20.1e100.net', [], ['74.125.226.84']) >>> socket.gethostbyaddr(socket.gethostbyname('www.twitter.com')) ('www2.twitter.com', [], ['199.59.149.198']) On the dev environment: >>> socket.gethostbyaddr(socket.gethostbyname('www.google.com')) ('sea09s02-in-f16.1e100.net', [], ['173.194.33.48']) >>> socket.gethostbyaddr(socket.gethostbyname('www.twitter.com')) ('www4.twitter.com', [], ['199.59.149.230']) Since I'm actually trying to write a twitter client, I was more focused on the results from twitter. Since google and twitter are so huge and so distributed, I'd bet neither are good tests for this, but they look approximately right. Are there better ways to test if our network setup is good? At least that would be a relatively easy thing to fix. Adrian. -Original Message- From: "Redcat" [red...@catfolks.net] Date: 12/01/2011 01:05 PM To: python-list@python.org Subject: Re: platform issues? > Our servers have the same version of python and we're running the same > OS (Fedora 14). Can anyone think of what might be causing this problem, > or why it works on most (but not all) machines? > > Thanks Is the server able to resolve www.google.com properly? If so, are you POSITIVE that the "url = " line on the server has no typos? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: platform issues?
Adrian Powell wrote: I'm new to python and I'm trying to get a twitter client running on a new machine but it keeps on failing. I tracked the problem down to an issue opening URLs and wrote this little test case: import urllib2 url = 'http://www.google.com/' opener = urllib2.build_opener() url_data = opener.open(url).read url_data When I run that on a dev machine it works fine, but when it's on one of our servers it crashes: import urllib2 url = 'http://www.google.com/' opener = urllib2.build_opener() url_data = opener.open(url).read Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1173, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1148, in do_open raise URLError(err) urllib2.URLError: Our servers have the same version of python and we're running the same OS (Fedora 14). Can anyone think of what might be causing this problem, or why it works on most (but not all) machines? Thanks Actually, Python did not crashed, some module raised an exception and nothing has been written to handle that exception, hence python stopping. But as you can see, python gave you a lot of meaningful informations about why it was not able to continue execution. urllib2.URLError: Your server may not be able to resolve that URL while your local dev machine can. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the Python Interpreter as a Reference
On Nov 29, 3:04 am, Steven D'Aprano wrote: > On Tue, 29 Nov 2011 12:49:49 +1100, Chris Angelico wrote: > > On Tue, Nov 29, 2011 at 11:54 AM, DevPlayer wrote: > >> To me, I would think the interpreter finding the coder's intended > >> indent wouldn't be that hard. And just make the need for consistant > >> spaces or tabs irrevelent simply by reformatting the indent as > >> expected. Pretty much all my text editors can. > > > The trouble with having a language declaration that "a tab is equivalent > > to X spaces" is that there's no consensus as to what X should be. > > Historically X has always been 8, and quite a few programs still assume > > this. I personally like 4. Some keep things narrow with 2. You can even > > go 1 - a strict substitution of \t with \x20. Once you declare it in > > your language, you immediately break everyone who uses anything > > different. > > Why should we enforce how many spaces a tab is set to? That is literally > only visible to the editor, not the compiler. (Unless the parser is > particularly stupid and merely substitutes X spaces for a tab every time > it sees one.) > > Mixed spaces and tabs in an indent are ambiguous, and so raises > SyntaxError (or at least it *should* raise SyntaxError). But separate > code blocks can use different absolute indent levels without ambiguity, > so long as the relative indentation is consistent: > > def ham(): # tab stops at 4 and 8 > do(a) > do(b) > if c: > do(c) > else: > do(d) > > def spam(): # tab stops at 8 and 12 > do(a) > do(b) > if c: > do(c) > else: > do(d) > > There is no meaningful difference in indentation between ham and spam > above. In either case, I could replace spaces with tabs to get the same > relative indents regardless of the absolute indentation. > > I can appreciate the aesthetic argument that *within a single file*, > indentation should be consistent. But it's not logically necessary for > the parser: it need only be consistent within a single code unit > (function or class usually). In other words: syntax should only care > about relative indentation, absolute indentation belongs as a coding > standard. > > -- > Steven Great point. Your point is why I started writting my own little Python parser/scanner (as an pet project/lesson project) and is in part, why I wrote my little reindent() in the first place. I am/was trying to figure out the algorithim for how Python's indent/dedents made logical "code blocks" or "closures" or whatever they are called. That and see if there was a way to interpret docstrings in various formats. I often get indentation syntax errors when I cut and paste stackflow.com, devprogrammer.com, daniweb.com, etc. code snippets into my various IDEs/ editors and I wanted to make a little tabnanny of my own. Some of the IDEs and editors (Editra) allow plugins. So I wanted to get a baseline for the various plugins. So I call the reindent() after I call the blocker(), which determines a block by -releative- indent/dedent as +1 or, 0 or -1 whether that be +4 spaces, +2 spaces, +1 tab or -3 spaces, whatever...; as you, Steve, mentioned indent is not fixed but relative. (btw I'v posted this in this topic because I thought it could contribute to how Unit's choice of how indents are handled my benefit from this discussion). My thoughts on tab verse space chars;, for most old and even current commandline interfaces, text editors, and historically line printers, tabs simply acted like a macro to move x number of fixed spaces. It wasn't until varible width fonts, kerning, and other advanced printing techniques became mainstream<- did space chars differ in meaning from tab chars, exception perhaps being file storage space (way back in the day). I only say this because I can't stand hitting the right and left arrow keys or using multiple fingers to move left and right 3 more times then I have to while editing my text. I -feel- I move faster around my text files with tabs then I do with 4 spaces. They only annoyance I've had with Python's flexiblity with indent using tab and or spaces is the docstrings. \t = tab def myfunc(): \t"""here is my docstring that bla bla bla's \t\tand indented do da days... \t""" verse (s = space) def myfunc(): """here is my docstring that bla bla bla's and indented do da days... """ verse space = tab or space def myfunc(): "here is my docstring that bla bla bla's"\ "and indented do da days..."\ "\n" verse the legal and sometimes seen form: def myfunc(): \tmyval = somefunc( arg0, arg1, arg2, lotsofargs, \t\tpaces_to_align_arg_to_arg0) If you strip the text and display it using basic reformatting in fixed font, like in the python interpreter, no biggy. But when you want to display the docstrings in an advanced font, like that of an ide with truetype fonts, formatting gets lost without having the app account for all the various ways Python coders do the
Re: platform issues?
> Our servers have the same version of python and we're running the same > OS (Fedora 14). Can anyone think of what might be causing this problem, > or why it works on most (but not all) machines? > > Thanks Is the server able to resolve www.google.com properly? If so, are you POSITIVE that the "url = " line on the server has no typos? -- http://mail.python.org/mailman/listinfo/python-list
platform issues?
I'm new to python and I'm trying to get a twitter client running on a new machine but it keeps on failing. I tracked the problem down to an issue opening URLs and wrote this little test case: import urllib2 url = 'http://www.google.com/' opener = urllib2.build_opener() url_data = opener.open(url).read url_data When I run that on a dev machine it works fine, but when it's on one of our servers it crashes: >>> import urllib2 >>> url = 'http://www.google.com/' >>> opener = urllib2.build_opener() >>> url_data = opener.open(url).read Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.7/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.7/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 1173, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.7/urllib2.py", line 1148, in do_open raise URLError(err) urllib2.URLError: Our servers have the same version of python and we're running the same OS (Fedora 14). Can anyone think of what might be causing this problem, or why it works on most (but not all) machines? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Fri, Dec 2, 2011 at 2:52 AM, Dave Angel wrote: > On 12/01/2011 10:35 AM, 8 Dihedral wrote: >> I knew a hash can replace a bi-directional linked list. >> The value can be a multi-field string to be parsed for further actions. >> Is this what you are asking? > > A hash is a number, so I don't see how it can replace any kind of linked > list. Perhaps you're thinking of some other language. A hashtable is a form of data structure that involves hashing values (ie calculating hashes for them) and storing them for easier retrieval than a simple linked list offers. That may be what you're thinking of. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Thursday, December 1, 2011 11:52:46 PM UTC+8, Dave Angel wrote: > On 12/01/2011 10:35 AM, 8 Dihedral wrote: > > On Wednesday, November 30, 2011 8:47:13 PM UTC+8, Peter Otten wrote: > >> Neal Becker wrote: > >> > >>> I like to hash a list of words (actually, the command line args of my > >>> program) in such a way that different words will create different hash, > >>> but not sensitive to the order of the words. Any ideas? > >> You mean a typical python hash value which would be /likely/ to differ for > >> different lists and /guaranteed/ to be equal for equal lists is not good > >> enough? Because that would be easy: > >> > >> args = sys.argv[1:] > >> hash(tuple(sorted(args))) # consider duplicate args > > I knew a hash can replace a bi-directional linked list. > > The value can be a multi-field string to be parsed for further actions. > > Is this what you are asking? > A hash is a number, so I don't see how it can replace any kind of linked > list. Perhaps you're thinking of some other language. > > -- > > DaveA A long number of a varied length allowed but can interpreted by the programmer. -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On 12/01/2011 10:35 AM, 8 Dihedral wrote: On Wednesday, November 30, 2011 8:47:13 PM UTC+8, Peter Otten wrote: Neal Becker wrote: I like to hash a list of words (actually, the command line args of my program) in such a way that different words will create different hash, but not sensitive to the order of the words. Any ideas? You mean a typical python hash value which would be /likely/ to differ for different lists and /guaranteed/ to be equal for equal lists is not good enough? Because that would be easy: args = sys.argv[1:] hash(tuple(sorted(args))) # consider duplicate args I knew a hash can replace a bi-directional linked list. The value can be a multi-field string to be parsed for further actions. Is this what you are asking? A hash is a number, so I don't see how it can replace any kind of linked list. Perhaps you're thinking of some other language. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On Wednesday, November 30, 2011 8:47:13 PM UTC+8, Peter Otten wrote: > Neal Becker wrote: > > > I like to hash a list of words (actually, the command line args of my > > program) in such a way that different words will create different hash, > > but not sensitive to the order of the words. Any ideas? > > You mean a typical python hash value which would be /likely/ to differ for > different lists and /guaranteed/ to be equal for equal lists is not good > enough? Because that would be easy: > > args = sys.argv[1:] > hash(tuple(sorted(args))) # consider duplicate args I knew a hash can replace a bi-directional linked list. The value can be a multi-field string to be parsed for further actions. Is this what you are asking? -- http://mail.python.org/mailman/listinfo/python-list
Re: Disable readline
Steven D'Aprano wrote: > On Thu, 01 Dec 2011 00:00:52 -0500, Roy Smith wrote: > > > Another possibility is setting your TERM environment variable to > > something that readline can't support: > > > > ~$ TERM=asr33 > > ~$ python > > Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. > > build 5646)] on darwin Type "help", "copyright", "credits" or "license" > > for more information. Cannot read termcap database; > > using dumb terminal settings. > > Cannot read termcap database; > > using dumb terminal settings. > > Cannot read termcap database; > > using dumb terminal settings. > > > Damn, my python is smarter than your python. > > steve@runes:~$ TERM=asr33 > steve@runes:~$ python > Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > And readline continues to work :/ > Two things: o Is TERM exported? Maybe Roy's is and yours isn't. o Is asr33 in your termcap database? Try export TERM=dumb perhaps? Nick > > I think I'll install from source a build with readline disabled. > > > > BTW, readline is the coolest, awesomist, most frabjulously gnarly thing > > to be invented since the pointed stick. The idea that somebody would > > want to turn it off (even for testing) disturbs me deeply. > > I know! I don't use more than about 1% of what readline offers, but I > can't imagine not using it. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
Gelonida N wrote: > On 11/30/2011 01:32 PM, Neal Becker wrote: >> I like to hash a list of words (actually, the command line args of my >> program) in such a way that different words will create different hash, but >> not sensitive >> to the order of the words. Any ideas? >> > Do youmean hash like digest like md5sum / sha1 ? > > > You should sort the words alphabetically, concatenate them with a space > or any character, that will NEVER be part of a word and calulate the hash. > > If words can exist multiple times, then youhad tu uniqufy them (u using > a python dict / set) first. Yes that sounds just like what I wanted - thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
Mark writes: > I'm a complete beginner to Python and, aside from HTML and CSS, to > coding in general. I've spent a few hours on it and think I understand > most of the syntax. Welcome! You should work your way through the Python tutorial, from beginning to end http://docs.python.org/tutorial/>. Actually do each exercise, experiment if you have questions, and then continue. Repeat until done. -- \ “Ours is a world where people don't know what they want and are | `\ willing to go through hell to get it.” —Donald Robert Perry | _o__) Marquis | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
Thanks a lot for the answers everyone, I really appreciate you getting back to me so quickly. I think that I understand where I am with this now :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
On 12/01/2011 06:32 AM, Pedro Henrique G. Souto wrote: On 01/12/2011 08:53, Mark wrote: Hi there, I'm a complete beginner to Python and, aside from HTML and CSS, to coding in general. I've spent a few hours on it and think I understand most of the syntax. However, I'm wondering a bit about For Loops. I know that the basic syntax for them is to define a list, and then to use something like: for x in y However, what does "for" and "in" mean in this context? Can anyone help me to understand this? I know it's a really basic question, but hopefully it will see me on my way to coding properly :) Thanks a lot. That means (in a free translation) "For each one of 'x' in 'y', do this" 'y' is a list, for example, then it means: "For each one of the elements of the list 'y' (the element on the current iteration is named 'x'), do this" And if y is a string, it means for each character in y, do this x = the character (then do the indented part) And if y is an arbitrary iterable, it means for each thing the iterable produces x = the thing (then do the indented part) Each time you go through the loop, x will be equal to the next item in the sequence. So you can systematically process the items in the list (or characters in the string, or values from an iterable), one at a time. The only real caveat is to not do something that would change the list (etc.) while you're looping through it. What are some other examples of iterables? infile = open("myfile.txt", "r") #infile is an iterable for line in infile: print "**", line, "**" for val in (1, 4, 9, 2007) for x in xrange(5000): #this does the same as range(), but doesn't actually build the list. #this way, we don't run out of memory You can also code your own generator function, which is an iterable, and may be used like the above. Some things in this message assume Python 2.x. in Python 3, range works differently, as does print. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
RE: Py and SQL
I find it easier to code like this Sql = ‘’’select yadda, yadda, yadda FROM a,b,c Where this=that ORDER BY deudderting’’’ With the appropriate %s(varname) and % against a dictionary rather than positional args, but that’s just me. From: python-list-bounces+frsells=adventistcare@python.org [mailto:python-list-bounces+frsells=adventistcare@python.org] On Behalf Of Jerry Hill Sent: Wednesday, November 30, 2011 5:15 PM To: Verde Denim Cc: Python list Subject: Re: Py and SQL On Wed, Nov 30, 2011 at 3:30 PM, Verde Denim wrote: dbCursor1.execute('select lpad(' ', 2*level) || c "Privilege, Roles and Users" from ( select null p, name c from system_privilege_map where name like upper(\'%&enter_privliege%\') union select granted_role p, grantee c from dba_role_privs union select privilege p, grantee c from dba_sys_privs) start with p is null connect by p = prior c') I think this is your problem. Your string is delimited with single quotes on the outside ('), but you also have a mix of single and double quotes inside your string. If you were to assign this to a variable and print it out, you would probably see the problem right away. You have two options. First, you could flip the outer quotes to double quotes, then switch all of the quotes inside the string to single quotes (I think that will work fine in SQL). Second, you could use a triple-quoted string by switching the outer quotes to ''' or """. Doing that would let you mix whatever kinds of quotes you like inside your string, like this (untested): sql = '''select lpad(' ', 2*level) || c "Privilege, Roles and Users" from ( select null p, name c from system_privilege_map where name like upper(\'%&enter_privliege%\') union select granted_role p, grantee c from dba_role_privs union select privilege p, grantee c from dba_sys_privs) start with p is null connect by p = prior c''' dbCursor1.execute(sql) Once you do that, I think you will find that the "&enter_priviliege" bit in your SQL isn't going to do what you want. I assume you're expecting that to automatically pop up some sort of dialog box asking the user to enter a value for that variable? That isn't going to happen in python. That's a function of the database IDE you use. You'll need to use python to ask the user for the privilege level, then substitute it into the sql yourself. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
On 01/12/2011 08:53, Mark wrote: Hi there, I'm a complete beginner to Python and, aside from HTML and CSS, to coding in general. I've spent a few hours on it and think I understand most of the syntax. However, I'm wondering a bit about For Loops. I know that the basic syntax for them is to define a list, and then to use something like: for x in y However, what does "for" and "in" mean in this context? Can anyone help me to understand this? I know it's a really basic question, but hopefully it will see me on my way to coding properly :) Thanks a lot. That means (in a free translation) "For each one of 'x' in 'y', do this" 'y' is a list, for example, then it means: "For each one of the elements of the list 'y' (the element on the current iteration is named 'x'), do this" Good Luck! Att; Pedro Henrique G. Souto ╔═╗ ║ ²²²d○_○b²²² ║ ╚═╝ -- http://mail.python.org/mailman/listinfo/python-list
Re: Complete beginner, any help appreciated :) - For Loops
for x in y However, what does "for" and "in" mean in this context? It means basically the same as in Englsish Does the following links answer the question ? http://www.ibiblio.org/g2swap/byteofpython/read/for-loop.html http://dsnra.jpl.nasa.gov/software/Python/diveintopython.pdf (page 58) Have a nice day Laurent -- http://mail.python.org/mailman/listinfo/python-list
Complete beginner, any help appreciated :) - For Loops
Hi there, I'm a complete beginner to Python and, aside from HTML and CSS, to coding in general. I've spent a few hours on it and think I understand most of the syntax. However, I'm wondering a bit about For Loops. I know that the basic syntax for them is to define a list, and then to use something like: for x in y However, what does "for" and "in" mean in this context? Can anyone help me to understand this? I know it's a really basic question, but hopefully it will see me on my way to coding properly :) Thanks a lot. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading twice from STDIN
On 12/01/2011 11:01 AM, janedenone wrote: Hi, > > I would like to read from a pipe, parse the input and ask the user > what to do next: > > message = sys.stdin.read() With above line you said, that you want to read ALL data from stdin, so it's obvious that any following command will be unable to reda anything from standartd in Thus the EOF error. If you want to get input you had to read directly from the console (tty) and NOT from stdin. Stdin has already been consumed. It is possible in python to get the tty related to your console window and read from it. Unfortunately I don't kno whte commands by heart and I don't have time now to look it up. Perhaps somebody else can point you in the right direction. If not I'll it up till tomorrow. -- http://mail.python.org/mailman/listinfo/python-list
Re: order independent hash?
On 11/30/2011 01:32 PM, Neal Becker wrote: > I like to hash a list of words (actually, the command line args of my > program) > in such a way that different words will create different hash, but not > sensitive > to the order of the words. Any ideas? > Do youmean hash like digest like md5sum / sha1 ? You should sort the words alphabetically, concatenate them with a space or any character, that will NEVER be part of a word and calulate the hash. If words can exist multiple times, then youhad tu uniqufy them (u using a python dict / set) first. -- http://mail.python.org/mailman/listinfo/python-list
Re: unpack('>f', b'\x00\x01\x00\x00')
Chris Rebert writes: > C does not have a built-in fixed-point datatype, so the `struct` > module doesn't handle fixed-point numbers directly. The built-in decimal module supports fixed-point arithmetic, but the struct module doesn't know about it. A bug report (or patch) by someone who works with binary representations of fixed-point would be a good start to improve it. -- http://mail.python.org/mailman/listinfo/python-list
get date from email
Hi, up to now I use this code to parse date values from emails: msg=email.message_from_file(open(file_name)) date=None date_str=msg.get('date') if date_str: date_tuple=email.utils.parsedate_tz(date_str) if date_tuple: date=datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple)) if date: ... # valid date found Somehow this looks too complicated. Any chance to integrate the datetime module into the email module? related: http://stackoverflow.com/questions/1790795/python-parsing-date-with-timezone-from-an-email -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de -- http://mail.python.org/mailman/listinfo/python-list
Reading twice from STDIN
Hi, I would like to read from a pipe, parse the input and ask the user what to do next: message = sys.stdin.read() # message is parsed and URLs are printed as a list to choose from... selected_index = raw_input('Which URL to open?') Calling raw_input() always raises in an EOFError. I tried reopening and resetting sys.stdin, but nothing worked (at least on OX X 10.7, see http://stackoverflow.com/questions/8034595/python-raw-input-following-sys-stdin-read-throws-eoferror). I am surprised to find that a seemingly trivial task cannot be accomplished with Python 2.7 on a current Mac. Or am I missing something simple? - Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On 1 December 2011 03:15, Roy Smith wrote: > I need to try a bunch of names in sequence until I find one that works > (definition of "works" is unimportant). The algorithm is: > > 1) Given a base name, "foo", first see if just plain "foo" works. > > 2) If not, try "foo-1", "foo-2", and so on > > 3) If you reach "foo-20", give up. > > What would you say if you saw this: > > for suffix in [''] + [str(i) for i in xrange(-1, -20, -1)]: > It's a little obfuscated ;) I would go for the simple: for i in xrange(21): suffix = "-%s" % i if i else "" -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Clever hack or code abomination?
On Thu, Dec 1, 2011 at 2:15 PM, Roy Smith wrote: > for suffix in [''] + [str(i) for i in xrange(-1, -20, -1)]: > > It generates the right sequence of strings. But, if you came upon that > code, would it make sense to you, or would you spend half the afternoon > trying to figure out what it did and the other half of the afternoon > ranting about the deranged lunatic who wrote it? That's a self-contained piece of code.If I came upon it, I'd probably copy and paste it to IDLE, see what it comes up with, and proceed from there. Deranged you may be, but so long as code can be dropped into an interactive interpreter, it's fine. ChrisA -- http://mail.python.org/mailman/listinfo/python-list