Re: I need some help interpreting this error

2021-02-17 Thread Terry Reedy

On 2/17/2021 10:40 AM, Chris Green wrote:

I'm running this using Python 3.7 on a Linux system.

Most of the time (i.e. for a couple of days now) the program has been
satifactorily delivering mail messages, hundreds of them.  However one
mail message has provoked the following error:-

 chris@cheddar$ tail mail.err
 Traceback (most recent call last):
   File "/home/chris/.mutt/bin/filter.py", line 95, in 
 if sbstrip in msghdr["subject"]:
 TypeError: argument of type 'Header' is not iterable


But msghdr["subject"] is surely just a string isn't it?


Obviously not.


 Why is it
complaining about something of type 'Header'?


Because you tried to iterate it.  Header is defined in email.header 
(find 'class Header').  It has a __str__ to turn one into a string.  I 
have never read the email doc so I have no idea if 'subject' being a 
Header is a bug.


Grepping email package for case-sensitive word 'Header' also returns 3 
comment saying that something might be a Header, so stringify it.  I 
have the impression that these might have been added after the original 
code, perhaps in response to error reports.  In any case, you can do the 
same.



As I said the program has been running happily for a couple of days
with no errors, I guess it must be something strange in a mail that
has broken things - but what?


To determine that, look at (after logging or saving) the raw email and 
maybe the resulting Message (using msg.as_string).



# Read the message from standard input and make a message object from it
#
msg = mailbox.MaildirMessage(sys.stdin.buffer.read())


raw = sys.stdin.buffer.read()  # So can save
msg = mailbox.MaildirMessage(raw)


msghdr["subject"] = msg.get("Subject", "unknown")

...

 if sbstrip in msghdr["subject"]:


Replace with

  sub = msghdr["subject"]
  if 'Header' in str(sub.__class__):
# Or import email.message.class and use isinstance
   # stringify or skip or ???
   else:

 msg.replace_header("Subject", msghdr["subject"].replace(sbstrip, 


--
Terry Jan Reedy

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


Re: I need some help interpreting this error

2021-02-17 Thread 2QdxY4RzWzUUiLuE
On 2021-02-17 at 17:36:48 +,
Chris Green  wrote:

> Stefan Ram  wrote:
> > Chris Green  writes:
> > >chris@cheddar$ tail mail.err
> > >Traceback (most recent call last):
> > >  File "/home/chris/.mutt/bin/filter.py", line 95, in 
> > >if sbstrip in msghdr["subject"]:
> > >TypeError: argument of type 'Header' is not iterable
> > >But msghdr["subject"] is surely just a string isn't it?  Why is it 
> > >complaining about something of type 'Header'?
> > 
> >   I presume that the error message has been edited (abbreviated).
> > 
> >   In "if sbstrip in msghdr["subject"]:", there is no argument.
> > 
> >   But the error message says "argument of ...".
> > 
> >   When something that is not iterable is presented to a for loop,
> >   the error message does not mention "argument":
> > 
> I have output everything that appears, I've not changed it at all.
> It's the whole content of the file ~/tmp/mail.err as it's the only
> error that has occurred for the last day or so.  The error log is
> created by the line:-
> 
> sys.stderr = open("/home/chris/tmp/mail.err", 'a')
> 
> So that's everything that was output to stderr.
> 
> I think you are puzzled in the same way that I was, the error message
> doesn't make a lot of sense.  

At some point, the internal code for the "in" operator is likely
iterating over the elements of msghdr["subject"].

That error message doesn't make a lot of sense if msghdr["subject"] is a
sub-class of str.  It makes more sense if msghdr["subject"] is something
else.

IMO, you need more information in the log, a try/except block to prevent
the code from crashing, and, yes, perhaps some patience to wait for it
to happen again.

Sometimes, developing software isn't all fortune, fame, and glory.  ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread 2QdxY4RzWzUUiLuE
On 2021-02-17 at 16:52:55 +,
Chris Green  wrote:

> Stefan Ram  wrote:
> > Chris Green  writes:
> > >But msghdr["subject"] is surely just a string isn't it?  Why is it 
> > >complaining about something of type 'Header'?
> > 
> >   What would you do to debug-print the type of an object?
> > 
> I don't know, what would I do?  :-)
> 
> Without knowing what provokes the problem I could be waiting for days
> or weeks even before I see the error again.  As I'd need to print the
> type for every message I'd get some big logs or I'd need to add a try:
> except to trap the specific error.

An intermittent problem!  They're our favorite!  ;-)

Seriously, though, do you have a message that provokes the problem?  Is
there a log at all?  Can you re-run that message through the code, in a
debugger or otherwise?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Chris Green
Stestagg  wrote:
> I don't particularly like to encourage this shotgun help request because,
> as previous commenter suggests, debugging this yourself is best.
> 
> Sometimes debugging is super hard, and especially so when uncommon
> situations occur, but it's always far easier to debug things when you have
> visibility into the system under test.
> 
> However, in this case, the email code is super complex, and this scenario
> also looks very uncommon, but not unique: (
> https://github.com/Sydius/mbox-to-txt/issues/2), so you successfully
> nerd-sniped me :).
> 
> My *guess*, from reading the python standard library source code is that
> you came across an email with some content in the subject line that is
> considered a "surrogate", roughly, some badly encoded unicode or binary
> data in it.
> 
> When this happens, the code in some situations (depending on the policy...)
> may return a header.Header() instance, rather than a
> headerregistry.UniqueUnstructuredHeader
> (which would have had a headerregistry.BaseHeader (mro: str) dynamically
> attached).
> 
> header.Header() does not inherit from str, and thus would throw the
> traceback you observed.
> 
Ah, thank you, a possible explanation.


> Your suggestion of a try: catch: may make sense, alternately, you could
> wrap the result in a call to str():
> 
> if sbstrip in str(msghdr["subject"]):
> 
> which should attempt to encode the binary into some form of string object
> for comparison (I haven't checked exactly what would happen, beyond: it
> tries).
> 
Yes, I did consider the str() approach but it feels a bit like making
the problem go away without actually fixing it.

However since the code in question is only 'cosmetic' (removing
unwanted [list name] from the subject, it's not all *that* important
to handle it properly.  I just need to stop the error from killing my
program.


> It should be possible to create a test mbox with some funky bytes in the
> subject, and try to reproduce it that way.
> 
That's a point, with the clues you have given me I can try some 'bad'
subject text and see if I can reproduce the error.

Thanks again.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Stestagg
Some sources, in case they help:

Message.get() calls policy.header_fetch_parse (
https://github.com/python/cpython/blob/cd80f430daa7dfe7feeb431ed34f88db5f64aa30/Lib/email/message.py#L471
)
Compat32.header_fetch_parse calls self._sanitize_header (
https://github.com/python/cpython/blob/cd80f430daa7dfe7feeb431ed34f88db5f64aa30/Lib/email/_policybase.py#L311
)
_sanitize_header calls _has_surrogates (
https://github.com/python/cpython/blob/cd80f430daa7dfe7feeb431ed34f88db5f64aa30/Lib/email/_policybase.py#L287
)
_has_surrogates check:
https://github.com/python/cpython/blob/cd80f430daa7dfe7feeb431ed34f88db5f64aa30/Lib/email/utils.py#L51



On Wed, Feb 17, 2021 at 5:42 PM Stestagg  wrote:

> I don't particularly like to encourage this shotgun help request because,
> as previous commenter suggests, debugging this yourself is best.
>
> Sometimes debugging is super hard, and especially so when uncommon
> situations occur, but it's always far easier to debug things when you have
> visibility into the system under test.
>
> However, in this case, the email code is super complex, and this scenario
> also looks very uncommon, but not unique: (
> https://github.com/Sydius/mbox-to-txt/issues/2), so you successfully
> nerd-sniped me :).
>
> My *guess*, from reading the python standard library source code is that
> you came across an email with some content in the subject line that is
> considered a "surrogate", roughly, some badly encoded unicode or binary
> data in it.
>
> When this happens, the code in some situations (depending on the
> policy...) may return a header.Header() instance, rather than a
> headerregistry.UniqueUnstructuredHeader (which would have had a
> headerregistry.BaseHeader (mro: str) dynamically attached).
>
> header.Header() does not inherit from str, and thus would throw the
> traceback you observed.
>
> Your suggestion of a try: catch: may make sense, alternately, you could
> wrap the result in a call to str():
>
> if sbstrip in str(msghdr["subject"]):
>
> which should attempt to encode the binary into some form of string object
> for comparison (I haven't checked exactly what would happen, beyond: it
> tries).
>
> It should be possible to create a test mbox with some funky bytes in the
> subject, and try to reproduce it that way.
>
> Steve
>
>
> On Wed, Feb 17, 2021 at 5:07 PM Chris Green  wrote:
>
>> Stefan Ram  wrote:
>> > Chris Green  writes:
>> > >But msghdr["subject"] is surely just a string isn't it?  Why is it
>> > >complaining about something of type 'Header'?
>> >
>> >   What would you do to debug-print the type of an object?
>> >
>> I don't know, what would I do?  :-)
>>
>> Without knowing what provokes the problem I could be waiting for days
>> or weeks even before I see the error again.  As I'd need to print the
>> type for every message I'd get some big logs or I'd need to add a try:
>> except to trap the specific error.
>>
>> --
>> Chris Green
>> ·
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Chris Green
Stefan Ram  wrote:
> Chris Green  writes:
> >chris@cheddar$ tail mail.err
> >Traceback (most recent call last):
> >  File "/home/chris/.mutt/bin/filter.py", line 95, in 
> >if sbstrip in msghdr["subject"]:
> >TypeError: argument of type 'Header' is not iterable
> >But msghdr["subject"] is surely just a string isn't it?  Why is it 
> >complaining about something of type 'Header'?
> 
>   I presume that the error message has been edited (abbreviated).
> 
>   In "if sbstrip in msghdr["subject"]:", there is no argument.
> 
>   But the error message says "argument of ...".
> 
>   When something that is not iterable is presented to a for loop,
>   the error message does not mention "argument":
> 
I have output everything that appears, I've not changed it at all.
It's the whole content of the file ~/tmp/mail.err as it's the only
error that has occurred for the last day or so.  The error log is
created by the line:-

sys.stderr = open("/home/chris/tmp/mail.err", 'a')

So that's everything that was output to stderr.

I think you are puzzled in the same way that I was, the error message
doesn't make a lot of sense.  

> |>>> for i in 0:
> |...print(i)
> |...
> |Traceback (most recent call last):
> |  File "", line 1, in 
> |TypeError: 'int' object is not iterable
> 
>   .
> 
> 

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Stestagg
I don't particularly like to encourage this shotgun help request because,
as previous commenter suggests, debugging this yourself is best.

Sometimes debugging is super hard, and especially so when uncommon
situations occur, but it's always far easier to debug things when you have
visibility into the system under test.

However, in this case, the email code is super complex, and this scenario
also looks very uncommon, but not unique: (
https://github.com/Sydius/mbox-to-txt/issues/2), so you successfully
nerd-sniped me :).

My *guess*, from reading the python standard library source code is that
you came across an email with some content in the subject line that is
considered a "surrogate", roughly, some badly encoded unicode or binary
data in it.

When this happens, the code in some situations (depending on the policy...)
may return a header.Header() instance, rather than a
headerregistry.UniqueUnstructuredHeader
(which would have had a headerregistry.BaseHeader (mro: str) dynamically
attached).

header.Header() does not inherit from str, and thus would throw the
traceback you observed.

Your suggestion of a try: catch: may make sense, alternately, you could
wrap the result in a call to str():

if sbstrip in str(msghdr["subject"]):

which should attempt to encode the binary into some form of string object
for comparison (I haven't checked exactly what would happen, beyond: it
tries).

It should be possible to create a test mbox with some funky bytes in the
subject, and try to reproduce it that way.

Steve


On Wed, Feb 17, 2021 at 5:07 PM Chris Green  wrote:

> Stefan Ram  wrote:
> > Chris Green  writes:
> > >But msghdr["subject"] is surely just a string isn't it?  Why is it
> > >complaining about something of type 'Header'?
> >
> >   What would you do to debug-print the type of an object?
> >
> I don't know, what would I do?  :-)
>
> Without knowing what provokes the problem I could be waiting for days
> or weeks even before I see the error again.  As I'd need to print the
> type for every message I'd get some big logs or I'd need to add a try:
> except to trap the specific error.
>
> --
> Chris Green
> ·
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Chris Green
2qdxy4rzwzuui...@potatochowder.com wrote:
> On 2021-02-17 at 16:42:03 +,
> Chris Green  wrote:
> 
> > 2qdxy4rzwzuui...@potatochowder.com wrote:
> > > On 2021-02-17 at 15:40:27 +,
> > > Chris Green  wrote:
> > > 
> > > > I'm running this using Python 3.7 on a Linux system.
> > > > 
> > > > Most of the time (i.e. for a couple of days now) the program has been
> > > > satifactorily delivering mail messages, hundreds of them.  However one
> > > > mail message has provoked the following error:-
> > > > 
> > > > chris@cheddar$ tail mail.err
> > > > Traceback (most recent call last):
> > > >   File "/home/chris/.mutt/bin/filter.py", line 95, in 
> > > > if sbstrip in msghdr["subject"]:
> > > > TypeError: argument of type 'Header' is not iterable
> > > > 
> > > > 
> > > > But msghdr["subject"] is surely just a string isn't it?  Why is it 
> > > > complaining about something of type 'Header'?
> > > 
> > > Isn't it?  ;-)
> > > 
> > > First step:  Print msghdr["subject"] and its type to know for sure.  The
> > > worst case is that you'll verify your assumption.
> > > 
> > The documentation says "Headers are represented by customized
> > subclasses of str", so it's a sub-class of str.  
> 
> So we still don't know what the content of msghdr["subject"] is at the
> time the error occurs.  I don't mean to sound harsh, but that the
> documentation and the code are correct, and that they match, remain
> assumptions.  Sometimes, seeing an actual value tells you what went
> wrong (e.g., "oh, that's the sender's address, not the receiver's
> address," "oh, that's my 'time' class, not the one from the standard
> library").
> 
> The traceback tells you that msghdr["subject"] is of type Header.  Is
> Header a sub-class of str?
> 
That's exactly what puzzled me! The line that gets the value is:-

msghdr["subject"] = msg.get("Subject", "unknown")

What I need to know is how that can return a value of type Header, and
not a str.

> Again, the worst case of looking at the value (whether in a log or in a
> debugger) is that you verify your assumption.
> 
> > > IIRC, the subject header is actually optional.  Maybe someone sent a
> > > message without a subject?  Is msghdr["subject"] None?
> > 
> > If you look at the code (and the documentation) if there's no subject
> > header I'll get the string "unknown", I've also tried sending myself
> > an E-Mail with no header and not provoked the error.
> 
> That's good news about subject-less emails not generating an error, and
> separate (possibly related) good news about your code handling an email
> without a subject header.  ;-)

I think the only sane approach at the moment may be to add a try:
except: and output some diagnostic information.  Though there may
still be an issue when trying to output the "what is it" object to the
error log of course.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Chris Green
Stefan Ram  wrote:
> Chris Green  writes:
> >But msghdr["subject"] is surely just a string isn't it?  Why is it 
> >complaining about something of type 'Header'?
> 
>   What would you do to debug-print the type of an object?
> 
I don't know, what would I do?  :-)

Without knowing what provokes the problem I could be waiting for days
or weeks even before I see the error again.  As I'd need to print the
type for every message I'd get some big logs or I'd need to add a try:
except to trap the specific error.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread 2QdxY4RzWzUUiLuE
On 2021-02-17 at 16:42:03 +,
Chris Green  wrote:

> 2qdxy4rzwzuui...@potatochowder.com wrote:
> > On 2021-02-17 at 15:40:27 +,
> > Chris Green  wrote:
> > 
> > > I'm running this using Python 3.7 on a Linux system.
> > > 
> > > Most of the time (i.e. for a couple of days now) the program has been
> > > satifactorily delivering mail messages, hundreds of them.  However one
> > > mail message has provoked the following error:-
> > > 
> > > chris@cheddar$ tail mail.err
> > > Traceback (most recent call last):
> > >   File "/home/chris/.mutt/bin/filter.py", line 95, in 
> > > if sbstrip in msghdr["subject"]:
> > > TypeError: argument of type 'Header' is not iterable
> > > 
> > > 
> > > But msghdr["subject"] is surely just a string isn't it?  Why is it 
> > > complaining about something of type 'Header'?
> > 
> > Isn't it?  ;-)
> > 
> > First step:  Print msghdr["subject"] and its type to know for sure.  The
> > worst case is that you'll verify your assumption.
> > 
> The documentation says "Headers are represented by customized
> subclasses of str", so it's a sub-class of str.  

So we still don't know what the content of msghdr["subject"] is at the
time the error occurs.  I don't mean to sound harsh, but that the
documentation and the code are correct, and that they match, remain
assumptions.  Sometimes, seeing an actual value tells you what went
wrong (e.g., "oh, that's the sender's address, not the receiver's
address," "oh, that's my 'time' class, not the one from the standard
library").

The traceback tells you that msghdr["subject"] is of type Header.  Is
Header a sub-class of str?

Again, the worst case of looking at the value (whether in a log or in a
debugger) is that you verify your assumption.

> > IIRC, the subject header is actually optional.  Maybe someone sent a
> > message without a subject?  Is msghdr["subject"] None?
> 
> If you look at the code (and the documentation) if there's no subject
> header I'll get the string "unknown", I've also tried sending myself
> an E-Mail with no header and not provoked the error.

That's good news about subject-less emails not generating an error, and
separate (possibly related) good news about your code handling an email
without a subject header.  ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread Chris Green
2qdxy4rzwzuui...@potatochowder.com wrote:
> On 2021-02-17 at 15:40:27 +,
> Chris Green  wrote:
> 
> > I'm running this using Python 3.7 on a Linux system.
> > 
> > Most of the time (i.e. for a couple of days now) the program has been
> > satifactorily delivering mail messages, hundreds of them.  However one
> > mail message has provoked the following error:-
> > 
> > chris@cheddar$ tail mail.err
> > Traceback (most recent call last):
> >   File "/home/chris/.mutt/bin/filter.py", line 95, in 
> > if sbstrip in msghdr["subject"]:
> > TypeError: argument of type 'Header' is not iterable
> > 
> > 
> > But msghdr["subject"] is surely just a string isn't it?  Why is it 
> > complaining about something of type 'Header'?
> 
> Isn't it?  ;-)
> 
> First step:  Print msghdr["subject"] and its type to know for sure.  The
> worst case is that you'll verify your assumption.
> 
The documentation says "Headers are represented by customized
subclasses of str", so it's a sub-class of str.  


> IIRC, the subject header is actually optional.  Maybe someone sent a
> message without a subject?  Is msghdr["subject"] None?

If you look at the code (and the documentation) if there's no subject
header I'll get the string "unknown", I've also tried sending myself
an E-Mail with no header and not provoked the error.


-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need some help interpreting this error

2021-02-17 Thread 2QdxY4RzWzUUiLuE
On 2021-02-17 at 15:40:27 +,
Chris Green  wrote:

> I'm running this using Python 3.7 on a Linux system.
> 
> Most of the time (i.e. for a couple of days now) the program has been
> satifactorily delivering mail messages, hundreds of them.  However one
> mail message has provoked the following error:-
> 
> chris@cheddar$ tail mail.err
> Traceback (most recent call last):
>   File "/home/chris/.mutt/bin/filter.py", line 95, in 
> if sbstrip in msghdr["subject"]:
> TypeError: argument of type 'Header' is not iterable
> 
> 
> But msghdr["subject"] is surely just a string isn't it?  Why is it 
> complaining about something of type 'Header'?

Isn't it?  ;-)

First step:  Print msghdr["subject"] and its type to know for sure.  The
worst case is that you'll verify your assumption.

IIRC, the subject header is actually optional.  Maybe someone sent a
message without a subject?  Is msghdr["subject"] None?
-- 
https://mail.python.org/mailman/listinfo/python-list


I need some help interpreting this error

2021-02-17 Thread Chris Green
I'm running this using Python 3.7 on a Linux system.

Most of the time (i.e. for a couple of days now) the program has been
satifactorily delivering mail messages, hundreds of them.  However one
mail message has provoked the following error:-

chris@cheddar$ tail mail.err
Traceback (most recent call last):
  File "/home/chris/.mutt/bin/filter.py", line 95, in 
if sbstrip in msghdr["subject"]:
TypeError: argument of type 'Header' is not iterable


But msghdr["subject"] is surely just a string isn't it?  Why is it 
complaining about something of type 'Header'?

As I said the program has been running happily for a couple of days 
with no errors, I guess it must be something strange in a mail that
has broken things - but what?

Full program listed below:-

#!/usr/bin/python3
#
#
# licenseApache v2 (http://www.apache.org/licenses/LICENSE-2.0) 
# author Chris Green - ch...@isbd.co.uk
# 
#
#
# Mail filtering script
#
import mailbox
import os
import sys
import time
import mailLib
import shlex
#
#
# Redirect any exceptions to a file
#
sys.stderr = open("/home/chris/tmp/mail.err", 'a')
#
#
# Some constants (i.e. configuration)
#
home = "/home/chris"
logfile = home + "/tmp/mail.log"
filtfile = home + "/.mutt/filter"
mldir = home + "/mail/"
indir = mldir + "In/"
#
#
# Set to log to mail.log in ~/tmp with name 'filter' and the
envelope/from
#
log = mailLib.initLog("filter")
#
#
# Initialise destination mailbox name to its default "In/default"
#
dest = indir + "default"
#
#
# Read the message from standard input and make a message object from it
#
msg = mailbox.MaildirMessage(sys.stdin.buffer.read())
#
#
# Extract various headers and the envelope/from
#
msghdr =  {}
msghdr["to"] = msg.get("To", "unknown").lower()
msghdr["subject"] = msg.get("Subject", "unknown")
msghdr["list-id"] = msg.get("List-Id", "unknown").lower()
msghdr["list-post"] = msg.get("List-Post", "unknown").lower()
msghdr["x-mailing-list"] = msg.get("X-Mailing-List", "unknown").lower()
msghdr["unknown"] = "unknown"
#
#
# See if there's a match in our filter file
#
f = open(filtfile, 'r')
for ln in f:# for each line in filter
if ln[0] == '#':# ignore comments
continue
#
#
# split the line into fields, shlex.split() does quoted strings, add a field
# to create a dummy fourth field if there isn't one in the filter file
#
fld = shlex.split(ln)
fld.append("")
#
#
# copy the fields into better named variables
#
nm = fld[0] # name/alias
destdir = fld[1] + "/"  # the destination directory
header = fld[2] # the header to find the match in
address = fld[3].lower()# list address to match
sbstrip = '[' + fld[4] + ']'# string to strip out of subject
#
#
# Does the address in the header match this entry
#
if (address in msghdr[header]):
#
#
# set the destination directory
#
dest = mldir + destdir + nm
#
#
# Strip out list name (4th field) from subject if it's there
#
if sbstrip in msghdr["subject"]:
msg.replace_header("Subject", msghdr["subject"].replace(sbstrip, 
''))
#
#
# we've found a match so assume we won't get another
#
break
#
#
# deliver the message
#
mailLib.deliverMdMsg(dest, msg, log)

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


reStrcuturedText WYSIWYG online editor (was: Need some help with Python Job Board)

2017-11-13 Thread Ben Finney
Skip Montanaro  writes:

> Thanks, Justin. I imagine editors probably exist which can switch between
> WYSIWYG and markup.

The ‘rsted’ app  is a
reStructuredText WYSIWYG editor written in the Flask framework.

-- 
 \   “Remember: every member of your ‘target audience’ also owns a |
  `\   broadcasting station. These ‘targets’ can shoot back.” —Michael |
_o__)   Rathbun to advertisers, news.admin.net-abuse.email |
Ben Finney

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


Re: [Jobs] Need some help with Python Job Board

2017-11-13 Thread justin walters
On Mon, Nov 13, 2017 at 1:16 AM, M.-A. Lemburg  wrote:

> Hi Justin,
>
> the default markup is currently set to restructuredtext:
>
> https://github.com/python/pythondotorg/blob/master/jobs/models.py
>
> but this can be changed to any of these supported ones:
>
> https://github.com/jamesturk/django-markupfield
>
> as long as we make sure that all existing records continue
> to be set to ReST (to not mess up the formatting).
>
> Since I had a look at WYSIWYG editors, some new ones may have
> surfaced.
>
> The templates are defined here:
>
> https://github.com/python/pythondotorg/tree/master/templates/jobs
>
> and the main project page has instructions on how to get
> a local copy of the website working:
>
> https://pythondotorg.readthedocs.io/
>
> Thanks,
> --
> Marc-Andre Lemburg
> Python Software Foundation
> http://www.python.org/psf/
> http://www.malemburg.com/
> _
> > Jobs mailing list
> > j...@python.org
> > https://mail.python.org/mailman/listinfo/jobs
> >
>
>

Thank you Marc.

I'll take a look over this stuff and hopefully I can squeeze in some time
this week to work on it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Jobs] Need some help with Python Job Board

2017-11-13 Thread M.-A. Lemburg
Hi Justin,

the default markup is currently set to restructuredtext:

https://github.com/python/pythondotorg/blob/master/jobs/models.py

but this can be changed to any of these supported ones:

https://github.com/jamesturk/django-markupfield

as long as we make sure that all existing records continue
to be set to ReST (to not mess up the formatting).

Since I had a look at WYSIWYG editors, some new ones may have
surfaced.

The templates are defined here:

https://github.com/python/pythondotorg/tree/master/templates/jobs

and the main project page has instructions on how to get
a local copy of the website working:

https://pythondotorg.readthedocs.io/

Thanks,
-- 
Marc-Andre Lemburg
Python Software Foundation
http://www.python.org/psf/
http://www.malemburg.com/

On 12.11.2017 18:52, Skip Montanaro wrote:
> Thanks, Justin. I imagine editors probably exist which can switch between
> WYSIWYG and markup. Whether that markup can be Markdown or not, I don't
> know. Marc-André Lemburg listed a few possible editors in the ticket he
> opened, but I've not dug into their properties.
> 
> Skip
> 
> On Sun, Nov 12, 2017 at 11:20 AM, justin walters > wrote:
> 
>> On Sat, Nov 11, 2017 at 3:27 PM, Skip Montanaro 
>> wrote:
>>
>>> The Python Job Board could use a little help in a couple areas. One, we
>> can
>>> always use help reviewing and approving (or rejecting) submissions. The
>>> backlog keeps growing, and the existing volunteers who help can't always
>>> keep up. (This is a good problem to have, reflecting on Python's broad
>>> popularity in many application domains.)
>>>
>>> Two, and perhaps more important, the submission form really needs to
>>> support WYSIWYG editing. Apparently, most posters are unable to handle
>>> markup-based systems, probably just pasting content from Word documents.
>>> Making this change would streamline the review process, as formatting
>>> problems are currently the biggest impediment to successful submissions.
>>> There is an open ticket to add this feature:
>>>
>>> https://github.com/python/pythondotorg/issues/655
>>>
>>> If you can help with either task, please drop a note to j...@python.org.
>>>
>>> Thanks,
>>>
>>> Skip
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>>>
>>
>> I might be able to help implement a wysiwyg editor. The only issue I can
>> think of at the moment
>> would be finding a way to determine if the template should render wysiswyg
>> content or Markdown content.
>>
>> I'll need to look over the repo a bit more closely first.
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
> 
> 
> 
> ___
> Jobs mailing list
> j...@python.org
> https://mail.python.org/mailman/listinfo/jobs
> 

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


Re: Need some help with Python Job Board

2017-11-12 Thread Skip Montanaro
Thanks, Justin. I imagine editors probably exist which can switch between
WYSIWYG and markup. Whether that markup can be Markdown or not, I don't
know. Marc-André Lemburg listed a few possible editors in the ticket he
opened, but I've not dug into their properties.

Skip

On Sun, Nov 12, 2017 at 11:20 AM, justin walters  wrote:

> On Sat, Nov 11, 2017 at 3:27 PM, Skip Montanaro 
> wrote:
>
> > The Python Job Board could use a little help in a couple areas. One, we
> can
> > always use help reviewing and approving (or rejecting) submissions. The
> > backlog keeps growing, and the existing volunteers who help can't always
> > keep up. (This is a good problem to have, reflecting on Python's broad
> > popularity in many application domains.)
> >
> > Two, and perhaps more important, the submission form really needs to
> > support WYSIWYG editing. Apparently, most posters are unable to handle
> > markup-based systems, probably just pasting content from Word documents.
> > Making this change would streamline the review process, as formatting
> > problems are currently the biggest impediment to successful submissions.
> > There is an open ticket to add this feature:
> >
> > https://github.com/python/pythondotorg/issues/655
> >
> > If you can help with either task, please drop a note to j...@python.org.
> >
> > Thanks,
> >
> > Skip
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >
>
> I might be able to help implement a wysiwyg editor. The only issue I can
> think of at the moment
> would be finding a way to determine if the template should render wysiswyg
> content or Markdown content.
>
> I'll need to look over the repo a bit more closely first.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need some help with Python Job Board

2017-11-12 Thread justin walters
On Sat, Nov 11, 2017 at 3:27 PM, Skip Montanaro 
wrote:

> The Python Job Board could use a little help in a couple areas. One, we can
> always use help reviewing and approving (or rejecting) submissions. The
> backlog keeps growing, and the existing volunteers who help can't always
> keep up. (This is a good problem to have, reflecting on Python's broad
> popularity in many application domains.)
>
> Two, and perhaps more important, the submission form really needs to
> support WYSIWYG editing. Apparently, most posters are unable to handle
> markup-based systems, probably just pasting content from Word documents.
> Making this change would streamline the review process, as formatting
> problems are currently the biggest impediment to successful submissions.
> There is an open ticket to add this feature:
>
> https://github.com/python/pythondotorg/issues/655
>
> If you can help with either task, please drop a note to j...@python.org.
>
> Thanks,
>
> Skip
> --
> https://mail.python.org/mailman/listinfo/python-list
>

I might be able to help implement a wysiwyg editor. The only issue I can
think of at the moment
would be finding a way to determine if the template should render wysiswyg
content or Markdown content.

I'll need to look over the repo a bit more closely first.
-- 
https://mail.python.org/mailman/listinfo/python-list


Need some help with Python Job Board

2017-11-11 Thread Skip Montanaro
The Python Job Board could use a little help in a couple areas. One, we can
always use help reviewing and approving (or rejecting) submissions. The
backlog keeps growing, and the existing volunteers who help can't always
keep up. (This is a good problem to have, reflecting on Python's broad
popularity in many application domains.)

Two, and perhaps more important, the submission form really needs to
support WYSIWYG editing. Apparently, most posters are unable to handle
markup-based systems, probably just pasting content from Word documents.
Making this change would streamline the review process, as formatting
problems are currently the biggest impediment to successful submissions.
There is an open ticket to add this feature:

https://github.com/python/pythondotorg/issues/655

If you can help with either task, please drop a note to j...@python.org.

Thanks,

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


Re: Need some help with argparse

2017-10-03 Thread Ben Finney
Kryptxy via Python-list  writes:

> I have a group of arguments, say: (-a, -b, -c, -d, -e) [lets call it group1]
> I have another group, say: (-z, -y, -x, -w) [lets call it group2]

Argument groups are a feature to control the help output from the
parser:

 When an argument is added to the group, the parser treats it just
 like a normal argument, but displays the argument in a separate
 group for help messages.

 

> Now I want to get arguments of group1 and group2 separately.

You don't want to use the “argument groups” feature for that, because
that's not what it does.

> How can I get all arguments of group 1 ONLY? Same goes for group 2?
> I tried subparsers too - but they require a mandatory `positional
> argument` - which is not application's requirement.

I don't know of a way to have the argument parser know the separation
you're talking about, without using a subparser.

You will need to maintain that separation yourself, outside the parser.

One simple way (I have not tried this)::

argument_names_by_group = {
'foo': {'lorem', 'donec', 'fusce'},
'bar': {'aliquam', 'nunc'},
}

args = parser.parse_args()

args_by_group = {
group_name: {
getattr(arg_name)
for arg_name in argument_names_by_group[group_name]
}
for group_name in argument_names_by_group
}

-- 
 \ “I believe our future depends powerfully on how well we |
  `\ understand this cosmos, in which we float like a mote of dust |
_o__) in the morning sky.” —Carl Sagan, _Cosmos_, 1980 |
Ben Finney

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


Need some help with argparse

2017-10-03 Thread Kryptxy via Python-list
Hi,
I am trying to figure out something with argparse.
Here is a scenario:

I have a group of arguments, say: (-a, -b, -c, -d, -e) [lets call it group1]
I have another group, say: (-z, -y, -x, -w) [lets call it group2]

Code:
import argparse
parser = argparse.ArgumentParser(description="Test this shiz")
group1= parser.add_argument_group("Group 1")
group2= parser.add_argument_group("Group 2")

group1.add_argument('-a', '--extendA', action="store_true", help="HELP")
group1.add_argument('-b', '--extendB', action="store_true", help="HELP")
group1.add_argument('-c', '--extendC', action="store_true", help="HELP")
group1.add_argument('-d', '--extendD', action="store_true", help="HELP")
group1.add_argument('-e', '--extendE', action="store_true", help="HELP")

# Similarly for group 2:
group2.add_argument('-z', '--extendZ', action="store_true", help="HELP")
group2.add_argument('-y', '--extendY', action="store_true", help="HELP")
group2.add_argument('-x', '--extendX', action="store_true", help="HELP")
group2.add_argument('-w', '--extendW', action="store_true", help="HELP")

args = parser.parse_args()

Now I want to get arguments of group1 and group2 separately.
If I print(args) - I get arguments from both the groups.
Also group1.parse_args() does not work (since ArgumentGroup does not have 
parse_args() method)

How can I get all arguments of group 1 ONLY? Same goes for group 2?
I tried subparsers too - but they require a mandatory `positional argument` - 
which is not application's requirement.

Any kind of help is appreciated.
Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need some help managing project and making it a little simple (pretty messed up code)

2017-08-17 Thread dieter
Kryptxy via Python-list  writes:
> ...
> I am new to python. While learning python, I began a side project. Its a 
> command-line search program.
> ...
> But, I am unable to understand how I should begin structuring the project 
> (updating code according to OOP). If someone could have a look? Could really 
> use some suggestions/ideas.

Manageing larger projects is in general helped by some kind of modularization:
you split the whole implementation into different parts which have
high internal and low external interaction. While the total
complexity increases, you have often a chance to concentrate
on a part only and this part is far less complex the the whole.


OOP is just one kind of modularization. Not all problems can
make high use of OOP modularization.


For OOP friendly problems, you can easily identify objects. They have
state and functions operating on this state (those functions are called
"method"s). The state is mostly relevant only for the object internally
and less (if at all) for the external world.


In your case, the search service itself might be an object. And the queries
might be objects. To gain something, you must have interesting
operations on those objects - operations that manipulate a mostly irrelevant
(but fairly complex) internal state.

> Also, can someone point me to some (small) project where something similar is 
> being implemented?

You might have a look at "Products.AdvancedQuery" (--> "PyPI").
Download its source; you will find a documentation in the
folder "Products/AdvancedQuery/doc/". It models
queries as objects and the relevant operations are query constructors.

You (likely) will not be able to "run" it. It depends on
a search service called "ZCatalog" (part of the web application framework
"Zope"). This search service, too, is implemented by an object.
To use it, you would need "Zope". But you can download the source
(--> "PyPI"; its name is "Products.ZCatalog") and look
at the interface description in "Products.ZCatalog.interfaces.py"
to learn about the "ZCatalog" methods. This file also contains
a good documentation (via so called "docstring"s).


Interfaces are a general way to document the relevant parts
of objects/classes for "external use". They are heavily used by "Zope".



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


Need some help managing project and making it a little simple (pretty messed up code)

2017-08-16 Thread Kryptxy via Python-list
Hello,
I am new to python. While learning python, I began a side project. Its a 
command-line search program.

Here: https://github.com/kryptxy/torrench

The project is becoming a little difficult to manage, and before it becomes 
more complex, I'd like to sort it out a little and make it more managable and 
readable.
As of now, I haven't used any OOP concepts (no classes) bc while I was 
learning, I didn't reach the OOP part, and then spent too much time on the 
project (and that's probably the part I want help with). Now however, I do know 
about classes and basics about OOP.

But, I am unable to understand how I should begin structuring the project 
(updating code according to OOP). If someone could have a look? Could really 
use some suggestions/ideas.

Also, can someone point me to some (small) project where something similar is 
being implemented? (as in sharing similar project-structure). They can be 
really helpful. I did have a look at youtube-dl source. Not helpful. Seemed too 
complex.

Hope for some positive response.

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


Re: Hi! i need some help with a program in python on Raspberry pi3.

2017-04-17 Thread breamoreboy
On Friday, April 14, 2017 at 3:27:29 PM UTC+1, Kasper wrote:
> every time i run the program i get this messeage:
> 
> Traceback (most recent call last):
>   File "smartmirror.py", line 159, in get_weather
> temprature2 = "%S%S" % (str(int(weather_obj['currently']['temperature'])),
> degree_sign)
> KeyError: 'currently'
> Error: 'currently'. Cannot get weather.
> 
> How do i fix that?
> 
> Here is the program:
> 
> r = requests.get(weather_req_url)
> weather_obj = json.loads(r.text)
> 
> degree_sign= u'\N{DEGREE SIGN}'
> temperature2 = "%s%s" % 
> (str(int(weather_obj['currently']['temperature'])), degree_sign)

Find the correct name for the key by printing out `weather_obj`.  At least I 
think so, as the line above does not match the line that you've given.

Kindest regards.

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


Re: Hi! i need some help with a program in python on Raspberry pi3.

2017-04-14 Thread Terry Reedy

On 4/14/2017 10:27 AM, Kasper wrote:

every time i run the program i get this messeage:

Traceback (most recent call last):
  File "smartmirror.py", line 159, in get_weather
temprature2 = "%S%S" % (str(int(weather_obj['currently']['temperature'])),
degree_sign)
KeyError: 'currently'
Error: 'currently'. Cannot get weather.

How do i fix that?


Use a valid key for weather_obj.  Check doc or add
print(list(weather_obj.keys()))
before the failing subscription.


Here is the program:


I second Steve's comment.

--
Terry Jan Reedy

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


Re: Hi! i need some help with a program in python on Raspberry pi3.

2017-04-14 Thread Peter Otten
Kasper wrote:

> every time i run the program i get this messeage:
> 
> Traceback (most recent call last):
>   File "smartmirror.py", line 159, in get_weather
> temprature2 = "%S%S" % (str(int(weather_obj['currently']
['temperature'])),
> degree_sign)
> KeyError: 'currently'
> Error: 'currently'. Cannot get weather.
> 
> How do i fix that?
> 
> Here is the program:
> 


> weather_api_token = '16dc67b56f94f8083b1afed7e69c5dc1' # create account at
> https://darksky.net/dev/ 

Oops, is that your personal token? You are probably not supposed to publish 
it and now run the risk of having it revoked.

> values weather_unit = 'nb' # see https://darksky.net/dev/docs/forecast for
> full list of unit parameters values
 
You have to replace nb with one of the allowed values listed on the site.

> weather_lang = 'nb' # see
> https://darksky.net/dev/docs/forecast for full list of language parameters

Again, you have to pick one of the values listed -- unless you want Norsk 
bokmål that is.

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


Re: Hi! i need some help with a program in python on Raspberry pi3.

2017-04-14 Thread Steve D'Aprano
On Sat, 15 Apr 2017 12:27 am, Kasper wrote:

> every time i run the program i get this messeage:
> 
> Traceback (most recent call last):
>   File "smartmirror.py", line 159, in get_weather
> temprature2 = "%S%S" %
> (str(int(weather_obj['currently']['temperature'])),
> degree_sign)
> KeyError: 'currently'
> Error: 'currently'. Cannot get weather.
> 
> How do i fix that?

We're unpaid volunteers, we're not being paid to debug your code. Don't dump
over 300 lines of code in our lap and expect us to debug it. If you can't
spend the time simplifying the problem and removing all the irrelevant
details, how can you expect us to do it for you?

If you want help, make it easy for people to help you. Cut your code down to
the simplest, shortest amount of code that demonstrates the problem. If
your code has nothing to do with the GUI, cut out all the GUI code.

More advice here:

http://sscce.org/




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Hi! i need some help with a program in python on Raspberry pi3.

2017-04-14 Thread Kasper
every time i run the program i get this messeage:

Traceback (most recent call last):
  File "smartmirror.py", line 159, in get_weather
temprature2 = "%S%S" % (str(int(weather_obj['currently']['temperature'])),
degree_sign)
KeyError: 'currently'
Error: 'currently'. Cannot get weather.

How do i fix that?

Here is the program:


# smartmirror.py
# requirements
# requests, feedparser, traceback, Pillow

from Tkinter import *
import locale
import threading
import time
import requests
import json
import traceback
import feedparser
from PIL import Image, ImageTk
from contextlib import contextmanager

LOCALE_LOCK = threading.Lock()

ui_locale = '' # e.g. 'fr_FR' fro French, '' as default
time_format = 24 # 12 or 24
date_format = "%b %d, %Y" # check python doc for strftime() for options
news_country_code = 'nb'
weather_api_token = '16dc67b56f94f8083b1afed7e69c5dc1' # create account at 
https://darksky.net/dev/
weather_lang = 'nb' # see https://darksky.net/dev/docs/forecast for full list 
of language parameters values
weather_unit = 'nb' # see https://darksky.net/dev/docs/forecast for full list 
of unit parameters values
latitude = (59.1311800) # Set this if IP location lookup does not work for you 
(must be a string)
longitude = (10.2166500) # Set this if IP location lookup does not work for you 
(must be a string)
xlarge_text_size = 94
large_text_size = 48
medium_text_size = 28
small_text_size = 18

@contextmanager
def setlocale(name): #thread proof function to work with locale
with LOCALE_LOCK:
saved = locale.setlocale(locale.LC_ALL)
try:
yield locale.setlocale(locale.LC_ALL, name)
finally:
locale.setlocale(locale.LC_ALL, saved)

# maps open weather icons to
# icon reading is not impacted by the 'lang' parameter
icon_lookup = {
'clear-day': "assets/Sun.png",  # clear sky day
'wind': "assets/Wind.png",   #wind
'cloudy': "assets/Cloud.png",  # cloudy day
'partly-cloudy-day': "assets/PartlySunny.png",  # partly cloudy day
'rain': "assets/Rain.png",  # rain day
'snow': "assets/Snow.png",  # snow day
'snow-thin': "assets/Snow.png",  # sleet day
'fog': "assets/Haze.png",  # fog day
'clear-night': "assets/Moon.png",  # clear sky night
'partly-cloudy-night': "assets/PartlyMoon.png",  # scattered clouds night
'thunderstorm': "assets/Storm.png",  # thunderstorm
'tornado': "assests/Tornado.png",# tornado
'hail': "assests/Hail.png"  # hail
}


class Clock(Frame):
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, parent, bg='black')
# initialize time label
self.time1 = ''
self.timeLbl = Label(self, font=('Helvetica', large_text_size), 
fg="white", bg="black")
self.timeLbl.pack(side=TOP, anchor=E)
# initialize day of week
self.day_of_week1 = ''
self.dayOWLbl = Label(self, text=self.day_of_week1, font=('Helvetica', 
small_text_size), fg="white", bg="black")
self.dayOWLbl.pack(side=TOP, anchor=E)
# initialize date label
self.date1 = ''
self.dateLbl = Label(self, text=self.date1, font=('Helvetica', 
small_text_size), fg="white", bg="black")
self.dateLbl.pack(side=TOP, anchor=E)
self.tick()

def tick(self):
with setlocale(ui_locale):
if time_format == 12:
time2 = time.strftime('%I:%M %p') #hour in 12h format
else:
time2 = time.strftime('%H:%M') #hour in 24h format

day_of_week2 = time.strftime('%A')
date2 = time.strftime(date_format)
# if time string has changed, update it
if time2 != self.time1:
self.time1 = time2
self.timeLbl.config(text=time2)
if day_of_week2 != self.day_of_week1:
self.day_of_week1 = day_of_week2
self.dayOWLbl.config(text=day_of_week2)
if date2 != self.date1:
self.date1 = date2
self.dateLbl.config(text=date2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
self.timeLbl.after(200, self.tick)


class Weather(Frame):
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, parent, bg='black')
self.temperature = ''
self.forecast = ''
self.location = ''
self.currently = ''
self.icon = ''
self.degreeFrm = Frame(self, bg="black")
self.degreeFrm.pack(side=TOP, anchor=W)
self.temperatureLbl = Label(self.degreeFrm, font=('Helvetica', 
xlarge_text_size), fg="white", bg="black")
self.temperatureLbl.pack(side=LEFT, anchor=N)
self.iconLbl = Label(self.degreeFrm, bg="black")
self.iconLbl.pack(side=LEFT, anchor=N, padx=20)
self.currentlyLbl = Label(self, font=('Helvetica', medium_text_size), 
fg="white", bg="black")

Re: Need some help with NetGroupAddUser

2014-11-11 Thread Jaimin Ajmeri
 kcollins15 at cfl.rr.com writes:

 
 New B question -- Need help with win32net.NetGroupAddUser.  I used Mark
Hammond 
 sample code to create a new user from his book Python Programming on Win32. I 
 then added one line to add the newuser to a group.
 def CreateUserAndShare(userName, fullName):
 homeDir = %s\\%s % (serverName, userName)
 # Create user data in information level 3 (PyUSER_INFO_3) format.
 userData = {}
 userData['name'] = userName
 userData['full_name'] = fullName
 userData['password'] = userName
 userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
 userData['priv'] = win32netcon.USER_PRIV_USER
 userData['home_dir'] = homeDir
 userData['home_dir_drive'] = P:
 userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
 userData['password_expired'] = 1 # User must change password next logon.
 
 # Create the user
 win32net.NetUserAdd(serverName, 3, userData)
 win32net.NetGroupAddUser(serverName, Administrator, userName)
 
 This is my error:
 pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be 
 found.')
 What should I be using for the groupname parameter, I've tried them all, 
 Administrator, Guests, Users ext Any help will be greatly appreciated. 
 Thanks,
 kc
 
 

Hello kcollins15,

   Just try this.

import win32api
import win32net

###

Code to create user goes here

###

##

# Code to add created user to a group (on a local machine)

serverName =  + win32api.GetComputerName()
domain = win32api.GetDomainName()
data = [{domainandname : domain + \\TestUser}]
print Adding
win32net.NetLocalGroupAddMembers(serverName,Users,3,data)
print Added Successfully !!

##

This is working piece of code. It worked for me, I needed to add newly
created user to the group called Users.

Just replace Users with Administrator. 

I'll get back soon on how and when NetGroupAddUser() should be used.

Hope it helps...!
Jaimin Ajmeri 



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


Re: Need some help with NetGroupAddUser

2014-11-11 Thread MRAB

On 2014-11-11 04:30, Jaimin Ajmeri wrote:

  kcollins15 at cfl.rr.com writes:



New B question -- Need help with win32net.NetGroupAddUser.  I used Mark

Hammond

sample code to create a new user from his book Python Programming on Win32. I
then added one line to add the newuser to a group.
def CreateUserAndShare(userName, fullName):
homeDir = %s\\%s % (serverName, userName)
# Create user data in information level 3 (PyUSER_INFO_3) format.
userData = {}
userData['name'] = userName
userData['full_name'] = fullName
userData['password'] = userName
userData['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
userData['priv'] = win32netcon.USER_PRIV_USER
userData['home_dir'] = homeDir
userData['home_dir_drive'] = P:
userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS
userData['password_expired'] = 1 # User must change password next logon.

# Create the user
win32net.NetUserAdd(serverName, 3, userData)
win32net.NetGroupAddUser(serverName, Administrator, userName)

This is my error:
pywintypes.api_error: (2220, 'NetGroupAddUser', 'The group name could not be
found.')
What should I be using for the groupname parameter, I've tried them all,
Administrator, Guests, Users ext Any help will be greatly appreciated.
Thanks,
kc




Hello kcollins15,

Just try this.

import win32api
import win32net

###

Code to create user goes here

###

##

# Code to add created user to a group (on a local machine)

serverName =  + win32api.GetComputerName()
domain = win32api.GetDomainName()
data = [{domainandname : domain + \\TestUser}]
print Adding
win32net.NetLocalGroupAddMembers(serverName,Users,3,data)
print Added Successfully !!

##

This is working piece of code. It worked for me, I needed to add newly
created user to the group called Users.

Just replace Users with Administrator.

I'll get back soon on how and when NetGroupAddUser() should be used.

Hope it helps...!
Jaimin Ajmeri


I think you're replying to a post that's more than 10 years old!

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


Re: Need some help confirming transactions using sha256

2013-02-01 Thread Christian Heimes
Am 31.01.2013 18:55, schrieb Peter Pearson:
 txid = 
 'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 secret = 
 '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
 hashlib.sha256(txid+:+secret).hexdigest()
 'dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4'
 0x48e4
 18660

 
 .. . . which is the number you wanted, right?

Kryptox, you have chosen the correct algorithm to calculate a MAC. Very
good!

But the designers of the game are using an improper algorithm.
Apparently they don't know much about cryptography, especially length
extension attacks ...

Christian

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


Need some help confirming transactions using sha256

2013-01-31 Thread kryptox . exchange
I'm wondering if anyone can help me as I can't seem to get this to work. There 
is an online dice game that is provably fair by calculating the 'dice roll' 
using using a sha256 hash calculated against my transaction ID generated by me. 
The secret used to make the calculation is revealed at the end of each day thus 
allowing you to prove they didn't cheat. So they provide the following to allow 
you to verify the calculation of the dice roll:

Secret used = 
r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA
Secret hash 
sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA)
 = 48d78d573b9b8e11a13a72d9a78011f2e5d9754d89de47b209f32c51777f535d
Lucky hash 
sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA:108128
 06653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1) = 
dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4

Lucky Number 0x48e4 = 18660


So, I'm doing the following:

C:\Python27python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on 
win32
Type help, copyright, credits or license for more information.
 import hashlib, hmac
 txid = 
 'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 secret = 
 '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
 for nout in range(10): print nout, int(hmac.new(secret, %s:%d % (txid, 
 nout), hashlib.sha256).hexdigest()[:4], 16)
...
0 39800
1 4705
2 24058
3 11188
4 36307
5 781
6 62165
7 44612
8 17042
9 46099


idx 1 should equal 18660 but it doesn't. What am I doing wrong?


Secondly, I'm wondering if someone could help take it one step further. I would 
like to import a .txt file with a unique transaction ID on each line. So txid = 
transactions.txt or something like this. I would like it to get the lucky 
number based on a static sha256 which I would supply and the script would 
output the result to a text file. I'd like the output to be for idx 1 only.

ie.
txid here, lucky number for idx 1

Thanks for any help in advance!

Edit/Delete Message
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help confirming transactions using sha256

2013-01-31 Thread kryptox . exchange
Ok, I'm still stuck! :(

I do however now think that I'm not supposed to use hmac here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help confirming transactions using sha256

2013-01-31 Thread Peter Pearson
On Thu, 31 Jan 2013 08:43:03 -0800 (PST), kryptox.excha...@gmail.com wrote:

 I'm wondering if anyone can help me as I can't seem to get
 this to work. There is an online dice game that is
 provably fair by calculating the 'dice roll' using using a
 sha256 hash calculated against my transaction ID generated
 by me. The secret used to make the calculation is revealed
 at the end of each day thus allowing you to prove they
 didn't cheat. So they provide the following to allow you
 to verify the calculation of the dice roll:

 Secret used = 
 r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA
 Secret hash 
 sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA)
  = 48d78d573b9b8e11a13a72d9a78011f2e5d9754d89de47b209f32c51777f535d
 Lucky hash 
 sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA:108128
  06653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1) = 
 dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4

 Lucky Number 0x48e4 = 18660

 So, I'm doing the following:

 C:\Python27python
 Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on 
 win32
 Type help, copyright, credits or license for more information.
 import hashlib, hmac
 txid = 
 'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 secret = 
 '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
[snip]

 txid = 
 'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 secret = 
 '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
 hashlib.sha256(txid+:+secret).hexdigest()
'dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4'
 0x48e4
18660
 

. . . which is the number you wanted, right?


-- 
To email me, substitute nowhere-spamcop, invalid-net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help confirming transactions using sha256

2013-01-31 Thread kryptox . exchange
On Thursday, January 31, 2013 6:55:05 PM UTC+1, Peter Pearson wrote:
 On Thu, 31 Jan 2013 08:43:03 -0800 (PST), kryptox.excha...@gmail.com wrote:
 
 
 
  I'm wondering if anyone can help me as I can't seem to get
 
  this to work. There is an online dice game that is
 
  provably fair by calculating the 'dice roll' using using a
 
  sha256 hash calculated against my transaction ID generated
 
  by me. The secret used to make the calculation is revealed
 
  at the end of each day thus allowing you to prove they
 
  didn't cheat. So they provide the following to allow you
 
  to verify the calculation of the dice roll:
 
 
 
  Secret used = 
  r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA
 
  Secret hash 
  sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA)
   = 48d78d573b9b8e11a13a72d9a78011f2e5d9754d89de47b209f32c51777f535d
 
  Lucky hash 
  sha256(r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA:108128
   06653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1) = 
  dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4
 
 
 
  Lucky Number 0x48e4 = 18660
 
 
 
  So, I'm doing the following:
 
 
 
  C:\Python27python
 
  Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] 
  on win32
 
  Type help, copyright, credits or license for more information.
 
  import hashlib, hmac
 
  txid = 
  'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 
  secret = 
  '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
 
 [snip]
 
 
 
  txid = 
  'r7A7clvs9waizF+6QEiI0tgAq1ar48JItK3kg9kaeAFXz2vsMsHmOd9r9fhkmtxTz3CQnGAPMaDeKLvgb1A2VA'
 
  secret = 
  '10812806653842663997bf5971637f86f26c71a4716276d7fa8f323a83588d91:1'
 
  hashlib.sha256(txid+:+secret).hexdigest()
 
 'dfa8769be81a543002865c88a5b52fa07f3b67fc7cd9b519c3f6a6452bcd48e4'
 
  0x48e4
 
 18660
 
  
 
 
 
 . . . which is the number you wanted, right?
 
 
 
 
 
 -- 
 
 To email me, substitute nowhere-spamcop, invalid-net.


Yes, thank you Peter!
-- 
http://mail.python.org/mailman/listinfo/python-list


need some help with unexpected signal exception when using input from a thread (Pypy 1.9.0 on osx/linux)

2012-12-15 Thread Irmen de Jong
Hi.
Using Pypy 1.9.0. Importing readline. Using a background thread to get input() 
from
stdin. It then crashes with:

  File /usr/local/Cellar/pypy/1.9/lib_pypy/pyrepl/unix_console.py, line 400, 
in restore
signal.signal(signal.SIGWINCH, self.old_sigwinch)
ValueError: signal() must be called from the main thread

Anyone seen this before? What's going on?
When I don't import readline, or do the input() from within the main thread, 
the problem
disappears.

(I tried to reproduce it in a small test scenario but unfortunately have not 
been able
to do so yet. Haven't figured out yet what the additional factors are that 
trigger this
problem. A simple import readline and input() from a new thread doesn't seem to 
trigger
it, unfortunately)


Regards
Irmen de Jong
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need some help with unexpected signal exception when using input from a thread (Pypy 1.9.0 on osx/linux)

2012-12-15 Thread Dieter Maurer
Irmen de Jong irmen.nos...@xs4all.nl writes:

 Using Pypy 1.9.0. Importing readline. Using a background thread to get 
 input() from
 stdin. It then crashes with:

   File /usr/local/Cellar/pypy/1.9/lib_pypy/pyrepl/unix_console.py, line 
 400, in restore
 signal.signal(signal.SIGWINCH, self.old_sigwinch)
 ValueError: signal() must be called from the main thread

 Anyone seen this before? What's going on?

Apparently, input is not apt to be called from a background thread.

I have no idea why signal should only be callable from the main thread.
I do not think this makes much sense. Speak with the Pypy developers
about this.

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


Re: First script. Need some help

2010-05-28 Thread ledpepper
Thanks Everyone. I followed your instructions and my script is
successfully copying the result to the clipboard. Now for the fun. To
work out the rest of the script :)

I use the IDLE IDE and not codepad.org. I just thought that was the
standard for pasting scripts here in this group.

Thanks all.
-- 
http://mail.python.org/mailman/listinfo/python-list


First script. Need some help

2010-05-27 Thread ledpepper
#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is  but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First script. Need some help

2010-05-27 Thread MRAB

ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is  but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.


You need to download and install the Windows-specific extensions:

http://sourceforge.net/projects/pywin32/

I'm assuming you're using Python 2.6 on Windows.
--
http://mail.python.org/mailman/listinfo/python-list


Re: First script. Need some help

2010-05-27 Thread Mark Lawrence

On 27/05/2010 19:41, ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is  but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

Thanks


Have you installed the Win32 extensions?

From http://www.devx.com/opensource/Article/37233/0/page/3

Author's Note: the win32clipboard module is not part of the standard 
Python distribution on Windows. You can get it (along with lots of other 
comprehensive Python bindings to Win32 APIs) as part of the Win32 
extensions project on SourceForge. Alternatively, the module is also 
bundled with the ActivePython distribution for Windows.


HTH.

Mark Lawrence

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


Re: First script. Need some help

2010-05-27 Thread Dave Angel

ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is  but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

Thanks

  
Why bother using codepad for this?  The problem occurs parsing the 3rd 
line, so you only needed that and the traceback.


Have you installed the Win32 extensions?  If you think you have, can you 
find the file ?


C:\ProgFiles\Python26\Lib\site-packages\win32\win32clipboard.pyd

Naturally, your install directory may be different.  But it should be in 
the site-packages directory, which is where add-ons are installed.


DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help speeding up this loop

2008-10-30 Thread Marc 'BlackJack' Rintsch
On Wed, 29 Oct 2008 19:24:32 -0700, erikcw wrote:

 I'm trying to write a loop that will build a list of template strings.
 
 My current implementation is *really slow*.  It took 15 minutes to
 finish. (final len(list) was about 16k entries.)

What is `list` here?  Do you mean ``len(templates)``?

 templates = []
 for c in combinations:
 if len(states):
 for state in states:
 if type(geo) is City:
 cities = state.city_set.all()
 else:
 cities = geo
 for city in cities:
 if type(city) is City:
 city = city.city
 templates.append(c.template.replace('{{ city }}',
 city))
 templates.append(c.template) #just in case there are no
 cities
 templates = [k.replace('{{ state }}',
 state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
 templates]

It seems you are iterating over *all* accumulated templates so far, over 
and over again, even those which don't have those place holders anymore.  
Looks like the source of quadratic runtime for me.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help speeding up this loop

2008-10-30 Thread Arnaud Delobelle
On Oct 30, 2:24 am, erikcw [EMAIL PROTECTED] wrote:
 Hi all,

 I'm trying to write a loop that will build a list of template
 strings.

 My current implementation is *really slow*.  It took 15 minutes to
 finish. (final len(list) was about 16k entries.)

 #combinations = 12 small template strings ie {{ city }},
 {{ state }}...
 #states = either a django model or a list of 50 states
 #cities = either a django model of 400 cities or a smaller list of
 cities.

 templates = []
 for c in combinations:
     if len(states):
         for state in states:
             if type(geo) is City:
                 cities = state.city_set.all()
             else:
                 cities = geo
             for city in cities:
                 if type(city) is City:
                     city = city.city
                 templates.append(c.template.replace('{{ city }}',
 city))
             templates.append(c.template) #just in case there are no
 cities
             templates = [k.replace('{{ state }}',
 state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
 templates]

The line above does a lot of unnecessary work as you iterate over lots
of templates which have already been completely substituted.

     elif len(geo):
         for city in geo:
             templates.append(c.template.replace('{{ city }}', city))
     else:
         #no cities or states so add roots
         templates.append(c.template)

 The final output needs to be a list of the templates combined with all
 the states and cities (some templates will only have the city, some
 only the state).

 Any ideas how I can optimize this?

 Thanks!

I would suggest this (untested):

def template_replace(template, values):
for var, val in values.iteritems():
template = template.replace('{{ %s }}' % var, val)
return template

templates = []
for c in combinations:
if len(states):
for state in states:
values = { 'state': state.state,
   'state_abbr': state.abbreviation }
#just in case there are no cities :
templates.append(template_replace(c.template, values)
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
values['city'] = city.city
# Do all the replacing in one go:
templates.append(template_replace(c.template,
values))
elif len(geo):
for city in geo:
templates.append(template_replace(c.template,
{'city':city}))
else:
#no cities or states so add roots
templates.append(c.template)

HTH

Even better would be to iterate over states, then cities, then only
templates.

--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list


Need some help speeding up this loop

2008-10-29 Thread erikcw
Hi all,

I'm trying to write a loop that will build a list of template
strings.

My current implementation is *really slow*.  It took 15 minutes to
finish. (final len(list) was about 16k entries.)

#combinations = 12 small template strings ie {{ city }},
{{ state }}...
#states = either a django model or a list of 50 states
#cities = either a django model of 400 cities or a smaller list of
cities.

templates = []
for c in combinations:
if len(states):
for state in states:
if type(geo) is City:
cities = state.city_set.all()
else:
cities = geo
for city in cities:
if type(city) is City:
city = city.city
templates.append(c.template.replace('{{ city }}',
city))
templates.append(c.template) #just in case there are no
cities
templates = [k.replace('{{ state }}',
state.state).replace('{{ state_abbr }}', state.abbreviation) for k in
templates]
elif len(geo):
for city in geo:
templates.append(c.template.replace('{{ city }}', city))
else:
#no cities or states so add roots
templates.append(c.template)

The final output needs to be a list of the templates combined with all
the states and cities (some templates will only have the city, some
only the state).

Any ideas how I can optimize this?

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


Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Martin v. Löwis
 I guess, Apache does some kind of memory caching for files, which are often
 requested and small enough to fit into the system memory. 

Are you sure about this? I could not find anything in the documentation
(other than mod_cache and friends, which is an unrelated functionality).
Also, I don't see the need for Apache to cache frequently requested
files itself. Instead, the operating system will cache frequently
requested directories and files in memory, and it will do the same for
a Python web server.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Sebastian 'lunar' Wiesner
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[ Martin v. Löwis [EMAIL PROTECTED] ]

 I guess, Apache does some kind of memory caching for files, which are
 often requested and small enough to fit into the system memory.
 
 Are you sure about this? 

No, I'm not.  That's why I said I guess ;)

 Also, I don't see the need for Apache to cache frequently requested
 files itself. Instead, the operating system will cache frequently
 requested directories and files in memory, and it will do the same for
 a Python web server.

Of course, a modern OS kernel will perform caching anyway, but this is most
likely slower than in-process caching, since it will still require context
switches from userspace into kernel space.

Considering this, it seems reasonable to me, that apache does memory
caching, but I'm by far not sure, I wouldn't put a bet on this ;)

- -- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.9 (GNU/Linux)

iEYEARECAAYFAkg5K7kACgkQn3IEGILecb48VwCeJYqoyi7IJKwASza9/u381dmg
PqMAn1M/JBe8xEsOAPNosNWA9WoKCvNh
=K3tE
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list

Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Diez B. Roggisch

Sebastian 'lunar' Wiesner schrieb:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[ Diez B. Roggisch [EMAIL PROTECTED] ]

I finally managed to work with static files with a little hack, but it's
ugly because I'm reading each static file per request.

How else should that work? Apache does that the same way.


I guess, Apache does some kind of memory caching for files, which are often
requested and small enough to fit into the system memory.  May be, that's
what the OP is referring to ...


I'm not aware of that, and I even more seriously doubt it. Because 
caching is a complicated, domain-dependend subject that would 
*immediately* cry for configuration - e.g. caching strategies and such.


And a common idiom for apache  caching is to use Squid as reverse 
proxy. Which wouldn't be the case would apache cache by itself.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Matthew Woodcraft
Diez B. Roggisch [EMAIL PROTECTED] wrote:
Sebastian 'lunar' Wiesner schrieb:
 I guess, Apache does some kind of memory caching for files, which are often
 requested and small enough to fit into the system memory.  May be, that's
 what the OP is referring to ...

 I'm not aware of that, and I even more seriously doubt it. Because 
 caching is a complicated, domain-dependend subject that would 
 *immediately* cry for configuration - e.g. caching strategies and such.

This is available in current apache with mod_file_cache (for an
explicitly configured list of files). I think the circumstances where
you'd want to use it are quite rare.

-M-
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Diez B. Roggisch

Matthew Woodcraft schrieb:

Diez B. Roggisch [EMAIL PROTECTED] wrote:

Sebastian 'lunar' Wiesner schrieb:

I guess, Apache does some kind of memory caching for files, which are often
requested and small enough to fit into the system memory.  May be, that's
what the OP is referring to ...


I'm not aware of that, and I even more seriously doubt it. Because 
caching is a complicated, domain-dependend subject that would 
*immediately* cry for configuration - e.g. caching strategies and such.


This is available in current apache with mod_file_cache (for an
explicitly configured list of files). I think the circumstances where
you'd want to use it are quite rare.


As I said - explicit configuration is needed. And of course apache  
it's module system are flexible enough to allow caching as add-on. But 
Sebastian speculated about some behind the scenes automatic caching. 
Which apparently isn't there.


Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-25 Thread Martin v. Löwis
 I guess, Apache does some kind of memory caching for files, which are often
 requested and small enough to fit into the system memory.  May be, that's
 what the OP is referring to ...
 
 I'm not aware of that, and I even more seriously doubt it. Because 
 caching is a complicated, domain-dependend subject that would 
 *immediately* cry for configuration - e.g. caching strategies and such.
 
 This is available in current apache with mod_file_cache (for an
 explicitly configured list of files). I think the circumstances where
 you'd want to use it are quite rare.

Interestingly enough, this *doesn't* do memory caching for files.
Instead, it either keeps the file handle open, so you can seek to the
beginning of the file on the next request (avoiding the directory
lookup), or you can mmap the file. However, even if you mmap the file,
it is still the operating system's choice whether or not to cache the
file contents in memory.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


need some help in serving static files inside a wsgi apps

2008-05-24 Thread Tool69
Hi,

Until now, I was running my own static site with Python, but I'm in
need of dynamism.

After reading some cgi tutorials, I saw Joe Gregorio's old article
Why so many Python web frameworks? about wsgi apps [http://
bitworking.org/news/Why_so_many_Python_web_frameworks] and have a
question about it. The code he gave works like a charm (I had to make
a little change because SQLAlchemy has changed since), but how the
hell can I serve static files (css, js, images, etc.) within an wsgi
app, ie inside a '/static' directory ?!

Sorry if my question is a stupid one, but I cannot find an easy way to
do this. Each tutorial I'm reading out there does not talk about them
at all. All of my python books didn't mention wsgi either.

I know I could use web.py, web2py, Cherrypy, Django, Pylons, etc. but
I'm trying to understand basics of web dev. from their roots.

thanks in advance for any advice ,

Kib.
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-24 Thread Diez B. Roggisch

Tool69 schrieb:

Hi,

Until now, I was running my own static site with Python, but I'm in
need of dynamism.

After reading some cgi tutorials, I saw Joe Gregorio's old article
Why so many Python web frameworks? about wsgi apps [http://
bitworking.org/news/Why_so_many_Python_web_frameworks] and have a
question about it. The code he gave works like a charm (I had to make
a little change because SQLAlchemy has changed since), but how the
hell can I serve static files (css, js, images, etc.) within an wsgi
app, ie inside a '/static' directory ?!


There is a wsgi-app out there that is called static. Use that.

And it's the first hit on google wsgi static... :)

http://lukearno.com/projects/static/

Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-24 Thread kib

Diez B. Roggisch a écrit :

Tool69 schrieb:

Hi,

Until now, I was running my own static site with Python, but I'm in
need of dynamism.

After reading some cgi tutorials, I saw Joe Gregorio's old article
Why so many Python web frameworks? about wsgi apps [http://
bitworking.org/news/Why_so_many_Python_web_frameworks] and have a
question about it. The code he gave works like a charm (I had to make
a little change because SQLAlchemy has changed since), but how the
hell can I serve static files (css, js, images, etc.) within an wsgi
app, ie inside a '/static' directory ?!


There is a wsgi-app out there that is called static. Use that.

And it's the first hit on google wsgi static... :)

http://lukearno.com/projects/static/

Diez


Hi Diez,

and thanks for yout help. In fact I already found it but never managed 
to get it work because the static doc says :


from wsgiref.simple_server import make_server
import static
make_server('localhost', , static.Cling('/var/www')).serve_forever()

and inside J.Gregorio's tutorial it is:

from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
httpd = WSGIServer(('localhost', 8080), WSGIRequestHandler)
httpd.set_app(urls.urls)

It does not use 'make_server()' so how can I adapt it ?

I finally managed to work with static files with a little hack, but it's 
ugly because I'm reading each static file per request.


Kib.
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-24 Thread Diez B. Roggisch

kib schrieb:

Diez B. Roggisch a écrit :

Tool69 schrieb:

Hi,

Until now, I was running my own static site with Python, but I'm in
need of dynamism.

After reading some cgi tutorials, I saw Joe Gregorio's old article
Why so many Python web frameworks? about wsgi apps [http://
bitworking.org/news/Why_so_many_Python_web_frameworks] and have a
question about it. The code he gave works like a charm (I had to make
a little change because SQLAlchemy has changed since), but how the
hell can I serve static files (css, js, images, etc.) within an wsgi
app, ie inside a '/static' directory ?!


There is a wsgi-app out there that is called static. Use that.

And it's the first hit on google wsgi static... :)

http://lukearno.com/projects/static/

Diez


Hi Diez,

and thanks for yout help. In fact I already found it but never managed 
to get it work because the static doc says :


from wsgiref.simple_server import make_server
import static
make_server('localhost', , static.Cling('/var/www')).serve_forever()

and inside J.Gregorio's tutorial it is:

from wsgiref.simple_server import WSGIServer, WSGIRequestHandler
httpd = WSGIServer(('localhost', 8080), WSGIRequestHandler)
httpd.set_app(urls.urls)

It does not use 'make_server()' so how can I adapt it ?


static.Cling is a wsgi-app. The other code just makes a specific 
wsgi-implementation based server out of it.



I finally managed to work with static files with a little hack, but it's 
ugly because I'm reading each static file per request.


How else should that work? Apache does that the same way.

Diez
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help in serving static files inside a wsgi apps

2008-05-24 Thread Sebastian 'lunar' Wiesner
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[ Diez B. Roggisch [EMAIL PROTECTED] ]
 I finally managed to work with static files with a little hack, but it's
 ugly because I'm reading each static file per request.
 
 How else should that work? Apache does that the same way.

I guess, Apache does some kind of memory caching for files, which are often
requested and small enough to fit into the system memory.  May be, that's
what the OP is referring to ...

- -- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.9 (GNU/Linux)

iEYEARECAAYFAkg4a1QACgkQn3IEGILecb5ibACgoYyLaOc+q51D0g+SuudnqHab
dYYAnjH3E0/e2y0owJ1PuWMk13i9YVA/
=7C8x
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Anyone into Paimei?? Need some help.

2008-01-22 Thread over
Hi. I have been trying to get Paimei running on Windoze but find it
very inconsistent. It works on certain apps really well, like Notepad,
but fails on other apps, especially those written in languages like
Delphi. There isn't a lot out there on Paimei and the author's site is
very terse on the app.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help with 'with'

2007-11-29 Thread Aahz
In article [EMAIL PROTECTED],
Mike Kent  [EMAIL PROTECTED] wrote:

I figure that if instead of returning the buffer from the context
directly, I instead returned the buffer in a list, I could then change
the buffer, put it in the returned list, then I'd have access to it
back inside the context, but this seems a bit ugly.

Does anyone have insight into the right way of doing this?

You're almost at the right approach: just create a class instance that
contains a buffer attribute.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

Typing is cheap.  Thinking is expensive.  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Need some help with 'with'

2007-11-27 Thread Mike Kent
I recently found myself needing to do this a lot:

lock a record in a file
read the record into a buffer
alter the buffer
write the buffer back to the record
unlock the record

I'd love to be able to create a context for this to use with the
'with' statement, something like:

from __future__ import with_statement
from contextlib import contextmanager
from fcntl import lockf, LOCK_EX, LOCK_UN

@contextmanager
def lockedRecord(fileObj, offset, length):
lockf(fileObj, LOCK_EX, offset, length)
try:
fileObj.seek(offset)
buff = fileObj.read(length)
newBuff = (yield buff)
fileObj.seek(offset)
fileObj.write(newBuff)
finally:
lockf(fileObj, LOCK_UN, offset, length)

Which would let me write code like:

fileObj = open(myfile.dat, r+b)

with lockedRecord(fileObj, 20, 10) as rec:
newRec = rec.replace('foo', 'bar')
# Somehow send newRec back into the context

I know you can now send data back into a generator via the send method
of the generator, however i don't seem to have access to the generator
object itself.

I figure that if instead of returning the buffer from the context
directly, I instead returned the buffer in a list, I could then change
the buffer, put it in the returned list, then I'd have access to it
back inside the context, but this seems a bit ugly.

Does anyone have insight into the right way of doing this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-11-02 Thread Boris Borcic
Ricardo Aráoz wrote:
  Boris Borcic wrote:
  Ricardo Aráoz wrote:
  Boris Borcic wrote:
  [EMAIL PROTECTED] wrote:
  I want to create a program that I type in a word.
 
  for example...
 
  chaos
 
  each letter equals a number
 
  A=1
  B=20
 
   and so on.
 
  So Chaos would be
 
  C=13 H=4 A=1 O=7 S=5
 
  I want to then have those numbers
  13+4+1+7+5 added together to be 30.
 
  How can I do that?
 
  Also, just curious, but, how could I then have the 3 and 0 added
  together to be 3?
 
  Please help me out.
 
  Thank you.
 
sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
  30
sum(eval(ch) for ch in str(_))
  3
  def sumToOneDigit(num) :
 if num  10 :
 return num
 else :
 return sumToOneDigit(sum(int(i) for i in str(num)))
 
 
  sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
  6
 
 
 
  HTH
  HTH what ?
 
 
  HTH : Hope that helps
 
  Citing your post :

Not me, the OP [EMAIL PROTECTED].

  
  Also, just curious, but, how could I then have the 3 and 0 added
  together to be 3?
  
 
  you have the function sumToOneDigit that adds the digits of a number
  till you get one digit (isn't that what you where curious about?)

I had provided a solution that conformed to the OP's 2 questions. Your 
non-conform addition simply proved that you hadn't bothered to read.

Or else you meant to read the OP's mind beyond what he specified; but then you 
should adress him, not me.

 
  And answering the main question : sum(ord(ch) for ch in 'chaos'.upper())
  which is inside the sumToOneDigit funtion in my answer.

No, you did not adress the original questions.

My hth what ? was an invitation to
rectify. Sorry it wasn't enough for you, but the verbosity was probably worth
what you paid for it.

 
  Sorry if that is not enough for you, but the answer is probably worth
  what you paid for it.
 
 
 

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


Re: Need some help...

2007-11-02 Thread Ricardo Aráoz
Gabriel Genellina wrote:
 En Thu, 01 Nov 2007 20:12:52 -0300, Ricardo Aráoz [EMAIL PROTECTED]  
 escribió:
 
 def sumToOneDigit(num) :
if num  10 :
return num
else :
return sumToOneDigit(sum(int(i) for i in str(num)))

 
 def sumToOneDigit(num):
  return num % 9 or 9
 
 Valid when num=1, which is guaranteed by the OP context.
 

Beautiful. Much better than mine.

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


Re: Need some help...

2007-11-01 Thread Boris Borcic
Ricardo Aráoz wrote:
 Boris Borcic wrote:
 [EMAIL PROTECTED] wrote:
 I want to create a program that I type in a word.

 for example...

 chaos

 each letter equals a number

 A=1
 B=20

  and so on.

 So Chaos would be

 C=13 H=4 A=1 O=7 S=5

 I want to then have those numbers
 13+4+1+7+5 added together to be 30.

 How can I do that?

 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?

 Please help me out.

 Thank you.

   sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
 30
   sum(eval(ch) for ch in str(_))
 3
 
 
 def sumToOneDigit(num) :
   if num  10 :
   return num
   else :
   return sumToOneDigit(sum(int(i) for i in str(num)))
 
   
 sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
 6
 
 
 
 HTH

HTH what ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-11-01 Thread Ricardo Aráoz
Boris Borcic wrote:
 Ricardo Aráoz wrote:
 Boris Borcic wrote:
 [EMAIL PROTECTED] wrote:
 I want to create a program that I type in a word.

 for example...

 chaos

 each letter equals a number

 A=1
 B=20

  and so on.

 So Chaos would be

 C=13 H=4 A=1 O=7 S=5

 I want to then have those numbers
 13+4+1+7+5 added together to be 30.

 How can I do that?

 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?

 Please help me out.

 Thank you.

   sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
 30
   sum(eval(ch) for ch in str(_))
 3

 def sumToOneDigit(num) :
  if num  10 :
  return num
  else :
  return sumToOneDigit(sum(int(i) for i in str(num)))

  
 sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
 6



 HTH
 
 HTH what ?


HTH : Hope that helps

Citing your post :

Also, just curious, but, how could I then have the 3 and 0 added
together to be 3?


you have the function sumToOneDigit that adds the digits of a number
till you get one digit (isn't that what you where curious about?)

And answering the main question : sum(ord(ch) for ch in 'chaos'.upper())
which is inside the sumToOneDigit funtion in my answer.

Sorry if that is not enough for you, but the answer is probably worth
what you paid for it.



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


Re: Need some help...

2007-11-01 Thread Gabriel Genellina
En Thu, 01 Nov 2007 20:12:52 -0300, Ricardo Aráoz [EMAIL PROTECTED]  
escribió:

 def sumToOneDigit(num) :
 if num  10 :
 return num
 else :
 return sumToOneDigit(sum(int(i) for i in str(num)))


def sumToOneDigit(num):
 return num % 9 or 9

Valid when num=1, which is guaranteed by the OP context.

-- 
Gabriel Genellina

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


Re: Need some help...

2007-10-31 Thread Ricardo Aráoz
Boris Borcic wrote:
 [EMAIL PROTECTED] wrote:
 I want to create a program that I type in a word.

 for example...

 chaos

 each letter equals a number

 A=1
 B=20

  and so on.

 So Chaos would be

 C=13 H=4 A=1 O=7 S=5

 I want to then have those numbers
 13+4+1+7+5 added together to be 30.

 How can I do that?

 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?

 Please help me out.

 Thank you.

 
   sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
 30
   sum(eval(ch) for ch in str(_))
 3


 def sumToOneDigit(num) :
if num  10 :
return num
else :
return sumToOneDigit(sum(int(i) for i in str(num)))


 sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
6



HTH





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


Re: Need some help...

2007-10-30 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
 I want to create a program that I type in a word.
 
 for example...
 
 chaos
 
 each letter equals a number
 
 A=1
 B=20
 
  and so on.
 
 So Chaos would be
 
 C=13 H=4 A=1 O=7 S=5
 
 I want to then have those numbers
 13+4+1+7+5 added together to be 30.
 
 How can I do that?
 
 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?
 
 Please help me out.
 
 Thank you.
 

  sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
30
  sum(eval(ch) for ch in str(_))
3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-10-29 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 I want to create a program that I type in a word.
 
 for example...
 
 chaos
 
 each letter equals a number
 
 A=1
 B=20
 
  and so on.
 
 So Chaos would be
 
 C=13 H=4 A=1 O=7 S=5
 
 I want to then have those numbers
 13+4+1+7+5 added together to be 30.
 
 How can I do that?

If the values are arbitrary:

letters_values = {'A':1, 'B':20, 'C':13, 'H':4, 'O':7, 'S':5, #etc...}
print letters_values['A']


 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?

help(sum)
help(map)
help(int)
print int('3')
help(list)
print list('30')
help(str)
print str(30)


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


Need some help...

2007-10-28 Thread hyozan . ux3
I want to create a program that I type in a word.

for example...

chaos

each letter equals a number

A=1
B=20

 and so on.

So Chaos would be

C=13 H=4 A=1 O=7 S=5

I want to then have those numbers
13+4+1+7+5 added together to be 30.

How can I do that?

Also, just curious, but, how could I then have the 3 and 0 added
together to be 3?

Please help me out.

Thank you.

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


Re: Need some help...

2007-10-28 Thread bearophileHUGS
 I want to create a program that I type in a word.

You can see that Python has a command to input strings from the
command line.

 chaos
 each letter equals a number
 A=1
 B=20
  and so on.
 So Chaos would be
 C=13 H=4 A=1 O=7 S=5
 I want to then have those numbers
 13+4+1+7+5 added together to be 30.
 How can I do that?

Python has a dictionary data structure called dict(), or {}, that you
can use to map your letters to those numbers. With it you can created
the letter-number association.

Then you can scan the characters of the input string one after the
other, and sum their values into a single total value. Try writing
that code, and then show it to us, we can give more suggestions if you
need them...

Bye,
bearophile

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


Re: Need some help...

2007-10-28 Thread martyw
[EMAIL PROTECTED] wrote:
 I want to create a program that I type in a word.
 
 You can see that Python has a command to input strings from the
 command line.
 
 chaos
 each letter equals a number
 A=1
 B=20
  and so on.
 So Chaos would be
 C=13 H=4 A=1 O=7 S=5
 I want to then have those numbers
 13+4+1+7+5 added together to be 30.
 How can I do that?
 
 Python has a dictionary data structure called dict(), or {}, that you
 can use to map your letters to those numbers. With it you can created
 the letter-number association.
 
 Then you can scan the characters of the input string one after the
 other, and sum their values into a single total value. Try writing
 that code, and then show it to us, we can give more suggestions if you
 need them...
 
 Bye,
 bearophile
 
as an alternative for the suggest dictionary approach you could study 
the built in functions ord() and chr(), see the documentation 
(http://docs.python.org/lib/built-in-funcs.html)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-10-28 Thread Peter Decker
On 10/28/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 I want to then have those numbers
 13+4+1+7+5 added together to be 30.

 How can I do that?

 Also, just curious, but, how could I then have the 3 and 0 added
 together to be 3?

 Please help me out.

Will you put our names on your homework when you hand it in?

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help with my first Twisted program

2007-10-20 Thread Bjoern Schliessmann
McCann, Brian wrote:

 I posted this to the Twisted list...figured I'd try here too.

Didn't you get an answer? The cracks for special topics are usually
there.
 
 to work right.  Looking through the API docs I found
 connectionLost(), which I put in my protocol class (EchoProtocol
 in the example), but it's
 never getting called.  Here's my connectionLost def:
 
 def connectionLost(self,reason):
 print lost:%s %reason
 self.serialServerSocket.close()
 self.alive = False
 self.serialSocketReadThread.join()
 
 Can someone please tell me what I'm doing wrong?

No, since the definition of a never called function won't help.

Try the following standard strategy: Make a copy of your project and
reduce it (removing functionality) until the error doesn't appear
anymore. If it does *not* vanish, post your short code here or in
the Twisted list.

Regards  happy hunting,


Björn

-- 
BOFH excuse #366:

ATM cell has no roaming feature turned on, notebooks can't connect

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


Need some help with my first Twisted program

2007-10-19 Thread McCann, Brian
I posted this to the Twisted list...figured I'd try here too.

I'm looking for what is probably an simple solution I can't figure out
on my own.  I'm writing an SSH server based on the example on the web
(using conch).  I'm trying to figure out how to detect when the client
exists (for example, when I just close out PuTTY), but I can't get this
to work right.  Looking through the API docs I found connectionLost(),
which I put in my protocol class (EchoProtocol in the example), but it's
never getting called.  Here's my connectionLost def:

def connectionLost(self,reason):
print lost:%s %reason
self.serialServerSocket.close()
self.alive = False
self.serialSocketReadThread.join()

Can someone please tell me what I'm doing wrong?

Thanks,
--Brian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I need some help with a regexp please

2006-09-26 Thread Frederic Rentsch
Dennis Lee Bieber wrote:
 On 25 Sep 2006 10:25:01 -0700, codefire [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:

   
 Yes, I didn't make it clear in my original post - the purpose of the
 code was to learn something about regexps (I only started coding Python
 last week). In terms of learning a little more the example was
 successful. However, creating a full email validator is way beyond me -
 the rules are far too complex!! :)
 

   I've been doing small things in Python for over a decade now
 (starting with the Amiga port)...

   I still don't touch regular expressions... They may be fast, but to
 me they are just as much line noise as PERL... I can usually code a
 partial parser faster than try to figure out an RE.
   
If I may add another thought along the same line: regular expressions 
seem to tend towards an art form, or an intellectual game. Many 
discussions revolving around regular expressions convey the impression 
that the challenge being pursued is finding a magic formula much more 
than solving a problem. In addition there seems to exist some code of 
honor which dictates that the magic formula must consist of one single 
expression that does it all. I suspect that the complexity of one single 
expression grows somehow exponentially with the number of 
functionalities it has to perform and at some point enters a gray zone 
of impending conceptual intractability where the quest for the magic 
formula becomes particularly fascinating. I also suspect that some 
problems are impossible to solve with a single expression and that no 
test of intractability exists other than giving up after so many hours 
of trying.
With reference to the OP's question, what speaks against passing his 
texts through several simple expressions in succession? Speed of 
execution? Hardly. The speed penalty would not be perceptible. 
Conversely, in favor of multiple expressions speaks that they can be 
kept simple and that the performance of the entire set can be 
incrementally improved by adding another simple expression whenever an 
unexpected contingency occurs, as they may occur at any time with 
informal systems. One may not win a coding contest this way, but saving 
time isn't bad either, or is even better.

Frederic

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


Re: I need some help with a regexp please

2006-09-26 Thread Fredrik Lundh
Frederic Rentsch wrote:

 If I may add another thought along the same line: regular expressions 
 seem to tend towards an art form, or an intellectual game. Many 
 discussions revolving around regular expressions convey the impression 
 that the challenge being pursued is finding a magic formula much more 
 than solving a problem. In addition there seems to exist some code of 
 honor which dictates that the magic formula must consist of one single 
 expression that does it all.

hear! hear!

for dense guys like myself, regular expressions work best if you use 
them as simple tokenizers, and they suck pretty badly if you're trying 
to use them as parsers.

and using a few RE:s per problem (or none at all) is a perfectly good 
way to get things done.

/F

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


Re: I need some help with a regexp please

2006-09-26 Thread codefire
 for dense guys like myself, regular expressions work best if you use
 them as simple tokenizers, and they suck pretty badly if you're trying
 to use them as parsers.

:) Well, I'm with you on that one Fredrik! :)

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


Re: I need some help with a regexp please

2006-09-26 Thread codefire

 I still don't touch regular expressions... They may be fast, but to
 me they are just as much line noise as PERL... I can usually code a
 partial parser faster than try to figure out an RE.

Yes, it seems to me that REs are a bit hit and miss - the only way to
tell if you've got a RE right is by testing exhaustively - but you
can never be sure They are fine for simple pattern matching though.

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


Re: I need some help with a regexp please

2006-09-25 Thread codefire
Yes, I didn't make it clear in my original post - the purpose of the
code was to learn something about regexps (I only started coding Python
last week). In terms of learning a little more the example was
successful. However, creating a full email validator is way beyond me -
the rules are far too complex!! :)

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


Re: I need some help with a regexp please

2006-09-22 Thread Ant

John Machin wrote:
...
 A little more is unfortunately not enough. The best advice you got was
 to use an existing e-mail address validator.

We got bitten by this at the last place I worked - we were using a
regex email validator (from Microsoft IIRC), and we kept having
problems with specific email addresses from Ireland. There are stack of
Irish email addresses out there of the form paddy.o'[EMAIL PROTECTED] -
perfectly valid email address, but doesn't satisfy the usual naive
versions of regex validators.

We use an even worse validator at my current job, but the feeling the
management have (not one I agree with) is that unusual email addresses,
whilst perhaps valid, are uncommon enough not to worry about

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


Re: Don't use regular expressions to validate email addresses (was: I need some help with a regexp please)

2006-09-22 Thread Ant

Ben Finney wrote:
...
 The best advice I've seen when people ask How do I validate whether
 an email address is valid? was Try sending mail to it.

There are advantages to the regex method. It is faster than sending an
email and getting a positive or negative return code. The delay may not
be acceptable in many applications. Secondly, the false negatives found
by a reasonable regex will be few compared to the number you'd get if
the smtp server went down, or a remote relay was having problems
delivering the message etc etc.

From a business point of view, it is probably more important to reduce
the number of false negatives than to reduce the number of false
positives - every false negative is a potential loss of a customer.
False positives? Who cares really as long as they are paying ;-)

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


Re: I need some help with a regexp please

2006-09-22 Thread John Machin

Ant wrote:
 John Machin wrote:
 ...
  A little more is unfortunately not enough. The best advice you got was
  to use an existing e-mail address validator.

 We got bitten by this at the last place I worked - we were using a
 regex email validator (from Microsoft IIRC), and we kept having
 problems with specific email addresses from Ireland. There are stack of
 Irish email addresses out there of the form paddy.o'[EMAIL PROTECTED] -
 perfectly valid email address, but doesn't satisfy the usual naive
 versions of regex validators.

 We use an even worse validator at my current job, but the feeling the
 management have (not one I agree with) is that unusual email addresses,
 whilst perhaps valid, are uncommon enough not to worry about

Oh, sorry for the abbreviation. use implies source from believedly
reliable s/w source; test; then deploy :-)

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


Re: I need some help with a regexp please

2006-09-22 Thread Ant

John Machin wrote:
 Ant wrote:
  John Machin wrote:
  ...
   A little more is unfortunately not enough. The best advice you got was
   to use an existing e-mail address validator.
 
  We got bitten by this at the last place I worked - we were using a
  regex email validator (from Microsoft IIRC)
...
 Oh, sorry for the abbreviation. use implies source from believedly
 reliable s/w source; test; then deploy :-)

I actually meant that we got bitten by using a regex validator, not by
using an existing one. Though we did get bitten by an existing one, and
it being from Microsoft we should have known better ;-)

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


I need some help with a regexp please

2006-09-22 Thread Sorin Schwimmer
Hi,My $0.02:re.compile('^\w+([\.-]?\w+)[EMAIL PROTECTED]([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|intl|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$')I picked it up from the Net, and while it may be not perfect (you've got lots of reply's telling you why),it's good enough for me.Good luck,Sorin-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Need some help here

2006-09-22 Thread ian

Frank Drackman [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
:
: Kareem840 [EMAIL PROTECTED] wrote in message
: news:[EMAIL PROTECTED]
:  Hello. Unfortunately, I am in need of money to pay my credit card
:  bills. If you could spare just $1, I would be grateful. I have a Paypal
:  account. [EMAIL PROTECTED] I swear this will go to my card
:  balances. Thank you.
: 
:
: Sell your sperm, we don't want you to reproduce.

erm can i just point out the flaw in your suggestion frank... 


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


I need some help with a regexp please

2006-09-21 Thread codefire
Hi,

I am trying to get a regexp to validate email addresses but can't get
it quite right. The problem is I can't quite find the regexp to deal
with ignoring the case [EMAIL PROTECTED], which is not valid. Here's
my attempt, neither of my regexps work quite how I want:

[code]
import os
import re

s = 'Hi [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] @@not
[EMAIL PROTECTED] partridge in a pear tree'
r = re.compile(r'[EMAIL PROTECTED]@\s]+\.\w+')
#r = re.compile(r'[EMAIL PROTECTED]')

addys = set()
for a in r.findall(s):
addys.add(a)

for a in sorted(addys):
print a
[/code]

This gives:
[EMAIL PROTECTED]
[EMAIL PROTECTED]
[EMAIL PROTECTED]   -- shouldn't be here :(
[EMAIL PROTECTED]

Nearly there but no cigar :)

I can't see the wood for the trees now :) Can anyone suggest a fix
please?

Thanks,
Tony

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


Re: I need some help with a regexp please

2006-09-21 Thread [EMAIL PROTECTED]

codefire wrote:
 Hi,

 I am trying to get a regexp to validate email addresses but can't get
 it quite right. The problem is I can't quite find the regexp to deal
 with ignoring the case [EMAIL PROTECTED], which is not valid. Here's
 my attempt, neither of my regexps work quite how I want:

 [code]
 import os
 import re

 s = 'Hi [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] @@not
 [EMAIL PROTECTED] partridge in a pear tree'
 r = re.compile(r'[EMAIL PROTECTED]@\s]+\.\w+')
 #r = re.compile(r'[EMAIL PROTECTED]')

 addys = set()
 for a in r.findall(s):
 addys.add(a)

 for a in sorted(addys):
 print a
 [/code]

 This gives:
 [EMAIL PROTECTED]
 [EMAIL PROTECTED]
 [EMAIL PROTECTED]   -- shouldn't be here :(
 [EMAIL PROTECTED]

 Nearly there but no cigar :)

 I can't see the wood for the trees now :) Can anyone suggest a fix
 please?

 Thanks,
 Tony

'[EMAIL PROTECTED](\.\w+)*'
Works for me, and SHOULD for you, but I haven't tested it all that
much.
Good luck.

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


Re: I need some help with a regexp please

2006-09-21 Thread Neil Cerutti
On 2006-09-21, codefire [EMAIL PROTECTED] wrote:
 I am trying to get a regexp to validate email addresses but
 can't get it quite right. The problem is I can't quite find the
 regexp to deal with ignoring the case [EMAIL PROTECTED],
 which is not valid. Here's my attempt, neither of my regexps
 work quite how I want:

I suggest a websearch for email address validators instead of
writing of your own.

Here's a hit that looks useful:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66439

-- 
Neil Cerutti
Next Sunday Mrs. Vinson will be soloist for the morning service.
The pastor will then speak on It's a Terrible Experience.
--Church Bulletin Blooper 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I need some help with a regexp please

2006-09-21 Thread Steve Holden
codefire wrote:
 Hi,
 
 I am trying to get a regexp to validate email addresses but can't get
 it quite right. The problem is I can't quite find the regexp to deal
 with ignoring the case [EMAIL PROTECTED], which is not valid. Here's
 my attempt, neither of my regexps work quite how I want:
 
 [code]
 import os
 import re
 
 s = 'Hi [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] @@not
 [EMAIL PROTECTED] partridge in a pear tree'
 r = re.compile(r'[EMAIL PROTECTED]@\s]+\.\w+')
 #r = re.compile(r'[EMAIL PROTECTED]')
 
 addys = set()
 for a in r.findall(s):
 addys.add(a)
 
 for a in sorted(addys):
 print a
 [/code]
 
 This gives:
 [EMAIL PROTECTED]
 [EMAIL PROTECTED]
 [EMAIL PROTECTED]   -- shouldn't be here :(
 [EMAIL PROTECTED]
 
 Nearly there but no cigar :)
 
 I can't see the wood for the trees now :) Can anyone suggest a fix
 please?
 
The problem is that your pattern doesn't start out by confirming that 
it's either at the start of a line or after whitespace. You could do 
this with a look-behind assertion if you wanted.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: I need some help with a regexp please

2006-09-21 Thread codefire
Hi,

thanks for the advice guys.

Well took the kids swimming, watched some TV, read your hints and
within a few minutes had this:

r = re.compile(r'[EMAIL PROTECTED]@\s]+\.\w+')

This works for me. That is if you have an invalid email such as
tony..bATblah.com it will reject it (note the double dots).

Anyway, now know a little more about regexps :)

Thanks again for the hints,

Tony

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


Re: I need some help with a regexp please

2006-09-21 Thread John Machin
codefire wrote:
 Hi,

 thanks for the advice guys.

 Well took the kids swimming, watched some TV, read your hints and
 within a few minutes had this:

 r = re.compile(r'[EMAIL PROTECTED]@\s]+\.\w+')

 This works for me. That is if you have an invalid email such as
 tony..bATblah.com it will reject it (note the double dots).

 Anyway, now know a little more about regexps :)

A little more is unfortunately not enough. The best advice you got was
to use an existing e-mail address validator. The definition of a valid
e-mail address is complicated. You may care to check out Mastering
Regular Expressions by Jeffery Friedl. In the first edition, at least
(I haven't looked at the 2nd), he works through assembling a 4700+ byte
regex for validating e-mail addresses. Yes, that's 4KB.  It's the best
advertisement for *not* using regexes for a task like that that I've
ever seen.

Cheers,
John

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


Don't use regular expressions to validate email addresses (was: I need some help with a regexp please)

2006-09-21 Thread Ben Finney
John Machin [EMAIL PROTECTED] writes:

 A little more is unfortunately not enough. The best advice you got was
 to use an existing e-mail address validator. The definition of a valid
 e-mail address is complicated. You may care to check out Mastering
 Regular Expressions by Jeffery Friedl. In the first edition, at least
 (I haven't looked at the 2nd), he works through assembling a 4700+ byte
 regex for validating e-mail addresses. Yes, that's 4KB.  It's the best
 advertisement for *not* using regexes for a task like that that I've
 ever seen.

The best advice I've seen when people ask How do I validate whether
an email address is valid? was Try sending mail to it.

It's both Pythonic, and truly the best way. If you actually want to
confirm, don't try to validate it statically; *use* the email address,
and check the result.  Send an email to that address, and don't use it
any further unless you get a reply saying yes, this is the right
address to use from the recipient.

The sending system's mail transport agent, not regular expressions,
determines which part is the domain to send the mail to.

The domain name system, not regular expressions, determines what
domains are valid, and what host should receive mail for that domain.

Most especially, the receiving mail system, not regular expressions,
determines what local-parts are valid.

-- 
 \   I believe in making the world safe for our children, but not |
  `\our children's children, because I don't think children should |
_o__)  be having sex.  -- Jack Handey |
Ben Finney

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


Need some help here

2006-09-20 Thread Kareem840
Hello. Unfortunately, I am in need of money to pay my credit card
bills. If you could spare just $1, I would be grateful. I have a Paypal
account. [EMAIL PROTECTED] I swear this will go to my card
balances. Thank you.

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


Re: Need some help here

2006-09-20 Thread Colin B.
In comp.unix.solaris Kareem840 [EMAIL PROTECTED] wrote:
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.

Better idea. Sell your computer. Or your organs.

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


Re: Need some help here

2006-09-20 Thread Todd H.
Kareem840 [EMAIL PROTECTED] writes:

 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.

If you have a story of unusual personal hardship that led to the
balances, share it--you may get more response.  

If you're just a usual idiot without the discipline to live within
their their means, get a job, or if you have one, get a better one and
dig yourself out of the whole you've created for yourself.  Otherwise,
we'd all just be enabling you to be an idiot again, we'd all be a
dollar poorer, and you'd be no wiser--just with a better credit score
for a time.

If you're just seeing how many folks will give you money without any
good reason (i.e. not a scam, just an internet beggar), hey, enjoy. 

If you're a clever sociology graduate student doing a pootentially
interesting thesis on various responses to an anonymous plea for money
on the internet, kudos.  I bet it'd be an interesting study.

Best Regards, 
--
Todd H.  
http://www.toddh.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help here

2006-09-20 Thread Dave
The money's on the way!


Kareem840 [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.
 


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


Re: Need some help here

2006-09-20 Thread Frank Drackman

Kareem840 [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.


Sell your sperm, we don't want you to reproduce. 


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


Re: Need some help here

2006-09-20 Thread John McWilliams
Frank Drackman wrote:
 Kareem840 [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.

 
 Sell your sperm, we don't want you to reproduce. 
 
 
f-u set

-- lsmft
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help here

2006-09-20 Thread di

Kareem840 [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.


There's this clown in Africa that will help you, please contact him. 


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


Re: Need some help here

2006-09-20 Thread Wildemar Wildenburger
Kareem840 wrote:
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.
 
And I need to get a bus. I mean literally. It's the best.
So chip in a few cents, will you?
[EMAIL PROTECTED]'s the address.
I swear I will use it to buy a bus.

wildemar
(sorry to be a jerk, I'm tired but can't sleep; too many money woes)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help here

2006-09-20 Thread gre
di wrote:
 Kareem840 [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Hello. Unfortunately, I am in need of money to pay my credit card
 bills. If you could spare just $1, I would be grateful. I have a Paypal
 account. [EMAIL PROTECTED] I swear this will go to my card
 balances. Thank you.

 
 There's this clown in Africa that will help you, please contact him. 
 
 
Post your bank account details and i will transfer my nigerian 
inheritance to you..honest!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >