Re: Dictionary
Le mercredi 8 janvier 2014 20:00:02 UTC+1, Bischoop a écrit : > Walter Hurry wrote: > > > > > On Mon, 30 Dec 2013 18:38:20 +, Bischoop wrote: > > > > > >> I have a txt file with some words, and need simply program that will > > >> print me words containing provided letters. > > >> > > >> For example: > > >> Type the letters: > > >> (I type: g,m,o) > > >> open the dictionary.txt > > >> check words containing:g,m,o in dictionary.txt > > >> if there are words containing: ["g", "m", "o" ] > > >> print words with g,m,o > > > > > > Well, what have you tried so far, and what result did you get? > > > > > > The incredibly helpful people here will provide advice, guidance and > > > pointers, but it won't help you at all if they just do your homework for > > > you. > > > > > > Honestly Im newbie in Python, years ago (10 already) I wrote simply program > > something like a TEST: Capitals of Countries. You could learn the capitals > > of some countries, and then you could try to solve a test. I know it's seems > > so simply for you guys but I was quite pride of myself :-) > > > > Now because of free time I took my book which I used years ago about python > > and try to learn it again, and as motivation I try to write the program I > > described above just to give me a kick :-), however got no idea how to start > > it, I meand there is so many moduls (import this, import that), I know how > > to open, read file etc. Just stuck with that, got no clue what and how use > > this that what I need to seek the words from the files if I need a words > > with letters I want. >>> # a starting point >>> lettres = set('üœŸ') >>> Wörter = ['abcüœŸb', 'aüꜟ', 'üœŸzzz', 'üœzz', 'Strauẞ', '', 'nul'] >>> for word in Wörter: ... tmp = set(word) ... print('{:10} : {}'.format(word, lettres.issubset(tmp))) ... abcüœŸb: True aüꜟ : True üœŸzzz : True üœzz : False Strauẞ : False : False nul: False >>> -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Roy Smith writes: > In article , > Chris Angelico wrote: > >> On Thu, Jan 9, 2014 at 2:35 PM, Roy Smith wrote: >> >> Yes, it *is* simple. It *is* easy. I've been working with pure-UTC >> >> times (either called time_t, or TIMESTAMP WITH TIME ZONE, or even just >> >> float) for decades. Like with so many other things, the easiest >> >> solution is also the best, because you can just work with one stable >> >> representation and abstraction on the inside, with conversions to/from >> >> it at the boundaries. It IS that easy. >> > >> > Please show me the simple code to obtain an aware UTC datetime >> > representing the current time. >> >> In Pike: >> time(); >> >> In PostgreSQL: >> SELECT now(); >> >> In C: >> time(0); >> >> All of these give a value in UTC. > > None of which answer my question. How, in Python, do you get an aware > UTC datetime object? I know how to get a numeric representation of the > time as the number of seconds since the Unix epoch. That's not what I > asked. > My local copy of the python 3.2.3 docs says: classmethod datetime.utcnow() Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc). See also now(). Hope this helps. >> So maybe the key is to use utcfromtimestamp()? I don't know. > > So, I'm really confused what point you're trying to make. You started > out arguing that I should be using aware datetimes instead of naive > datetimes. I said that the reason I don't use aware datetimes is > because they're so much more difficult to generate. You said they were > simple to generate. > > So, I'd like to see your code which generates an aware UTC datetime > object in Python. And then we can argue about whether it's simple or > not :-) -- regards, kushal pgpj8L6oBjbeP.pgp Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 01:27, Roy Smith wrote: In article , Kevin Walzer wrote: I haven't updated my Python apps to 3.x because there's nothing in 3.x that offers benefits to my users. I almost found a reason to move to Python 3 today. Then I got smacked. I had a datetime. I needed a unix timestamp. People need to go back and forth between these two things all the time and in Python 2 it's the very definition of impedance mismatch. What should be a dead simple operation involves long threads on stackoverflow discussing which of several amalgamations of duct tape is the least ugly. Anyway, I discovered that Python 3.3's datetime has a .timestamp() method. Yeah. Finally. Exactly what the world had needed for years. Then I kept reading and found: Note: There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. Ugh. So, we're back to square one. They go on to suggest one of two workarounds, either calling datetime.replace() to insert a timezone, or subtracting from the epoch manually. Naive datetimes are what everybody uses. It's what utcnow() gives you. So why make life difficult for everybody? Python 3 didn't win a convert today. Yep, dates and times are easy. That's why there are 17 issues open on the bug tracker referencing tzinfo alone. Poor old 1100942 is high priority, was created 12/01/2005 and has missed 3.4. So if it gets into 3.5 it'll have already celebrated its 10th birthday. It doesn't say much for the amount of effort that we put into looking after issues. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 06:06, Kushal Kumaran wrote: My local copy of the python 3.2.3 docs says: classmethod datetime.utcnow() Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc). See also now(). Hope this helps. Blimey, you learn something new everyday, thanks. And it works :) In [7]: datetime.datetime.now(datetime.timezone.utc) Out[7]: datetime.datetime(2014, 1, 9, 8, 51, 13, 945312, tzinfo=datetime.timezone.utc) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Kushal Kumaran writes: > Roy Smith writes: > > How, in Python, do you get an aware UTC datetime object? > > My local copy of the python 3.2.3 docs says: > > classmethod datetime.utcnow() > > Return the current UTC date and time, with tzinfo None. This is > like now(), but returns the current UTC date and time, as a naive > datetime object. An aware current UTC datetime can be obtained by > calling datetime.now(timezone.utc). See also now(). > > Hope this helps. No, that won't do what was asked. The ‘datetime.datetime.utcnow’ function explicitly returns a naive datetime object, not an aware datetime object. -- \ “We must respect the other fellow's religion, but only in the | `\ sense and to the extent that we respect his theory that his | _o__) wife is beautiful and his children smart.” —Henry L. Mencken | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Ben Finney writes: > Kushal Kumaran writes: > >> Roy Smith writes: >> > How, in Python, do you get an aware UTC datetime object? >> >> My local copy of the python 3.2.3 docs says: >> >> classmethod datetime.utcnow() >> >> Return the current UTC date and time, with tzinfo None. This is >> like now(), but returns the current UTC date and time, as a naive >> datetime object. An aware current UTC datetime can be obtained by >> calling datetime.now(timezone.utc). See also now(). >> >> Hope this helps. > > No, that won't do what was asked. The ‘datetime.datetime.utcnow’ > function explicitly returns a naive datetime object, not an aware > datetime object. > Yes, but the documentation for utcnow explicitly tells you how to get an aware object. "An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc)." -- regards, kushal pgpkuzTEDWuQ3.pgp Description: PGP signature -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 09:03, Ben Finney wrote: Kushal Kumaran writes: Roy Smith writes: How, in Python, do you get an aware UTC datetime object? My local copy of the python 3.2.3 docs says: classmethod datetime.utcnow() Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc). See also now(). Hope this helps. No, that won't do what was asked. The ‘datetime.datetime.utcnow’ function explicitly returns a naive datetime object, not an aware datetime object. How closely do you bother to read posts that people like Kushal Kumaran have taken the trouble to post? Eleven lines above this one it says (my emphasis) "An *AWARE* current UTC datetime can be obtained by calling datetime.now(timezone.utc)". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Constructive Criticism
jeremiahvalerio...@gmail.com wrote: > Hi, hows it going I've been self teaching myself python, and i typed up > this small script now i know its not the best the coding is not the best > but i would like to know of ways to make a small script like this better > so all constructive critisim is Welcome. > > > > Here is the link to the code > >" http://pastebin.com/5uCFR2pz " > time.sleep(1) > import time > print("Closing in 9 ") > time.sleep(1) > import time > print("Closing in 8 ") - You should import modules just once, at the beginning of your script. - Repetetive tasks are best handled with a for-loop, e. g.: >>> import time >>> for seconds_left in reversed(range(1, 10)): ... print("Closing in", seconds_left, "seconds") ... time.sleep(1) ... Closing in 9 seconds Closing in 8 seconds Closing in 7 seconds Closing in 6 seconds Closing in 5 seconds Closing in 4 seconds Closing in 3 seconds Closing in 2 seconds Closing in 1 seconds > user_input = input("\nWhos your favorite Football team? \n 1.Arizona > Cardinals\n 2.Atlanta Falcons\n 3.Baltimore Ravens\n 4.Buffalo Bills\n > 5.Miami Dolphins\n 6.Minnesota Vikings \n 7.New England Patriots \n > 8.New Orleans Saints \n 9.Carolina [snip] Python offers triple-quoted strings which may include newline literals: user_input = input(""" Who's your favorite Football team? 1. Arizona Cardinals 2. Atlanta Falcons ... """) > if user_input == "1" : > print("\nThey suck! BYE!") > > elif user_input == "2" : > print("\nThey suck! BYE!") > > elif user_input == "3" : > print("\nThey suck!BYE!") [snip] Ignoring the typos you are taking the same action for all inputs but "17". So: if user_input != "17": print() print("They suck! BYE!") You should give some thought how unexpected user input like "", "123", "whatever" should be handled. > elif user_input == "no" : > print("\nAlrighty bye have a nice day! :)\n\nClosing in 10.") > import time > time.sleep(1) > import time > print("Closing in 9 ") > time.sleep(1) > import time > print("Closing in 8 ") > time.sleep(1) > import time OK, you are doing the count-down thing twice -- time to write a function, say countdown(), that you can put where you need a count-down instead of the repetetive code. -- https://mail.python.org/mailman/listinfo/python-list
Re: nested dictionaries and functions in data structures.
Thanks for that. I will have a play and see how I can apply your example. On 07/01/2014, at 11:19 PM, Jean-Michel Pichavant wrote: > - Original Message - >> Thanks for that. It resolved the issue and it was so simple compared >> to everything else I saw on the net. >> >> Only outstanding thing I have to work out is how to execute functions >> from a dictionary. I will continue searching on the net. >> >> >> Sean > > This may help you (untested code) > > class Workers: > @staticmethod > def ospf(*args, **kwargs): >print args, kwargs >return 'Bar' > > @staticmethod > def bhp(*args, **kwargs): >return 'Foo' > > outputs = {'ospf' : {1 : {'param1' : 'foo', 'param2' : 'foo2'}} > > for command, value in outputs.items(): > for counter, kwargs in value: >func = getattr(Workers, command) # get the function >func(**kwargs) # the actual call > > It would be possible to do it without the *args, **kwargs magic. You can > write ospf and bhp with the explicit parameters, however you must make sure > you pass the correct number of parameter in the call. > > JM > > > -- IMPORTANT NOTICE: > > The contents of this email and any attachments are confidential and may also > be privileged. If you are not the intended recipient, please notify the > sender immediately and do not disclose the contents to any other person, use > it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
AW: WebSocket for Python 2 and 3 on Twisted and asyncio
Autobahn now also supports asyncio on Python 2! https://github.com/tavendo/AutobahnPython#python-support This is made possible by Trollius, an awesome backport of asyncio: https://pypi.python.org/pypi/trollius/0.1.2 > -Ursprüngliche Nachricht- > Von: Python-list [mailto:python-list- > bounces+tobias.oberstein=tavendo...@python.org] Im Auftrag von Tobias > Oberstein > Gesendet: Freitag, 3. Januar 2014 13:08 > An: python-list@python.org > Betreff: WebSocket for Python 2 and 3 on Twisted and asyncio > > Hi, > > Autobahn provides open-source implementations of > > * The WebSocket Protocol > * The Web Application Messaging Protocol (WAMP) > > https://github.com/tavendo/AutobahnPython > https://pypi.python.org/pypi/autobahn > > Starting with the release 0.7.0, Autobahn now fully supports (with all > features) both > > * Twisted (on Python 2/3) and > * asyncio (on Python 3.3+) > > as the underlying networking framework. > > Here is a complete example of WebSocket server and client: > > Twisted: > https://github.com/tavendo/AutobahnPython/tree/master/examples/twist > ed/websocket/echo > > Asyncio: > https://github.com/tavendo/AutobahnPython/tree/master/examples/asyn > cio/websocket/echo > > The application code is very similar or even identical. > > Cheers, > /Tobias > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Kushal Kumaran writes: > Yes, but the documentation for utcnow explicitly tells you how to get > an aware object. > > "An aware current UTC datetime can be obtained by calling >datetime.now(timezone.utc)." And in Python 2.7 you can just copy the definition of utc from the doc and use that: from datetime import tzinfo, timedelta, datetime ZERO = timedelta(0) class UTC(tzinfo): """UTC""" def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO utc = UTC() -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- https://mail.python.org/mailman/listinfo/python-list
Re: Learning python networking
On Wed, 08 Jan 2014 19:49:40 -0800, Dan Stromberg wrote: > > The third quote, from Brian Kernighan, seems to underestimate the > complexity of asynchronous programming in the large - it's probably not > just twice as hard. Perhaps it should be rephrased as "at least twice as hard" It really does pay to follow the KISS (Keep It Simple Stupid) philosophy. -- Save energy: Drive a smaller shell. -- https://mail.python.org/mailman/listinfo/python-list
Re : Python GTK GUI struck when process is going on.
Hi all, I'm using python gtk to upload file to S3 service by boto API , GUI struck when uploading file and releases the GUI after completed download I'm using thread to show progress of upload in GUI but it struck. Can you some suggestion how to show progress of upload in GUI or any spinner until upload finish With Regards Prapulla Kumar R -- https://mail.python.org/mailman/listinfo/python-list
Re: Time zones and why they change so damned often
On Thu, 09 Jan 2014 07:17:25 +, Mark Lawrence wrote: > On 09/01/2014 04:14, Chris Angelico wrote: >> On Thu, Jan 9, 2014 at 2:54 PM, Ben Finney >> wrote: >>> I'm approaching it with the goal of knowing better what I'm talking >>> about when I advocate scrapping the whole DST system :-) >> >> I would definitely support the scrapping of DST. I'm less sure that we >> need exactly 24 timezones around the world, though. It's not nearly as >> big a problem to have the half-hour and quarter-hour timezones - >> though it would be easier if timezone were strictly an integer number >> of hours. But DST is the real pain. >> >> What I find, most of the time, is that it's Americans who can't handle >> DST. I run an international Dungeons and Dragons campaign (we play >> online, and new players are most welcome, as are people watching!), >> and the Aussies (myself included) know to check UTC time, the Brits and >> Europeans check UTC or just know what UTC is, and the Americans say >> "Doesn't that happen at 8 o'clock Eastern time?" and get confused. >> I don't understand this. Are my players drawn exclusively from the pool >> of people who've never worked with anyone in Arizona [1]? Yes, >> I'm stereotyping a bit here, and not every US player has had problems >> with this, but it's the occasional US player who knows to check, and >> the rare European, British, or Aussie player who doesn't. >> >> In any case, the world-wide abolition of DST would eliminate the >> problem. The only remaining problem would be reminding people to change >> the batteries in their smoke detectors. >> >> ChrisA >> >> [1] For those who aren't right up on timezone trivia, AZ has no DST. >> Similarly the Australian state of Queensland does not shift its clocks. >> >> > I remember this "From February 1968 to November 1971 the UK kept > daylight saving time throughout the year mainly for commercial reasons, > especially regarding time conformity with other European countries". My > source http://www.timeanddate.com/time/uk/time-zone-background.html we dont have "Daylight saving time" we switch between GMT (Greenwich Mean Time) and BST (British Summer Time) at some point in the past we have also used DST (Double Summer Time). -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Kushal Kumaran writes: > Ben Finney writes: > > > Kushal Kumaran writes: > > > >> Roy Smith writes: > >> > How, in Python, do you get an aware UTC datetime object? > >> > >> classmethod datetime.utcnow() > >> > >> Return the current UTC date and time, with tzinfo None. […] > > > > No, that won't do what was asked. The ‘datetime.datetime.utcnow’ > > function explicitly returns a naive datetime object, not an aware > > datetime object. > > Yes, but the documentation for utcnow explicitly tells you how to get > an aware object. > > "An aware current UTC datetime can be obtained by calling >datetime.now(timezone.utc)." And we come full circle: This is exactly what Roy's original question was (IIUC) trying to address. That process is not obvious, and it's not simple: it's a series of difficult-to-discover function calls instead of just one obvious one. -- \ “If you don't know what your program is supposed to do, you'd | `\ better not start writing it.” —Edsger W. Dijkstra | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Chris Angelico writes: > On Thu, Jan 9, 2014 at 2:34 PM, Ben Finney wrote: >> [ a bunch of stuff that I totally agree with ] > > No response needed here :) > > So I was wrong on the specific example of .today(), but asking the > question the other way is at least helpful. Maybe the best solution is > exactly what Roy already posted, or maybe there's some other way to > achieve that. In any case, there is a solution, albeit not as clean as > I would have liked. > >> With time zones, as with text encodings, there is a single technically >> elegant solution (for text: Unicode; for time zones: twelve simple, >> static zones that never change) > > Twelve or twenty-four? Or are you thinking we should all be an even > number of hours away from UTC, which would also work? Even 24 doesn't take into account DST. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
In article , Chris Angelico wrote: > What can you (Roy), with your use-case, achieve with datetime that > you can't achieve (at least reasonably easily) with a timestamp? As I'm mentioned several times, when you print a datetime, you get something that's human friendly. When you print a timestamp (i.e. a float), you get a lot of digits. I don't know about you, but I can't look at 1389274842 and get any feel for whether that was in the middle of the night or at 5 in the afternoon, near our peak traffic time. Nor can I tell if it was today, yesterday, last month, or a week from next Tuesday. Datetimes make it easy to do things like, "find the time of the preceding (or following) midnight". Or, "what month is this timestamp part of?" These are operations we need to do a lot, to answer questions like, "How many unique users did we have on a given day?", or "Which monthly database archive file do I need to grab to get information about this historical event?" Datetimes are self-documenting. If I'm in the python shell and have something called t, I can do help(t) or dir(t) to find out what operations it has. Datetimes are self-describing. If I have a datetime or a timedelta, I know what I've got. I've written more than one bug where I assumed a number somebody handed me was in seconds but it turned out to be in ms. That can never happen with a timedelta. We do a lot of stuff in javascript, where times are ms, so this is a common problem for us. Oh, and another thing I can do with a datetime that I can't do with a unix timestamp. I can represent the day I was born. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 1:06 AM, Piet van Oostrum wrote: > Chris Angelico writes: > >> On Thu, Jan 9, 2014 at 2:34 PM, Ben Finney >> wrote: >>> With time zones, as with text encodings, there is a single technically >>> elegant solution (for text: Unicode; for time zones: twelve simple, >>> static zones that never change) >> >> Twelve or twenty-four? Or are you thinking we should all be an even >> number of hours away from UTC, which would also work? > > Even 24 doesn't take into account DST. That was the point. We can abolish codepages by using Unicode, which covers everything. We could abolish time messes by having every locality settle permanently on one timezone; Ben's theory demands that all timezones be some integer number of hours +/- UTC, which IMO is optional, but mainly it should be easy to figure out any two locations' difference: just subtract one's UTC offset from the other's. Similarly, you can calculate the difference between two times at the same location by simple subtraction; currently, you also have to consider the possibility of a DST switch (from noon to noon across a switch is either 23 or 25 hours). Actually, the nearest parallel to Unicode is probably "use UTC everywhere", which makes for a superb internal representation and transmission format, but bugs most human beings :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
In article , Chris Angelico wrote: > Actually, the nearest parallel to Unicode is probably "use UTC > everywhere", which makes for a superb internal representation and > transmission format, but bugs most human beings :) It is, by the way, the solution that the aviation industry has adopted. All communication between aircraft and controllers is in UTC (pronounced "zulu"). Weather reports and forecasts are in UTC. Regulatory notices are in UTC. The time when one edition of a chart will be replaced by the next edition is in UTC. If I'm somewhere over the Atlantic, talking to a controller sitting in Shannon, Ireland, negotiating when I'm going to be allowed to continue on my route from New York to Istambul, the last thing I want is anybody to be confused about timezones. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
In article , Ben Finney wrote: > Kushal Kumaran writes: > > > Ben Finney writes: > > > > > Kushal Kumaran writes: > > > > > >> Roy Smith writes: > > >> > How, in Python, do you get an aware UTC datetime object? > > >> > > >> classmethod datetime.utcnow() > > >> > > >> Return the current UTC date and time, with tzinfo None. [â¦] > > > > > > No, that won't do what was asked. The âdatetime.datetime.utcnowâ > > > function explicitly returns a naive datetime object, not an aware > > > datetime object. > > > > Yes, but the documentation for utcnow explicitly tells you how to get > > an aware object. > > > > "An aware current UTC datetime can be obtained by calling > >datetime.now(timezone.utc)." > > And we come full circle: This is exactly what Roy's original question > was (IIUC) trying to address. That process is not obvious, and it's not > simple: it's a series of difficult-to-discover function calls instead of > just one obvious one. Yes, exactly. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 1:14 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> What can you (Roy), with your use-case, achieve with datetime that >> you can't achieve (at least reasonably easily) with a timestamp? Thanks for this collection! Now we can discuss. > As I'm mentioned several times, when you print a datetime, you get > something that's human friendly. When you print a timestamp (i.e. a > float), you get a lot of digits. I don't know about you, but I can't > look at 1389274842 and get any feel for whether that was in the middle > of the night or at 5 in the afternoon, near our peak traffic time. Nor > can I tell if it was today, yesterday, last month, or a week from next > Tuesday. Sure. There is a lot of value in having a class that knows how it should be displayed. I'm not sure the current datetime repr is good for anything more than debugging, but I agree that "datetime.datetime(2014, 1, 9, 5, 57, 59, 929176)" is more likely to be useful than a raw number. > Datetimes make it easy to do things like, "find the time of the > preceding (or following) midnight". Or, "what month is this timestamp > part of?" These are operations we need to do a lot, to answer questions > like, "How many unique users did we have on a given day?", or "Which > monthly database archive file do I need to grab to get information about > this historical event?" That's true; the same operations done with timestamps look like this: >>> ts = time.time() >>> ts_at_midnight_utc = ts - ts%86400 >>> ts_at_midnight_utc 1389225600.0 Not nearly as obvious what's happening. And months are more complicated still, so it's probably easiest to use strftime: >>> time.strftime("%Y%m",time.gmtime(ts)) '201401' which could then be used as a lookup key for a counter or whatever. Yep, that's not as clean as simply calling a method. > Datetimes are self-documenting. If I'm in the python shell and have > something called t, I can do help(t) or dir(t) to find out what > operations it has. Partly true, but not everything's there. For instance, if you have a list of strings, you won't find a way to join them together in its help() or dir(), and yet it's a fundamental and very important operation. > Datetimes are self-describing. If I have a datetime or a timedelta, I > know what I've got. I've written more than one bug where I assumed a > number somebody handed me was in seconds but it turned out to be in ms. > That can never happen with a timedelta. We do a lot of stuff in > javascript, where times are ms, so this is a common problem for us. Sure. Though that's no different from other cases where you need out-of-band information to understand something, as we've just been discussing in the threads about text handling - if you have a puddle of bytes, you can't decode them to text without knowing what the encoding is. [1] If your data's coming from JS, it won't be a timedelta, it'll be a number; at some point you have to turn that into a timedelta object, so you still have the same problem. > Oh, and another thing I can do with a datetime that I can't do with a > unix timestamp. I can represent the day I was born. Maybe you can't with the original C definition of time_t as an unsigned integer, but the notion of a Unix timestamp can plausibly be extended (a) to negative numbers, and (b) to non-integers. Python definitely does the latter; its ability to do the former depends somewhat on the underlying C library's support: Windows: >>> time.strftime("%Y%m",time.gmtime(-10)) Traceback (most recent call last): File "", line 1, in time.strftime("%Y%m",time.gmtime(-10)) OSError: [Errno 22] Invalid argument Linux: >>> time.strftime("%Y%m",time.gmtime(-10)) '196912' >>> time.strftime("%Y%m",time.gmtime(-2**31)) '190112' >>> time.strftime("%Y%m",time.gmtime(-2**31-1)) Traceback (most recent call last): File "", line 1, in ValueError: timestamp out of range for platform time_t So what I'm seeing here is that the direct use of a time_t will cover everything in an ugly way, but that a class wrapping it up could fix that. And fundamentally, the only problem with datetime (which, for the most part, is exactly that wrapper) is that it's unobvious how to get a simple UTC timestamp. Has the unobviousness been solved by a simple recipe? And if so, should that tip be added to the datetime module docs somewhere? ChrisA [1] Yes, I said "puddle of bytes". What would you call it? Am interested to hear! -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Thu, 09 Jan 2014 09:14:22 -0500, Roy Smith wrote: > Oh, and another thing I can do with a datetime that I can't do with a > unix timestamp. I can represent the day I was born. At the risk of dating myself, the day I was born is -231094800. Dan -- https://mail.python.org/mailman/listinfo/python-list
Re: Re : Python GTK GUI struck when process is going on.
On 2014-01-09 11:53, Prapulla Kumar wrote: Hi all, I'm using python gtk to upload file to S3 service by boto API , GUI struck when uploading file and releases the GUI after completed download I'm using thread to show progress of upload in GUI but it struck. Can you some suggestion how to show progress of upload in GUI or any spinner until upload finish You say that you're using a thread to show the progress. Does that mean that you're doing the uploading in the main thread? If yes, then that's the wrong way round. It's the uploading that needs to be done in the background thread. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 2:01 AM, Dan Sommers wrote: > On Thu, 09 Jan 2014 09:14:22 -0500, Roy Smith wrote: > >> Oh, and another thing I can do with a datetime that I can't do with a >> unix timestamp. I can represent the day I was born. > > At the risk of dating myself, the day I was born is -231094800. Which, according to a Unix build of Python, is quite representable: >>> time.strftime("%Y-%m-%d",time.gmtime(-231094800)) '1962-09-05' This isn't a problem. Now, if you were considering yourself for a romantic candle-lit dinner and a movie afterward, then maybe there's some risk in dating yourself :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: argparse action on default values
On Thu, Jan 9, 2014 at 5:20 AM, Florian Lindner wrote: > def norm_path(*parts): > """ Returns the normalized, absolute, expanded and joined path, assembled > of all parts. """ > parts = [ str(p) for p in parts ] > return os.path.abspath(os.path.expanduser(os.path.join(*parts))) Apologies for responding to something that's not the point of your post, but I see this as a job for map, rather than a list comp: def norm_path(*parts): """ Returns the normalized, absolute, expanded and joined path, assembled of all parts. """ path = os.path.join(*map(str,parts)) return os.path.abspath(os.path.expanduser(path)) (or completely onelinered, since you don't seem to mind longish lines). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Editor for Python
On Friday, 23 November 2001 04:13:40 UTC+5:30, MANUEL FERNANDEZ PEREZ wrote: > > Hello, > > I'm looking for an editor for Python.I' m interested it works on > Windows.Can > > anybody help me? > It's an IDE rather than "just" an editor but how about PyCharm 3 Community Edition? [1] [1] https://www.jetbrains.com/pycharm/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Time zones and why they change so damned often (was: the Gravity of Python 2)
On Thu, 9 Jan 2014 15:14:55 +1100, Chris Angelico wrote: [1] For those who aren't right up on timezone trivia, AZ has no DST. Similarly the Australian state of Queensland does not shift its clocks. And Indiana. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Editor for Python
- Original Message - > > On Jan 8, 2014, at 10:53 AM, Jean-Michel Pichavant > wrote: > > >>> -- IMPORTANT NOTICE: > >>> > >> > >> too late you have sent this to a public forum > > > > No pb with that, the python list is the intended recipient :) > > > > I tried to negotiate this with my IT guys, but it looks like it's > > now mandatory, something related to being in the USA stock market. > Yeah, when in doubt blame the Americans. Sorry if I hurt your feelings, have a look at http://www.sarbanes-oxley-101.com/ I don't blame anyone, would I be blaming the law, that wouldn't imply the americans anyway. cheers, JM "The Sarbanes-Oxley Act of 2002, sponsored by Paul Sarbanes and Michael Oxley, represents a huge change to federal securities law. It came as a result of the corporate financial scandals involving Enron, WorldCom and Global Crossing. Effective in 2006, all publicly-traded companies are required to implement and report internal accounting controls to the SEC for compliance." -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Is email.parser a good replacement for formail?
Hi, I have a script (https://github.com/mcepl/gg_scraper) where I need to read possibly malformed mbox messages. I use subprocess.Popen() and /usr/bin/formail to clean up them to be correct mbox messages (with correct leading From line etc.). Now I try to run tests for my script on Travis-CI, where I don't have installed formail. Actually, I learned now that I can run apt-get install procmail in .travis.yml. But still, I started to think whether I couldn’t fix my script to be purely Pythonic. I know that msg = email.message_from_string(original_msg) print(msg.as_string(unixfrom=True)) works as a poor-man’s replacement for `formail -d`. Now, I would like to know how reliable replacement it is. Does anybody have (or know about) a corpus of poorly formatted messages which can be fixed by formail to test upon it? Thanks a lot for any reply, Matěj -- http://www.ceplovi.cz/matej/, Jabber: mc...@ceplovi.cz GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC Less is more or less more. -- Y_Plentyn on #LinuxGER (from fortunes -- I cannot resist :-) signature.asc Description: OpenPGP digital signature -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Thursday, January 9, 2014 9:57:57 AM UTC-5, Chris Angelico wrote: > And months are more > complicated still, so it's probably easiest to use strftime: > > >>> time.strftime("%Y%m",time.gmtime(ts)) > > '201401' strftime is a non-starter at far as "easy" goes. I don't know about you, but I certainly haven't memorized the table of all the format specifiers. Is month "m" or "M"? What's "%U" or "%B". Every time I use strftime, I have to go pull up the docs and read the table. Not to mention that "%z" is not available on all platforms, and "%s" (which is incredibly useful) is not even documented (I suspect it's also not available on all platforms). > So what I'm seeing here is that the direct use of a time_t will cover > everything in an ugly way, but that a class wrapping it up could fix > that. And fundamentally, the only problem with datetime (which, for > the most part, is exactly that wrapper) is that it's unobvious how to > get a simple UTC timestamp. > > Has the unobviousness been solved by a simple recipe? And if so, > should that tip be added to the datetime module docs somewhere? No, it would be solved by a built-in method. Recipes are a cop-out. If something is complicated enough to require a recipe, and used frequently enough to be worth writing that recipe up and documenting it, you might as well have gone the one additional step and made it a method. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 16:21, Roy Smith wrote: No, it would be solved by a built-in method. Recipes are a cop-out. If something is complicated enough to require a recipe, and used frequently enough to be worth writing that recipe up and documenting it, you might as well have gone the one additional step and made it a method. So all of the itertools recipes should be part of the Python module and not in more-itertools on pypi? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 16:30, Mark Lawrence wrote: > On 09/01/2014 16:21, Roy Smith wrote: >> >> No, it would be solved by a built-in method. Recipes are a cop-out. >> If something is complicated enough to require a recipe, and used >> frequently enough to be worth writing that recipe up and documenting >> it, you might as well have gone the one additional step and made it a >> method. >> > > So all of the itertools recipes should be part of the Python module and > not in more-itertools on pypi? To be fair, Mark, it's a matter of taste. Raymond [the author/maintainer of itertools] prefers not to multiply the API; other developers might legitimately make other calls. Sometimes the cut-off is more obvious; say, when the effort to make a recipe general purpose creates an over-engineered API. Other times it's just preference. Does that mean that every recipe ever conceived should be stuffed into the class or module it uses? No; but it doesn't rule out adding things which are genuinely useful. I think the new statistics module has hit a nice balance on its initial release: it's a stripped down aesthetic without precluding later additions. TJG -- https://mail.python.org/mailman/listinfo/python-list
RE: the Gravity of Python 2
> and "%s" (which is incredibly useful) is not even documented (I suspect it's > also not available on all platforms). The format specifiers available to Python are just whatever is available to the underlying c time.h. The manpage for strftime indicates that %s isn't part of the C standard, but part of "Olson's timezone package", which means it's not available on Windows. Your suspicion is unfortunately correct. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 16:42, Nick Cash wrote: and "%s" (which is incredibly useful) is not even documented (I suspect it's also not available on all platforms). The format specifiers available to Python are just whatever is available to the underlying c time.h. The manpage for strftime indicates that %s isn't part of the C standard, but part of "Olson's timezone package", which means it's not available on Windows. Your suspicion is unfortunately correct. Methinks http://www.python.org/dev/peps/pep-0431/ Time zone support improvements may be of interest here. Still at draft issue unfortunately. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 01/09/2014 12:42 AM, Mark Lawrence wrote: On 09/01/2014 01:27, Roy Smith wrote: Naive datetimes are what everybody uses. It's what utcnow() gives you. So why make life difficult for everybody? Python 3 didn't win a convert today. Yep, dates and times are easy. That's why there are 17 issues open on the bug tracker referencing tzinfo alone. Poor old 1100942 is high priority, was created 12/01/2005 and has missed 3.4. So if it gets into 3.5 it'll have already celebrated its 10th birthday. It doesn't say much for the amount of effort that we put into looking after issues. Mark, I hope you are addressing the community at large and not the core-devs. There are only so many of us, with limited time available. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
Chris Angelico writes: > On Fri, Jan 10, 2014 at 1:06 AM, Piet van Oostrum wrote: >> Chris Angelico writes: >> >>> On Thu, Jan 9, 2014 at 2:34 PM, Ben Finney >>> wrote: With time zones, as with text encodings, there is a single technically elegant solution (for text: Unicode; for time zones: twelve simple, static zones that never change) >>> >>> Twelve or twenty-four? Or are you thinking we should all be an even >>> number of hours away from UTC, which would also work? >> >> Even 24 doesn't take into account DST. > > That was the point. We can abolish codepages by using Unicode, which > covers everything. We could abolish time messes by having every > locality settle permanently on one timezone; Ben's theory demands that > all timezones be some integer number of hours +/- UTC, which IMO is > optional, but mainly it should be easy to figure out any two > locations' difference: just subtract one's UTC offset from the > other's. Similarly, you can calculate the difference between two times > at the same location by simple subtraction; currently, you also have > to consider the possibility of a DST switch (from noon to noon across > a switch is either 23 or 25 hours). > > Actually, the nearest parallel to Unicode is probably "use UTC > everywhere", which makes for a superb internal representation and > transmission format, but bugs most human beings :) I don't know how other countries do it, but here, when the clock goes back, it goes from 03:00 to 02:00. So I wonder how they communicate when your plane leaves at 02:30 in that night. Which 02:30? In that case using UTC may come out handy, if it would be understood. Or do the planes just stop leaving during that interval? Not that there will be many leaving during that time in general, I presume. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 01/09/2014 06:57 AM, Chris Angelico wrote: On Fri, Jan 10, 2014 at 1:14 AM, Roy Smith wrote: Thanks for this collection! Now we can discuss. [snip] Datetimes are self-describing. If I have a datetime or a timedelta, I know what I've got. I've written more than one bug where I assumed a number somebody handed me was in seconds but it turned out to be in ms. That can never happen with a timedelta. We do a lot of stuff in javascript, where times are ms, so this is a common problem for us. Sure. Though that's no different from other cases where you need out-of-band information to understand something, as we've just been discussing in the threads about text handling - if you have a puddle of bytes, you can't decode them to text without knowing what the encoding is. [1] If your data's coming from JS, it won't be a timedelta, it'll be a number; at some point you have to turn that into a timedelta object, so you still have the same problem. Yup, and you do at the boundary instead of having a float wandering through your code with an easily forgotten meta-data type. So what I'm seeing here is that the direct use of a time_t will cover everything in an ugly way, but that a class wrapping it up could fix that. And fundamentally, the only problem with datetime (which, for the most part, is exactly that wrapper) is that it's unobvious how to get a simple UTC timestamp. It has at least one other problem: bool(midnight) == False. -- ~Ethan~ [1] Yes, I said "puddle of bytes". What would you call it? Am interested to hear! I think that's a perfect name! :) -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
I wrote: > Recipes are a cop-out On Thursday, January 9, 2014 11:30:31 AM UTC-5, Mark Lawrence wrote: > So all of the itertools recipes should be part of the Python module and > not in more-itertools on pypi? Certainly, the recipes that are documented on the official itertools page, yes. -- https://mail.python.org/mailman/listinfo/python-list
Re: Bytes indexing returns an int
Ned Batchelder writes: > On 1/8/14 11:08 AM, wxjmfa...@gmail.com wrote: >> Byte strings (encoded code points) or native unicode is one >> thing. >> >> But on the other side, the problem is elsewhere. These very >> talented ascii narrow minded, unicode illiterate devs only >> succeded to produce this (I, really, do not wish to be rude). > > If you don't want to be rude, you are failing. You've been told a > number of times that your obscure micro-benchmarks are meaningless. Now > you've taken to calling the core devs narrow-minded and Unicode > illiterate. They are neither of these things. > > Continuing to post these comments with no interest in learning is rude. > Other recent threads have contained details rebuttals of your views, > which you have ignored. This is rude. Please stop. Please ignore jmf's repeated nonsense. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- https://mail.python.org/mailman/listinfo/python-list
Re: Bytes indexing returns an int
On 01/09/2014 09:05 AM, Piet van Oostrum wrote: Ned Batchelder writes: On 1/8/14 11:08 AM, wxjmfa...@gmail.com wrote: Byte strings (encoded code points) or native unicode is one thing. But on the other side, the problem is elsewhere. These very talented ascii narrow minded, unicode illiterate devs only succeded to produce this (I, really, do not wish to be rude). If you don't want to be rude, you are failing. You've been told a number of times that your obscure micro-benchmarks are meaningless. Now you've taken to calling the core devs narrow-minded and Unicode illiterate. They are neither of these things. Continuing to post these comments with no interest in learning is rude. Other recent threads have contained details rebuttals of your views, which you have ignored. This is rude. Please stop. Please ignore jmf's repeated nonsense. Or ban him. His one, minor, contribution has been completely swamped by the rest of his belligerent, unfounded, refuted posts. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 16:01, Ethan Furman wrote: On 01/09/2014 12:42 AM, Mark Lawrence wrote: On 09/01/2014 01:27, Roy Smith wrote: Naive datetimes are what everybody uses. It's what utcnow() gives you. So why make life difficult for everybody? Python 3 didn't win a convert today. Yep, dates and times are easy. That's why there are 17 issues open on the bug tracker referencing tzinfo alone. Poor old 1100942 is high priority, was created 12/01/2005 and has missed 3.4. So if it gets into 3.5 it'll have already celebrated its 10th birthday. It doesn't say much for the amount of effort that we put into looking after issues. Mark, I hope you are addressing the community at large and not the core-devs. There are only so many of us, with limited time available. -- ~Ethan~ As I'm not a core dev to whom do you think I'm referring? I'm aware that the high horse I get on about this is so tall that you'll need an oxygen supply to survive should you want to sit on it, but to me this is easily the worst aspect of the Python community as a whole. If every regular contributor to this list was to fix even one bug a week the figures would look rather better. Still, you can no more enforce that than you can enforce the core devs working on Python 2.8 :) Talking of which, have we got a PEP for that yet, or are the whingers still simply in whinging mode? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 09/01/2014 17:07, Roy Smith wrote: I wrote: Recipes are a cop-out On Thursday, January 9, 2014 11:30:31 AM UTC-5, Mark Lawrence wrote: So all of the itertools recipes should be part of the Python module and not in more-itertools on pypi? Certainly, the recipes that are documented on the official itertools page, yes. No thank you, I don't want the Python docs getting anywhere near the size of their Java equivalents. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 01/09/2014 10:18 AM, Mark Lawrence wrote: On 09/01/2014 16:01, Ethan Furman wrote: On 01/09/2014 12:42 AM, Mark Lawrence wrote: On 09/01/2014 01:27, Roy Smith wrote: Naive datetimes are what everybody uses. It's what utcnow() gives you. So why make life difficult for everybody? Python 3 didn't win a convert today. Yep, dates and times are easy. That's why there are 17 issues open on the bug tracker referencing tzinfo alone. Poor old 1100942 is high priority, was created 12/01/2005 and has missed 3.4. So if it gets into 3.5 it'll have already celebrated its 10th birthday. It doesn't say much for the amount of effort that we put into looking after issues. Mark, I hope you are addressing the community at large and not the core-devs. There are only so many of us, with limited time available. As I'm not a core dev to whom do you think I'm referring? Cool, just double-checking. :) Still, you can no more enforce that than you can enforce the core devs working on Python 2.8 :) Talking of which, have we got a PEP for that yet. . . As a matter of fact. It's called PEP 404. ;) -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On 01/09/2014 10:20 AM, Mark Lawrence wrote: On Thursday, January 9, 2014 11:30:31 AM UTC-5, Mark Lawrence wrote: So all of the itertools recipes should be part of the Python module and not in more-itertools on pypi? Certainly, the recipes that are documented on the official itertools page, yes. No thank you, I don't want the Python docs getting anywhere near the size of their Java equivalents. To be fair, the recipes on the itertools page are there so that minor changes can be made (flavor to taste, so to speak) to get exactly the semantics needed by the individual programmer. With the timezone stuff we're looking for The One Obvious Way, which should be a method, not a recipe. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Bytes indexing returns an int
09.01.14 19:28, Ethan Furman написав(ла): On 01/09/2014 09:05 AM, Piet van Oostrum wrote: Please ignore jmf's repeated nonsense. Or ban him. His one, minor, contribution has been completely swamped by the rest of his belligerent, unfounded, refuted posts. Please not. I have a fun from every his appearance. -- https://mail.python.org/mailman/listinfo/python-list
unicode troubles and postgres
So I'm working with postgres, and I get a datadump which I try to restore to my test system, and I get this: ERROR: value too long for type character varying(4) CONTEXT: COPY res_currency, line 32, column symbol: "руб" "py6" sure looks like it should fit, but it don't. Further investigation revealed that "py6" is made up of the bytes d1 80 d1 83 d0 b1. Any ideas on what that means, exactly? -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode troubles and postgres
Ethan Furman wrote: > So I'm working with postgres, and I get a datadump which I try to restore > to my test system, and I get this: > > ERROR: value too long for type character varying(4) > CONTEXT: COPY res_currency, line 32, column symbol: "руб" > > "py6" sure looks like it should fit, but it don't. Further investigation > revealed that "py6" is made up of the bytes d1 80 d1 83 d0 b1. > > Any ideas on what that means, exactly? It may look like the ascii "py6", but you have three cyrillic letters: >>> import unicodedata as ud >>> [ud.name(c) for c in u"руб"] ['CYRILLIC SMALL LETTER ER', 'CYRILLIC SMALL LETTER U', 'CYRILLIC SMALL LETTER BE'] The dump you are seeing are the corresponding bytes in UTF-8: >>> u"руб".encode("utf-8") '\xd1\x80\xd1\x83\xd0\xb1' So postgres may be storing the string as utf-8. -- https://mail.python.org/mailman/listinfo/python-list
Re: Constructive Criticism
On Thursday, January 9, 2014 3:56:37 AM UTC-6, Peter Otten wrote: > jeremiahvalerio...@gmail.com wrote: > > > > > Hi, hows it going I've been self teaching myself python, and i typed up > > > this small script now i know its not the best the coding is not the best > > > but i would like to know of ways to make a small script like this better > > > so all constructive critisim is Welcome. > > > > > > > > > > > > Here is the link to the code > > > > > >" http://pastebin.com/5uCFR2pz " > > > > > time.sleep(1) > > > import time > > > print("Closing in 9 ") > > > time.sleep(1) > > > import time > > > print("Closing in 8 ") > > > > - You should import modules just once, at the beginning of your script. > > > > - Repetetive tasks are best handled with a for-loop, e. g.: > > > > >>> import time > > >>> for seconds_left in reversed(range(1, 10)): > > ... print("Closing in", seconds_left, "seconds") > > ... time.sleep(1) > > ... > > Closing in 9 seconds > > Closing in 8 seconds > > Closing in 7 seconds > > Closing in 6 seconds > > Closing in 5 seconds > > Closing in 4 seconds > > Closing in 3 seconds > > Closing in 2 seconds > > Closing in 1 seconds > > > > > user_input = input("\nWhos your favorite Football team? \n 1.Arizona > > > Cardinals\n 2.Atlanta Falcons\n 3.Baltimore Ravens\n 4.Buffalo Bills\n > > > 5.Miami Dolphins\n 6.Minnesota Vikings \n 7.New England Patriots \n > > > 8.New Orleans Saints \n 9.Carolina > > [snip] > > > > Python offers triple-quoted strings which may include newline literals: > > > > user_input = input(""" > > Who's your favorite Football team? > > 1. Arizona Cardinals > > 2. Atlanta Falcons > > ... > > """) > > > > > if user_input == "1" : > > > print("\nThey suck! BYE!") > > > > > > elif user_input == "2" : > > > print("\nThey suck! BYE!") > > > > > > elif user_input == "3" : > > > print("\nThey suck!BYE!") > > [snip] > > > > Ignoring the typos you are taking the same action for all inputs but "17". > > So: > > > > if user_input != "17": > > print() > > print("They suck! BYE!") > > > > You should give some thought how unexpected user input like "", "123", > > "whatever" should be handled. > > > > > elif user_input == "no" : > > > print("\nAlrighty bye have a nice day! :)\n\nClosing in 10.") > > > import time > > > time.sleep(1) > > > import time > > > print("Closing in 9 ") > > > time.sleep(1) > > > import time > > > print("Closing in 8 ") > > > time.sleep(1) > > > import time > > > > OK, you are doing the count-down thing twice -- time to write a function, > > say countdown(), that you can put where you need a count-down instead of the > > repetetive code. Thanks so much,exactly what i was looking for thanks for taking the time. -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 3:21 AM, Roy Smith wrote: > On Thursday, January 9, 2014 9:57:57 AM UTC-5, Chris Angelico wrote: >> And months are more >> complicated still, so it's probably easiest to use strftime: >> >> >>> time.strftime("%Y%m",time.gmtime(ts)) >> >> '201401' > > strftime is a non-starter at far as "easy" goes. I don't know about you, but > I certainly haven't memorized the table of all the format specifiers. Is > month "m" or "M"? What's "%U" or "%B". Every time I use strftime, I have to > go pull up the docs and read the table. Not to mention that "%z" is not > available on all platforms, and "%s" (which is incredibly useful) is not even > documented (I suspect it's also not available on all platforms). > Have you ever used a regular expression? Does it bother you that both percent-formatting and str.format() have compact/cryptic mini-languages? Why is it a problem to have a mini-language for formatting dates? It at least follows a measure of common sense, unlike the PHP date function. In fact, I've given end users the ability to enter strftime strings (eg to construct a filename), and it's worked just fine. *Non-programmers* can figure them out without much difficulty. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode troubles and postgres [SOLVED]
On 01/09/2014 10:49 AM, Ethan Furman wrote: So I'm working with postgres, and I get a datadump which I try to restore to my test system, and I get this: ERROR: value too long for type character varying(4) CONTEXT: COPY res_currency, line 32, column symbol: "руб" "py6" sure looks like it should fit, but it don't. Further investigation revealed that "py6" is made up of the bytes d1 80 d1 83 d0 b1. Any ideas on what that means, exactly? For the curious, it means CYRILLIC SMALL LETTER ER, CYRILLIC SMALL LETTER U, CYRILLIC CAPITAL LETTER IE WITH GRAVE in utf-8 format. The problem was I had created the database from template0 instead of template1, and 0 is SQL-ASCII while 1 is UTF8. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 3:51 AM, Piet van Oostrum wrote: > I don't know how other countries do it, but here, when the clock goes back, > it goes from 03:00 to 02:00. So I wonder how they communicate when your plane > leaves at 02:30 in that night. Which 02:30? In that case using UTC may come > out handy, if it would be understood. Or do the planes just stop leaving > during that interval? Not that there will be many leaving during that time in > general, I presume. > The fundamental is that the timezone changes. Times roll from 02:00 Daylight time through 02:30 Daylight time to the instant before 03:00 Daylight time, which doesn't happen, and instead time jumps to 02:00 Standard time and starts rolling forward. How this is adequately communicated on the plane ticket is a separate issue, though, and as I've never actually flown during a DST changeover, I wouldn't know. I'm sure there would be planes departing during those two hours (neither airlines nor airports can afford to have two, or even one, "dead" hour!), so this must have been solved somehow. Maybe people could figure it out from the "check-in by" time? For instance, last time I flew, the plane departed at 0240 local time (but this was in July, so not anywhere near changeover), and check-in opened at 2340; so if it were the "other" 0240, then check-in would have opened at 0040 instead. Either that, or they'll tell everyone to arrive in time for the first instance of that time, and then just make us all wait around for an extra hour ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Constructive Criticism
On 01/08/2014 11:56 PM, jeremiahvalerio...@gmail.com wrote: Hi, hows it going I've been self teaching myself python, and i typed up this small script now i know its not the best the coding is not the best but i would like to know of ways to make a small script like this better so all constructive critisim is Welcome. Here is the link to the code " http://pastebin.com/5uCFR2pz " I'm not sure if someone already pointed this out, but imports only need to be done once. Usually at the beginning of the file, but not always. In your case I would say yes, at the beginning. import sys import time def countdown(seconds):' # start at 'seconds' and count down with a for-loop for i in range(seconds, 0, -1): # print the current second (i) print('closing in {} seconds.'.format(i)) # sleep for one second (no need to import time again). time.sleep(1) # Example usage: print('hello') # Prints the countdown. countdown(10) sys.exit(0) -- - Christopher Welborn http://welbornprod.com -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode troubles and postgres [SOLVED]
On Fri, Jan 10, 2014 at 6:51 AM, Ethan Furman wrote: > The problem was I had created the database from template0 instead of > template1, and 0 is SQL-ASCII while 1 is UTF8. Ah, this is one of the traps with Postgres. This is one of the reasons I prefer not to touch template[01] and to script the initialization of a new database - any config changes are committed to source control as part of that script. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Thursday, January 9, 2014 3:35:05 PM UTC-5, Chris Angelico wrote: > In fact, I've given end users the ability to enter strftime strings (eg > to construct a filename), and it's worked just fine. I assume you realize that "../../../../../../../../../../../../../../../../etc/passwd" is a valid strftime() format specifier? :-) But, to answer your question, no, I have nothing against small languages, per-se (and I've done plenty of regex work). But, if my goal is to print a time in some human-readable form: >>> print t is a lot easier than anything involving strftime(). -- https://mail.python.org/mailman/listinfo/python-list
Re: Constructive Criticism
On Thursday, January 9, 2014 2:54:44 PM UTC-6, Christopher Welborn wrote: > On 01/08/2014 11:56 PM, jeremiahvalerio...@gmail.com wrote: > > > Hi, hows it going I've been self teaching myself python, and i typed up > > this small script now i know its not the best the coding is not the best > > but i would like to know of ways to make a small script like this better so > > all constructive critisim is Welcome. > > > > > > > > > > > > Here is the link to the code > > > > > > " http://pastebin.com/5uCFR2pz " > > > > > > > I'm not sure if someone already pointed this out, but imports only need > > to be done once. Usually at the beginning of the file, but not always. > > In your case I would say yes, at the beginning. > > > > import sys > > import time > > > > def countdown(seconds):' > > # start at 'seconds' and count down with a for-loop > > for i in range(seconds, 0, -1): > > # print the current second (i) > > print('closing in {} seconds.'.format(i)) > > # sleep for one second (no need to import time again). > > time.sleep(1) > > > > # Example usage: > > print('hello') > > # Prints the countdown. > > countdown(10) > > sys.exit(0) > > -- > > > > - Christopher Welborn > >http://welbornprod.com Mr.Peter Otten did "- You should import modules just once, at the beginning of your script. " -Peter Otten With his help this is what i have now def countdown(): import time for seconds_left in reversed(range(1, 10)): print("Closing in", seconds_left, "seconds") time.sleep(1) exit() if user_input == "yes" : user_input = input("\nGreat what should we talk about?\nSports\nWeather") elif user_input == "no" : print("\nAlrighty bye have a nice day! :)\n\nClosing in 10.") countdown() -- https://mail.python.org/mailman/listinfo/python-list
Re: the Gravity of Python 2
On Fri, Jan 10, 2014 at 7:54 AM, Roy Smith wrote: > On Thursday, January 9, 2014 3:35:05 PM UTC-5, Chris Angelico wrote: >> In fact, I've given end users the ability to enter strftime strings (eg >> to construct a filename), and it's worked just fine. > > I assume you realize that > "../../../../../../../../../../../../../../../../etc/passwd" is a valid > strftime() format specifier? :-) Yes, and since this was for the creation of a log file by an unprivileged process, that would simply fail :) Though the specific case I'm thinking of here was on Windows, so you could probably find an equivalent filename (it didn't prevent absolute names, so you could just stuff whatever you want in) and shoot yourself in the foot big-time. It's the user's own system, let him make a mess of it if he wants :) > But, to answer your question, no, I have nothing against small languages, > per-se (and I've done plenty of regex work). But, if my goal is to print a > time in some human-readable form: > print t > > is a lot easier than anything involving strftime(). Sure, it's easier. But there are plenty of types that don't provide a particularly useful repr - regexes being one that only recently changed: 2.7 and 3.3: >>> re.compile(r"(.)\1\1\1") <_sre.SRE_Pattern object at 0x012464F0> >>> _.search("This is a test string with a quaduple letter in it!") <_sre.SRE_Match object at 0x012C3EE0> 3.4: >>> re.compile(r"(.)\1\1\1") re.compile('(.)\\1\\1\\1') >>> _.search("This is a test string with a quaduple letter in it!") <_sre.SRE_Match object; span=(33, 37), match=''> Would you avoid using regexes in anything less than 3.4 simply because of this lack of repr? It's a convenience, not a deal-breaker. (Or if you disagree with me on that point, you're cutting out a lot of very useful types.) It's not hard to call time.ctime(ts) or strftime(...) for display; the big loser is the interactive interpreter, where a good repr is everything. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Editor for Python
On Thu, Jan 9, 2014 at 10:50 AM, Jean-Michel Pichavant wrote: > - Original Message - >> >> On Jan 8, 2014, at 10:53 AM, Jean-Michel Pichavant >> wrote: >> > I tried to negotiate this with my IT guys, but it looks like it's >> > now mandatory, something related to being in the USA stock market. >> Yeah, when in doubt blame the Americans. > > Sorry if I hurt your feelings, have a look at > http://www.sarbanes-oxley-101.com/ You didn't. I was just having fun. However, I couldn't find anything at that site which referred to email disclaimers. It seems to me that this sort of thing has gone out of style. It was more common ten years ago. However, I won't waste any more time arguing the point. > > I don't blame anyone, would I be blaming the law, that wouldn't imply the > americans anyway. > > cheers, > JM -- https://mail.python.org/mailman/listinfo/python-list
Monkeypatching a staticmethod?
This is kind of surprising. I'm running Python 2.7.1. I've got a class with a staticmethod that I want to monkeypatch with a lambda: -- class Foo: @staticmethod def x(): return 1 Foo.x = lambda: 2 print Foo.x() -- What's weird is that it seems to remember that x is a staticmethod despite having been patched: Traceback (most recent call last): File "static.py", line 8, in Foo.x() TypeError: unbound method () must be called with Foo instance as first argument (got nothing instead) What seems to work is to patch it with another staticmethod: -- class Foo: @staticmethod def x(): return 1 @staticmethod def x(): return 2 Foo.x = x print Foo.x() -- $ python static.py 2 I didn't even know you could define a staticmethod outside of a class! I suspect this post is really just my way of admitting that while I've used staticmethods plenty, I've never fully understood the details of what happens when you construct them :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Re : Python GTK GUI struck when process is going on.
On 01/09/2014 08:15 AM, MRAB wrote: > On 2014-01-09 11:53, Prapulla Kumar wrote: >> Hi all, >> I'm using python gtk to upload file to S3 service by boto API , >> GUI struck when uploading file and releases the GUI after completed download >> I'm using thread to show progress of upload in GUI but it struck. >> Can you some suggestion how to show progress of upload in GUI or any >> spinner until upload finish >> > You say that you're using a thread to show the progress. Does that mean > that you're doing the uploading in the main thread? > > If yes, then that's the wrong way round. It's the uploading that needs > to be done in the background thread. And you can post update messages from the thread using a queue of some kind. The GUI just has to have a timeout that checks the queue and updates the gui with messages (percent complete, bytes transferred, etc). Or have the thread use gobject.idle_add to schedule a callback in the main thread that will check on the upload status and update the GUI. -- https://mail.python.org/mailman/listinfo/python-list
Re: Monkeypatching a staticmethod?
On Thu, Jan 9, 2014 at 10:23 PM, Roy Smith wrote: > This is kind of surprising. I'm running Python 2.7.1. I've got a class > with a staticmethod that I want to monkeypatch with a lambda: > > -- > class Foo: > @staticmethod > def x(): > return 1 > > Foo.x = lambda: 2 > print Foo.x() > -- > > What's weird is that it seems to remember that x is a staticmethod > despite having been patched: > > Traceback (most recent call last): > File "static.py", line 8, in > Foo.x() > TypeError: unbound method () must be called with Foo instance as > first argument (got nothing instead) No, if it were still a staticmethod then the call would work without error. That error is the same that you would get in Python 2 if you defined the function directly in the class without the staticmethod decorator. (In Python 3 the call succeeds as long as it's made from the class and not from an instance). > What seems to work is to patch it with another staticmethod: > > -- > class Foo: > @staticmethod > def x(): > return 1 > > @staticmethod > def x(): > return 2 > > Foo.x = x > print Foo.x() > -- > > $ python static.py > 2 > > I didn't even know you could define a staticmethod outside of a class! I suggest defining x as a normal function and writing the assignment as "Foo.x = staticmethod(x)" to keep x callable from the global namespace. Or just del it after doing the monkey patch. -- https://mail.python.org/mailman/listinfo/python-list
Re: Time zones and why they change so damned often
in 714232 20140109 120741 Alister wrote: >On Thu, 09 Jan 2014 07:17:25 +, Mark Lawrence wrote: > >> On 09/01/2014 04:14, Chris Angelico wrote: >>> On Thu, Jan 9, 2014 at 2:54 PM, Ben Finney >>> wrote: >>>> I'm approaching it with the goal of knowing better what I'm talking >>>> about when I advocate scrapping the whole DST system :-) >>> >>> I would definitely support the scrapping of DST. I'm less sure that we >>> need exactly 24 timezones around the world, though. It's not nearly as >>> big a problem to have the half-hour and quarter-hour timezones - >>> though it would be easier if timezone were strictly an integer number >>> of hours. But DST is the real pain. >>> >>> What I find, most of the time, is that it's Americans who can't handle >>> DST. I run an international Dungeons and Dragons campaign (we play >>> online, and new players are most welcome, as are people watching!), >>> and the Aussies (myself included) know to check UTC time, the Brits and >>> Europeans check UTC or just know what UTC is, and the Americans say >>> "Doesn't that happen at 8 o'clock Eastern time?" and get confused. >>> I don't understand this. Are my players drawn exclusively from the pool >>> of people who've never worked with anyone in Arizona [1]? Yes, >>> I'm stereotyping a bit here, and not every US player has had problems >>> with this, but it's the occasional US player who knows to check, and >>> the rare European, British, or Aussie player who doesn't. >>> >>> In any case, the world-wide abolition of DST would eliminate the >>> problem. The only remaining problem would be reminding people to change >>> the batteries in their smoke detectors. >>> >>> ChrisA >>> >>> [1] For those who aren't right up on timezone trivia, AZ has no DST. >>> Similarly the Australian state of Queensland does not shift its clocks. >>> >>> >> I remember this "From February 1968 to November 1971 the UK kept >> daylight saving time throughout the year mainly for commercial reasons, >> especially regarding time conformity with other European countries". My >> source http://www.timeanddate.com/time/uk/time-zone-background.html > >we dont have "Daylight saving time" we switch between GMT (Greenwich Mean >Time) and BST (British Summer Time) at some point in the past we have >also used DST (Double Summer Time). British Summer Time *is* Daylight Saving Time. -- https://mail.python.org/mailman/listinfo/python-list