Re: PyWart: Python modules are not so "modular" after all!

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 1:34:54 AM UTC-6, Steven D'Aprano wrote:
> import sys
> sys.modules["mymodule"] = any_object_you_like()

Thanks for this great advice!

I'm not particularly fond of injecting names and objects in
this manner due to the "surprise factor", especially when
the names are going to be global, but i'm going to do it
anyway since python gives me no other choice!

*evil-grin*

However, there is no reason why "good" cannot prevail over
"evil". By utilizing an intelligent design, logical
hierarchy, and most importantly: quality documentation and
commenting to shine a light on such dark and mystical
practices, i can elevate a kludge into the realms of
elegance.

Stay tuned for a future thread discussion on the topic...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread Mark Lawrence

On 11/11/2013 23:49, Joel Goldstick wrote:

On Mon, Nov 11, 2013 at 5:47 PM,   wrote:


Lets get this right folks once and for all.  Let's carry on welcoming 
Nikos with open arms as he's such a wonderful benefactor to the 
community, but ban people such as Matt who had the audacity to write 
about an hour ago "Thank you guys so much. Brain fart moment. I 
appreciate it".  This latter approach is simply intolerable.  I'm 
assuming that representatives of the Python Software Foundation will be 
protesting to Matt in the strongest possible terms about this, and 
threatening him with a life long ban from this list should he repeat 
such disgusting words on our forum.


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Steven D'Aprano
On Mon, 11 Nov 2013 12:55:56 -0800, Ned Batchelder wrote:

> On Monday, November 11, 2013 3:47:45 PM UTC-5, Frank-Rene Schäfer wrote:
>> I prepared a PEP and was wondering what your thoughts are about it:
> 
> The best place to discuss proposals for changes to the Python language
> and library is the Python-Ideas mailing list:
> https://mail.python.org/mailman/listinfo/python-ideas

Actually it is recommended to get at least initial feedback here first, 
to weed out proposals like:

"Python ought to allow function currying, like in Haskell."

"You mean like functools.partial?"

"Oh, never mind then."


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Mark Lawrence

On 12/11/2013 00:17, Steven D'Aprano wrote:

On Mon, 11 Nov 2013 12:55:56 -0800, Ned Batchelder wrote:


On Monday, November 11, 2013 3:47:45 PM UTC-5, Frank-Rene Schäfer wrote:

I prepared a PEP and was wondering what your thoughts are about it:


The best place to discuss proposals for changes to the Python language
and library is the Python-Ideas mailing list:
https://mail.python.org/mailman/listinfo/python-ideas


Actually it is recommended to get at least initial feedback here first,
to weed out proposals like:

"Python ought to allow function currying, like in Haskell."

"You mean like functools.partial?"



"But I don't want to do it like that, I want..."

--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Steven D'Aprano
On Mon, 11 Nov 2013 14:51:45 -0800, Rick Johnson wrote:

> 2. Never, ever, *EVER* write data to disc before confirming the paths
> your passing are pointing to the location you intended to write the
> data. Use os.path.exists(path) to test your paths BEFORE trying to write
> data.

This is subject to a race condition, which opens you to a security 
vulnerability: "time of check to time of use" bugs.

If you follow Rick's advice, and write code like this:

if os.path.exists(path):
write_to(path)  # custom function to open and write to the file
else:
handle_missing_file()


your code is doubly buggy. First, os.path.exists only tells you if the 
path exists, not whether it is writable. Perhaps it is on read-only 
media, or you don't have permission to open it, or it's a directory.

Secondly, even if the file exists at the moment you call os.path.exists, 
there is no guarantee that it will still exist a moment later when you 
try writing to it. Another process may delete or rename the file, or 
change permissions in the meantime. So you have to write:

if os.path.exists(path):
try:
write_to(path)
except (IOError, OSError):
handle_missing_or_locked_file()
else:
handle_missing_or_locked_file()


But now your test doesn't actually accomplish anything. Worse, just 
because the path *doesn't* exist when you check using exists, that 
doesn't mean it won't exist by the time you call write_to!

Using os.path.exists before opening a file is, for the most part, a waste 
of time.



-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread Ned Batchelder
On Monday, November 11, 2013 5:47:28 PM UTC-5, [email protected] wrote:
> On 11/08/2013 11:08 AM, Chris Angelico wrote:
> > On Sat, Nov 9, 2013 at 4:11 AM,   wrote:
> >> On 11/08/2013 03:05 AM, Νίκος Αλεξόπουλος wrote:
> >>> I never ignore advices.
> >>> I read all answers as carefully as i can.
> >>> But nevertheless sometimes i feel things should have been better
> >>> implemented using my way.
> >>>
> >>> Not of course that i know better, but thats better suited for me in the
> >>> level iam.
> >>
> >> Most of the "advice" I've seen posted here has, as far
> >> as I can tell, not intended to be useful but to serve
> >> as a way to telling you are incompetent are in other ways
> >> insulting or useless.  I think you are quite right to
> >> ignore it (or tell the poster to get lost.)
> > 
> > Actually no; most of the advice has been genuine.
> 
> Actually yes; most of the advice has not been genuine.
> 

rurpy, I applaud your efforts to make this forum more civil.  I do not like the 
general tone of the responses to Nikos these days.  But you are being naive to 
present this as "the big bad meanies against the innocent OP."

Nikos has received a good deal of genuine advice.  He has also been genuinely 
difficult to help.

> If you want to be helpful try posting useful information
> without the insults, with an attempt to tune it to the 
> level of understanding the recipient and without the 
> offensive "do what I tell you" attitude.

Lots of people have provided useful information, tuned to the recipient.  And 
yet the threads continue to spiral out of control.  You must acknowledge that 
threads started by Nikos end up going badly far more often than average.  It 
can't simply be that everyone irrationally hates Nikos.

> He didn't reject it out of hand, he gave some reasons why he 
> rejected it.   But as is SOP here, you chose not to see or pay
> any attention to those reasons.

Actually, Nikos often has rejected advice out of hand.  "I want to do it in one 
line" isn't a good reason to reject advice.  "But I don't want to make another 
table" isn't a good criterion for database design.  "I like mine better than 
yours, it just doesn't work, can you help me fix it" isn't a good way to get 
help.

As I said, I applaud your efforts to improve the tone of this forum.  But you 
won't do it by ignoring part of the problem: Nikos is difficult to help.  He 
ignores advice; he doesn't seem to want to research the fundamentals of his 
problems; he refuses suggestions for capricious reasons; he reposts panicky 
questions, sometimes within minutes of each other.  All of these things make 
him difficult to help, and raise the ire of people who are otherwise generous 
with their time and experience.

I don't know how best to make things better overall.  I know that overlooking 
Nikos' faults won't do it.

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Stop feeding the Ferrous Cranus troll

2013-11-11 Thread Chuck Quast
http://www.politicsforum.org/images/flame_warriors/flame_62.php

why are any of you replying?
-- 
https://mail.python.org/mailman/listinfo/python-list


Where to handle try-except - close to the statement, or in outer loop?

2013-11-11 Thread Victor Hooi
Hi,

I have a general question regarding try-except handling in Python.

Previously, I was putting the try-handle blocks quite close to where the errors 
occured:

A somewhat contrived example:

if __name__ == "__main__":
my_pet = Dog('spot', 5, 'brown')
my_pet.feed()
my_pet.shower()

and then, in each of the methods (feed(), shower()), I'd open up files, open 
database connections etc.

And I'd wrap each statement there in it's own individual try-except block. (I'm 
guessing I should wrap the whole lot in a single try-except, and handle each 
exception there?)

However, the author here:

http://stackoverflow.com/a/3644618/139137

suggests that it's a bad habit to catch an exception as early as possible, and 
you should handle it at an outer level.

>From reading other posts, this seems to be the consensus as well.

However, how does this work if you have multiple methods which can throw the 
same types of exceptions?

