Re: Obfuscated factorial

2013-10-27 Thread Vito De Tullio
Joshua Landau wrote:

> Python already supports the factorial operator, -ⵘ.

why use ⵘ (TIFINAGH LETTER AYER YAGH) when you can have the BANG? 방 (HANGUL 
SYLLABLE BANG)


> You just have to
> import it.
> 
> # Import statement
> ⵘ = type("",(),{"__rsub__":lambda s,n:(lambda f,n:f(f,n))(lambda
> f,z:round((2.5066282746310002*(z+0j+7.5)**(z+0.5)*2.718281828459045**(-
z-7.5)*(0.80993+676.5203681218851/(z+1)-1259.1392167224028/(z+2)+771.32342877765313/(z+3)-176.61502916214059/(z+4)+12.507343278686905/(z+5)-0.13857109526572012/(z+6)+9.9843695780195716e-6/(z+7)+1.5056327351493116e-7/(z+8))).real)if
> z>=0.5 else
> 3.141592653589793/(__import__("math").sin(3.141592653589793*z)*f(f,1-
z)),n)})()

I'm really, really impressed!

-- 
By ZeD

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


Logging to file and not to console

2013-10-27 Thread Johannes Findeisen
Hi all,

I am going crazy with logging. I have an application which sets up
logging after parsing the args in the main() funktion. It needs to be
setup after parsing the args because I can set the loglevel via
commandline flags.

I have tried many variants on how to do that but every time with an
weird result.

What I want is logging in from all libs and really understand that doing
this should be enough there:

from logging import getLogger
logger = getLogger(__name__)

But, I need to setup the logger in the main() function to log only to a
file and not to console because my application has an own shell
interface which should not be spammed with log messages - never a
message should show up there.

I think it should be only some few lines of code but I can't figure
that out. The logger should be configured to have a max file size and
rotate logfiles.

Can someone help me with this?

Thanks in advance,
Johannes  
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Printing a drop down menu for a specific field.

2013-10-27 Thread Nick the Gr33k

Στις 27/10/2013 6:00 πμ, ο/η ru...@yahoo.com έγραψε:

On 10/26/2013 06:11 PM, Nick the Gr33k wrote:

Στις 27/10/2013 2:52 πμ, ο/η Nick the Gr33k έγραψε:

Ah foun it had to change in you code this line:
  key = host, city, useros, browser, ref

to this line:

  key = host, city, useros, browser

so 'ref' wouldnt be calculated in the unique combination key.

I'am still trying to understand the logic of your code and trying to
create a history list column for the 'referrers'

I dont know how to write it though to produce the sam


Iam trying.

Ah foun it had to change in you code this line:
  key = host, city, useros, browser, ref

to this line:

  key = host, city, useros, browser

so 'ref' wouldnt be calculated in the unique combination key.

I'am still trying to understand the logic of your code and trying to
create a history list column for the 'referrers'

I dont know how to write it though to produce the same output for referrers.

The bast i came up with is:

[code]
def coalesce( data ):
newdata = []
seen = {}
for host, city, useros, browser, ref, hits, visit in data:
# Here i have to decide how to group the rows together.
# I want an html row for every unique combination of 
(host, city,
useros, browser) and that hits should be summed together.
key = host, city, useros, browser
if key not in seen:
newdata.append( [host, city, useros, browser, 
[ref], hits, [visit]] )
seen[key] = len( newdata ) - 1  # Save 
index (for 'newdata') of this
row.
else:   # This row is a duplicate row with a 
different visit time.
rowindex = seen[key]
newdata[rowindex][4].append( ref )
newdata[rowindex][5] += hits
newdata[rowindex][6].append( visit )
return newdata


cur.execute( '''SELECT host, city, useros, browser, ref, hits,
lastvisit FROM visitors
WHERE counterID = (SELECT ID FROM 
counters WHERE url = %s) ORDER BY
lastvisit DESC''', page )
data = cur.fetchall()


newdata = coalesce( data )
for row in newdata:
(host, city, useros, browser, refs, hits, visits) = row
# Note that 'ref' & 'visits' are now lists of visit times.

print( "" )
for item in (host, city, useros, browser):
print( " %s " % 
item )

print( "" )
for n, ref in enumerate( refs ):
if n == 0:
op_selected = 'selected="selected"'
else:
op_selected = ''
print( "%s" % (op_selected, ref) )
print( "" )

for item in (hits):
print( " %s " % 
item )

print( "" )
for n, visit in enumerate( visits ):
visittime = visit.strftime('%A %e %b, %H:%M')
if n == 0:
op_selected = 'selected="selected"'
else:
op_selected = ''
print( "%s" % (op_selected, 
visittime) )
print( "" )

print( "" )
[/code]

But this doesnt work correctly for refs and also doenst not print for
some reason the hits and visit colums.


Without a traceback it is hard to figure out what is happening.
(Actually in this case there is one obvious error, but there are
also some unobvious ones.)

Here is what I did to find the problems, and what you can do
the next time.  The main thing was to extract the code from
the cgi script so that I could run it outside of the web server
and without needing access to the database.  Then you can add
print statements (or run with the pdb debugger) and see tracebacks
and other errors easily.

1. Copy and paste the code from your message into a .py file.
2. Put a "def main(): line at the top of your main code.
3. Add a line at the bottom to call main()
4. Copy and paste a part of the web page you gave that list all the visits.
5. Edit it (change TAB to "|", add comma's after each line, etc, to
  create a statement that will create variable, DATA.
6. Add a few statements to turn DATA into variable 'data' which has a
  format similar to the format returned by your cur.fetchall() call.

This all took just 10 or 15 minutes, and I ended up with the
following code:
--
 def main():
 data = [ln.split('|') for ln in DATA]
 for r 

Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rusi
On Sunday, October 27, 2013 10:34:11 AM UTC+5:30, ru...@yahoo.com wrote:
> On 10/26/2013 07:45 PM, rusi wrote:
> 
> > On Sunday, October 27, 2013 2:07:53 AM UTC+5:30, Peter Cacioppi wrote:
> >> Rusi said:
> >> 
> >> "Users of GG are requested to read and follow these instructions
> >> https://wiki.python.org/moin/GoogleGroupsPython " 
> >> 
> >> Seriously, it's not exactly clear what protocol GG users are expected 
> >> follow 
> >> to make posts hygenic.
> 
> 
> First, thanks (both of you) very much for the feedback.  I originally 
> wrote that page.

One more 'to-be-removed' from that page is the bit about new and old GG at the 
end.  It used to work for a while. Now google has completely removed the 'old 
interface' (at least to the best of my knowledge).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Gregory Ewing

Ben Finney wrote:

On systems conforming to the Filesystem Hierarchy Standard, it's
forbidden: programs go in a platform-specific location
http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA>,
while platform-independent data files go in a separate location
http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRSHAREARCHITECTUREINDEPENDENTDATA>.


But Python code itself is platform-independent, so it
should count as data for the purposes of the FHS,
shouldn't it?

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


Re: Using the nntplib module to count Google Groups users

2013-10-27 Thread rusi
On Sunday, October 27, 2013 12:07:29 PM UTC+5:30, Zero Piraeus wrote:
> The results:
> 
> 
> Senders: 1701
> GG users: 879
> 
> ... so just over 50%.
> 
> 
> If anyone wants the complete output, just let me know and I'll email it
> privately.

If you have a GG account just go to the 'aboutgroup' info here:
https://groups.google.com/forum/#!aboutgroup/comp.lang.python

It tells me there are 21447 members.

What that means I shall not hazard.

Instead I quote a book 'Mathsemantics' by Edward Macneal


I 1980 I was one passenger, ten passengers, eighteen passengers, thirty-six 
passengers, forty-two passengers, fifty-five passengers, seventy-two passengers 
and ninety-four passengers.  Each of these statements is true.
---
... explanation...
---
I was one passenger in the sense that I was a person who traveled by air in 
that year.
I was eighteen passengers in the sense that I made eighteen round trips.
I was forty-two passengers in the sense that on forty-two different occasions I 
entered and exited the system of a different carrier.
I was seventy-two passengers in the sense that on seventy-two occasions I was 
on board an aircraft when it took off from one place and landed at another.
I was ninety-four passengers in the sense that I made ninety-four separate 
entrances and exits from airport terminal buildings.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: trying to strip out non ascii.. or rather convert non ascii

2013-10-27 Thread Mark Lawrence

On 27/10/2013 01:11, Roy Smith wrote:

In article ,
  Dennis Lee Bieber  wrote:


Compared to Baudot, both ASCII and EBCDIC were probably considered
wondrous.


Wonderous, indeed.  Why would anybody ever need more than one case of
the alphabet?  It's almost as absurd as somebody wanting to put funny
little marks on top of their vowels.



True indeed but it gets worse.  For example those silly Spanish speaking 
types consider this ñ a letter in its own right and not a funny little 
mark on top of a consonant :)


--
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: array/list of sockets

2013-10-27 Thread rusi
On Sunday, October 27, 2013 4:47:16 AM UTC+5:30, theel...@gmail.com wrote:
> I apologize but I do not understand what you mean by "lack of context." I 
> have 
> taken Chris' words into consideration, for my previous post was supposed to 
> be 
> my last (I just had to say thank you). This is my first google groups post, 
> so > I am a total noob. Once again, I apologize for whatever that I may have 
> done. I 
> will not post in google groups again : )

See http://en.wikipedia.org/wiki/Posting_style
in particular the difference between 'top-posting' and 'interleaved style'

There is no universal standard about this.
Ive been in corporate cultures where doing anything other than top-posting is 
taken as doing something fishy -- hiding, distorting etc.

However on this forum which BTW is Usenet and predates the popular internet 
(WWW) by some decades, it is considered impolite to do anything other than 
'interleaved'

This means 
1. You need to cut out most of useless crufty context
2. Keep a little so that the reader knows who/what you are speaking in response 
to
3. Keep your response as close to and generally below the context
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logging to file and not to console

2013-10-27 Thread Peter Otten
Johannes Findeisen wrote:

> Hi all,
> 
> I am going crazy with logging. I have an application which sets up
> logging after parsing the args in the main() funktion. It needs to be
> setup after parsing the args because I can set the loglevel via
> commandline flags.
> 
> I have tried many variants on how to do that but every time with an
> weird result.
> 
> What I want is logging in from all libs and really understand that doing
> this should be enough there:
> 
> from logging import getLogger
> logger = getLogger(__name__)
> 
> But, I need to setup the logger in the main() function to log only to a
> file and not to console because my application has an own shell
> interface which should not be spammed with log messages - never a
> message should show up there.
> 
> I think it should be only some few lines of code but I can't figure
> that out. The logger should be configured to have a max file size and
> rotate logfiles.
> 
> Can someone help me with this?

import logging
import logging.handlers

logger = logging.getLogger(__name__)

def levelnames():
try:
names = logging._nameToLevel
except AttributeError:
names = (name for name in logging._levelNames if isinstance(name, 
str))

def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--logging-file", default="tmp.log")
parser.add_argument("--logging-level", choices=levelnames(), 
default="INFO")
args = parser.parse_args()

root = logging.getLogger()

formatter = logging.Formatter(logging.BASIC_FORMAT)
handler = logging.handlers.RotatingFileHandler(args.logging_file, 
maxBytes=100, backupCount=3)
handler.setFormatter(formatter)

root.addHandler(handler)
root.setLevel(args.logging_level)

logger.info("your info")
logger.warn("your warning")
logger.critical("your critical message")

if __name__ == "__main__":
main()

Does this do what you want?
(maxBytes is probably a bit low)


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


Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rusi
On Sunday, October 27, 2013 2:07:53 AM UTC+5:30, Peter Cacioppi wrote:
> Rusi said:
> 
> > Users of GG are requested to read and follow these instructions
> > https://wiki.python.org/moin/GoogleGroupsPython
> 
> Yes, I read those instructions and found them fairly opaque. If you want to 
> instruct "children" (odd that I find myself categorized that way on a CS 
> forum, but whatever) then you use pictures.

The children is intended almost literally:
GG claims that the python list (or its version thereof) has 21447 'members'.
I am willing to bet that the average age of the 21447 humans whose records are 
in google's dbms is between half and one-third of those that use usenet 
channels.

I am speaking a bit legalistically because just as statisticians will argue 
about what 'average' (or mean) means, likewise we could argue about what a 
'member' means:
- someone who joins but does not post
- someone who joins and does not even read
- someone who posts frequently. [What's the frequency threshold?]

And which is why I quoted the passage from mathsemantics in the other thread 
(repeated below). So all we can really infer is that the table in some GG 
database contains 21447 records



I 1980 I was one passenger, ten passengers, eighteen passengers, thirty-six 
passengers, forty-two passengers, fifty-five passengers, seventy-two passengers 
and ninety-four passengers.  Each of these statements is true.
---
... explanation...
---
I was one passenger in the sense that I was a person who traveled by air in 
that year.
I was eighteen passengers in the sense that I made eighteen round trips.
I was forty-two passengers in the sense that on forty-two different occasions I 
entered and exited the system of a different carrier.
I was seventy-two passengers in the sense that on seventy-two occasions I was 
on board an aircraft when it took off from one place and landed at another.
I was ninety-four passengers in the sense that I made ninety-four separate 
entrances and exits from airport terminal buildings. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logging to file and not to console

2013-10-27 Thread Peter Otten
Peter Otten wrote:

> def levelnames():
> try:
> names = logging._nameToLevel
> except AttributeError:
> names = (name for name in logging._levelNames if isinstance(name,
> str))

Trainwreck alert :(

I recommend that you use the following list

"DEBUG INFO WARN ERROR CRITICAL".split()

directly rather than fixing the above.


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


Re: Removing python django projects

2013-10-27 Thread rusi
On Sunday, October 27, 2013 6:44:35 AM UTC+5:30, Gary Roach wrote:
> Hi
> 
> In the process of trying to learn python, django, mysql and 
> virtualenvwrapper, I have created two projects and a mess. How can I 
> strip everything from a Debian, Wheezy, linux system. The files are all 
> over the place. Much of the information in this area is for Mac or 
> Windoz systems that do not have the apt-get, aptitude tools that Debian 
> makes available.
> 
> My goal is to end up with a clean system ready for re installation of a 
> development environment.

Disclaimer: This subject interests me and I know nothing about it ;-) 

1. Aren't you asking for something self-contradictory -- the benefits of apt in 
apt-disabled systems?
Anyways… leaving that aside…

2. Not clear what you mean by 'clean system'.
One meaning could be remove all the 'crufty' files
Another could be disengage the system so that it runs easily on mac and windows.
For the first apt is a boon for second its a mess

3. I see questions like yours here
https://groups.google.com/forum/#!searchin/python-virtualenv/Advice$20on$20Updating$20Virtualenv/python-virtualenv/4lgTsf9EwZM/MhNvwkIVq6sJ
Maybe you could also ask there about use of 'wheel'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Printing a drop down menu for a specific field.

2013-10-27 Thread Dave Angel
On 27/10/2013 03:31, Nick the Gr33k wrote:

> Στις 27/10/2013 6:00 πμ, ο/η ru...@yahoo.com έγραψε:

 
>
> I read it thoroughly and tested it and it works as it should.
>
> I just wanted to mention that the definition of the function coalesce() 
> must come prior of:
>
>>  newdata = coalesce( data )
>>  for row in newdata:
>
> because function must be defined first before we try to call it and pass 
> data to ti, so i placed it just before that.
>

I found the above two lines in the function main(), in Rurpy's code.  If
that's where you were talking about, the comment about order does not
apply.

If you are calling from one function into another (in this case from
main() into coalesce()), and the two functions are defined at global
scope, then the functions may be appear in either order.

it's only when you're calling a function from global scope, or sometimes
when nesting functions inside each other, that order of
definition of the two functions matters.  Naturally, the call to main()
from top-level has to be after both functions are defined.

-- 
DaveA


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


Re: Check if this basic Python script is coded right

2013-10-27 Thread rusi
On Saturday, October 26, 2013 11:50:33 PM UTC+5:30, MRAB wrote:
> On 26/10/2013 18:36, HC wrote:
> > I'm doing my first year in university and I need help with this basic 
> > assignment.
> >
> > Assignment: Write Python script that prints sum of cubes of numbers between 
> > 0-200 that are multiples of 3. 3^3+6^3+9^3+12^3+198^3=?

> >
> > Is it all okay?
> >
> Just one small point: the assignment says that the numbers should be in
> the range 0-200, but the loop's condition is count<200 it's excluding
> 200, so the numbers will actually be in the range 0-199.
> 
> However, as 200 isn't a multiple of 3, it won't affect the result, but
> in another assignment it might.
> 
> (For the record, this is known as an "off-by-one" error.)

So is an off-by-one error that did not happen an off-by-an-off-by-one error?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Function for the path of the script?

2013-10-27 Thread Roy Smith
In article ,
 Ben Finney  wrote:

> Peter Cacioppi  writes:
> 
> > Am I the only one who finds this function super useful?
> >
> > def _code_file() :
> > return os.path.abspath(inspect.getsourcefile(_code_file))
> 
> I've used ‘os.path.dirname(os.path.abspath(__file__))’ to find the
> directory containing the current file, in the past. But that was before
> Python's ‘unittest’ module could discover where the test code lives.
> 
> > I've got one in every script. It's the only one I have to copy around.
> > For my workflow ... so handy.
> 
> What workflow requires you to know the filename of the module, within
> the module?

We use:

config_dir = os.path.abspath(os.path.dirname(__file__))
songza_dir, _ = os.path.split(config_dir)
top_dir, _ = os.path.split(songza_dir)
assert os.path.exists(top_dir + "/.hg")
return top_dir

in our config files.  This gives us the absolute path to the top of our 
source tree (I don't remember why we do the double os.path.split() 
instead of the more obvious "../..").  We know the file where this code 
lives is two levels down from the top of the source tree.

Once we've got the absolute path to the top of the tree, that's used in 
all sorts of places to locate data files, and to generate configurations 
for other applications (nginx, etc).
-- 
https://mail.python.org/mailman/listinfo/python-list


Running Python programmes

2013-10-27 Thread David
I am an absolute beginner and am working through the book Python Programming 
for the Absolute Beginner by Michael Dawson.  Everything is fine except if I 
run a scripted programme, or one I have downloaded, and then run another one, 
the second one will not run, I just get the >>> in the interactive window.  I 
have to exit Python and start again, when the second programme then runs fine.

Any suggestions much appreciated.

David

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


Re: Cookie fucking problem

2013-10-27 Thread Antoon Pardon

Op 26-10-13 23:43, Ben Finney schreef:

Mark Lawrence  writes:


I could almost feel sorry for you.  But the more of your time I waste
the longer it'll take you to get your website working.


Feel free to occupy your time with baiting Nikos. But *do not* do it in
this forum.


Would you mind telling this to others too. AFAICS Chris Angelico is just
as much baiting Nikos, as Mark Lawrence is. But I don't see you reacting
to Chris. So it seems you don't have a problem so much with baiting as
long as the baiting is done in a way you find acceptable.

Personnaly I don't see much difference between the two, so if you allow
Chris baiting Nikos, I don't see why Mark should hold back.

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


Re: Logging to file and not to console

2013-10-27 Thread Johannes Findeisen
On Sun, 27 Oct 2013 11:09:08 +0100
Peter Otten wrote:

> Johannes Findeisen wrote:
> 
> > Hi all,
> > 
> > I am going crazy with logging. I have an application which sets up
> > logging after parsing the args in the main() funktion. It needs to be
> > setup after parsing the args because I can set the loglevel via
> > commandline flags.
> > 
> > I have tried many variants on how to do that but every time with an
> > weird result.
> > 
> > What I want is logging in from all libs and really understand that doing
> > this should be enough there:
> > 
> > from logging import getLogger
> > logger = getLogger(__name__)
> > 
> > But, I need to setup the logger in the main() function to log only to a
> > file and not to console because my application has an own shell
> > interface which should not be spammed with log messages - never a
> > message should show up there.
> > 
> > I think it should be only some few lines of code but I can't figure
> > that out. The logger should be configured to have a max file size and
> > rotate logfiles.
> > 
> > Can someone help me with this?
> 
> import logging
> import logging.handlers
> 
> logger = logging.getLogger(__name__)
> 
> def levelnames():
> try:
> names = logging._nameToLevel
> except AttributeError:
> names = (name for name in logging._levelNames if isinstance(name, 
> str))
> 
> def main():
> import argparse
> parser = argparse.ArgumentParser()
> parser.add_argument("--logging-file", default="tmp.log")
> parser.add_argument("--logging-level", choices=levelnames(), 
> default="INFO")
> args = parser.parse_args()
> 
> root = logging.getLogger()
> 
> formatter = logging.Formatter(logging.BASIC_FORMAT)
> handler = logging.handlers.RotatingFileHandler(args.logging_file, 
> maxBytes=100, backupCount=3)
> handler.setFormatter(formatter)
> 
> root.addHandler(handler)
> root.setLevel(args.logging_level)
> 
> logger.info("your info")
> logger.warn("your warning")
> logger.critical("your critical message")
> 
> if __name__ == "__main__":
> main()
> 
> Does this do what you want?
> (maxBytes is probably a bit low)

Yes! That was exactly what I want! Thank you very much! Now it behaves
well. I know that maxBytes is slow but that will be configurable in the
future. I just needed some clean way to get debug messages even from
libs like APScheduler. When running my application in production mode
logging will be completely disabled so it is Ok this way.

You saved my day... :)

Happy hacking!
Johannes
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logging to file and not to console

2013-10-27 Thread Johannes Findeisen
On Sun, 27 Oct 2013 11:09:08 +0100
Peter Otten wrote:

> Johannes Findeisen wrote:
> 
> > Hi all,
> > 
> > I am going crazy with logging. I have an application which sets up
> > logging after parsing the args in the main() funktion. It needs to be
> > setup after parsing the args because I can set the loglevel via
> > commandline flags.
> > 
> > I have tried many variants on how to do that but every time with an
> > weird result.
> > 
> > What I want is logging in from all libs and really understand that doing
> > this should be enough there:
> > 
> > from logging import getLogger
> > logger = getLogger(__name__)
> > 
> > But, I need to setup the logger in the main() function to log only to a
> > file and not to console because my application has an own shell
> > interface which should not be spammed with log messages - never a
> > message should show up there.
> > 
> > I think it should be only some few lines of code but I can't figure
> > that out. The logger should be configured to have a max file size and
> > rotate logfiles.
> > 
> > Can someone help me with this?
> 
> import logging
> import logging.handlers
> 
> logger = logging.getLogger(__name__)
> 
> def levelnames():
> try:
> names = logging._nameToLevel
> except AttributeError:
> names = (name for name in logging._levelNames if isinstance(name, 
> str))
> 
> def main():
> import argparse
> parser = argparse.ArgumentParser()
> parser.add_argument("--logging-file", default="tmp.log")
> parser.add_argument("--logging-level", choices=levelnames(), 
> default="INFO")
> args = parser.parse_args()
> 
> root = logging.getLogger()
> 
> formatter = logging.Formatter(logging.BASIC_FORMAT)
> handler = logging.handlers.RotatingFileHandler(args.logging_file, 
> maxBytes=100, backupCount=3)
> handler.setFormatter(formatter)
> 
> root.addHandler(handler)
> root.setLevel(args.logging_level)
> 
> logger.info("your info")
> logger.warn("your warning")
> logger.critical("your critical message")
> 
> if __name__ == "__main__":
> main()
> 
> Does this do what you want?
> (maxBytes is probably a bit low)

Yes! That was exactly what I want! Thank you very much! Now it behaves
well. I know that maxBytes is slow but that will be configurable in the
future. I just needed some clean way to get debug messages even from
libs like APScheduler. When running my application in production mode
logging will be completely disabled so it is Ok this way.

I knew there must be an easy way because in Python most things are well
designed so logging is an every day task and it should be implemented
well. And, it definitely is.

I only did "logger = logging.getLogger(__name__)" on top of my file
where the main() function resists. Afterwards I played around with that
object in main() and tried to configure it. As I can see you are
requesting the logger object twice as "root" and the configures it.
You put that problem across to me.

You saved my day... :)

Happy hacking!
Johannes
-- 
https://mail.python.org/mailman/listinfo/python-list


indentation blocking in Python

2013-10-27 Thread ajetrumpet
hello all,

This has got me a tad bit confused I think.  I am running 3.3.0 and I know that 
Python looks to group code together that is supposed to be in the same block.  
But the question is, where are the rules for this?  For instance, if I type the 
following in a PY file, it errors out and I don't see the DOS window with the 
output in Vista:

a=1;
   if a==1: print(1)
   else: print(0)
wait = input("press key")

However, if I don't indent anything at all, it works!

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

Can someone offer just a little explanation for this?  'IF' and 'ELSE' are 
obviously in the same code block.  Are they not?  Maybe it's not so obvious.  
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Running Python programmes

2013-10-27 Thread Colin J. Williams

On 27/10/2013 10:32 AM, David wrote:

I am an absolute beginner and am working through the book Python Programming for the 
Absolute Beginner by Michael Dawson.  Everything is fine except if I run a scripted 
programme, or one I have downloaded, and then run another one, the second one will not 
run, I just get the >>> in the interactive window.  I have to exit Python and 
start again, when the second programme then runs fine.

Any suggestions much appreciated.

David



David,

Perhaps you could show a very small program, maybe 3 or 4 lines, that 
illustrates the problem.


Python 3?  Windows? Using Idle?

Colin W.


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


Re: indentation blocking in Python

2013-10-27 Thread Colin J. Williams

On 27/10/2013 11:31 AM, ajetrum...@gmail.com wrote:

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

You indent only subordinate statements.

You don't need a semi-colon unless it separates two statements on the 
same line.


Your code:

a=1
if a==1:
print(1)
else:
print(0)
wait = input("press key")

I hope that this helps.

Colin W.

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


Re: indentation blocking in Python

2013-10-27 Thread Mark Lawrence

On 27/10/2013 15:31, ajetrum...@gmail.com wrote:

hello all,

This has got me a tad bit confused I think.  I am running 3.3.0 and I know that 
Python looks to group code together that is supposed to be in the same block.  
But the question is, where are the rules for this?  For instance, if I type the 
following in a PY file, it errors out and I don't see the DOS window with the 
output in Vista:

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

However, if I don't indent anything at all, it works!

a=1;
if a==1: print(1)
else: print(0)
wait = input("press key")

Can someone offer just a little explanation for this?  'IF' and 'ELSE' are 
obviously in the same code block.  Are they not?  Maybe it's not so obvious.  
Thanks.



You don't have a new block, the if else is in the same block as a=1, 
which by the way doesn't need that semi colon.  Restructure the if else 
and you must then write.


a=1
if a==1:
print(1)
else:
print(0)
wait = input("press key")

HTH.

--
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: Cookie xxxxing problem

2013-10-27 Thread rusi
On Sunday, October 27, 2013 1:02:38 AM UTC+5:30, Stephan Vladimir Bugaj wrote:
> I rarely ever post here.
> 
> But I wanted to say that people responding to this Nikos troll makes reading 
> this list a nuisance.
> You've never ever been successful in convincing him to behave, and it's been 
> going on for quite a while now.
> I remain subscribed for occasional  interesting new idioms and tips, but 
> always have to sift through this nonsense.
> And all of you who take the bait are as much a part of the problem as the 
> troll. 
> 
> Just ignore the guy.
> 
> S

Thanks for your contribution.
Hope you will stay for more interesting stuff -- like python -- questions or 
answers is fine.
See… when there's x% good stuff and 100-x% BS, we can all do our little bit to 
improve the statistics.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: indentation blocking in Python

2013-10-27 Thread Chris “Kwpolska” Warrick
On Sun, Oct 27, 2013 at 4:31 PM,   wrote:
> hello all,
>
> This has got me a tad bit confused I think.  I am running 3.3.0 and I know 
> that Python looks to group code together that is supposed to be in the same 
> block.  But the question is, where are the rules for this?  For instance, if 
> I type the following in a PY file, it errors out and I don't see the DOS 
> window with the output in Vista:

It’s called the command prompt.
> a=1;
>if a==1: print(1)
>else: print(0)
> wait = input("press key")
>
> However, if I don't indent anything at all, it works!
>
> a=1;
> if a==1: print(1)
> else: print(0)
> wait = input("press key")

You indented the wrong thing.  You put your if/else statement in a
non-standard way (which works, but is discouraged).  Also, you ended
the first line with a semicolon (same case).  So, the proper code
would be:

a=1
if a==1:
print(1)
else:
print(0)
wait = input("press key")

(I resisted the urge to add spaces around `=` and `==`, something most
people want you to do.)

-- 
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: How to find where data files are installed for my Python program

2013-10-27 Thread Ian Kelly
On Sun, Oct 27, 2013 at 1:58 AM, Gregory Ewing
 wrote:
> Ben Finney wrote:
>>
>> On systems conforming to the Filesystem Hierarchy Standard, it's
>> forbidden: programs go in a platform-specific location
>>
>> http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA>,
>> while platform-independent data files go in a separate location
>>
>> http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRSHAREARCHITECTUREINDEPENDENTDATA>.
>
>
> But Python code itself is platform-independent, so it
> should count as data for the purposes of the FHS,
> shouldn't it?

I don't see why Python files should be treated any differently than
other non-binary executables, e.g. shell scripts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Removing python django projects

2013-10-27 Thread Gary Roach

On 10/27/2013 04:38 AM, rusi wrote:

On Sunday, October 27, 2013 6:44:35 AM UTC+5:30, Gary Roach wrote:

Hi

In the process of trying to learn python, django, mysql and
virtualenvwrapper, I have created two projects and a mess. How can I
strip everything from a Debian, Wheezy, linux system. The files are all
over the place. Much of the information in this area is for Mac or
Windoz systems that do not have the apt-get, aptitude tools that Debian
makes available.

My goal is to end up with a clean system ready for re installation of a
development environment.

Disclaimer: This subject interests me and I know nothing about it ;-)

1. Aren't you asking for something self-contradictory -- the benefits of apt in 
apt-disabled systems?
Anyways… leaving that aside…

2. Not clear what you mean by 'clean system'.
One meaning could be remove all the 'crufty' files
Another could be disengage the system so that it runs easily on mac and windows.
For the first apt is a boon for second its a mess

3. I see questions like yours here
https://groups.google.com/forum/#!searchin/python-virtualenv/Advice$20on$20Updating$20Virtualenv/python-virtualenv/4lgTsf9EwZM/MhNvwkIVq6sJ
Maybe you could also ask there about use of 'wheel'
In Debian Linux "apt-get" is a command that can be used to completely 
manage all of the programs on the system - mostly automatically. Windows 
and Mac? have nothing equivalent. This is one of the main reasons that I 
use Debian. If you have never worked with any Unix / Linux systems then 
you must understand that the philosophy is totally different than 
Windows. Mac is closer to a Unix style system but not close enough in my 
book.


By a clean system, I mean one that no longer has files lying around from 
django, virtualenv or my projects. Python is used all over the system 
and has to stay.


Please reply to the list via the original message or the thread will be 
fragmented and be impossible to follow.


Thanks for the reply

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


Re: Debugging decorator

2013-10-27 Thread Eric S. Johansson


On 10/25/2013 7:55 PM, Yaşar Arabacı wrote:

Hi people,

I wrote this decorator: https://gist.github.com/yasar11732/7163528


wow, this looks really powerful. I would like to add the ability to 
associate a tag or set of tags with the decorator so that the debug 
output only happens when there is a matching tag in some global or 
environmental variable.

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


Re: Cookie issue(cant fix it with anyhting)

2013-10-27 Thread Denis McMahon
On Sat, 26 Oct 2013 15:29:52 +0300, Nick the Gr33k wrote:

> Hello i having the following code to try and retrieve the visitor's
> saved cookie form the browser.
> 
> [CODE]
> # initialize cookie and retrieve cookie from clients browser try:
>  cookie = cookies.SimpleCookie( os.environ['HTTP_COOKIE'] )
>  cookieID = cookie['name'].value
> except:
>  cookieID = 'visitor'
> [/CODE]
> 
> It works as expected except form the fact from when the visitor enters
> my webpage(superhost.gr) by clicking a backlink of another webpage.
> 
> Then even if the cookie exists in his browser for some reason the try
> fails and except take actions.
> 
> Can somebody explain why this is happening?
> 
> You can see this action yourself by hitting:
> 
> 1. superhost.gr as a direct hit 2. by clicking superhost.gr's backlink
> from ypsilandio.gr/mythosweb.gr
> 
> You will see than in 2nd occasion another ebtry will appear in the
> database here:
> 
> http://superhost.gr/?show=log&page=index.html

OK

I tried it. The counter in the database is incrementing (I think it's the 
counter). There's only one entry in the table for my system.

I used the backlinks on each of the two pages above - the backlink on 
mythosweb.gr I used twice.

So, whatever behaviour you're seeing is not what I'm seeing.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Confusion about python versions

2013-10-27 Thread Aseem Bansal
Python 2.7.6 release candidate 1 and 3.3.3 release candidate 1 was released 
yesterday. Also Python 3.4.0 alpha 4 was released a week ago.

I thought as Python 3.4.0 alpha was released 3.3 branch was done. The 3.3.3 
release candidate fixes many bugs as per the changelog so would they be 
included in 3.4.0?

For how long do the older versions get supported in case of Python? Do bugfix 
releases for older versions keeps on happening even when new branch is 
released? Isn't that a lot of work to manage so many versions?

How do the Python versions work? For how long is Python 2 going to be supported?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Confusion about python versions

2013-10-27 Thread Mark Lawrence

On 27/10/2013 18:13, Aseem Bansal wrote:

Python 2.7.6 release candidate 1 and 3.3.3 release candidate 1 was released 
yesterday. Also Python 3.4.0 alpha 4 was released a week ago.

I thought as Python 3.4.0 alpha was released 3.3 branch was done. The 3.3.3 
release candidate fixes many bugs as per the changelog so would they be 
included in 3.4.0?

For how long do the older versions get supported in case of Python? Do bugfix 
releases for older versions keeps on happening even when new branch is 
released? Isn't that a lot of work to manage so many versions?

How do the Python versions work? For how long is Python 2 going to be supported?



Take a look at the various release schedule PEPs here 
http://www.python.org/dev/peps/ where 373 refers to Python 2.7.


--
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: Confusion about python versions

2013-10-27 Thread Ned Batchelder

On 10/27/13 2:13 PM, Aseem Bansal wrote:

Python 2.7.6 release candidate 1 and 3.3.3 release candidate 1 was released 
yesterday. Also Python 3.4.0 alpha 4 was released a week ago.

I thought as Python 3.4.0 alpha was released 3.3 branch was done. The 3.3.3 
release candidate fixes many bugs as per the changelog so would they be 
included in 3.4.0?

For how long do the older versions get supported in case of Python? Do bugfix 
releases for older versions keeps on happening even when new branch is 
released? Isn't that a lot of work to manage so many versions?

How do the Python versions work? For how long is Python 2 going to be supported?


They're also preparing 2.6.9.  Older versions get supported for a long 
time, not sure of the official schedule.  2.7.x will be supported for 
even longer, since it's the last of the 2.x series.


Python takes backward compatibility and long-term support seriously.

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


Re: Removing python django projects

2013-10-27 Thread Ned Batchelder

On 10/26/13 9:14 PM, Gary Roach wrote:

Hi

In the process of trying to learn python, django, mysql and 
virtualenvwrapper, I have created two projects and a mess. How can I 
strip everything from a Debian, Wheezy, linux system. The files are 
all over the place. Much of the information in this area is for Mac or 
Windoz systems that do not have the apt-get, aptitude tools that 
Debian makes available.


My goal is to end up with a clean system ready for re installation of 
a development environment.


Any help will be sincerely appreciated.

Gary R.


The way to keep things clean is with virtualenv.  When creating a 
project, start by making a virtualenv for it.  Always activate the 
virtualenv when working on the project.  Always install Python packages 
with pip, they will be installed into your virtualenv.


When you no longer need the project, you can simply delete the 
virtualenv directory, it has everything in it.


The helper virtualenvwrapper provides some shell tools to make some of 
this easier, but it's completely optional.


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


Re: Cookie issue(cant fix it with anyhting)

2013-10-27 Thread Benjamin Schollnick
Nikos,

Hello i having the following code to try and retrieve the visitor's
>> saved cookie form the browser.
>> 
>> [CODE]
>> # initialize cookie and retrieve cookie from clients browser try:
>> cookie = cookies.SimpleCookie( os.environ['HTTP_COOKIE'] )
>> cookieID = cookie['name'].value
>> except:
>> cookieID = 'visitor'

As it has been said before, change the except to be an explicit error check.  
The all purpose except is hiding an error condition from you.

Take a look at this:

http://www.jayconrod.com/posts/17/how-to-use-http-cookies-in-python

- Benjamin


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


[RELEASE] Python 2.7.6 release candidate 1

2013-10-27 Thread Benjamin Peterson
I'm happy to announce the availability of Python 2.7.6 release candidate 1.

Most importantly, this release candidate resolves crashes of the interactive
interpreter on OS X 10.9. It also includes the usual collection of bugfixes over
2.7.5. These are described in excruciating detail in the Misc/NEWS file of the
source tarball. You can view it online at

http://hg.python.org/cpython/raw-file/9750acbf7c40/Misc/NEWS

Downloads are at

http://python.org/download/releases/2.7.6/

As always, please test the release and report bugs to

http://bugs.python.org/

With any luck, the final release will follow in a week.

Enjoy,
Benjamin Peterson
2.7 Release Manager
-- 
https://mail.python.org/mailman/listinfo/python-list


[RELEASED] Python 3.3.3 release candidate 1

2013-10-27 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 1.

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.3 also contains a new batteries-included feature for OS X users of
IDLE and other Tkinter-based programs.  The python.org Mac OS X 64-bit/32-bit
x86-64/i386 Installer for OS X 10.6+ now includes its own builtin version of
Tcl/Tk 8.5.  It is no longer necessary to install a third-party version of
Tcl/Tk 8.5 to workaround the problematic system versions.  See
http://www.python.org/download/mac/tcltk/ for more information.

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

and for the detailed changelog of 3.3.3, see

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

To download Python 3.3.3 rc1 visit:

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

This is a preview release, please report any bugs to

 http://bugs.python.org/

The final version is scheduled to be released in two weeks' time, on or about
the 10th of November.

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)

iEYEARECAAYFAlJte8kACgkQN9GcIYhpnLDx8wCgqtabbC8DaoW+Vy03AYGWyLhw
sWcAoIK5jQeXDAxHayG+VWH/rRF1+qHC
=yOed
-END PGP SIGNATURE-
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Cookie issue(cant fix it with anyhting)

2013-10-27 Thread Nick the Gr33k

Στις 27/10/2013 9:25 μμ, ο/η Benjamin Schollnick έγραψε:

Nikos,

Hello i having the following code to try and retrieve the visitor's

saved cookie form the browser.

[CODE]
# initialize cookie and retrieve cookie from clients browser try:
cookie = cookies.SimpleCookie( os.environ['HTTP_COOKIE'] )
cookieID = cookie['name'].value
except:
cookieID = 'visitor'


*As it has been said before*, change the except to be an explicit error
check.
The all purpose except is hiding an error condition from you.

Take a look at this:

http://www.jayconrod.com/posts/17/how-to-use-http-cookies-in-python

- Benjamin




# initialize cookie and retrieve cookie from clients browser
cookie = cookies.SimpleCookie( os.environ.get('HTTP_COOKIE', '') )

try:
cookieID = cookie['name'].value
except KeyError:
cookieID = 'visitor'

As for the article i had found it myself 1 weeek ago read it but 
unfortunately it wasnt of any help.


--
What is now proved was at first only imagined! & WebHost

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


Re: Cookie issue(cant fix it with anyhting)

2013-10-27 Thread Nick the Gr33k

Στις 27/10/2013 8:01 μμ, ο/η Denis McMahon έγραψε:

On Sat, 26 Oct 2013 15:29:52 +0300, Nick the Gr33k wrote:


Hello i having the following code to try and retrieve the visitor's
saved cookie form the browser.

[CODE]
# initialize cookie and retrieve cookie from clients browser try:
  cookie = cookies.SimpleCookie( os.environ['HTTP_COOKIE'] )
  cookieID = cookie['name'].value
except:
  cookieID = 'visitor'
[/CODE]

It works as expected except form the fact from when the visitor enters
my webpage(superhost.gr) by clicking a backlink of another webpage.

Then even if the cookie exists in his browser for some reason the try
fails and except take actions.

Can somebody explain why this is happening?

You can see this action yourself by hitting:

1. superhost.gr as a direct hit 2. by clicking superhost.gr's backlink
from ypsilandio.gr/mythosweb.gr

You will see than in 2nd occasion another ebtry will appear in the
database here:

http://superhost.gr/?show=log&page=index.html


OK

I tried it. The counter in the database is incrementing (I think it's the
counter). There's only one entry in the table for my system.

I used the backlinks on each of the two pages above - the backlink on
mythosweb.gr I used twice.

So, whatever behaviour you're seeing is not what I'm seeing.




I have changed the code that why you dont see it.
I just couldnt resilve the cookie issues i was facing and decided to 
track visitors just by their hostaname instead of a non working cookie.


--
What is now proved was at first only imagined! & WebHost

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


Re: Confusion about python versions

2013-10-27 Thread Terry Reedy

On 10/27/2013 2:13 PM, Aseem Bansal wrote:

Python 2.7.6 release candidate 1 and 3.3.3 release candidate 1 was
released yesterday. Also Python 3.4.0 alpha 4 was released a week
ago.

I thought as Python 3.4.0 alpha was released 3.3 branch was done.


Normal 3.3 bugfixes are not done until 3.4.0 (final) is released. There 
will be a 3.3.4 at that time.



3.3.3 release candidate fixes many bugs as per the changelog so would
they be included in 3.4.0?


Yes. 3.3 patches are merged forward unless not applicable.

> How long do the older versions get supported in case of Python?

After normal maintenance ends, code-only, security-fix-only releases of 
x.y continue after that until 5 years after x.y.0.  3.3.0 was released 
2012 Feb so security releases will continue until about 2017 Feb.


The initial 2.6 release was about 2008 Sept, I believe, so this is 5 
years later.



Do bugfix releases for older versions keeps on happening even when
new branch is released?



Isn't that a lot of work to manage so many versions?


Yes. Core developers will be very happy when normal maintenance of 2.7 ends.


How do the Python versions work? For how long is Python 2 going to be
supported?


2.7, released about 2010 July, is a special case. It is already past the 
normal maintenance period of 2 years and will get occasional releases 
until 2015. Security fixes after that are not decided.


--
Terry Jan Reedy

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


Re: Check if this basic Python script is coded right

2013-10-27 Thread Tim Delaney
On 27 October 2013 23:20, rusi  wrote:

> On Saturday, October 26, 2013 11:50:33 PM UTC+5:30, MRAB wrote:
> > On 26/10/2013 18:36, HC wrote:
> > > I'm doing my first year in university and I need help with this basic
> assignment.
> > >
> > > Assignment: Write Python script that prints sum of cubes of numbers
> between 0-200 that are multiples of 3. 3^3+6^3+9^3+12^3+198^3=?
> 
> > >
> > > Is it all okay?
> > >
> > Just one small point: the assignment says that the numbers should be in
> > the range 0-200, but the loop's condition is count<200 it's excluding
> > 200, so the numbers will actually be in the range 0-199.
> >
> > However, as 200 isn't a multiple of 3, it won't affect the result, but
> > in another assignment it might.
> >
> > (For the record, this is known as an "off-by-one" error.)
>
> So is an off-by-one error that did not happen an off-by-an-off-by-one
> error?
>

I would say yes. When someone realises that the requirements were also off
by one and the specification gets changed to  "between 0-201" (inclusive)
then whoever fixes it might naively just add one to the existing code,
giving an incorrect result.

Obviously I'm ignoring the possibility of appropriate unit tests to prevent
this - just looking at the code itself.

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


Parsing multiple lines from text file using regex

2013-10-27 Thread Marc
Hi,
I am having an issue with something that would seem to have an easy
solution, but which escapes me.  I have configuration files that I would
like to parse.  The data I am having issue with is a multi-line attribute
that has the following structure:

banner  
Banner text
Banner text
Banner text
...


The regex 'banner\s+(\w+)\s+(.+)' captures the command nicely and
banner.group(2) captures the delimiter nicely.

My issue is that I need to capture the lines between the delimiters (both
delimiters are the same).

I have tried various permutations of 

Delimiter=banner.group(2)
re.findall(Delimiter'(.*?)'Delimiter, line, re.DOTALL|re.MULTILINE)

with no luck

Examples I have found online all assume that the starting and ending
delimiters are different and are defined directly in re.findall().  I would
like to use the original regex extracting the banner.group(2), since it is
already done, if possible.  

Any help in pointing me in the right direction would be most appreciated.

Thank you,

Marc


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


Re: Python Front-end to GCC

2013-10-27 Thread Mark Janssen
> I see the big man stepping in to answer for his homies

After re-reading the discussion, I wish to retract what I'm saying
here and apologize to John who seems like a decent guy.

>, but while his
> explanation satisfies their question of "well why do these magic
> values get used then, if what Mark says is true?", it doesn't address
> the real confusion:  What is the difference between "script" code
> (like Javascript and visual) made for the screen (where such magic
> values are utilized) and compiled source (made for the machine)?  And
> that is where John, while benevolent, hasn't done the homework of
> computer science.   Ask him.

Otherwise, most of this, while sloppy, still stands.

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


Re: Parsing multiple lines from text file using regex

2013-10-27 Thread Rhodri James

On Sun, 27 Oct 2013 21:09:46 -, Marc  wrote:


Hi,
I am having an issue with something that would seem to have an easy
solution, but which escapes me.  I have configuration files that I would
like to parse.  The data I am having issue with is a multi-line attribute
that has the following structure:

banner  
Banner text
Banner text
Banner text
...


The regex 'banner\s+(\w+)\s+(.+)' captures the command nicely and
banner.group(2) captures the delimiter nicely.

My issue is that I need to capture the lines between the delimiters (both
delimiters are the same).


I really, really wouldn't do this with a single regexp.  You'll get a much  
easier to understand program if you implement a small state machine  
instead.  In rough pseudocode:


collecting_banner = False
for line in configuration_file:
if not collecting_banner:
if found banner start:
get delimiter
collecting_banner = True
banner_lines = []
elif found other stuff:
do other stuff
elif found delimiter:
collecting_banner = False
else:
banner_lines.append(line)

--
Rhodri James *-* Wildebeest Herder to the Masses
--
https://mail.python.org/mailman/listinfo/python-list


Re: Parsing multiple lines from text file using regex

2013-10-27 Thread Mark Lawrence

On 27/10/2013 21:09, Marc wrote:

Hi,
I am having an issue with something that would seemtohave an easy
solution,butwhich escapes me.  I have configuration files that I would
like to parse.  The data I am having issue with is a multi-line
attribute that has the following structure:

banner  
Banner text
Banner text
Banner text
...


The regex 'banner\s+(\w+)\s+(.+)' captures the command nicely and
banner.group(2) captures the delimiter nicely.

My issue is that I need to capture the lines between the delimiters
(both delimiters are the same).

I have tried various permutations of

Delimiter=banner.group(2)
re.findall(Delimiter'(.*?)'Delimiter, line, re.DOTALL|re.MULTILINE)

with no luck

Examples I have found online all assume that the starting and ending
delimiters are different and are defined directly in re.findall().  I
would like to use the original regex extracting the banner.group(2),
since it is already done, if possible.


Any help in pointing me in the right direction would be most appreciated.

Thank you,

Marc



What was wrong with the answer Peter Otten gave you earlier today on the 
tutor mailing list?


--
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: Parsing multiple lines from text file using regex

2013-10-27 Thread Roy Smith
In article ,
 "Rhodri James"  wrote:

> I really, really wouldn't do this with a single regexp.  You'll get a much  
> easier to understand program if you implement a small state machine  
> instead.

And what is a regex if not a small state machine?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Ben Finney
Gregory Ewing  writes:

> Ben Finney wrote:
> > On systems conforming to the Filesystem Hierarchy Standard, it's
> > forbidden: programs go in a platform-specific location
> > http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA>,
> > while platform-independent data files go in a separate location
> > http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRSHAREARCHITECTUREINDEPENDENTDATA>.
>
> But Python code itself is platform-independent, so it should count as
> data for the purposes of the FHS, shouldn't it?

True in most cases, but not all (think extension modules, compiled to
architecture-specific bytecode). But you're right, I over-simplified.

The FHS specifies that the first location isn't only for
platform-specific files, but is also for “object files, libraries, and
internal binaries that are not intended to be executed directly by users
or shell scripts”.

The second location is for “all read-only architecture independent data
files” (where the context makes it clear that “data files” is exclusive
of program files).

So, whether Python bytecode is platform-specific or not, it is relegated
by the FHS to a separate location from data files. The separation
requirement remains, and Python's distutils doesn't support it.

What Python facilities do we have for supporting both install-time
decisions about package install layout, and run-time requirements to
find the files wherever they were installed?

-- 
 \ “Two paradoxes are better than one; they may even suggest a |
  `\ solution.” —Edward Teller |
_o__)  |
Ben Finney

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


Re: Cookie fucking problem

2013-10-27 Thread Ben Finney
Antoon Pardon  writes:

> Op 26-10-13 23:43, Ben Finney schreef:
> > Feel free to occupy your time with baiting Nikos. But *do not* do it
> > in this forum.
>
> Would you mind telling this to others too.

I'm not in any special position of power here; I'm not beholden to
address every instance of bad behaviour or none at all. Any member of
this community can apply the same social pressure, and together we can
cover as many of them as we choose.

I have no particular objection to you responding to those instances of
bad behaviour that I've omitted.

-- 
 \“Always code as if the guy who ends up maintaining your code |
  `\ will be a violent psychopath who knows where you live.” —John |
_o__) F. Woods |
Ben Finney

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


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Ben Finney
Ian Kelly  writes:

> I don't see why Python files should be treated any differently than
> other non-binary executables, e.g. shell scripts.

It is an unfortunate artefact of Unix history that “binary” has an
established connotation of “executable”, encompassing even executable
text files.

So the separation I'm drawing attention to in the FHS has nothing to do
with whether the files are text files, and everything to do with whether
they're executable programs and code libraries.

According to the FHS (with which, of course, not every operating system
is bound to conform), executable program libraries belong in an entirely
separate location from non-executable data files.

This thread is about how to best use Python's standard tools to support
that separation on systems following the FHS.

-- 
 \   “If [a technology company] has confidence in their future |
  `\  ability to innovate, the importance they place on protecting |
_o__) their past innovations really should decline.” —Gary Barnett |
Ben Finney

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


Re: Parsing multiple lines from text file using regex

2013-10-27 Thread Ben Finney
Roy Smith  writes:

> In article ,
>  "Rhodri James"  wrote:
>
> > I really, really wouldn't do this with a single regexp.  You'll get a much  
> > easier to understand program if you implement a small state machine  
> > instead.
>
> And what is a regex if not a small state machine?

Regex is not a state machine implemented by the original poster :-)

Or, in other words, I interpret Rhodri as saying that the right way to
do this is by implementing a *different* small state machine, which will
address the task better than the small state machine of regex.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but three round meals a day wouldn't be as hard to |
_o__) swallow.” —_Pinky and The Brain_ |
Ben Finney

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


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Chris Angelico
On Mon, Oct 28, 2013 at 10:31 AM, Ben Finney  wrote:
> It is an unfortunate artefact of Unix history that “binary” has an
> established connotation of “executable”, encompassing even executable
> text files.

That's a lot broader than Unix - people talk about "binaries" meaning
executables in Windows and OS/2 too. Unix is, if anything, _less_
inclined that way - the executable segment is called "text", which
always struck me as a bit odd.

> So the separation I'm drawing attention to in the FHS has nothing to do
> with whether the files are text files, and everything to do with whether
> they're executable programs and code libraries.

Yup. Unix does a fairly good job of blurring the line between
"executables that can be loaded and jumped to" and "scripts that get
loaded by an interpreter". I actually have a few scripts that take
several levels of interpreter, something like:

foo.pike
#!/usr/local/bin/pike

bar.pike:
#!/.../foo.pike --parameter

fum.pike:
#!/.../bar.pike --otherparameter

Unix will happily execute ./fum.pike as "/usr/local/bin/pike
/.../foo.pike --parameter /.../bar.pike --otherparameter ./fum.pike".
There's a limit on the number of interpreters (to prevent loops), but
I haven't hit it :)

There is one important place, though, where scripts are called data
files, and that's licensing. The GPL, for instance, does NOT cover
your scripts, even if it covers the interpreter, because *to the
language interpreter*, your scripts are just data files. But that's
more of a legal distinction than a filesystem hierarchical one.

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


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Mark Lawrence

On 27/10/2013 23:58, Chris Angelico wrote:

On Mon, Oct 28, 2013 at 10:31 AM, Ben Finney  wrote:

It is an unfortunate artefact of Unix history that “binary” has an
established connotation of “executable”, encompassing even executable
text files.


That's a lot broader than Unix - people talk about "binaries" meaning
executables in Windows and OS/2 too. Unix is, if anything, _less_
inclined that way - the executable segment is called "text", which
always struck me as a bit odd.


So the separation I'm drawing attention to in the FHS has nothing to do
with whether the files are text files, and everything to do with whether
they're executable programs and code libraries.


Yup. Unix does a fairly good job of blurring the line between
"executables that can be loaded and jumped to" and "scripts that get
loaded by an interpreter". I actually have a few scripts that take
several levels of interpreter, something like:

foo.pike
#!/usr/local/bin/pike

bar.pike:
#!/.../foo.pike --parameter

fum.pike:
#!/.../bar.pike --otherparameter

Unix will happily execute ./fum.pike as "/usr/local/bin/pike
/.../foo.pike --parameter /.../bar.pike --otherparameter ./fum.pike".
There's a limit on the number of interpreters (to prevent loops), but
I haven't hit it :)

There is one important place, though, where scripts are called data
files, and that's licensing. The GPL, for instance, does NOT cover
your scripts, even if it covers the interpreter, because *to the
language interpreter*, your scripts are just data files. But that's
more of a legal distinction than a filesystem hierarchical one.

ChrisA



Quoting from another thread

"What is the difference between "script" code (like Javascript and 
visual) made for the screen (where such magic values are utilized) and 
compiled source (made for the machine)?"


This obviously impacts on the discussion above, so how does Unix, 
Windows and other operating systems distinguish these with respect to 
binary, executable, code library or whatever?


--
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: Parsing multiple lines from text file using regex

2013-10-27 Thread Marc
>What was wrong with the answer Peter Otten gave you earlier today on the
>tutor mailing list?
>
>--
>Python is the second best programming language in the world.
>But the best has yet to be invented.  Christian Tismer
>
>Mark Lawrence
>


I did not receive any answers from the Tutor list, so I thought I'd ask
here.  If an answer was posted to the Tutor list, it never made it to my
inbox.  Thanks to all that responded.

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


Re: Parsing multiple lines from text file using regex

2013-10-27 Thread Mark Lawrence

On 28/10/2013 00:35, Marc wrote:

What was wrong with the answer Peter Otten gave you earlier today on the
tutor mailing list?

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

Mark Lawrence




I did not receive any answers from the Tutor list, so I thought I'd ask
here.  If an answer was posted to the Tutor list, it never made it to my
inbox.  Thanks to all that responded.



Okay, the following is taken directly from Peter's reply to you.  Please 
don't shoot the messenger :)


You can reference a group in the regex with \N, e. g.:

>>> text = banner option delim
... banner text
... banner text
... banner text
... delim
... """
>>> re.compile(r"banner\s+(\w+)\s+(\S+)\s+(.+?)\2", re.MULTILINE |
re.DOTALL).findall(text)
[('option', 'delim', 'banner text\nbanner text\nbanner text\n')]


--
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: Python Front-end to GCC

2013-10-27 Thread rusi
On Monday, October 28, 2013 3:44:14 AM UTC+5:30, zipher wrote:
> Otherwise, most of this, while sloppy, still stands.

Yes

All your quotes are unattributed

So your discussion is both sloppy and meaningless
-- 
https://mail.python.org/mailman/listinfo/python-list


Organising packages/modules - importing functions from a common.py in a separate directory?

2013-10-27 Thread Victor Hooi
Hi,

I have a collection of Python scripts I'm using to load various bits of data 
into a database.

I'd like to move some of the common functions (e.g. to setup loggers, reading 
in configuration etc.) into a common file, and import them from there.

I've created empty __init__.py files, and my current directory structure looks 
something like this:

foo_loading/
__init__.py
common/
common_foo.py
em_load/
__init__.py
config.yaml
sync_em.py
pg_load/
__init__.py
config.yaml
sync_pg.py

So from within the sync_em.py script, I'm trying to import a function from 
foo_loading/common/common_foo.py.

from ..common.common_foo import setup_foo_logging

I get the error:

ValueError: Attempted relative import in non-package 

If I change directories to the parent of "foo_loading", then run

python -m foo_loading.em_load.sync_em sync_em.py

it works. However, this seems a bit roundabout, and I suspect I'm not doing 
things correctly.

Ideally, I want a user to be able to just run sync_em.py from it's own 
directory, and have it correctly import the logging/config modules from 
common_foo.py, and just work.

What is the correct way to achieve this?

Secondly, if I want to move all of the config.yaml files to a common 
foo_loading/config.yaml, or even foo_loading/config/config.yaml, what is the 
correct way to access this from within the scripts? Should I just be using 
"../", or is there a better way?

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


Re: Cookie fucking problem

2013-10-27 Thread rusi
On Monday, October 28, 2013 4:56:38 AM UTC+5:30, Ben Finney wrote:
> I'm not in any special position of power here; I'm not beholden to
> address every instance of bad behaviour or none at all. Any member of
> this community can apply the same social pressure, and together we can
> cover as many of them as we choose.

Democracy and all that is good stuff for arm-chair philosophising.
On this list, as in real life, everyone is equal and some people are more equal.
So…

I think you are more influential here than the majority out here
And you are using that to try to keep some order out here -- for which thanks
(from me at least)

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


Try-except for flow control in reading Sqlite

2013-10-27 Thread Victor Hooi
Hi,

I'd like to double-check something regarding using try-except for controlling 
flow.

I have a script that needs to lookup things in a SQLite database.

If the SQLite database file doesn't exist, I'd like to create an empty 
database, and then setup the schema.

Is it acceptable to use try-except in order to achieve this? E.g.:

try:
# Try to open up the SQLite file, and lookup the required entries
except OSError:
# Open an empty SQLite file, and create the schema


My thinking is that it is (easier to ask forgiveness than permission), but I 
just wanted to check if there is a better way of achieving this?

I'd also be doing the same thing for checking if a file is gzipped or not - we 
try to open it as a gzip, then as an ordinary text file, and if that also 
fails, raise a parsing error.


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


Re: Python on a MacBook Pro (not my machine)

2013-10-27 Thread Cameron Simpson
On 26Oct2013 12:07, John Ladasky  wrote:
> My side job as a Python tutor continues to grow.  In two weeks, I will start 
> working with a high-school student who owns a MacBook Pro.  
> 
> I have had students with Linux systems (my preference) and Windows systems 
> before, but not Macs.  On my first visit, I set up each student's computer 
> with Python 3.x, and SciTE for editing.  I would like to do something similar 
> for my Mac student, and I want to make sure that it goes smoothly.
> 
> My first question is whether Mac OS X ships with Python 2.x, and whether I 
> need to be aware of any compatibility issues when I install 3.x.  (It's 2013, 
> and my students are new to programming.  I refuse to hitch them to Python 2.)

MacOSX ships with Python 2.x. My Mountain Lion macbook here has
2.7.2 as /usr/bin/python.

I install MacPorts on my Macs (alternatives include Fink and HomeBrew,
and I belive you can install them side by side; Fink uses /sw,
MacPorts /opt/local and I haven't tried HomeBrew).

I have /opt/local/bin in my $PATH ahead of /usr/bin, so it finds the MacPorts
"python" (2.7.5) and "python3.2" (3.2.5) and "python3.3" (3.3.2).

> Second: it doesn't look like I will be able to obtain SciTE for this student. 
>  SciTE is free for Windows and Linux.  Apparently, it's $42 for Mac OSX?  If 
> I recall, SciTE is open-source, so I suppose that I could compile the source 
> myself.  But since it is not my computer, and I'm being paid for my time, and 
> I haven't done much with Macs (to say nothing of building from source code), 
> I don't think that this is appropriate.

Building from source for most projects is much like Linux or any
other UNIX system.

  configure --prefix=/usr/local# or --prefix=/usr/local/app-version, my 
personal preference
  make && make install && echo OK

You will need a compiler (your student needs XCode installed if
they haven't already; it is free). MacPorts needs XCode anyway, as
do the others.

> I know, we can use IDLE.  I continue to find IDLE clumsy.  Also, there are 
> potential issues with event handling which arise when you use IDLE.  I am 
> working with an adult professional who is developing a Telnet application, 
> which refuses to cooperate with IDLE/Tk.  I had similar issues myself with 
> wxPython applications I was writing.  While these issues may not affect a 
> beginning student, these experiences have informed my choices.
> 
> So, what other free and lightweight editing options do I have for a Mac?  I 
> have found a few (fairly old) discussions on comp.lang.python which suggest 
> Eric (http://eric-ide.python-projects.org/) and Editra (http://editra.org/).  
> Opinions on these and other choices are appreciated.

Personally, I use terminals (iTerm2 on a Mac in preference to
MacOSX's terminal, with a shell pane beside the editor pane) and
vim with syntax highlighting. And a web browser open on a local
copy of the 2.x or 3.x HTML docs - I keep one of each on my desktop
for easy access.

I'm not an IDE person, so I can't speak to those (even IDLE).

Cheers,
-- 
Cameron Simpson 

You want to tempt the wrath of the whatever from high atop the thing?
- Toby Zeigler, _The_West_Wing_ - Election Night
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Printing a drop down menu for a specific field.

2013-10-27 Thread rurpy
On 10/27/2013 01:31 AM, Nick the Gr33k wrote:
> Στις 27/10/2013 6:00 πμ, ο/η ru...@yahoo.com έγραψε:
>[...] 
[following quote lightly edited for clarity] 
> I almost understand your code, but this part is not so clear to me:
>
  key = host, city, useros, browser
> if key not in seen:
   newdata.append( [host, city, useros, browser, [ref], hits, [visit]] )
>  seen[key] = len( newdata ) - 1 # Save index (for 'newdata') of this row.
> else:# This row is a duplicate row with a different referrer & visit time.
>  rowindex = seen[key]
>  newdata[rowindex][4].append( ref )
>  newdata[rowindex][5] += hits
>  newdata[rowindex][6].append( visit )

I'm not sure exactly what part is not clear to you so I'll give 
you a very long-winded explanation and you can ignore any parts 
that are already obvious to you.

The code above is inside a loop that looks at each row in .

In  there can be several rows for the same visitor, where you
define a visitor as a unique combination of , ,  
and .

What you want to do is combine all of the rows that are for the same
visitor into one row.  That one row, instead of having a single value
for  and  will have lists of all the s and 
s from all the rows that have the same visitor value.

So first, for each row, we set  to a tuple that identifies the 
visitor.  (Actually, I should have named that variable "visitor" 
instead of "key".)  Then we use an ordinary python dictionary  
to record each visitor as we see them.  Remember that a dictionary 
can use a tuple as a key (unlike Perl were a hash key has to be a 
string).  

For each row we look in the dictionary  to see if this visitor
is a new one that we haven't seen before.  If we haven't seen them
before we create a new row in  for them that is a copy of 
the row in  except we change the  and  fields 
from single values to lists.  We also add an entry to  whose 
key is the visitor, and whose value is the index of the vistor's row 
in . 

If the visitor *was* seen before (because we find an entry for the 
visitor in ), then the value of that entry tells us the index 
of that visitor's row in  and instead of adding a new row
to  we update the visitors row that is already there.

Maybe it's easier to see what is happening by looking at how the 
code actually runs.

Suppose the data you get from your database is

data = ['mail14.ess.barracuda.com',   'Άγνωστη Πόλη', 'Windows', 
'Explorer', 'Direct Hit',   '1', 'Σάββατο 26 Οκτ, 18:49',
'209.133.77.165.T01713-01.above.net', 'Άγνωστη Πόλη', 'Windows', 
'Explorer', 'Direct Hit',   '1', 'Σάββατο 26 Οκτ, 18:59',
'mail14.ess.barracuda.com',   'Άγνωστη Πόλη', 'Windows', 
'Explorer', 'http://superhost.gr/', '1', 'Σάββατο 26 Οκτ, 18:48',
   ]

When the first row of  is processed,  will be
set to the 4-tuple:

  ('mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer').

Then, when "if key not in seen" is executed.  This will look in 
dictionary  and see if there in an entry in it with a key that 
matches the tuple above.  Since  is still an empty dictionary,
 is not in the dictionary because there is nothing in the
dictionary and "if key not in seen" is true.

So the first branch of the if statement runs:

   newdata.append( [host, city, useros, browser, [ref], hits, [visit]] )
   seen[key] = len( newdata ) - 1 # Save index (for 'newdata') of this row.

Now,  contains 1 row:

[ 'mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer', ['Direct 
Hit'], 1, ['Σάββατο 26 Οκτ, 18:49'] ]

And,  contains:

  { ('mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer'): 0 }

Note the the 0 value in the  dictionary is the index of the 
corresponding row in .

When the second row of  is processed, the same thing happens.
 is the tuple

  ('209.133.77.165.T01713-01.above.net','Άγνωστη Πόλη','Windows','Explorer')

but since the only key in  is 

  ('mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer')

again the "not in" branch is executed.  When it runs this time it
adds another row to  so  now looks like:

[ 'mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer', ['Direct 
Hit'], 1, ['Σάββατο 26 Οκτ, 18:49'], 
  '209.133.77.165.T01713-01.above.net','Άγνωστη Πόλη','Windows','Explorer', 
['Direct Hit'], 1, ['Σάββατο 26 Οκτ, 18:59'], ]

and adds another entry to  so that  is now:

  { ('mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer'): 0, 
('209.133.77.165.T01713-01.above.net','Άγνωστη Πόλη','Windows','Explorer'): 
1 }

Again, the 1 is the index of the corresponding row in .

Now the third row of  is processed.   is set to

  ('mail14.ess.barracuda.com','Άγνωστη Πόλη','Windows','Explorer')

This time when "if key not in seen" is executed, it is false because
that key *is* in seen, it was added the when the first  was
processed (look at  above).  So the statements

   rowindex = seen[key]
   newdata[rowindex][4].append( ref )
   ne

Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rurpy
On 10/26/2013 07:56 PM, Chris Angelico wrote:
> On Sun, Oct 27, 2013 at 12:45 PM, rusi  wrote:
>> Yes... that page is longer and more confusing than necessary.
>> 1. The double-posting bit is unnecessary -- not been happening after the 
>> 'new' GG.
>> 2. The missing attributions problem is new and needs to be added
>> 3. The main message of that page that needs to be noted is
>> - to remove extra spurious lines
>> - to NOT top-post
> 
> If someone's editing that page, it'd be nice to also ask people to
> chop their lines short - most newsgroup and mail clients hard-wrap to
> 80 characters, but GG posts invariably come through with one-line
> paragraphs. It's annoying when you try to quote the text, and several
> online archives look ugly when the lines are too long.

That describes my personal preferences too but...

I know people who complain about manually wrapped lines.  When you 
widen the window they don't expand to fill the width, and when you 
narrow the window they wrap and create this awful ragged effect.

Long lines wrapped by the client reader seem to be pretty common
these days, not just from GG but from many sources although they 
remain a minority of messages in c.l.p.

Further, although I've commonly seen complaints about top-posting 
or occasionally excessive untrimmed context or html, I don't recall 
seeing any complaints about long lines.  Rusi posts here frequently
with long lines and I've not seen any complaints related to that.

I seems to me unfair to demand different standards from GG users 
than others even if such posts are more common from GG.

Maybe there should be a c.l.p etiquette page somewhere applicable 
to all posters.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rurpy
On Sunday, October 27, 2013 1:59:05 AM UTC-6, rusi wrote:
> On Sunday, October 27, 2013 10:34:11 AM UTC+5:30, ru...@yahoo.com wrote:
> > On 10/26/2013 07:45 PM, rusi wrote:
> > > On Sunday, October 27, 2013 2:07:53 AM UTC+5:30, Peter Cacioppi wrote:
> > First, thanks (both of you) very much for the feedback.  I originally 
> > wrote that page.
> 
> One more 'to-be-removed' from that page is the bit about new and old GG at 
> the end.  It used to work for a while. Now google has completely removed the 
> 'old interface' (at least to the best of my knowledge).

I updated the page, hopefully it's an improvement?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rusi
On Monday, October 28, 2013 11:10:21 AM UTC+5:30, ru...@yahoo.com wrote:
> I updated the page, hopefully it's an improvement?


Most people who top-post have no idea that they are top-posting and that there
are alternatives and they are preferred (out here)
http://en.wikipedia.org/wiki/Posting_style#Placement_of_replies should help

Otherwise ok I think
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Try-except for flow control in reading Sqlite

2013-10-27 Thread Steven D'Aprano
On Sun, 27 Oct 2013 20:43:07 -0700, Victor Hooi wrote:

> Hi,
> 
> I'd like to double-check something regarding using try-except for
> controlling flow.
> 
> I have a script that needs to lookup things in a SQLite database.
> 
> If the SQLite database file doesn't exist, I'd like to create an empty
> database, and then setup the schema.
> 
> Is it acceptable to use try-except in order to achieve this? E.g.:
> 
> try:
> # Try to open up the SQLite file, and lookup the required
> entries
> except OSError:
> # Open an empty SQLite file, and create the schema

Yes, that's the right way to do it.


> My thinking is that it is (easier to ask forgiveness than permission),
> but I just wanted to check if there is a better way of achieving this?
> 
> I'd also be doing the same thing for checking if a file is gzipped or
> not - we try to open it as a gzip, then as an ordinary text file, and if
> that also fails, raise a parsing error.

Correct.

The problem with checking in advance is that there is a race condition 
between checking and the using the file:


if database exists: # at this moment, the file is guaranteed to exist
# but a moment later, guarantee is no longer valid
open database


In a multitasking operating system, some other process may have deleted 
the database. Or changed its name, removed your access privileges, even 
replaced it with a different file. Apart from hard-to-diagnose bugs, this 
is also the source of some security vulnerabilities:

https://www.owasp.org/index.php/Race_Conditions

Scroll down and read the section on "Time of check, time of use race 
condition".

So using a try...except block is precisely the right solution.



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


Re: Try-except for flow control in reading Sqlite

2013-10-27 Thread Chris Angelico
On Mon, Oct 28, 2013 at 2:43 PM, Victor Hooi  wrote:
> Is it acceptable to use try-except in order to achieve this? E.g.:
>
> try:
> # Try to open up the SQLite file, and lookup the required entries
> except OSError:
> # Open an empty SQLite file, and create the schema
>
>
> My thinking is that it is (easier to ask forgiveness than permission), but I 
> just wanted to check if there is a better way of achieving this?

That looks fine as a model, but is OSError what you want to be
catching? I'd go with FileNotFoundError if that's what you're looking
for - OSError would also catch quite a bit else, like permissions
errors.

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


Re: How to find where data files are installed for my Python program

2013-10-27 Thread Chris Angelico
On Mon, Oct 28, 2013 at 11:34 AM, Mark Lawrence  wrote:
> "What is the difference between "script" code (like Javascript and visual)
> made for the screen (where such magic values are utilized) and compiled
> source (made for the machine)?"
>
> This obviously impacts on the discussion above, so how does Unix, Windows
> and other operating systems distinguish these with respect to binary,
> executable, code library or whatever?

Suppose you pull up a shell - for argument's sake, let's say it's
Debian GNU/Linux and you're running bash. You get a prompt that ends
with a dollar sign, and you type "ls". What's going to get executed?

* An alias? You might have an internal function defined in your
.bashrc, or maybe a wrapper that adds parameters to your command.

* A bash internal command? The shell might directly interpret what you
specified. (I don't think ls is like that, but time is, on my
systems.)

* An external binary? On my systems, /bin/ls is an executable binary,
compiled and ready to run.

* A script? Another alternative to the shell alias, you could have
/usr/local/bin/ls that does something different, then maybe drops
through to /bin/ls. If it starts with "#!/usr/bin/python", it'll get
dropped through to Python for execution.

Chances are you wouldn't know the difference, as a human executing the
commands. And you shouldn't need to care, except in really weird
circumstances (maybe you broke your Python install and need to type
"/bin/ls" to figure out what's going on).

Most programs, trying to execute code, won't care about the difference
between binaries and scripts, though of course exec*() won't parse
bash aliases or internals. But if you need to distinguish for whatever
reason, the easiest way is to look at the magic numbers, which can be
done with the 'file' command:

rosuav@sikorsky:~$ file `which ls`
/bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV),
dynamically linked (uses shared libs), for GNU/Linux 2.6.26,
BuildID[sha1]=0x55f1e005df252708d4c456dcc2c7dccea1006553, stripped

rosuav@sikorsky:~$ file `which zcat`
/bin/zcat: Bourne-Again shell script, ASCII text executable

Executables happily together, regardless of type.

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


Re: Possibly better loop construct, also labels+goto important and on the fly compiler idea.

2013-10-27 Thread rusi
On Monday, October 28, 2013 11:26:21 AM UTC+5:30, rusi wrote:
> On Monday, October 28, 2013 11:10:21 AM UTC+5:30, ru...@yahoo.com wrote:
> > I updated the page, hopefully it's an improvement?
> 
> 
> Otherwise ok I think

Just looked at the general netiquette link -- its long and not much use for a 
technical oriented forum.

Some items missed (irrespective of GG usage)
1. Good subject line
2. Good code examples http://sscce.org/
3. http://www.catb.org/esr/faqs/smart-questions.html
-- 
https://mail.python.org/mailman/listinfo/python-list