For example, if both feed() and shower() above need to write to files, when you 
get your IOError, how do you distinguish where it came from? (e.g. If you 
wanted to print a friendly error message, saying "Error writing to file while 
feeding.", or if you otherwise wanted to handle it different).

Would I wrap all of the calls in a try-except block?

try:
my_pet.feed()
my_pet.shower()
except IOError as e:
# Do something to handle exception?

Can anybody recommend any good examples that show current best practices for 
exception handling, for programs with moderate complexity? (i.e. anything more 
than the examples in the tutorial, basically).

Cheers,
Victor
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 11:17 AM, Steven D'Aprano
 wrote:
> On Mon, 11 Nov 2013 12:55:56 -0800, Ned Batchelder wrote:
>
>> On Monday, November 11, 2013 3:47:45 PM UTC-5, Frank-Rene Schäfer wrote:
>>> I prepared a PEP and was wondering what your thoughts are about it:
>>
>> The best place to discuss proposals for changes to the Python language
>> and library is the Python-Ideas mailing list:
>> https://mail.python.org/mailman/listinfo/python-ideas
>
> Actually it is recommended to get at least initial feedback here first,
> to weed out proposals like:
>
> "Python ought to allow function currying, like in Haskell."
>
> "You mean like functools.partial?"
>
> "Oh, never mind then."

aka "Guido's Time Machine" situations. I think this might be one of
them - I read the proposal and thought "Hashability should answer
that", and random832 also posted the same. Love that time machine!

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 9:44 AM, Joel Goldstick
 wrote:
> Sorry for incorect answer. Those guys nailed it

Your answer wasn't incorrect, because it didn't give any false
information. Bob and I saw the problem itself and gave advice, but you
gave useful general advice on how to find the problem, which is worth
bearing in mind. Matt, read Joel's response for useful tips on how to
figure out what might have gone wrong. :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Programa no modo gráfico

2013-11-11 Thread Elias de Oliveira
Also, we have a huge community in Brazil. If you want to write in
Portuguese, you could use the official python-brasil list:
https://groups.google.com/forum/#!forum/python-brasil

[]`s


2013/11/8 Izar Tarandach 

> You can find many resources for GUI programming in Python here:
> https://wiki.python.org/moin/GuiProgramming
>
> I believe you'll have better results with this list if you post your
> queries in English.
>
>
> --izar
>
>
> 2013/11/8 Guitar Men 
>
>> Como faço para fazer um programa  no modo gráfico sem usar o prompt?
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>


-- 
Elias Granja
Web and Android developer
http://www.eliasgranja.com
Phone: +55 19 8124-2645
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Steven D'Aprano
Hi Frank-Rene, and welcome. Comments below.


On Mon, 11 Nov 2013 21:47:45 +0100, Frank-Rene Schäfer wrote:

> I prepared a PEP and was wondering what your thoughts are about it:
> 
>   PEP:
>   Title:  ``isimmutable(Obj)`` and/or ``ImmutableNester``
[...]
> * Python-Version: 2.7.1

That won't do. Python 2.7 is in maintenance mode, it will not gain any 
new functionality. There won't be a Python 2.8 either. If you want to 
propose new functionality, it will have to go into 3.5. (You've missed 
the opportunity for 3.4, since "feature-freeze" is only weeks away.)


> General Idea
> 
> 
> A built-in function 'isimmutable()' shall tell efficiently whether the
> object of concern is mutable or not. That is it must reflect on the
> whole object tree whether it contains mutable elements or not.  For
> example, in the code fragment

This has been proposed before. It has failed because there is no way to 
tell in general whether an arbitrary object is immutable or not. If you 
only look at the common built-in types, it is quite trivial, e.g.:

- int, str, bytes, float, frozenset, bool, None are immutable;
- list, dict, set are not immutable;
- tuple is immutable if all of its elements are immutable.


But as soon as you allow arbitrary objects, you're in trouble. How do you 
tell whether an object is immutable?

I recommend that you start by writing a reference implementation:

def isimmutable(obj):
... # ?

Some obvious thoughts:

- It is not enough to include a big list of immutable classes:

# don't do this
if isinstance(obj, (float, int, frozenset, ...)): 
return True

  because that list will never be complete and can become out-of-date.

- You could try writing to the object (how?), and if it succeeds, 
  you know it is mutable. But if it fails, that might just mean 
  that you haven't tried writing to it in the correct manner.

- But if the obj is mutable, you've just mutated it. That's bad.

- You can try hashing the object:

  hash(obj)

  If that fails, then the object *might as well* be mutable, since 
  you can't use it in sets or as dict keys. But if that's all 
  isimmutable() does, why not just call hash(obj) directly?


Anyway, I recommend you spend some time on this exercise. The PEP will 
not be accepted without a reference implementation, so you're going to 
have to do it at some point.


Another thing which your proto-PEP fails to cover in sufficient detail is 
why you think such a function and/all class would be useful. You do say 
this:

> If an object is immutable then copying of it can be safely be replaced
> by a setting of a reference. The principal scenario is when an instance
> A gives an instance B access to some data D under the provision that B
> does not change it. Therefore, B must either clone the data or it must
> be safe to assume that the data cannot change, i.e. is immutable.

but I really don't think much of this as the principle scenario. I don't 
think I've ever written code that matches this scenario. If possible, you 
should give a real example. If not real, at least a toy example. Either 
way, using code rather than just a vague description is better.


> If the objects are large and/or many there a significant performance
> impact may raise from a deepcopy or manual cloning of objects.
> Therefore, the ``isimmutable()`` built-in function is key for a safe
> implementation of reference-instead-of-copying.

I don't think this is true. deepcopy (at least sometimes) will avoid 
making a copy if the object is immutable:

py> import copy
py> x = (10001, 20002, 30003, (40004, 50005, (60006, 70007)), 80008)
py> copy.copy(x) is x
True
py> copy.deepcopy(x) is x
True

so what advantage does isimmutable give you?



> Ensuring immutability is also key for the so called 'Flyweight Design
> Pattern'.

More details please.


Ultimately, nothing knows whether an object is immutable or not better 
than the object itself. copy.copy and copy.deepcopy know this, and ask 
the object to copy itself rather than copy it from the outside. Since the 
object knows whether it is immutable, it knows whether or not to make a 
copy or just return itself. It seems to me that isimmutable() *appears* 
to be a useful function to have, but if you look into it in detail the 
apparently uses for it don't hold up. In practice, it would be almost 
impossible to implement (except as below) and even if you could you would 
never need it.

Really, it seems to me that the only way to implement isimmutable would 
be to delegate to the object:

def isimmutable(obj):
return obj.__isimmutable__()

This gives you:

if isimmutable(obj):
x = obj
else:
x = copy.copy(obj)
function_that_might_modify(x)


but that gives you no advantage at all that the simpler:

function_that_might_modify(copy.copy(obj))

doesn't give. So what's the point?


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: توقيت وموعد اذاعة مباراة الزمالك ووادى دجلة فى نهائى كأس مصر اليوم السبت 9/11/2013 والقنوات الناقلة

2013-11-11 Thread alex23

On 12/11/2013 6:32 AM, Tony the Tiger wrote:

May your woman betray you, your son be gay, and your daughter screw pigs
for a living. Now go eat some pork and choke on it, like a good little
terrorist.


This is completely unacceptable and has no place on this list.

--
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Joshua Landau
On 11 November 2013 22:21, Chris Angelico  wrote:
> On Tue, Nov 12, 2013 at 7:50 AM, Joshua Landau  wrote:
>> The obvious way to me is a binary search:
>
> Which makes an O(log n) search where I have an O(1) lookup. The
> startup cost of denormalization doesn't scale, so when the server
> keeps running for two years or more, it's definitely worth processing
> it that way.

log 4 is tiny so I'd expect constant factors to be far more
significant here. Then you add on the better asymptotic behaviours for
large n, space wise, and the simplicity of implementation. This just
seems like a premature optimisation to me, I guess.

I agree that your way is faster; I just don't see a single case in
which I'd care. I do see several circumstances (large or floating
numbers) in which I'd probably prefer my way.

Feel free to disagree, I'm not really trying to convince you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where to handle try-except - close to the statement, or in outer loop?

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 12:34 PM, Victor Hooi  wrote:
> Would I wrap all of the calls in a try-except block?
>
> try:
> my_pet.feed()
> my_pet.shower()
> except IOError as e:
> # Do something to handle exception?
>

It really depends more on how you go about recovering from errors. If
feeding the dog and showering the dog are completely independent, you
should catch errors for them separately (probably inside feed() and
shower()), but if a problem with feeding the dog stops you from
showering him, then do what you have here. Catch exceptions where it
makes sense to recover from the issue. Sometimes that means putting a
blanket catch-all at some point ("if anything goes wrong here, log the
error, return an HTTP 500, and go deal with the next query"), and
sometimes it means not catching errors at all (any that bubble all the
way up will get reported on STDERR, which is often the most useful
handling anyway).

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting globals of the caller, not the defining module

2013-11-11 Thread Terry Reedy

On 11/11/2013 7:02 AM, [email protected] wrote:

(Sorry for posting through GG, I'm at work.)

On Monday, November 11, 2013 11:25:42 AM UTC, Steven D'Aprano wrote:

Suppose I have a function that needs access to globals:

# module A.py
def spam():
 g = globals()  # this gets globals from A
 introspect(g)

As written, spam() only sees its own globals, i.e. those of the module in
which spam is defined. But I want spam to see the globals of the caller.

# module B
import A
A.spam()  # I want spam to see globals from B

I can have the caller explicitly pass the globals itself:

def spam(globs=None):
 if globs is None:
 globs = globals()
 introspect(globs)

But since spam is supposed to introspect as much information as possible,
I don't really want to do that. What (if anything) are my other options?


How about this?

# module A.py
import inspect
def spam():
 return inspect.stack()[1][0].f_globals


In Python 3, the attribute is __globals__. In either case, it is only 
defined on Python coded functions, so one should be prepared for it to 
not exist. That possibility is real because there *are* builtins like 
map and filter that take function args and call them.


Inspect has been modified in Py 3, but stack is still there.


# module B.py
import A
print(A.spam() is globals()) # prints True
def f():
 return A.spam()

# module C.py
import B
print(B.f() is vars(B)) # prints True

I don't really know what I'm doing but I guess it won't work in alternative 
implementations of Python.




--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 12:59 PM, Dennis Lee Bieber
 wrote:
> Of course, I'm spoiled... My /watch/ has a dial for UTC, along with 
> one
> for 24-hour indication (one hand, range 1 to 24)

Heh. Mine doesn't, so I bought myself a second watch and set it to
UTC. So my left hand has local time (changes at DST breaks, changes
when I travel internationally), and my right hand has UTC (never
changes).

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: When I send email as HTML, why do erroneous whitespaces get introduced to the HTML source and a few < > chars get converted to < and > ???

2013-11-11 Thread Richard Balbat
On Saturday, November 9, 2013 2:29:00 AM UTC-5, dieter wrote:
> rich writes:
> Dieter, you were right!!! I broke up the string by inserting CRLF before I 
> reached 72 chars / line. Problem solved!
> 
> 
> > I have the following script that reads in an HTML file containing a table 
> > then sends it out via email with a content type of text/html.
> 
> >
> 
> > For some reason a few erroneous whitespaces get introduced to the HTML 
> > source and a few < > chars get converted to < and > ???
> 
> > ...
> 
> > Contents of results.html
> 
> >
> 
> > Test Campaign ResultsSoapUI 
> > regression testing has completed against the following:  
> > Environment: Auto.QABuild: testDetailed results can be found 
> > here: 
> > http://-AUTO1..xxx/SoapUITestResults/Auto.QA-2013-6-11_22-54-50 >  border="1">SoapUI Project 
> > (WSDL/WADL)TotalPassFailurePass 
> > PercentageacceptancePartnerEndpointWSDefinition-soapui-project.xml7 >  color="green">7 > color="red">0100.00%AIM-Automation.xml25 >  color="green">23 > color="red">292.00%ATM-Automation.xml41 >  color="green
> 
> > ...
> 
> 
> 
> I suggest to log the generated email (before sending) to verify whether
> 
> the transformation happens in your script or somewhere during the
> 
> email transport.
> 
> 
> 
> 
> 
> The email transport protocol ("SMTP" - "Simple Mail Transfer Protocol")
> 
> in principle imposes quite a strict limitation on line length
> 
> (72 characters, when I remember right). Your html input has much larger
> 
> lines - maybe, they are broken up somewhere - at the cost of spurious
> 
> whitespace. Usually, a "Content-Transfer-Encoding" is used
> 
> to satisfy the line length limitation. If this is quoted printable,
> 
> then reading the text undecoded, it may seem to have additional
> 
> characters (whitespace and control characters).
> 
> 
> 
> I have no idea what may replace "<" and ">" by html entity references.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where to handle try-except - close to the statement, or in outer loop?

2013-11-11 Thread Steven D'Aprano
On Mon, 11 Nov 2013 17:34:21 -0800, Victor Hooi wrote:

> Hi,
> 
> I have a general question regarding try-except handling in Python.
> 
> Previously, I was putting the try-handle blocks quite close to where the
> errors occured:
> 
> A somewhat contrived example:
> 
> if __name__ == "__main__":
> my_pet = Dog('spot', 5, 'brown')
> my_pet.feed()
> my_pet.shower()
> 
> and then, in each of the methods (feed(), shower()), I'd open up files,
> open database connections etc.
> 
> And I'd wrap each statement there in it's own individual try-except
> block. (I'm guessing I should wrap the whole lot in a single try-except,
> and handle each exception there?)

Your description is ambiguous. Do you mean you have:

if __name__ == "__main__":
try:
my_pet = Dog('spot', 5, 'brown')
except Whatever:
pass
try:
my_pet.feed()
except Whatever:
pass
try:
my_pet.shower()
except Whatever:
pass

or that each individual method has it's own try...except block?

The first is certainly not good. If the call to Dog fails, you shouldn't 
proceed with the following lines, they certainly cannot succeed. On the 
other hand, if the call to my_pet.feed() fails (perhaps Spot is not 
hungry), then it is perfectly acceptable to ignore the exception and give 
Spot a bath regardless. So it depends on the circumstances.

On the other hand:

if __name__ == "__main__":
try:
my_pet = Dog('spot', 5, 'brown')
my_pet.feed()
my_pet.shower()
except Whatever:
pass

is too much, since an error in feeding the dog prevents you from showing 
the dog.


> However, the author here:
> 
> http://stackoverflow.com/a/3644618/139137
> 
> suggests that it's a bad habit to catch an exception as early as
> possible, and you should handle it at an outer level.

Since the poster doesn't give an actual example of this, it is hard to 
tell what he considers too early or too late. But in general, one should 
only catch exceptions that you can do something about, as soon as you can 
do something about it. Depending on what you can do to recover from an 
error, that may mean wrapping each statement in it's own try block, or 
(more rarely, in my experience) a whole bunch of statements.


> From reading other posts, this seems to be the consensus as well.
> 
> However, how does this work if you have multiple methods which can throw
> the same types of exceptions?
> 
> For example, if both feed() and shower() above need to write to files,
> when you get your IOError, how do you distinguish where it came from?

You can't, at least not easily and/or portably.


> (e.g. If you wanted to print a friendly error message, saying "Error
> writing to file while feeding.", or if you otherwise wanted to handle it
> different).

If your only reason for catching the error is to suppress the stack trace 
and provide a "friendly" (i.e. useless) error message, then don't use 
try...except at all. Instead, install a customer error handler:

http://docs.python.org/2/library/sys.html#sys.excepthook


Otherwise, you should only catch exceptions that you can do something 
about. That might mean retrying the operation:

while True:
try:
dog.feed()
except DogNotHungryError:
time.sleep(60*60)
continue
break


or ignoring the failure:

try:
dog.feed()
except DogNotHungryError:
pass
dog.bath()


or doing something else. If you can't do anything about the error, then 
you shouldn't catch it, and leave it to code higher up to deal with it.


> Can anybody recommend any good examples that show current best practices
> for exception handling, for programs with moderate complexity? (i.e.
> anything more than the examples in the tutorial, basically).

Yes. Read the code in the Python standard library! Open your text editor, 
if possible set it to open files in read-only mode, and browse the 
standard library.



-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Rick Johnson
PyMyth: Global variables are evil... WRONG!


 Python's Global Hysteria:

How many times have your heard or read the phrase: "Global
variables are evil"? Well if you've been a member of the
Python community, I'll bet you've heard or read it more than
most other community members.

In this thread, i want to get to the bottom of this whole
"global-phobia" thing once and for all, and hopefully help
you folks understand that globals are not all that bad --
when DESIGNED and USED correctly that is!


 The denial of the 99%:

Python has globals, but we just can't admit it!

The creators thought they would prevent the little
"PyPeople" from hurting themselves by "handicapping" our
globals in the form of "module level" globals.

But even the "module level" globals can be accessed
"globally" if the module they are contained in is imported
everywhere.

import glomod
glomod.var # Access
global.var = newValue

Which leads me to the conclusion that the designers were
either naive or underestimated the chutzpah of this fine
community.


 The Power of the 1%:

Most of this "fear of globals" can be traced back to a
minority of naive coders who used globals haphazardly and
were hurt by them, and now we ALL have to suffer
because future idiots need to be protected from themselves!


Too many times I've seen idiotic uses for globals.

One more atrocious example was "dialog return values" stored
as globals so the "dumb coder" could eaisly restore the
previous state of the dialog values between successive
calls.

Obviously the best solution would be for the dialog object
ITSELF to store (and restore) the values when necessary, but
alas, here i am again expecting people to create interfaces
that are consistent and logical. *rolls-eyes*

Of course we can only blame the dialog designer and not the
caller for this design flaw, but the caller still has no
excuse for globally storaging these values.

If the caller cannot repair the mistake by extending the
dialog object himself, then he can store the values within
the current module or class level scope. There is no excuse
for elevating this information to global scope.

However, there ARE justified uses of global variables!


 Justifying Global Variables:

Globals are justified when they are used to communicate
information between scopes that otherwise were meant to be
mutually exclusive. One good example would be package sub-
modules.

Now. Some might believe that the purity of namespaces
becomes tainted if they can be violently penetrated by
global variables. But again, they are falling back on gut
reactions fostered from years of brain washing. Yes, globals
can be bad (if misused), but for the most part they are
crucial to transferring information CLEANLY between isolated
namespaces

But even globals themselves are not good enough UNLESS we
engineer a "global hierarchy"!


 From Flat to Nested == From Tricked to Bested:

One of the shortcomings of the current implementation of
global variables is their inherent "flat" access nature.
There is no hierarchy of globals, and once all the good
names are taken, your screwed!

 "But Rick, even when we use globals, we don't need that many"

Only if you consider the single package that represents your
program, but what about the thousands of support libraries
with millions of lines of code that work in the background
to make your measly few thousand lines of code work?  What
about all the globals that they have injected?

 "Never thought of that really"

Throwing out global names UNADORNED is folly. Could you
imagine telephone numbers without area codes?

 Hmm: Am i calling "Jim" in Beverly Hills California???

   california.beverlyhills.jim

 or "Jim" in "Spokane Washington"???

   washington.spokane.jim

You see, you need to QUALIFY these names not only to make
then unique, but also so the caller will understand who he
is calling.

Same goes for globals.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: UTF-32 decoder optimization in Python 3.4

2013-11-11 Thread Terry Reedy

On 11/11/2013 4:41 PM, Mark Lawrence wrote:

 From http://docs.python.org/dev/whatsnew/3.4.html#optimizations "The
UTF-32 decoder is now 3x to 4x faster.".  Does anybody have any
references to this work?  All I can find is the 3.3 what's new which
refers to PEP 393 (Flexible String Representation) optimizations as a
result of work done by Serhiy Storchaka on issues 14624, 14738 and 15026.


The second line at the top has "For full details, see the changelog." 
where changelog links to

http://docs.python.org/3.4/whatsnew/changelog.html
Searching that for 'UTF-34' goes to this line
"Issue #14625: Rewrite the UTF-32 decoder. It is now 3x to 4x faster. 
Patch written by Serhiy Storchaka." where 'Issue #14625' links to

http://bugs.python.org/issue14625
with full discussion. (I know that you, Mark, could have found that, but 
not everyone reading could.)


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Tim Daneliuk

On 11/11/2013 08:06 PM, Rick Johnson wrote:

Globals are justified when they are used to communicate
information between scopes that otherwise were meant to be
mutually exclusive.



I think this is certainly the use case most people would suggest.

But I think you may have missed the real reason most modern
designers object to inter-module globals:  The presence of
such entities almost always means the code has been designed
badly.  Whether we're writing pristine OO code (cough, cough)
or more traditional procedural stuff, information hiding
is a good thing.  When and where there is a need for modules
(or programs, or machines, or "clouds", or interstellar space ...)
to share information, my view is this is better done via some sort
of interface/message passing mechanism.  The more "things" that have
to be shared across modules/programs/machines/clouds/space ... the more
*brittle* the end system becomes.

This problem is broader than just variables, BTW.  It exists anytime you
share *anything* across many computational components, especially in highly
parallel and/or distributed systems.  For example, RPCs tend to be lousy
at building high scale distributed system because they usually have
a call-and-wait semantic which will fail if the caller never responds.
In this case the system is sharing the semantics of *time*.  As a general
matter, exactly-once asynchronous messaging tends to be a better implementation
model here.

Just my 2 cents worth.  Interesting read.  Thanks for taking the time
--

Tim Daneliuk [email protected]
PGP Key: http://www.tundraware.com/PGP/

--
https://mail.python.org/mailman/listinfo/python-list


Re: Where to handle try-except - close to the statement, or in outer loop?

2013-11-11 Thread Terry Reedy

On 11/11/2013 8:34 PM, Victor Hooi wrote:


I have a general question regarding try-except handling in Python.


In Python, try-except can unapologetically be used as as alternate 
conditional-execution control-flow construct.


if :
  
else:
  

can often be re-written

try:
  
except :
  

Some reasons for using the try_except form:
1.  is volatile and may change between the 'if  
check and the  performance.

2.  is expensive to check>.
3.  is nearly always True (say >= 90% of the time).

Notice that 'except' is at least as close to 'try' as 'else' is to 'if'.

General rule: handle exceptions as soon as you can do something useful.

You can find lots of examples in the stdlib where  is a 
single simple statement.***  I recommend that beginners try reading some 
of the stdlib code. It is not necessarily all great, but the average 
quality should be pretty decent. Of course, some modules are more recent 
than others.



Previously, I was putting the try-handle blocks quite close to where
the errors occured:

A somewhat contrived example:

if __name__ == "__main__": my_pet = Dog('spot', 5, 'brown')
my_pet.feed() my_pet.shower()

and then, in each of the methods (feed(), shower()), I'd open up
files, open database connections etc.


Do use with blocks.


And I'd wrap each statement there in it's own individual try-except
block. (I'm guessing I should wrap the whole lot in a single
try-except, and handle each exception there?)

However, the author here:

http://stackoverflow.com/a/3644618/139137

suggests that it's a bad habit to catch an exception as early as
possible, and you should handle it at an outer level.


This was a side comment in a specific context of IOErrors that he thinks 
are best handled later. Perhaps Bernd has seen some useless inner code 
try-excepts that I have not.



From reading other posts, this seems to be the consensus as well.


As stated above, not among the people who develop Python.


However, how does this work if you have multiple methods which can
throw the same types of exceptions?


You have noticed the reason for the *** statement above ;-).


For example, if both feed() and shower() above need to write to
files, when you get your IOError, how do you distinguish where it
came from? (e.g. If you wanted to print a friendly error message,
saying "Error writing to file while feeding.", or if you otherwise
wanted to handle it different).

Would I wrap all of the calls in a try-except block?

try: my_pet.feed() my_pet.shower() except IOError as e: # Do
something to handle exception?

Can anybody recommend any good examples that show current best
practices for exception handling, for programs with moderate
complexity? (i.e. anything more than the examples in the tutorial,
basically).


See comment above about stdlib modules. Pick some that interest you.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Reading c struct via python

2013-11-11 Thread Lakshmipathi.G
Hi -
We have C code which writes following struct into berkeley db ("my_db.db").

struct my_info {
unsigned long int i, e;
int o;
char *f;
char *s;
};

How to read this via Python? Google search gave this code
---
$ cat pybsd2.py
from bsddb import db
fruitDB = db.DB()
fruitDB.open('my_db.db', None, db.DB_BTREE, db.DB_DIRTY_READ)
cursor = fruitDB.cursor()
rec = cursor.first()
while rec:
print rec
rec = cursor.next()
fruitDB.close()
---

While storing an entry (o=>500,f=>/home/laks/abcde,s=>OSr,i=>4668368
,e=>1) and reading it back i get

$ python pybsd2.py
("\x10'\x00\x00\x00\x00\x00\x00",
"\xf4\x01\x00\x00\xd0;G\x00\x00\x00\x00\x00\x10'\x00\x00\x00\x00\x00\x00/home/laks/abcde\x00OSr\x00")

And this http://docs.python.org/2/library/bsddb.html says bdb module is
removed  recently.

Further Searching provides modules like cpickle,ctypes,struct - not sure
which is the right approach/way to proceed.
Should we proceed with bdb module and find out how to retrive integer from
db or use others like ctypes/(c)pickle/struct etc?

Thanks for any help.

Ps : If this question already answered and discussed often, please redirect
me to that thread.

-- 

Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 8:47:09 PM UTC-6, Tim Daneliuk wrote:
> I think this is certainly the use case most people would
> suggest. But I think you may have missed the real reason
> most modern designers object to inter-module globals:  The
> presence of such entities almost always means the code has
> been designed badly.  Whether we're writing pristine OO
> code (cough, cough) or more traditional procedural stuff,
> information hiding is a good thing.

Yes, and i agree. But you cannot "hide" everything. There
will always be a need to share information.

> When and where there is a need for modules (or programs,
> or machines, or "clouds", or interstellar space ...) to
> share information, my view is this is better done via some
> sort of interface/message passing mechanism.

But python modules can't be interfaces because interfaces
should protect internal data, prevent external forces from
meddling with internal state (EXCEPT via the rules of a
predefined "contract"), hide dirty details from the caller,
and have clearly defined access points.

  BUT PYTHON MODULES DON'T FOLLOW THIS DESIGN PATTERN!

No, Python modules can be poked, prodded, and violated by
any pervert who can spell the word "import".

Attribute values can be reassigned and state can be
externally manipulated resulting in all types of undefined
behaviors -- that does not sound like an interface to me.

So if python modules are importable everywhere, and mutable
from everywhere, then python modules are merely addresses to
a collection of global variables? And they're only
interfaces "superficially"?

So that leaves us with Python's current implementation of
unofficial "global" variables implemented as "puesdo-
interfaces" by module objects that are victims waiting to be
violated.

Interesting.

  IF IT WALKS LIKE A GLOBAL DUCK AND...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Grant Edwards
On 2013-11-11, Mark Lawrence  wrote:
> On 11/11/2013 23:21, mm0fmf wrote:
>> On 11/11/2013 19:39, Ethan Furman wrote:
>>> On 11/11/2013 11:19 AM, Denis McMahon wrote:
 On Mon, 11 Nov 2013 11:57:36 +0200, ?? ?? 
 wrote:

>> lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
>> '%y-%m-%d %H:%M:%S' )# MySQL datetime format

> Someone has an idea what to add to this line to automatically adjust
> itself if DST happens?

 Yes, but the scarcity of universal whitespace is preventing me from
 posting it.
>>>
>>> Boy, are you in luck!  I just happen to have a whole heap of marked down
>>> ascii white-space at bargain basement prices!
>>
>> Is that metric or imperial whitespace?
>>
>> You need metric whitespace for programs written in Europe.
>
> Except for the UK, our multi-national approach means that both imperial 
> and metric whitespace are acceptable.

Don't forget that there are also some differences between American and
Imperial whitespace.  Since it's ASCII whitespace, you should probably
assume American...

-- 
Grant



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 3:46 PM, Rick Johnson
 wrote:
> But python modules can't be interfaces because interfaces
> should protect internal data, prevent external forces from
> meddling with internal state (EXCEPT via the rules of a
> predefined "contract"), hide dirty details from the caller,
> and have clearly defined access points.
>
>   BUT PYTHON MODULES DON'T FOLLOW THIS DESIGN PATTERN!
>
> No, Python modules can be poked, prodded, and violated by
> any pervert who can spell the word "import".

And C++ objects can be poked by anyone who can do a pointer cast. And
Java objects by anyone who notices that 'const' checks don't apply to
byte-code. In fact, the only language I can think of that actually
"prevent[s] external forces from meddling with internal state" is
HQ9++, which follows the very best principles of data hiding.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread Gregory Ewing

Ned Batchelder wrote:
I don't know how best to make things better overall.  I know that overlooking 
Nikos' faults won't do it.


If everyone who reached the point where they don't think
they can help any more would simply say so in a calm
manner and then walk away, that would make things better
overall. It wouldn't help *Nikos*, but it would prevent
the discussion from degenerating into a flamefest.

It takes two to spiral.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 5:11:52 PM UTC-6, Chris Angelico wrote:
> On Tue, Nov 12, 2013 at 9:51 AM, Rick Johnson
> > 1. i believe win32 file paths require a qualifying volume
> > letter.
> They do not; omitting the drive letter makes the path relative to the
> current drive (and since it doesn't start with a directory specifier,
> the current directory).

Hmm. Let's confirm:

>>> import os
>>> os.path.exists("C:/Windows/System32")
True
>>> os.path.exists("/Windows/System32")
True

Yep, it's official. "Implicit File Path Resolution"
I need to author a PyWart on this soon!

> > 2. Never, ever, *EVER* write data to disc before confirming
> > the paths your passing are pointing to the location you
> > intended to write the data. Use os.path.exists(path) to test
> > your paths BEFORE trying to write data.
> Why? Why, oh why? If there's a problem, it'll be signalled
> with an exception.

Except when there's a problem that won't be signaled by an
EXCEPTION, but will be signaled by EMOTIONS; like for
instance removing the wrong directory or truncating the
wrong file because of a typo in your source code.

 OPPS! :-'(

> Testing that the path exists opens you up to race
> problems, so you won't see anything now, but some day your
> code will be in a concurrent situation and you'll get
> unexpected exceptions. Why not just expect the exception?

Because today i'm not facing a concurrent situation, so i'm
not going to bother and protect from it. Just like i'm not
facing a snake bite, so i won't bother to lug around a vial
of antidote. Your attempts to discredit me via hypothetical
scenarios is entertaining however.

> This one's arguable. How often do you use the 'file'
> builtin? I've worked with files in Python innumerable
> times, and I don't remember the last time I used 'file'.
> Yes, avoid shadowing important builtins like 'list' and
> 'int', but 'id' and 'file' aren't that big a deal.

My first concern is with the OP adopting "self documenting"
names. Shadowing file is merely ensuring that the OP knows
"file" is a builtin. Shadowing any builtin can create very
difficult bugs to track. This is the point the OP should
remember.

> They won't float around forever. The garbage collector
> will get to them.

That depends on how they are stored. You make too many
assumptions Chris. I don't have an problems with GC's, but
i'm not about to write sloppy code and "assume" the GC is
going to swoop in and save me like a feline trapped in a 
tree.

> > 5. Remember, you cannot write a file into a directory that
> > does not exist.
> So? Exception thrown, traceback printed to console,
> process terminated cleanly. I'm not seeing a problem here.

Now you're just trolling!

def firstdev(file):
in_file = open("desktop/%s.txt") % file
indata = in_file.read()
out_file = open("desktop/newfolder/%s.txt", 'w') % file

Just from reading that code NO ONE could know for sure if
"newfolder" even existed BEFORE the OP tried to open the
"out_file". Maybe the OP thinks that missing sub-directories
are auto-created by the open function, but there's no way to
know for sure, hence my comment.

> > 6 For OS compatibility always use os.path.join() to join
> > path parts into a whole. This method will insert the proper
> > separator for you depending on the OS.
> Technically true. However, most modern OSes will accept a
> slash. There'll be a few situations where that's not true,
> but the OP an happily just use slashes for simplicity.

Many a developer have lived to regret those words.

PS: I thought Steven was the official "devils advocate"
around here? Hmm. I guess everyone needs a day off.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Buffering of sys.stdout and sys.stderr in python3 (and documentation)

2013-11-11 Thread swatkins
It's surprising and broken that stderr should be buffered in python3.  python3 
calls setvbuf(3) on stderr at startup to achieve this chuckle-headed behavior.  
It makes stderr line buffered if on a terminal, and fully buffered if 
redirected to a log file.  A fully buffered stderr is a very bad idea.

This change goes against the C89 and C99 standards, 40+ years of precedent, and 
the behavior of nearly every other current programming language.

Error messages will not show up in logs on time, and may be completely lost if 
the process is terminated before the buffer is flushed, e.g. with SIGTERM

How about fixing this?

Until then, we should write this in every script:

sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Buffering of sys.stdout and sys.stderr in python3 (and documentation)

2013-11-11 Thread swatkins
> sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

which unfortunately doesn't work!  I guess will resort to python3 -u, although 
I don't want stdout to be unbuffered.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 4:42 PM, Rick Johnson
 wrote:
> On Monday, November 11, 2013 5:11:52 PM UTC-6, Chris Angelico wrote:
>> On Tue, Nov 12, 2013 at 9:51 AM, Rick Johnson
>> > 1. i believe win32 file paths require a qualifying volume
>> > letter.
>> They do not; omitting the drive letter makes the path relative to the
>> current drive (and since it doesn't start with a directory specifier,
>> the current directory).
>
> Hmm. Let's confirm:
>
> >>> import os
> >>> os.path.exists("C:/Windows/System32")
> True
> >>> os.path.exists("/Windows/System32")
> True
>
> Yep, it's official. "Implicit File Path Resolution"
> I need to author a PyWart on this soon!

That's not a Python issue at all. And are you seriously going to decry
relative pathnames?!?

>> > 2. Never, ever, *EVER* write data to disc before confirming
>> > the paths your passing are pointing to the location you
>> > intended to write the data. Use os.path.exists(path) to test
>> > your paths BEFORE trying to write data.
>> Why? Why, oh why? If there's a problem, it'll be signalled
>> with an exception.
>
> Except when there's a problem that won't be signaled by an
> EXCEPTION, but will be signaled by EMOTIONS; like for
> instance removing the wrong directory or truncating the
> wrong file because of a typo in your source code.

Which os.path.exists will not protect you from. So?

>> Testing that the path exists opens you up to race
>> problems, so you won't see anything now, but some day your
>> code will be in a concurrent situation and you'll get
>> unexpected exceptions. Why not just expect the exception?
>
> Because today i'm not facing a concurrent situation, so i'm
> not going to bother and protect from it. Just like i'm not
> facing a snake bite, so i won't bother to lug around a vial
> of antidote. Your attempts to discredit me via hypothetical
> scenarios is entertaining however.
>> > 6 For OS compatibility always use os.path.join() to join
>> > path parts into a whole. This method will insert the proper
>> > separator for you depending on the OS.
>> Technically true. However, most modern OSes will accept a
>> slash. There'll be a few situations where that's not true,
>> but the OP an happily just use slashes for simplicity.
>
> Many a developer have lived to regret those words.

(Reordered to bring together two comments getting one response) Do you
care about what you currently are seeing, or what you might some day
see? Concurrency is a common problem on many platforms; platforms not
supporting slashes between paths are rare, and most of them will have
other porting issues. Why are you ignoring the likely, while trying to
prevent the unlikely?

>> They won't float around forever. The garbage collector
>> will get to them.
>
> That depends on how they are stored. You make too many
> assumptions Chris. I don't have an problems with GC's, but
> i'm not about to write sloppy code and "assume" the GC is
> going to swoop in and save me like a feline trapped in a
> tree.

Ah, actually yes you are. When have you ever explicitly disposed of an
object in Python? You just let the GC deal with it for you.

>> > 5. Remember, you cannot write a file into a directory that
>> > does not exist.
>> So? Exception thrown, traceback printed to console,
>> process terminated cleanly. I'm not seeing a problem here.
>
> Now you're just trolling!

Mercurial signals some errors by dumping an exception to stderr. This
works quite nicely, even in production. If your script can't recover
from being given a non-writeable directory, don't catch the exception.

> def firstdev(file):
> in_file = open("desktop/%s.txt") % file
> indata = in_file.read()
> out_file = open("desktop/newfolder/%s.txt", 'w') % file
>
> Just from reading that code NO ONE could know for sure if
> "newfolder" even existed BEFORE the OP tried to open the
> "out_file". Maybe the OP thinks that missing sub-directories
> are auto-created by the open function, but there's no way to
> know for sure, hence my comment.

And the OP might have thought that it would automatically publish that
to the world, tweet the URL, and create a Facebook status saying "just
opened a file lolol" and get five people to Like it. Doesn't mean we
need to probe before doing things.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread rurpy
On 11/11/2013 04:49 PM, Joel Goldstick wrote:
> On Mon, Nov 11, 2013 at 5:47 PM,   wrote:
>> On 11/08/2013 11:08 AM, Chris Angelico wrote:
>>> On Sat, Nov 9, 2013 at 4:11 AM,   wrote:
 On 11/08/2013 03:05 AM, Νίκος Αλεξόπουλος wrote:
> I never ignore advices.
> I read all answers as carefully as i can.
> But nevertheless sometimes i feel things should have been better
> implemented using my way.
>
> Not of course that i know better, but thats better suited for me in the
> level iam.

 Most of the "advice" I've seen posted here has, as far
 as I can tell, not intended to be useful but to serve
 as a way to telling you are incompetent are in other ways
 insulting or useless.  I think you are quite right to
 ignore it (or tell the poster to get lost.)
>>>
>>> Actually no; most of the advice has been genuine.
>>
>> Actually yes; most of the advice has not been genuine.
>>
>> Of course neither you nor I know for sure since we can't
>> read minds.  But when "advice" consists of things like
>>  "Maybe try some of the advice you have been given instead? "
>>  "use php"
> 
> It seems like you take the view that people have decided to bully or
> tease or laugh at this one person here.  Sometimes other's ask
> question and they quickly get gently (maybe not gently) teased, but
> since I have been listening here it is one person overwhelmingly who
> gets this response.  It doesn't mean its really the highest order
> behavior, but its not done in a vacuum either.

I do not (as another poster put it) think that Nikos is
an "innocent" being picked on.  I do think that this group
would be a better place were those who enjoy baiting, 
flaming and otherwise venting their frustration with 
Nikos to vent in some other private way, but it seems I
was unable to convince anyone else of that (or at least 
any of those who do it most).  I am not unequivocally 
defending Nikos but in this particular case, where he is 
being bashed for not accepting a "solution" that doesn't 
meet his needs (as he sees them), I think he is right.

>>  "Try starting with something simple. The following is a
>>   step by step guide... Now, and this is really really
>>   going to tax you..."
> 
> So, you don't like teasing.  Why not go back and see where this
> teasing started.  I would guess that its not from the beginning.  Its
> only after a history that makes it appropriate (maybe not appropriate,
> but understandable).

Ridicule is a more accurate description than teasing.
And you're right, I don't like it.  Yes, it's understandable
(in the same way it is understandable that the victim of
a crime might want to murder the perpetrator) but that
doesn't make it acceptable.

>>  A treatise on 1nf in six short sentences followed by
>>   ruminations on competence including "...never shows
>>   a glimmer of interest in learning."
> 
> This one I think is mine.  I don't pretend to be able to write a
> treatise in however many sentences, let alone 6.  This 'guidance' was
> to provide a link to a more substantial authority than me about why
> its a bad idea to use a database without normalizing data.  If you
> want to get stuff out of a database with sql you have to normalize it,
> or know well why you would not.  The thread about normalizing
> degenerated (sorry if the term is loaded) into people talking about
> various language data types that can be stored in a sql database.
> Blob, is the one I remember.  So, if you refuse the idea that its
> better to build a second table with a one to many relationship to the
> first table rows, then you need to know how much python code will be
> required to reverse that 'shoving stuff' in a single column.  Its a
> choice.  

Right, that's my point.  It is a choice with tradeoffs;
either option will have some advantages and some disadvantages.
He was trying to figure out the Python code needed.  And your
suggestion is not necessarily best either: why a 1:M relationship?
why not a M:M relationship?  There may be duplicate file downloads
resulting in your suggestion being non-normalized.  So I think 
there is some justification in his looking for a simpler
Python solution even if it is not the way the majority here
would do it.

>[...]
>> No you're not.  Without determining how the data is to be
>> used you can't say it's not normalized.  Otherwise one
>> could claim every of the millions of databases containing
>> addresses is not even 1nf because their designers crammed
>> two pieces of information (street number and street name)
>> into a single datum.
> 
> Talking about whether an address is atomic is a can of worms.  Anyone
> who has worked with addresses finds this out.  But in the generic
> sense an address is a single description of a location.  Saying that
> it should be two fields, one with number, and one with name doesn't
> sound right to me because each field is too small to have any meaning.

Of course it has meaning.  The number identifies a locatio

Re: To whoever hacked into my Database

2013-11-11 Thread rurpy
On 11/11/2013 06:16 PM, Ned Batchelder wrote:
> On Monday, November 11, 2013 5:47:28 PM UTC-5, [email protected] wrote:
>> On 11/08/2013 11:08 AM, Chris Angelico wrote:
>>> On Sat, Nov 9, 2013 at 4:11 AM,   wrote:
 On 11/08/2013 03:05 AM, Νίκος Αλεξόπουλος wrote:
> I never ignore advices. I read all answers as carefully as i
> can. But nevertheless sometimes i feel things should have
> been better implemented using my way.
> 
> Not of course that i know better, but thats better suited for
> me in the level iam.
 
 Most of the "advice" I've seen posted here has, as far as I can
 tell, not intended to be useful but to serve as a way to
 telling you are incompetent are in other ways insulting or
 useless.  I think you are quite right to ignore it (or tell the
 poster to get lost.)
>>> 
>>> Actually no; most of the advice has been genuine.
>> 
>> Actually yes; most of the advice has not been genuine.
> 
> rurpy, I applaud your efforts to make this forum more civil.  I do
> not like the general tone of the responses to Nikos these days.  But
> you are being naive to present this as "the big bad meanies against
> the innocent OP."

I never claimed Nikos was "innocent".  I was complaining 
about responses, driven by frustration or hostility, that 
go beyond reasonable and become so dogmatic and absolutist 
that they themselves become wrong.  Nikos (or anyone else) 
is right to reject such responses.

> Nikos has received a good deal of genuine advice.  He has also been
> genuinely difficult to help.

Yes.  If he is too difficult to help without getting
angry because he won't do what you (generic) tell him
then perhaps a more constructive response is to stop
trying to help him rather than join the lynch mob that
is making the atmosphere here far worse (IMO) than
Nikos alone could.  However, I have made that argument
in the past and am not interested in rearguing it.

>[...]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Frank-Rene Schäfer
A tuple is immutable but it may contain mutable objects. In larger
hierarchies of objects it may become less obvious whether down
the lines, there is some mutable object somewhere in the data tree.

One can define a recursive function to check for immutability
manually. However first, it may not be as efficient as if it was
built-in. Second, the existence of a built-in function 'isimmutable'
puts the concept of immutability some more into the spotlight.

You might indeed implement some personal 'policy for copy/deepcopy'.
But, how can you prevent the insertion of an object into the data
tree which does not follow your copy/deepcopy convention? As soon
as you allow members of type 'tuple' you must either check recursively
or only allow ints and strings as tuple members.
-- 
https://mail.python.org/mailman/listinfo/python-list


[RELEASED] Python 3.3.3 release candidate 2

2013-11-11 Thread Georg Brandl
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On behalf of the Python development team, I'm quite happy to announce the
Python 3.3.3 release candidate 2.

Python 3.3.3 includes several security fixes and over 150 bug fixes compared to
the Python 3.3.2 release.

This release fully supports OS X 10.9 Mavericks.  In particular, this release
fixes an issue that could cause previous versions of Python to crash when typing
in interactive mode on OS X 10.9.

Python 3.3 includes a range of improvements of the 3.x series, as well as easier
porting between 2.x and 3.x.  In total, almost 500 API items are new or improved
in Python 3.3.  For a more extensive list of changes in the 3.3 series, see

http://docs.python.org/3.3/whatsnew/3.3.html

To download Python 3.3.3 rc2 visit:

http://www.python.org/download/releases/3.3.3/


This is a preview release, please report any bugs to

 http://bugs.python.org/


Enjoy!

- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.3's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)

iEYEARECAAYFAlKB1G4ACgkQN9GcIYhpnLAu5gCfRkfpnEs+rmtZ9iTjaaZcHDx3
sNYAn180Q4cFZmKtwJdaG+g/3jHAVd97
=n/Tt
-END PGP SIGNATURE-
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 6:01 PM, Frank-Rene Schäfer  wrote:
> A tuple is immutable but it may contain mutable objects. In larger
> hierarchies of objects it may become less obvious whether down
> the lines, there is some mutable object somewhere in the data tree.
>
> One can define a recursive function to check for immutability
> manually. However first, it may not be as efficient as if it was
> built-in. Second, the existence of a built-in function 'isimmutable'
> puts the concept of immutability some more into the spotlight.
>
> You might indeed implement some personal 'policy for copy/deepcopy'.
> But, how can you prevent the insertion of an object into the data
> tree which does not follow your copy/deepcopy convention? As soon
> as you allow members of type 'tuple' you must either check recursively
> or only allow ints and strings as tuple members.

>>> x=1,2,3
>>> hash(x)
-378539185
>>> x=1,2,[3]
>>> hash(x)
Traceback (most recent call last):
  File "", line 1, in 
hash(x)
TypeError: unhashable type: 'list'

There's your recursive function!

def isimmutable(x):
try:
hash(x)
return True
except TypeError:
return False
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread alex23

On 12/11/2013 2:49 PM, Grant Edwards wrote:

Don't forget that there are also some differences between American and
Imperial whitespace.  Since it's ASCII whitespace, you should probably
assume American...


>>> sys.getsizeof(' ')
34
>>> sys.getsizeof(u' ')
52

bad by design
--
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 6:25 PM, alex23  wrote:
> On 12/11/2013 2:49 PM, Grant Edwards wrote:
>>
>> Don't forget that there are also some differences between American and
>> Imperial whitespace.  Since it's ASCII whitespace, you should probably
>> assume American...
>
>
 sys.getsizeof(' ')
> 34
 sys.getsizeof(u' ')
> 52
>
> bad by design

Yeah, but the proper way to delimit whitespace is with parentheses,
not quotes. Look:

>>> sys.getsizeof(( ))
28

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The narcissism of small code differences

2013-11-11 Thread Mark Lawrence

I never thought I'd be saying this but welcome back Rick :)

On 11/11/2013 06:50, Rick Johnson wrote:

On Saturday, November 9, 2013 6:42:04 AM UTC-6, Steven
D'Aprano wrote:

Uses an example written in Ruby, but don't
let that put you off:


Why would it? I write Ruby code all the time. Ruby code in
and of itself does not bother me, what bothers me about Ruby
is the ease at which a programmer can write inconsistent and
convoluted code -- evidenced by the poor examples in your
linked article. Case in point.

To save anyone else from reading this long-winded "blab
fest" chalk full the driest humor and "cyclic illogical
meandering" that could make a ferris-wheel blush with
jealousy...

   In a nutshell the author attempts to plead for the
   "longevity" of "old code bases" simply on the basis of his
   assertion that "old code bases" are "less buggy" and
   contain more "wisdom" than their new brethren -- both of
   which are absurd conclusions!



I recall that the demise of Netscape was due to them trying to 
completely rewrite code of this nature.  The exception that proves the rule?


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)

2013-11-11 Thread wxjmfauth
> 
> 
> * Some languages are just fundamentally bad. 

The flexible string representation is a perfect exemple.

Again, a short explanation:

This FSR splits unicode in chunks. Two immediate consequences:
- It's necessary to keep track of "each individual internal pieces of text".
- It's necessary to waste time in switching between the internal coding
schemes.

Bad memory and bad performance at the same time.


In fact, with such a mechanism, it is even impossible to write an editor.

jmf



I do not recommend ever
> 
> writing production code in Whitespace, Ook, or Piet.
> 
> 
> 
> * Some languages force you to do a lot of bookkeeping, memory
> 
> management, etc. These are inferior unless their corresponding
> 
> advantages (usually performance or memory use) justify it.
> 
> 
> 
> * Some situations specifically demand one language. If you're writing
> 
> code to be deployed on cheap web servers, it's probably going to have
> 
> to be in PHP. If it's to run inside a web browser, it pretty much has
> 
> to be JavaScript, ActionScript, or maybe something that compiles to
> 
> one of those.
> 
> 
> 
> But that would still leave you with a good few choices. When it comes
> 
> down to it, how do you choose between Ruby, Python, Perl, Pike,
> 
> JavaScript, , etcetera? I can think of
> 
> a few considerations that may or may not be important... and I'm sure
> 
> you can add more.
> 
> 
> 
> - Library support. For web work, it might be useful to be able to
> 
> create a PNG image on the fly (live graphs and such), or to have a
> 
> simple one-liner that handles cookies and persistence.
> 
> 
> 
> - Familiarity with the language. Why learn another one when you
> 
> already know this one?
> 
> 
> 
> - *Un*familiarity with the language. If you're going to have to learn,
> 
> may as well charge your boss for it!
> 
> 
> 
> - Proper Unicode support. For manipulating text, helps to be able to
> 
> work with it as text.
> 
> 
> 
> - Lack of proper Unicode support. Maybe it's easier to just work with
> 
> bytes everywhere? :)
> 
> 
> 
> - Ease/atomicity of deployment of new versions (maybe even while it's running)
> 
> 
> 
> - Buzzwordiness? If your boss asks you to choose a language and you
> 
> can say either "Ruby on Rails" or "CherryPy", are you more likely to
> 
> get approval for the former?
> 
> 
> 
> Something to throw open there. Citations from actual choices made a bonus. :)
> 
> 
> 
> ChrisA

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread Νίκος Αλεξόπουλος

Στις 6/11/2013 5:25 μμ, ο/η Νίκος Γκρ33κ έγραψε:

Okey let the hacker try again to mess with my database!!!

He is done it twice, lets see if he will make it again!

I'am waiting!


I can't believe your ignorance. You're actually telling a huge group of 
developers from all over the globe that your site is impenetrable. Do 
you know how ridiculous you sound? Have you stopped and thought that 
maybe people have better things to do than try to hack your stupid circa 
1990 website? My three year old could have modified your database. It 
doesn't take a pro to take down your 'security'. Have you not read up on 
anything these people have suggested? Cross Site Scripting? SQL 
Injection? Digital Piracy? Private User Information? No.. you haven't. 
That's why your code is starting to look like this:
if not '..' in page and not page == '/etc/passwd' and 
os.path.isfile(page) and os.path.exists('/cgi-bin' + page) and cookieID 
== 'some_secret' and host == 'superhost.gr' and 
hacker_is_not_being_mean_today:

   load_site()

load_private_user_phone_numbers_and_then_post_a_screenshot_for_everyone_to_see()
else:
   play_pre_millenium_music_and_load_lots_of_gifs()
wait___go_back_and_load_pirated_music_and_gifs_from_1995_anyway(extra_sauce=True)
You can't sue me for posting the code to your site, there was no copyright.
I guess my whole point is, if someone really cared I'm sure they could 
get into your site. They could get into a lot of sites that were created 
by people way smarter than you. Ever heard of apache exploits? cpanel 
exploits? for that matter..python exploits? Some of this is beyond your 
control. Actually, all of this is beyond your personal control, you lack 
the capability. What I meant to say is that you could not possibly fix 
all of this even if you were a better python programmer. Be glad 'she' 
wasn't mean.


==

Somebody this morning sent me an email as [email protected] sayign 
the above.

My code is not like you provided you ignorant.

# is it a python file or an html template?
if page and page in os.listdir( cgi_path ):
pyvalid = True
elif os.path.isfile( file ):
page = file.replace( path, '' )
htmlvalid = True
else:
file = 'forbidden'


if 'forbidden' in file:
print( '''Δεν επιτρέπεται η απευθείας πρόσβαση 
στο script παρά μόνον μέσω της αρχικής σελίδας!Ανακατεύθυνση σε 
5...''' )
print( '''content="5;URL=http://superhost.gr";>''' )

sys.exit(0)


if cookieID != 'wont_say' and ( htmlvalid or pyvalid ) and re.search( 
r'(amazon|google|proxy|cloud|reverse|fetch|msn|who|spider|crawl|ping)', 
host ) is None:

# do database insertion here


Tell the mighty female hacker to polish her nails, do her hair and fix a 
good meal.


She is incompetent just like yourself.

These all is just an excuse of not being able to mess with my script 
again, because is she could she would.

--
https://mail.python.org/mailman/listinfo/python-list


fd leak in parent process for logger.

2013-11-11 Thread ravindrapai34
Hi All,
   I have server process which spawns a process for each request. Where 
parent process is leaking fd for logger. Please find example code.

from threading import Thread
from multiprocessing import Process
from time import sleep
import logging
from uuid import uuid4

class ChildFile(object):
def __init__(self):
self.logger = logging.getLogger('test')
fh = logging.FileHandler('/tmp/test'+str(uuid4()))
fh.setLevel(logging.INFO)
self.logger.addHandler(fh)
self.fd = open('test2', 'wb')

def run(self):
self.logger.info('dummy run')
 
def child_file_creator():
a = ChildFile()
child_process = Process(target=a.run)
child_process.start()
child_process.join()

if __name__ == '__main__':
print 'parent process run'
while True:
child_file_creator()
sleep(10)

1) after child process exits.
2) For parent process, still fd remains open.
one can check out using,

cd /proc/23223/fd

ravindra@ravindra-Ideapad-Z570:/proc/23223/fd$ ls -ltr
total 0
l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 6 -> 
/tmp/test62bba7f1-223c-4c17-a483-f6d92ab67222
l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 5 -> 
/tmp/test2946cdf6-7e4c-4979-b56a-fd2cc698
l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 4 -> 
/tmp/test0488579b-10d7-4635-abb0-a31a0ea79eeb
lr-x-- 1 ravindra ravindra 64 Nov 11 15:10 3 -> /dev/urandom
lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 2 -> /dev/pts/19
lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 1 -> /dev/pts/19
lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 0 -> /dev/pts/19

3) while normal file descriptor of open 'test2' is closed. But fd attached to 
logger is leaking.

How can I close for the same for logger object.

Thanks and Regards,
Ravindra M
-- 
https://mail.python.org/mailman/listinfo/python-list


Implementing a multivibrator function with python

2013-11-11 Thread JL
I am trying to implement a multivibrator function with python. This is how it 
works; 

- An trigger event happens
- Upon receiving the event, a variable goes high for 5secs, then go low.
- If the event happens again before the 5secs expire, the high duration will be 
extended by another 5 secs. This works like a retriggerable multivibrator for 
those who are into electronics. 

Is there some sample code for this problem or can someone point me to using the 
right library for this feature?

Thank you very much.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The narcissism of small code differences

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 8:25 PM, Mark Lawrence  wrote:
> On 11/11/2013 06:50, Rick Johnson wrote:
>>In a nutshell the author attempts to plead for the
>>"longevity" of "old code bases" simply on the basis of his
>>assertion that "old code bases" are "less buggy" and
>>contain more "wisdom" than their new brethren -- both of
>>which are absurd conclusions!
>>
>
> I recall that the demise of Netscape was due to them trying to completely
> rewrite code of this nature.  The exception that proves the rule?

No, I would say Netscape's experience is a strong supporting example
of the contrary position. I've frequently had need to reimplement
something (most recently as part of porting functionality from RosMud,
written in C++, to Gypsum, written in Pike), and referencing the old
code is the best way to benefit from X years of corner-case
discoveries and bug fixes. Sometimes I'll even copy and paste a
comment from one version to another, because it perfectly explains
some oddity that the code has to handle - even if the code itself is
completely rewritten. Definitely if hunks of code can be kept, they
should be. The old code base *IS* less buggy and contains more wisdom.
Hardly absurd.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 8:28 PM,   wrote:
>> * Some languages are just fundamentally bad.
>
> The flexible string representation is a perfect exemple.

Wow. A new low for you, jmf... comparing PEP 393 to Ook?!?

> In fact, with such a mechanism, it is even impossible to write an editor.

And somehow a performance tradeoff makes Python no longer Turing complete.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Νίκος Αλεξόπουλος

Στις 8/11/2013 11:11 μμ, ο/η Νίκος Αλεξόπουλος έγραψε:

Is there someway to write the following line even better with the
ability to detect daylight saving time by itself so i don't have to
alter the line manually when time changes?

lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
'%y-%m-%d %H:%M:%S' )# MySQL datetime format

Thanks.



Someone has an idea what to add to this line to automatically adjust 
itself if DST happens?

--
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread lorenzo . gatti
Regarding the "select" statement, I think the most "Pythonic" approach is using 
dictionaries rather than nested ifs. 
Supposing we want to decode abbreviated day names ("mon") to full names 
("Monday"):
day_abbr='mon'

day_names_mapping={
'mon':'Monday',
'tue':'Tuesday',
'wed':'Wednesday',
'thu':'Thursday',
'fri':'Friday',
'sat':'Saturday',
'sun':'Sunday'
}
try:
full_day_name=day_names_mapping[day_abbr.casefold()]
except KeyError:
raise GoodLuckFixingItException('We don't have "'+day_abbr+'" in our week')

This style is more compact (usually one line per case) and more meaningful 
(generic processing driven by separate data) than a pile of if statement, and 
more flexible: 

full_day_names=('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')
day_names={x.casefold()[0:3] : x for x in full_day_names}
#

A dict can also contain tuples, lists, and nested dicts, consolidating multiple 
switches over the same keys and organizing nested switches and other more 
complex control structures.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 9:09 PM,   wrote:
> Regarding the "select" statement, I think the most "Pythonic" approach is 
> using dictionaries rather than nested ifs.
> Supposing we want to decode abbreviated day names ("mon") to full names 
> ("Monday"):

That's an obvious mapping, though. If you're using a select/switch
statement to handle straight-forward one-to-one mappings, then yes,
obviously the better way to do it is to use a dictionary. In the more
general sense, a switch/case block is much more directly translated
into if/elif/else statements. You can't, for instance, build up a
dictionary that handles inequalities, but you can do that with elif.

That is, normally you can't. I have occasionally built up mappings
that handle inequalities - it's a form of denormalization. Consider
the following logic:

A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
weapon]"; and if 91 to 100, "Special ability [minor special weapon]
and roll again".

My code to handle that starts out with this array:

"minor weapon":({
70,"+1 weapon: 2,000gp [weapon]",
85,"+2 weapon: 8,000gp [weapon]",
90,"Specific weapon [minor specific weapon]",
100,"Special ability [minor special weapon] and roll again",
}),

(that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
and denormalizes it into a lookup table by creating 70 entries quoting
the first string, 15 quoting the second, 5, and 10, respectively. So,
with a bit of preprocessing, a lookup table (which in this case is an
array (list), but could just as easily be a dict) can be used to
handle inequalities. But this is because lookup tables can be treated
as data, where if/elif/else blocks have to be code; there are roughly
42 million such lookup tables in the code I snagged that from, and
having code for each one would work out far less manageable. Normally,
you'll want to render inequalities with code as if/elif.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Implementing a multivibrator function with python

2013-11-11 Thread Dave Angel
On Mon, 11 Nov 2013 01:41:58 -0800 (PST), JL  
wrote:
- If the event happens again before the 5secs expire, the high 
duration will be extended by another 5 secs. This works like a 
retriggerable multivibrator for those who are into electronics.


More precisely a retriggerable monostable multivibrator.

The question makes little sense unless you're running in an event 
driven environment, such as a gui. Name the environment and somebody 
can probably help.


--
DaveA

--
https://mail.python.org/mailman/listinfo/python-list


Re: Implementing a multivibrator function with python

2013-11-11 Thread Terry Reedy

On 11/11/2013 4:41 AM, JL wrote:

I am trying to implement a multivibrator function with python. This is how it 
works;

- An trigger event happens
- Upon receiving the event, a variable goes high for 5secs, then go low.
- If the event happens again before the 5secs expire, the high duration will be 
extended by another 5 secs. This works like a retriggerable multivibrator for 
those who are into electronics.

Is there some sample code for this problem or can someone point me to using the 
right library for this feature?


Python 3.4 will have a new asyncio package that includes an event loop 
module. It will be in the forthcoming 3.4.b0 release; it might be in 
3.4.a4 but I have not installed that yet. In any case, I believe it 
should make the above easy.


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Steven D'Aprano
On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:

> My code to handle that starts out with this array:
> 
> "minor weapon":({
> 70,"+1 weapon: 2,000gp [weapon]",
> 85,"+2 weapon: 8,000gp [weapon]",
> 90,"Specific weapon [minor specific weapon]", 100,"Special ability
> [minor special weapon] and roll again",
> }),
> 
> (that's Pike; in Python it'd be a list, or maybe a tuple of tuples), and
> denormalizes it into a lookup table by creating 70 entries quoting the
> first string, 15 quoting the second, 5, and 10, respectively.

Ewww :-(

Imagine having to print out the dict looking for an error in the lookup 
table. Or imagine the case where you have:

0...2: do this
20001...890001: do that
890001...890003: do something else

Don't get me wrong, it's a clever and reasonable solution for your 
specific use-case. But I'd much rather have a lookup table variant that 
matches on intervals.

Hmmm... if you had an interval data type, which was hashable, that would 
probably be trivial... what am I missing? Ah, of course, what I'm missing 
is that although you're storing intervals as the keys, you're matching 
regular ints.

I wonder if this would be a good use-case for Antoine Pitrou's 
TransformDict?

http://www.python.org/dev/peps/pep-0455/


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting globals of the caller, not the defining module

2013-11-11 Thread Steven D'Aprano
Suppose I have a function that needs access to globals:

# module A.py
def spam():
g = globals()  # this gets globals from A
introspect(g)

As written, spam() only sees its own globals, i.e. those of the module in 
which spam is defined. But I want spam to see the globals of the caller.

# module B
import A
A.spam()  # I want spam to see globals from B


I can have the caller explicitly pass the globals itself:

def spam(globs=None):
if globs is None:
globs = globals()
introspect(globs)


But since spam is supposed to introspect as much information as possible, 
I don't really want to do that. What (if anything) are my other options?


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting globals of the caller, not the defining module

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 10:25 PM, Steven D'Aprano
 wrote:
> But since spam is supposed to introspect as much information as possible,
> I don't really want to do that. What (if anything) are my other options?

You're playing with introspection, so I'd look at poking around in the
stack trace. It'll be esoteric, but I think this is the right place to
use it.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 10:17 PM, Steven D'Aprano
 wrote:
> On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:
>> denormalizes it into a lookup table by creating 70 entries quoting the
>> first string, 15 quoting the second, 5, and 10, respectively.
>
> Ewww :-(
>
> Imagine having to print out the dict looking for an error in the lookup
> table. Or imagine the case where you have:
>
> 0...2: do this
> 20001...890001: do that
> 890001...890003: do something else
>
> Don't get me wrong, it's a clever and reasonable solution for your
> specific use-case. But I'd much rather have a lookup table variant that
> matches on intervals.

Of course it's "Ewww" in isolation :) But just imagine there are piles
and piles of these tables, themselves keyed by keyword, and I want to
be able to let untrusted people create tables (which means they
basically have to be data, not code). Also, bear in mind, all the
tables are based around dice that can be physically rolled, so none
has more than 100 entries after denormalization. Quite a lot of the
tables actually have unique entries per value (eg it's a d10 roll,
with ten unique outputs), so it's simplest to just turn all the tables
into that format; that way, the main code needs worry about one type
only, and the preprocessor handles the denormalization.

And if there's an error in the lookup table, well, you look at the
normalized version, not at the one that actually gets parsed :) That's
basically like looking back at the Python source code rather than the
disassembled byte-code; apart from actually debugging the preprocessor
itself (which can be done with a ten-entry table that's easily
eyeballed), the denormalized version needn't be looked at by a human.

But this is a very VERY specific situation. Normally it's best to just
use an if/elif block. That's why this looks so "Ewww". :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Robert Kern

On 2013-11-11 10:39, Chris Angelico wrote:


A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
weapon]"; and if 91 to 100, "Special ability [minor special weapon]
and roll again".

My code to handle that starts out with this array:

"minor weapon":({
 70,"+1 weapon: 2,000gp [weapon]",
 85,"+2 weapon: 8,000gp [weapon]",
 90,"Specific weapon [minor specific weapon]",
 100,"Special ability [minor special weapon] and roll again",
}),

(that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
and denormalizes it into a lookup table by creating 70 entries quoting
the first string, 15 quoting the second, 5, and 10, respectively. So,
with a bit of preprocessing, a lookup table (which in this case is an
array (list), but could just as easily be a dict) can be used to
handle inequalities. But this is because lookup tables can be treated
as data, where if/elif/else blocks have to be code; there are roughly
42 million such lookup tables in the code I snagged that from, and
having code for each one would work out far less manageable. Normally,
you'll want to render inequalities with code as if/elif.


Heh. I've done pretty much exactly the same thing to implement an engine[1] to 
draw from the random tables on Abulafia[2] which have nearly the same structure. 
It scales up reasonably well beyond d100s. It's certainly not a technique I 
would pull out to replace one-off if-elif chains that you literally write, but 
it works well when you write the generic code once to apply to many tables.


[1] http://rollmeup.mechanicalkern.com/
[2] http://www.random-generator.com/index.php?title=Main_Page

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
https://mail.python.org/mailman/listinfo/python-list


Re: Help - Exercise Decision

2013-11-11 Thread Kennedy Salvino
Em domingo, 10 de novembro de 2013 19h56min45s UTC-3, Kennedy Salvino  escreveu:
> I'm trying to make a ranking of 3 numbers and say which the greatest and 
> consider whether there is a tie between them, I am not able to make the 
> conditions of draws.  
> 
> 
> 
> Code in PT-BR: http://pastebin.com/18pYJjPC

My teacher asked .. I will try to do as you said.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help - Exercise Decision

2013-11-11 Thread Kennedy Salvino
My teacher asked .. I will try to do as you said.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting globals of the caller, not the defining module

2013-11-11 Thread sg552
(Sorry for posting through GG, I'm at work.)

On Monday, November 11, 2013 11:25:42 AM UTC, Steven D'Aprano wrote:
> Suppose I have a function that needs access to globals:
> 
> # module A.py
> def spam():
> g = globals()  # this gets globals from A
> introspect(g)
> 
> As written, spam() only sees its own globals, i.e. those of the module in 
> which spam is defined. But I want spam to see the globals of the caller.
> 
> # module B
> import A
> A.spam()  # I want spam to see globals from B
> 
> I can have the caller explicitly pass the globals itself:
> 
> def spam(globs=None):
> if globs is None:
> globs = globals()
> introspect(globs)
> 
> But since spam is supposed to introspect as much information as possible, 
> I don't really want to do that. What (if anything) are my other options?

How about this?

# module A.py
import inspect
def spam():
return inspect.stack()[1][0].f_globals

# module B.py
import A
print(A.spam() is globals()) # prints True
def f():
return A.spam()

# module C.py
import B
print(B.f() is vars(B)) # prints True

I don't really know what I'm doing but I guess it won't work in alternative 
implementations of Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Chris Angelico
On Mon, Nov 11, 2013 at 10:53 PM, Robert Kern  wrote:
> Heh. I've done pretty much exactly the same thing to implement an engine[1]
> to draw from the random tables on Abulafia[2] which have nearly the same
> structure. It scales up reasonably well beyond d100s. It's certainly not a
> technique I would pull out to replace one-off if-elif chains that you
> literally write, but it works well when you write the generic code once to
> apply to many tables.

I'd trust my current code for several orders of magnitude beyond where
I'm currently using it, but as Steven said, you really don't want to
be manually looking at the denormalized tables. Since all the strings
are referenced anyway, having a lookup array of (say) 1,000,000 object
pointers is fairly cheap.

>>> lst = ["Low" if i<50 else "High" for i in range(100)]
>>> sys.getsizeof(lst)
4348736

That's pretty close to four bytes per entry, which would be the
cheapest you could hope for on a 32-bit system. 10% overhead is quite
acceptable. And this is a fairly extreme example :)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Joel Goldstick
On Mon, Nov 11, 2013 at 4:57 AM, Νίκος Αλεξόπουλος
 wrote:
> Στις 8/11/2013 11:11 μμ, ο/η Νίκος Αλεξόπουλος έγραψε:
>
>> Is there someway to write the following line even better with the
>> ability to detect daylight saving time by itself so i don't have to
>> alter the line manually when time changes?
>>
>> lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
>> '%y-%m-%d %H:%M:%S' )# MySQL datetime format
>>
>> Thanks.
>
>
>
> Someone has an idea what to add to this line to automatically adjust itself

Three days ago Mark Lawrence pointed you to a stack overflow answer to
your question.  While it didn't suit your demand for a single line
answer, it could easily be made into a function which returned the
string format that you requested.  You've been around long enough to
try to work that out for yourself.  If you yourself had returned with
a one liner to perform what Mark showed you, I can imagine a lot of
people would be impressed at your dedication!

I think you are oversimplifying the problem.  I recall that you server
is in Germany, and you are in Greece.  If these are two different time
zones, I am guessing that the German time will be given.  Also, any
linux user who runs package updates regularly (thinking Ubuntu)
realizes that some file that starts with tz gets changed quite often.
This is because time zones are set by governments, and the date of
change from standard to daylight time can be differently, depending
upon the location and the governing body.

I pose this question to you:

Why not display UTC?  If it is so important to you to display local
time, why do you think that your host's local time is something that
is useful for a visitor?  Daylight savings time is more complicated
that you have suggested
> if DST happens?

If you insist upon displaying the local time of your server, you
should not be hardcoding in a 2 hour difference.  Let the python
library figure out the delta by giving the country code
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fd leak in parent process for logger.

2013-11-11 Thread Roy Smith
In article ,
 [email protected] wrote:

> Hi All,
>I have server process which spawns a process for each request. Where 
>parent process is leaking fd for logger. Please find example code.

You've got a lot of code here.  The first thing to do when trying to 
debug a problem like this is get rid of anything that's not essential to 
demonstrating the problem.  You import Thread, but don't appear to use 
it.  Get rid of the import line.  You also do this in a loop.  Can you 
demonstrate the same problem with a single pass?

Anyway, my guess here is that the logging package is keeping a reference 
to your log file when you create each FileHandler.  Try configuring the 
logger in your run() method instead of __init__().  I believe (untested) 
that will make the file get opened in the child process.


> 
> from threading import Thread
> from multiprocessing import Process
> from time import sleep
> import logging
> from uuid import uuid4
> 
> class ChildFile(object):
> def __init__(self):
> self.logger = logging.getLogger('test')
> fh = logging.FileHandler('/tmp/test'+str(uuid4()))
> fh.setLevel(logging.INFO)
> self.logger.addHandler(fh)
> self.fd = open('test2', 'wb')
> 
> def run(self):
> self.logger.info('dummy run')
>  
> def child_file_creator():
> a = ChildFile()
> child_process = Process(target=a.run)
> child_process.start()
> child_process.join()
> 
> if __name__ == '__main__':
> print 'parent process run'
> while True:
> child_file_creator()
> sleep(10)
> 
> 1) after child process exits.
> 2) For parent process, still fd remains open.
> one can check out using,
> 
> cd /proc/23223/fd
> 
> ravindra@ravindra-Ideapad-Z570:/proc/23223/fd$ ls -ltr
> total 0
> l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 6 -> 
> /tmp/test62bba7f1-223c-4c17-a483-f6d92ab67222
> l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 5 -> 
> /tmp/test2946cdf6-7e4c-4979-b56a-fd2cc698
> l-wx-- 1 ravindra ravindra 64 Nov 11 15:10 4 -> 
> /tmp/test0488579b-10d7-4635-abb0-a31a0ea79eeb
> lr-x-- 1 ravindra ravindra 64 Nov 11 15:10 3 -> /dev/urandom
> lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 2 -> /dev/pts/19
> lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 1 -> /dev/pts/19
> lrwx-- 1 ravindra ravindra 64 Nov 11 15:10 0 -> /dev/pts/19
> 
> 3) while normal file descriptor of open 'test2' is closed. But fd attached to 
> logger is leaking.
> 
> How can I close for the same for logger object.
> 
> Thanks and Regards,
> Ravindra M
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Implementing a multivibrator function with python

2013-11-11 Thread Antoon Pardon
Op 11-11-13 10:41, JL schreef:
> I am trying to implement a multivibrator function with python. This is how it 
> works; 
> 
> - An trigger event happens
> - Upon receiving the event, a variable goes high for 5secs, then go low.
> - If the event happens again before the 5secs expire, the high duration will 
> be extended by another 5 secs. This works like a retriggerable multivibrator 
> for those who are into electronics. 
> 
> Is there some sample code for this problem or can someone point me to using 
> the right library for this feature?
> 
> Thank you very much.
> 
The problem is that it depnds on the kind of trigger event. Is it a signal?
Is it a character that arrives through a pipe or socket?

I would take a look at the signal module and see if it can get you started.

-- 
Antoon Pardon
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Roy Smith
> On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:

> > print ( {"mon":"mondays suck",
> >  "tue":"at least it's not monday",
> >  "wed":"humpday"
> > }.get(day_of_week,"its some other day")
> >   )

In article <[email protected]>,
 Rick Johnson  wrote:
> Proper code formatting can do WONDERS for readability!
> 
> d = {
> "mon":"mondays suck",
> "tue":"at least it's not monday",
> "wed":"humpday"
> }
> default = "some other day"
> target = "tue"
> print d.get(target, default)
> target = "blah"
> print d.get(target, default)

I agree that Rick's version is better than rusi's version, but possibly 
not for the the reason Rick thinks it is :-)  rusi's version has a 
"parsing surprise" in it.  As a human scans the code, the thought 
process goes something like this:

> > print ( {"mon":"mondays suck",

"OK, I'm going to print a dictionary"

> >  "tue":"at least it's not monday",

"Yeah, still looks like I'm printing a dictionary"

> >  "wed":"humpday"

"Yeah, more dictionary, this still makes sense, I'm just waiting to get 
to the and of the dictionary so I can print it"

> > }.get(day_of_week,"its some other day")

"Oh, my!  I'm not printing a dictionary after all!  I'm doing a get() on 
it!"

> >   )

"Ugh, what's this close paren?  Does it terminate the get(), or the 
print()?  I need to go back and count open parens to make sure"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Roy Smith
In article ,
 Joel Goldstick  wrote:

> Why not display UTC?  If it is so important to you to display local
> time, why do you think that your host's local time is something that
> is useful for a visitor?

In general, it makes sense to run servers (and log everything) in UTC, 
and display local time to your users.  The idea is to do the conversion 
(in both directions) as close to the user as possible (which, for a web 
application, means a little piece of javascript right in the browser).

It seems like extra work, but, trust me, it will preserve your sanity 
eventually.

We've got a data supplier who (for reasons I cannot fathom), runs their 
network in local time.  Every time we talk to them about problems, it's 
a mess just trying to figure out what time we're talking about.  We say, 
"we saw a latency spike at 2243 UTC, what caused that?", and then we 
play 20-questions trying to figure out if that's 1443 PDT, or 1543 PST, 
or who knows what.  Further complicated by them occasionally asking us 
off-the-wall questions like, "Is that UTC daylight savings time?"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 1:14 AM, Roy Smith  wrote:
> We've got a data supplier who (for reasons I cannot fathom), runs their
> network in local time.  Every time we talk to them about problems, it's
> a mess just trying to figure out what time we're talking about.  We say,
> "we saw a latency spike at 2243 UTC, what caused that?", and then we
> play 20-questions trying to figure out if that's 1443 PDT, or 1543 PST,
> or who knows what.  Further complicated by them occasionally asking us
> off-the-wall questions like, "Is that UTC daylight savings time?"

UGH. Yes. I get the same thing from some of the US players in my
Dungeons & Dragons campaign. To avoid the hassles of international
times, everything's scheduled in UTC; the Aussies, the Europeans, and
_some of_ the Americans an handle it, but there are a few who keep
asking me crazy questions about DST and UTC. I'm like... no, there is
no daylight time! Just look at the current UTC time and see how that
compares! There's even a command in-game that shows current UTC time.

Fortunately, those people are in the minority. Most of the players can
handle the time conversions.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Joel Goldstick
So this is a physics joke.  The engineers and physicists at the
conference went to dinner.  They ordered wine with dinner.  The wait
person asked: "Would you like the small liter, or the large liter?"



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)

2013-11-11 Thread Mark Lawrence

On 11/11/2013 09:28, [email protected] wrote:


* Some languages are just fundamentally bad.


The flexible string representation is a perfect exemple.

Again, a short explanation:

This FSR splits unicode in chunks. Two immediate consequences:
- It's necessary to keep track of "each individual internal pieces of text".
- It's necessary to waste time in switching between the internal coding
schemes.

Bad memory and bad performance at the same time.


In fact, with such a mechanism, it is even impossible to write an editor.

jmf



For the benefit of newbies, lurkers or whatever please ignore the 
rubbish written by "Joseph McCarthy" Faust regarding PEP 393 and the 
Flexible String Representation.  He keeps making these false claims in 
double spaced google crap despite having been shot down in this thread
https://groups.google.com/forum/#!topic/comp.lang.python/JkVQT0Wbq1A[1-25-false], 
where he was asked to provide evidence to support his claims.  he didn't 
do so then, he's been asked repeatedly since to do so but hasn't because 
he can't, hence his newly aquired nickname.


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread rusi
On Monday, November 11, 2013 7:31:07 PM UTC+5:30, Roy Smith wrote:
> > On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:

> > > print ( {"mon":"mondays suck",
> > >  "tue":"at least it's not monday",
> > >  "wed":"humpday"
> > > }.get(day_of_week,"its some other day")
> > >   )

>  Rick Johnson  wrote:
> > Proper code formatting can do WONDERS for readability!
> > d = {
> > "mon":"mondays suck",
> > "tue":"at least it's not monday",
> > "wed":"humpday"
> > }
> > default = "some other day"
> > target = "tue"
> > print d.get(target, default)
> > target = "blah"
> > print d.get(target, default)

> I agree that Rick's version is better than rusi's version, but possibly 
> not for the the reason Rick thinks it is :-)  rusi's version has a 
> "parsing surprise" in it.  As a human scans the code, the thought 
> process goes something like this:

Yes I did not like my own version for similar reason: I expect the
switch order (classic C) to be
1. expression
2. body
3. default

The following does not quite do it but is it better?

def switch(val, default, body_dict):
return body_dict.get(val,default)

day=...
switch(day,  "something else",
 {"mon"  : "mondays suck",
  "tue"  : "at least it's not monday",
  "wed"  : "humpday"
 }
  )

Of course one can flip the body and the default but I find that looks more 
confusing.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Neil Cerutti
> On Saturday, November 9, 2013 8:27:02 AM UTC-5, Joshua Landau wrote:
> The C switch statement is very limited.  The select statement
> in the dialect of BASIC I regularly use is more flexible.
> It's more concise on long if chains because it elides the "end
> if"s.  But the use of indentation for blocks and the "in"
> operator certainly reduce the need for it in Python.

It's say the C switch isn't limited enough to be a Python
resident. The default fallthrough, labels, jumps and breaks make
it a poor Python construct.

K&R have this to say: "Falling through from one case to another
is not robust, being prone to disintegration when the program is
modified."

So Python would need something simler. Once you winnow it down to
a robust feature, it provide virtually nothing you don't get with
an if/elif/else. At best it would save a temporary.

> The switch statement in (the language) go is similar, except
> that  defaults to true and it doesn't elide
>  in the case statements.

Go makes interesting use of switch statements. In addition to
what you might expect, you can also do type switches. A type
switch lets you provide a different execution path depending on
the underlying object represented by an interface.

Thus, Go carved out a useful niche for a robust switch statement.
Python used duck-typing instead of interfaces and generally
doesn't need any special syntax for type checks, hence Go's
version of switch doesn't make sense for Python, either.

Go's cases must be constants, and allows optional fallthrough
with the 'fallthrough' keyword. This forces them to provide break
semantics to break out of a switch, which makes using them to
break of an immediately outer loop messy.

> Dictionaries can't handle the uses where expression0 is
> constant and the case expressions are not. Function variables
> beg the question.  How did you decide what to assign to the
> variable?

A Python generator might take the place of that application, but
I haven't tried it for that.

> I'd use this select if it was in Python, but I don't see much
> need for it.

Same here. Perhaps the real value of a switch is that it seems to
be a more natural way of thinking about execution. The caveat to
that is most *actual* switch implementations are a mess.

-- 
Neil Cerutti
-- 
https://mail.python.org/mailman/listinfo/python-list


Install Tkinter for Windows 7 64-bit

2013-11-11 Thread jonas . thornvall
I have installed Python 3.3, and i want to add a library with some basic 
functions like canvas and basic geomteric objects, fonts etc. Preferably 
something similar to the Javascript canvas.

I've looked for graphic packages, and from what i can see something called 
Tkinter may be what i look for.

However i have no luck install it, i installed something called Visual studio 
in hope it would incorporate Tkinter, but it did not and it also do not seem to 
work with 3.3 only 3.1 and below.

Next i found ActiveStateTCL that from what i could see incorporated Tkinter 
library?

But i have no luck runn the Tkinter example file i downloaded in idel, it still 
says no module called Tkinter.


===
Traceback (most recent call last):
  File "D:\Python33\test2.py", line 16, in 
from Tkinter import Tk, Canvas, Frame, BOTH
ImportError: No module named 'Tkinter'
===

Maybe i should use some other module, i just need a canvas and the basic 
geometric objects functions line,rectangle,circle and some font.

JT
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread Tim Golden
On 11/11/2013 16:38, [email protected] wrote:
> I have installed Python 3.3, and i want to add a library with some
> basic functions like canvas and basic geomteric objects, fonts etc.
> Preferably something similar to the Javascript canvas.
> 
> I've looked for graphic packages, and from what i can see something
> called Tkinter may be what i look for.
> 
> However i have no luck install it, i installed something called
> Visual studio in hope it would incorporate Tkinter, but it did not
> and it also do not seem to work with 3.3 only 3.1 and below.
> 
> Next i found ActiveStateTCL that from what i could see incorporated
> Tkinter library?
> 
> But i have no luck runn the Tkinter example file i downloaded in
> idel, it still says no module called Tkinter.
> 
> 
> === Traceback (most recent call last): File "D:\Python33\test2.py",
> line 16, in  from Tkinter import Tk, Canvas, Frame, BOTH 
> ImportError: No module named 'Tkinter' ===
> 
> Maybe i should use some other module, i just need a canvas and the
> basic geometric objects functions line,rectangle,circle and some
> font.

I'll let others comment on the use of Tk. But...

The Tkinter module has been reorganised under Python 3.x:

  http://docs.python.org/3.3/library/tkinter.html#module-tkinter

You're presumably working from a Python 2.x example

TJG
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread Tim Golden
On 11/11/2013 16:38, [email protected] wrote:
> === Traceback (most recent call last): File "D:\Python33\test2.py",
> line 16, in  from Tkinter import Tk, Canvas, Frame, BOTH 
> ImportError: No module named 'Tkinter' ===

In addition, I really don't recommend running your test scripts straight
out of the Python install directory. Consider using a separate "dev"
area somewhere else.

TJG
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread jonas . thornvall
Here is the example file i have tried.

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

This program draws three
rectangles filled with different
colors.

author: Jan Bodar
last modified: January 2011
website: www.zetcode.com
"""

from Tkinter import Tk, Canvas, Frame, BOTH


class Example(Frame):
  
def __init__(self, parent):
Frame.__init__(self, parent)   
 
self.parent = parent
self.initUI()

def initUI(self):
  
self.parent.title("Colors")
self.pack(fill=BOTH, expand=1)

canvas = Canvas(self)
canvas.create_rectangle(30, 10, 120, 80, 
outline="#fb0", fill="#fb0")
canvas.create_rectangle(150, 10, 240, 80, 
outline="#f50", fill="#f50")
canvas.create_rectangle(270, 10, 370, 80, 
outline="#05f", fill="#05f")
canvas.pack(fill=BOTH, expand=1)



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread Mark Lawrence

On 11/11/2013 16:38, [email protected] wrote:

I have installed Python 3.3, and i want to add a library with some basic 
functions like canvas and basic geomteric objects, fonts etc. Preferably 
something similar to the Javascript canvas.

I've looked for graphic packages, and from what i can see something called 
Tkinter may be what i look for.

However i have no luck install it, i installed something called Visual studio 
in hope it would incorporate Tkinter, but it did not and it also do not seem to 
work with 3.3 only 3.1 and below.

Next i found ActiveStateTCL that from what i could see incorporated Tkinter 
library?

But i have no luck runn the Tkinter example file i downloaded in idel, it still 
says no module called Tkinter.


===
Traceback (most recent call last):
   File "D:\Python33\test2.py", line 16, in 
 from Tkinter import Tk, Canvas, Frame, BOTH
ImportError: No module named 'Tkinter'
===

Maybe i should use some other module, i just need a canvas and the basic 
geometric objects functions line,rectangle,circle and some font.

JT



Renamed in Python 3 to tkinter see 
http://www.python.org/dev/peps/pep-3108/#tkinter-package


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread Chris “Kwpolska” Warrick
On Mon, Nov 11, 2013 at 5:38 PM,   wrote:
> But i have no luck runn the Tkinter example file i downloaded in idel, it 
> still says no module called Tkinter.
IDLE*
> ===
> Traceback (most recent call last):
>   File "D:\Python33\test2.py", line 16, in 
> from Tkinter import Tk, Canvas, Frame, BOTH
> ImportError: No module named 'Tkinter'
> ===

In Python 3, 'Tkinter' was renamed to 'tkinter' (both sans quotes).
Please change the file to reflect that (as the traceback points out,
line 16).

-- 
Chris “Kwpolska” Warrick 
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread jonas . thornvall
Den måndagen den 11:e november 2013 kl. 17:43:12 UTC+1 skrev Chris “Kwpolska” 
Warrick:
> On Mon, Nov 11, 2013 at 5:38 PM,   wrote:
> 
> > But i have no luck runn the Tkinter example file i downloaded in idel, it 
> > still says no module called Tkinter.
> 
> IDLE*
> 
> > ===
> 
> > Traceback (most recent call last):
> 
> >   File "D:\Python33\test2.py", line 16, in 
> 
> > from Tkinter import Tk, Canvas, Frame, BOTH
> 
> > ImportError: No module named 'Tkinter'
> 
> > ===
> 
> 
> 
> In Python 3, 'Tkinter' was renamed to 'tkinter' (both sans quotes).
> 
> Please change the file to reflect that (as the traceback points out,
> 
> line 16).
> 
> 
> 
> -- 
> 
> Chris “Kwpolska” Warrick 
> 
> PGP: 5EAAEA16
> 
> stop html mail | always bottom-post | only UTF-8 makes sense

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Install Tkinter for Windows 7 64-bit

2013-11-11 Thread MRAB

On 11/11/2013 16:43, [email protected] wrote:

Here is the example file i have tried.

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

This program draws three
rectangles filled with different
colors.

author: Jan Bodar
last modified: January 2011
website: www.zetcode.com
"""

from Tkinter import Tk, Canvas, Frame, BOTH


class Example(Frame):

 def __init__(self, parent):
 Frame.__init__(self, parent)

 self.parent = parent
 self.initUI()

 def initUI(self):

 self.parent.title("Colors")
 self.pack(fill=BOTH, expand=1)

 canvas = Canvas(self)
 canvas.create_rectangle(30, 10, 120, 80,
 outline="#fb0", fill="#fb0")
 canvas.create_rectangle(150, 10, 240, 80,
 outline="#f50", fill="#f50")
 canvas.create_rectangle(270, 10, 370, 80,
 outline="#05f", fill="#05f")
 canvas.pack(fill=BOTH, expand=1)

That looks like it was written for Python 2 because in Python 3 the 
module is named "tkinter".


It's also lacking the part where it calls the .mainloop method.


from tkinter import Tk, Canvas, Frame, BOTH

class Example(Frame):

def __init__(self, parent):
Frame.__init__(self, parent)

self.parent = parent
self.initUI()

def initUI(self):

self.parent.title("Colors")
self.pack(fill=BOTH, expand=1)

canvas = Canvas(self)
canvas.create_rectangle(30, 10, 120, 80,
outline="#fb0", fill="#fb0")
canvas.create_rectangle(150, 10, 240, 80,
outline="#f50", fill="#f50")
canvas.create_rectangle(270, 10, 370, 80,
outline="#05f", fill="#05f")
canvas.pack(fill=BOTH, expand=1)

def main():

root = Tk()
#root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()

if __name__ == '__main__':
main()

--
https://mail.python.org/mailman/listinfo/python-list


Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)

2013-11-11 Thread Ethan Furman

On 11/11/2013 01:28 AM, [email protected] wrote:



* Some languages are just fundamentally bad.


The flexible string representation is a perfect exemple.


Argh!  He escaped!  *chase* *scuffle* *stuff* *stuff* *stuff*

Whew.  Safely back in the troll bin.

Okay, back to my day.

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)

2013-11-11 Thread 88888 Dihedral
On Sunday, November 10, 2013 4:56:38 PM UTC+8, Jorgen Grahn wrote:
> On Sun, 2013-11-10, Chris Angelico wrote:
> 
> > On Sun, Nov 10, 2013 at 11:41 AM, Roy Smith  wrote:
> 
> >> On 09/11/2013 22:58, Chris Angelico wrote:
> 
> >>> >
> 
> >>> > * Some languages are just fundamentally bad. I do not recommend ever
> 
> >>> > writing production code in Whitespace, Ook, or Piet.
> 
> >>
> 
> >> One of the worst coding experiences I ever had was trying to build an
> 
> >> app for a Roku media player.  They have a home-grown language called
> 
> >> BrightScript.  Barf.
> 
> >
> 
> > And this is exactly why I was so strongly against the notion of
> 
> > developing an in-house scripting language. It may be a lot of work to
> 
> > evaluate Lua, Python, JavaScript, and whatever others we wanted to
> 
> > try, but it's a *lot* less work than making a new language that
> 
> > actually is worth using.
> 
> 
> 
> Yes.  I am baffled that people insist on doing the latter. Designing a
> 
> limited /data/ language is often a good idea; designing something
> 
> which eventually will need to become Turing-complete is not.

Python is designed with the VM 
interpreter to execute compiled 
byte codes.

Of course, C/C++/JAVA are lower 
level languages not designed in 
this way.

To remedy the efficient part, 
cython and C-extensions are available
in Python. 


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Denis McMahon
On Mon, 11 Nov 2013 11:57:36 +0200, Νίκος Αλεξόπουλος wrote:

>> lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
>> '%y-%m-%d %H:%M:%S' )# MySQL datetime format

> Someone has an idea what to add to this line to automatically adjust
> itself if DST happens?

Yes, but the scarcity of universal whitespace is preventing me from 
posting it.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Ethan Furman

On 11/11/2013 11:19 AM, Denis McMahon wrote:

On Mon, 11 Nov 2013 11:57:36 +0200, Νίκος Αλεξόπουλος wrote:


lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
'%y-%m-%d %H:%M:%S' )# MySQL datetime format



Someone has an idea what to add to this line to automatically adjust
itself if DST happens?


Yes, but the scarcity of universal whitespace is preventing me from
posting it.


Boy, are you in luck!  I just happen to have a whole heap of marked down ascii 
white-space at bargain basement prices!

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


dateutil.relativedelta.WE and friends?

2013-11-11 Thread Skip Montanaro
I found a rather inscrutable use of dateutil recurrence rules in
StackOverflow which generates a series of dates corresponding to the
third Wednesday of the  month:

import dateutil.rrule as dr
import dateutil.relativedelta as drel

dt = datetime.datetime(2012, 1, 1, 0, 0)
rule = dr.rrule(dr.MONTHLY, byweekday=drel.WE(3), dtstart=dt, count=12)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dateutil.relativedelta.WE and friends?

2013-11-11 Thread Skip Montanaro
damn gmail. Please ignore the drivel below (and this top post)...

Skip

On Mon, Nov 11, 2013 at 2:33 PM, Skip Montanaro  wrote:
> I found a rather inscrutable use of dateutil recurrence rules in
> StackOverflow which generates a series of dates corresponding to the
> third Wednesday of the  month:
>
> import dateutil.rrule as dr
> import dateutil.relativedelta as drel
>
> dt = datetime.datetime(2012, 1, 1, 0, 0)
> rule = dr.rrule(dr.MONTHLY, byweekday=drel.WE(3), dtstart=dt, count=12)
-- 
https://mail.python.org/mailman/listinfo/python-list


'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Frank-Rene Schäfer
I prepared a PEP and was wondering what your thoughts are about it:

  PEP:
  Title:  ``isimmutable(Obj)`` and/or ``ImmutableNester``
  Version:
  Last-Modified:  
  Author: Frank-Rene Schaefer, [email protected]
* BDFL-Delegate:  
* Discussions-To: [email protected]
  Status: Draft
  Type:   
* Content-Type:   text/x-rst
* Requires:   
  Created:11-nov-2013
* Python-Version: 2.7.1
  Post-History:   
* Replaces:   
* Superseded-By:  
* Resolution: 

General Idea


A built-in function 'isimmutable()' shall tell efficiently whether the object
of concern is mutable or not. That is it must reflect on the whole object tree
whether it contains mutable elements or not.  For example, in the code fragment

::
verdict_0 = isimmutable(3.14)
verdict_1 = isimmutable((1,2,3))
verdict_2 = isimmutable(((1,2),(2,3),(3,4)))

all verdicts are 'True' because the tested objects consist of purely immutable
components. However, the ``x`` in

::
x   = (1,(2,"abc", [1,2,3]))
verdict = isimmutable(x)

triggers the verdict to be 'False' because ``x[1][2]`` is a list and therefore
mutable.

It may be conceivable to have a special class-type called ``ImmutableNester``
which has no write-access member functions and does not allow its derived
classes to have write-access member functions. Instead, any derived class
aggregates members at the time of construction. At this point in time, when
members are nested in the class, it is checked if the members are of subclasses
of ``ImmutableNester``.

The advantage of the ``isimmutable()`` function is that no extra class
functionality needs to be implemented. The disadvantage is that the
immutability must be checked manually and at each time the object is used. The
``ImmutableNester`` class type checks for immutability once, at construction
time and no further manual checks are necessary.

Rationale
=

If an object is immutable then copying of it can be safely be replaced by a
setting of a reference. The principal scenario is when an instance A gives an
instance B access to some data D under the provision that B does not change it.
Therefore, B must either clone the data or it must be safe to assume that the
data cannot change, i.e. is immutable.

If the objects are large and/or many there a significant performance impact may
raise from a deepcopy or manual cloning of objects. Therefore, the
``isimmutable()`` built-in function is key for a safe implementation of
reference-instead-of-copying.

Ensuring immutability is also key for the so called 'Flyweight Design Pattern'.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: datetime question

2013-11-11 Thread Grant Edwards
On 2013-11-11, Ethan Furman  wrote:
> On 11/11/2013 11:19 AM, Denis McMahon wrote:
>> On Mon, 11 Nov 2013 11:57:36 +0200, ?? ?? wrote:
>>
 lastvisit = ( datetime.utcnow() + timedelta(hours=2) ).strftime(
 '%y-%m-%d %H:%M:%S' )# MySQL datetime format
>>
>>> Someone has an idea what to add to this line to automatically adjust
>>> itself if DST happens?
>>
>> Yes, but the scarcity of universal whitespace is preventing me from
>> posting it.
>
> Boy, are you in luck!  I just happen to have a whole heap of marked
> down ascii white-space at bargain basement prices!

Careful, a lot of the cheap imported whitespace was made with toxic
lead carbonate instead of the non-toxic titatium oxide that should be
used...

-- 
Grant Edwards   grant.b.edwardsYow! I'd like MY data-base
  at   JULIENNED and stir-fried!
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Joshua Landau
On 11 November 2013 10:39, Chris Angelico  wrote:
> On Mon, Nov 11, 2013 at 9:09 PM,   wrote:
>> Regarding the "select" statement, I think the most "Pythonic" approach is 
>> using dictionaries rather than nested ifs.
>> Supposing we want to decode abbreviated day names ("mon") to full names 
>> ("Monday"):
>
> You can't [normally], for instance, build up a
> dictionary that handles inequalities, but you can do that with elif.
> [...] Consider the following logic:
>
> A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to
> 70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon:
> 8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific
> weapon]"; and if 91 to 100, "Special ability [minor special weapon]
> and roll again".
>
> My code to handle that starts out with this array:
>
> "minor weapon":({
> 70,"+1 weapon: 2,000gp [weapon]",
> 85,"+2 weapon: 8,000gp [weapon]",
> 90,"Specific weapon [minor specific weapon]",
> 100,"Special ability [minor special weapon] and roll again",
> }),
>
> (that's Pike; in Python it'd be a list, or maybe a tuple of tuples),
> and denormalizes it into a lookup table by creating 70 entries quoting
> the first string, 15 quoting the second, 5, and 10, respectively. So,
> with a bit of preprocessing, a lookup table (which in this case is an
> array (list), but could just as easily be a dict) can be used to
> handle inequalities.

The obvious way to me is a binary search:

from bisect import bisect_left

class FloorMap:
def __init__(self, dct):
self.indexes = sorted(list(dct))
self.dct = dct

def __getitem__(self, itm):
index = self.indexes[bisect_left(self.indexes, itm)]
return self.dct[index]


minor_weapon = FloorMap({
70:  "+1 weapon: 2,000gp [weapon]",
85:  "+2 weapon: 8,000gp [weapon]",
90:  "Specific weapon [minor specific weapon]",
100: "Special ability [minor special weapon] and roll again"
})

minor_weapon[63]
#>>> '+1 weapon: 2,000gp [weapon]'

The precise details of the wrapper class here are just to make
initialisation pretty; it could be done straight from a pair of lists
too:

from bisect import bisect_left

minor_weapon_indexes = 70, 85, 90, 100
minor_weapon_descriptions = (
"+1 weapon: 2,000gp [weapon]",
"+2 weapon: 8,000gp [weapon]",
"Specific weapon [minor specific weapon]",
"Special ability [minor special weapon] and roll again"
)

minor_weapon_descriptions[bisect_left(minor_weapon_indexes, 80)]
#>>> '+2 weapon: 8,000gp [weapon]'

Compare to

if 80 <= 70:
res = "+1 weapon: 2,000gp [weapon]"

elif 80 <= 85:
res = "+2 weapon: 8,000gp [weapon]"

elif 80 <= 90:
res = "Specific weapon [minor specific weapon]"

elif 80 <= 100:
res = "Special ability [minor special weapon] and roll again"

which although shorter¹ is a lot less data-driven and much less reusable.

¹ Longer if you ignore the import and class declaration.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread Ned Batchelder
On Monday, November 11, 2013 3:47:45 PM UTC-5, Frank-Rene Schäfer wrote:
> I prepared a PEP and was wondering what your thoughts are about it:

The best place to discuss proposals for changes to the Python language and 
library is the Python-Ideas mailing list: 
https://mail.python.org/mailman/listinfo/python-ideas

There you will get in-depth discussion about the details of your proposal.  
Fair warning: it's very unlikely that your proposal will be adopted (most are 
not), but you will learn a lot about how Python works in the process. :)

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 'isimmutable' and 'ImmutableNester'

2013-11-11 Thread random832
> A built-in function 'isimmutable()' shall tell efficiently whether the
> object
> of concern is mutable or not.

What's the benefit over attempting to hash() the object?

copy.deepcopy already has special case for int, string, and tuples
(including tuples that do and do not have mutable members) - could what
you need be accomplished by overriding __copy__ and __deepcopy__ in your
custom class to return itself if it is immutable?
-- 
https://mail.python.org/mailman/listinfo/python-list


UTF-32 decoder optimization in Python 3.4

2013-11-11 Thread Mark Lawrence
From http://docs.python.org/dev/whatsnew/3.4.html#optimizations "The 
UTF-32 decoder is now 3x to 4x faster.".  Does anybody have any 
references to this work?  All I can find is the 3.3 what's new which 
refers to PEP 393 (Flexible String Representation) optimizations as a 
result of work done by Serhiy Storchaka on issues 14624, 14738 and 15026.


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 7:50 AM, Joshua Landau  wrote:
> The obvious way to me is a binary search:

Which makes an O(log n) search where I have an O(1) lookup. The
startup cost of denormalization doesn't scale, so when the server
keeps running for two years or more, it's definitely worth processing
it that way.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-11 Thread Mark Janssen
On Mon, Nov 11, 2013 at 3:32 AM, Chris Angelico  wrote:
> On Mon, Nov 11, 2013 at 10:17 PM, Steven D'Aprano
>  wrote:
>> On Mon, 11 Nov 2013 21:39:27 +1100, Chris Angelico wrote:
>>> denormalizes it into a lookup table by creating 70 entries quoting the
>>> first string, 15 quoting the second, 5, and 10, respectively.
>>
>> Ewww :-(
>>
>> Imagine having to print out the dict looking for an error in the lookup
>> table. Or imagine the case where you have:
>>
>> 0...2: do this
>> 20001...890001: do that
>> 890001...890003: do something else
>>
>> Don't get me wrong, it's a clever and reasonable solution for your
>> specific use-case. But I'd much rather have a lookup table variant that
>> matches on intervals.
>
> Of course it's "Ewww" in isolation :) But just imagine there are piles
> and piles of these tables, themselves keyed by keyword, and I want to
> be able to let untrusted people create tables (which means they
> basically have to be data, not code). Also, bear in mind, all the
> tables are based around dice that can be physically rolled, so none
> has more than 100 entries after denormalization. Quite a lot of the
> tables actually have unique entries per value (eg it's a d10 roll,
> with ten unique outputs), so it's simplest to just turn all the tables
> into that format; that way, the main code needs worry about one type
> only, and the preprocessor handles the denormalization.

Hmm, I automatically think of creating a hash function, but then
that's how Python implements keys in dicts, so a dict is fine
solution.

-- 
MarkJ
Tacoma, Washington
-- 
https://mail.python.org/mailman/listinfo/python-list


Creating a function for a directory

2013-11-11 Thread Matt
So I want to take the file, "desktop/test.txt" and write it to 
"desktop/newfolder/test.txt". I tried the below script, and it gave me: 
"IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any 
suggestions would be great.



def firstdev(file):
in_file = open("desktop/%s.txt") % file
indata = in_file.read()
out_file = open("desktop/newfolder/%s.txt", 'w') % file
out_file.write(indata)
out_file.close()
in_file.close()

firstdev("test")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Joel Goldstick
On Mon, Nov 11, 2013 at 5:26 PM, Matt  wrote:
> So I want to take the file, "desktop/test.txt" and write it to 
> "desktop/newfolder/test.txt". I tried the below script, and it gave me: 
> "IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any 
> suggestions would be great.

Its better in the future to cut and paste the traceback rather than
paraphrase...

That being said, it can't find the in_file.  Maybe you aren't in the
directory above desktop?  Try specifying a complete path, instead of
relative.  Once you solve that, be sure the ouput path is specificed
completely and that it exists.
>
>
>
> def firstdev(file):
> in_file = open("desktop/%s.txt") % file
> indata = in_file.read()
> out_file = open("desktop/newfolder/%s.txt", 'w') % file
> out_file.write(indata)
> out_file.close()
> in_file.close()
>
> firstdev("test")
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Chris Angelico
On Tue, Nov 12, 2013 at 9:26 AM, Matt  wrote:
> So I want to take the file, "desktop/test.txt" and write it to 
> "desktop/newfolder/test.txt". I tried the below script, and it gave me: 
> "IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any 
> suggestions would be great.
>
>
>
> def firstdev(file):
> in_file = open("desktop/%s.txt") % file
> indata = in_file.read()
> out_file = open("desktop/newfolder/%s.txt", 'w') % file

You're using the % operator, which does your interpolations, at the
wrong point. You want to be adjusting the file name, not adjusting the
opened file:

in_file = open("desktop/%s.txt" % file)
out_file = open("desktop/newfolder/%s.txt" % file, 'w')

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread bob gailer

On 11/11/2013 5:26 PM, Matt wrote:

So I want to take the file, "desktop/test.txt" and write it to 
"desktop/newfolder/test.txt". I tried the below script, and it gave me: "IOError: [Errno 2] No 
such file or directory: 'desktop/%s.txt'". Any suggestions would be great.



def firstdev(file):
in_file = open("desktop/%s.txt") % file

The problem is the above line. Rewrite is thus:

in_file = open("desktop/%s.txt" % file)



indata = in_file.read()
out_file = open("desktop/newfolder/%s.txt", 'w') % file

Same here:

 out_file = open("desktop/newfolder/%s.txt"% file, 'w')


out_file.write(indata)
out_file.close()
in_file.close()

Also don't get in the habit of reassigning built-in functions e;g; file.


firstdev("test")



--
Bob Gailer
919-636-4239
Chapel Hill NC

--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Joel Goldstick
Sorry for incorect answer. Those guys nailed it
On Nov 11, 2013 5:43 PM, "bob gailer"  wrote:

> On 11/11/2013 5:26 PM, Matt wrote:
>
>> So I want to take the file, "desktop/test.txt" and write it to
>> "desktop/newfolder/test.txt". I tried the below script, and it gave me:
>> "IOError: [Errno 2] No such file or directory: 'desktop/%s.txt'". Any
>> suggestions would be great.
>>
>>
>>
>> def firstdev(file):
>> in_file = open("desktop/%s.txt") % file
>>
> The problem is the above line. Rewrite is thus:
>
> in_file = open("desktop/%s.txt" % file)
>
>
>  indata = in_file.read()
>> out_file = open("desktop/newfolder/%s.txt", 'w') % file
>>
> Same here:
>
>>  out_file = open("desktop/newfolder/%s.txt"% file, 'w')
>>
>>
>> out_file.write(indata)
>> out_file.close()
>> in_file.close()
>>
> Also don't get in the habit of reassigning built-in functions e;g; file.
>
>>
>> firstdev("test")
>>
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Mark Lawrence

On 11/11/2013 22:26, Matt wrote:

So I want to take the file, "desktop/test.txt" and write it to 
"desktop/newfolder/test.txt". I tried the below script, and it gave me: "IOError: [Errno 2] No 
such file or directory: 'desktop/%s.txt'". Any suggestions would be great.



def firstdev(file):
in_file = open("desktop/%s.txt") % file


in_file = open("desktop/%s.txt" % file)


indata = in_file.read()
out_file = open("desktop/newfolder/%s.txt", 'w') % file
out_file.write(indata)
out_file.close()
in_file.close()

firstdev("test")



--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list


Re: To whoever hacked into my Database

2013-11-11 Thread rurpy
On 11/08/2013 11:08 AM, Chris Angelico wrote:
> On Sat, Nov 9, 2013 at 4:11 AM,   wrote:
>> On 11/08/2013 03:05 AM, Νίκος Αλεξόπουλος wrote:
>>> I never ignore advices.
>>> I read all answers as carefully as i can.
>>> But nevertheless sometimes i feel things should have been better
>>> implemented using my way.
>>>
>>> Not of course that i know better, but thats better suited for me in the
>>> level iam.
>>
>> Most of the "advice" I've seen posted here has, as far
>> as I can tell, not intended to be useful but to serve
>> as a way to telling you are incompetent are in other ways
>> insulting or useless.  I think you are quite right to
>> ignore it (or tell the poster to get lost.)
> 
> Actually no; most of the advice has been genuine.

Actually yes; most of the advice has not been genuine.

Of course neither you nor I know for sure since we can't
read minds.  But when "advice" consists of things like
 "Maybe try some of the advice you have been given instead? "
 "use php"
 "Try starting with something simple. The following is a 
  step by step guide... Now, and this is really really
  going to tax you..."
 A treatise on 1nf in six short sentences followed by
  ruminations on competence including "...never shows
  a glimmer of interest in learning."
 "Now that helpful suggestions have been offered, and
  the OP continues to obstinately refuse to learn,"
I don't consider it "helpful" nor do I believe the 
claims of  such people (who have an history of antagonistic
responses) that they are genuinely trying to be helpful.

If you want to be helpful try posting useful information
without the insults, with an attempt to tune it to the 
level of understanding the recipient and without the 
offensive "do what I tell you" attitude.

>> Long before you showed up here, I noticed the tendency
>> to not answer questions directly but to jerk people off
>> by giving hints or telling them to do something other
>> than they want to do.
>>
>> Often that is good because the original request was
>> for something that the OP really didn't want to do.
>> But sometimes the OP knows they want to do (but doesn't
>> want or is unable to clearly explain why) and when
>> they clearly state that, yes, they do want to do it
>> their way, their question should be answered in good
>> faith or, for those who just can't tell how to do
>> something "wrong", ignored.
> 
> I disagree. If you go to a doctor and ask for a prescription for
> , the doctor is quite right in refusing if
> s/he believes that that won't help you. If the OP asks for a way to
> stuff more into a single record in MySQL, then we're right to say "No,
> don't do it that way".

No you're not.  Without determining how the data is to be 
used you can't say it's not normalized.  Otherwise one
could claim every of the millions of databases containing 
addresses is not even 1nf because their designers crammed
two pieces of information (street number and street name) 
into a single datum.

Second, to simply say, "don't do that, it's not 1nf" when 
most database systems provide data types like arrays, set, 
composites etc whose purpose is to do what you're saying not 
to do is not being helpful -- it's being domineering and 
condescending.

Finally you're wrong to say "no" because you are not in
a position to evaluate all the criteria that determines 
right or wrong for the OP.  For example it is often easier 
when learning to use something one understands better, or 
uses less code or is  simpler is some other way to the learner, 
with the intent to fix it later if experience shows the need.

> Generally, people who ask for one thing and are advised another will
> see that the advice is actually getting them to where they really
> wanted to be. There's another thread now about calling from Python
> into C, which I haven't been following closely, but I saw a comment
> from its OP to the effect of "Oh right! Standard input/output would do
> what I want!" - it may not have been specifically what was asked for,
> but it was helpful. If it's not helpful, give a reason for that.

Right.  Which is why I wrote 

  >> Often that telling the OP he is doing it wrong] is good because
  >> the original request was for something that the OP really didn't
  >> want to do.

I then went on to address my comments to the case where the OP insists 
he *does* want what he asks for.  So you could have saved us all a 
little time by leaving out the above irrelevant paragraph.

> Do you (anyone) know better than all the people of this newsgroup?

That you are so naive as to propose that majority opinion
is always right is so naive I'm not sure what to think, other 
than to wonder how old you are.

> I would think not, firstly because you're asking the question (why are
> you asking if you already know better), 

That's pretty illogical thinking.  How can he know better *before*
he asks and sees the answers.  Only after he gets the answers can
one decide if they are better or not.  

> and secondly bec

Re: datetime question

2013-11-11 Thread rurpy
On Friday, November 8, 2013 3:06:33 PM UTC-7, Joel Goldstick wrote:
> rurpy?  can you help?

No, sorry.  For your future reference, if there is a 
question I can help with (have the technical knowledge, 
haven't seen a good answer yet, have time, etc) I will
post my attempt at an answer.  

So lack of such a response is a pretty good clue that
I can't help at the current time, and there is no need
to ping me explicitly.

I do appreciate your "genuine" concern for Nikos and 
that he gets a good answer though.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >