how update MultipartPostHandler pypi

2011-06-04 Thread sergio

Hi,
As Wrote in
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306

http://pypi.python.org/pypi/MultipartPostHandler/0.1.0 is not updated ,
the author email doesn't not exist ,
how I send a comment update MultipartPostHandler
anyway patch attach

--
Sérgio M.B.
Only in MultipartPostHandler-0.1.0: build
Only in MultipartPostHandler-0.1.0: dist
Common subdirectories: MultipartPostHandler-0.1.0.orig/doc and MultipartPostHandler-0.1.0/doc
Common subdirectories: MultipartPostHandler-0.1.0.orig/MultipartPostHandler.egg-info and MultipartPostHandler-0.1.0/MultipartPostHandler.egg-info
diff -u MultipartPostHandler-0.1.0.orig/MultipartPostHandler.py MultipartPostHandler-0.1.0/MultipartPostHandler.py
--- MultipartPostHandler-0.1.0.orig/MultipartPostHandler.py	2010-06-05 20:35:37.0 +0100
+++ MultipartPostHandler-0.1.0/MultipartPostHandler.py	2011-06-04 12:54:31.958597227 +0100
@@ -1,4 +1,5 @@
 #!/usr/bin/python
+# From http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html
 
 
 # 02/2006 Will Holcomb 
@@ -13,6 +14,8 @@
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 # Lesser General Public License for more details.
 #
+# 7/26/07 Slightly modified by Brian Schneider  
+# in order to support unicode files ( multipart_encode function )
 """
 Usage:
   Enables the use of multipart/form-data for posting forms
@@ -42,6 +45,7 @@
 import urllib2
 import mimetools, mimetypes
 import os, stat
+from cStringIO import StringIO
 
 class Callable:
 def __init__(self, anycallable):
@@ -86,22 +90,23 @@
 if boundary is None:
 boundary = mimetools.choose_boundary()
 if buffer is None:
-buffer = ''
+buffer = StringIO()
 for(key, value) in vars:
-buffer += '--%s\r\n' % boundary
-buffer += 'Content-Disposition: form-data; name="%s"' % key
-buffer += '\r\n\r\n' + value + '\r\n'
+buffer.write('--%s\r\n' % boundary)
+buffer.write('Content-Disposition: form-data; name="%s"' % key)
+buffer.write('\r\n\r\n' + value + '\r\n')
 for(key, fd) in files:
 file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
 filename = fd.name.split('/')[-1]
 contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
-buffer += '--%s\r\n' % boundary
-buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
-buffer += 'Content-Type: %s\r\n' % contenttype
+buffer.write('--%s\r\n' % boundary)
+buffer.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
+buffer.write('Content-Type: %s\r\n' % contenttype)
 # buffer += 'Content-Length: %s\r\n' % file_size
 fd.seek(0)
-buffer += '\r\n' + fd.read() + '\r\n'
-buffer += '--%s--\r\n\r\n' % boundary
+buffer.write('\r\n' + fd.read() + '\r\n')
+buffer.write('--' + boundary + '--\r\n\r\n')
+buffer = buffer.getvalue()
 return boundary, buffer
 multipart_encode = Callable(multipart_encode)
 

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


Re: HTMLParser.HTMLParseError: EOF in middle of construct

2007-06-20 Thread sergio
Rob Wolfe wrote:

> 
> Sérgio Monteiro Basto wrote:
>> Stefan Behnel wrote:
>>
>> > Sérgio Monteiro Basto wrote:
>> >> but is one single error that blocks this.
>> >> Finally I found it , it is :
>> >> > >> if I put :
>> >> > >>
>> >> p = re.compile('"align')
>> >> content = p.sub('" align', content)
>> >>
>> >> I can parse the html
>> >> I don't know if it a bug of HTMLParser
>> >
>> > Sure, and next time your key doesn't open your neighbours house, please
>> > report to the building company to have them fix the door.
>> >
>>
>> The question, here, is if
>> > is valid HTML or not ?
>> I think is valid , if so it's a bug on HTMLParser
> 
> According to the HTML 4.01 specification this is *not valid* HTML.
> 
> """
> Elements may have associated properties, called attributes, which may
> have values
> (by default, or set by authors or scripts). Attribute/value pairs
> appear before the final
> ">" of an element's start tag. Any number of (legal) attribute value
> pairs, separated
> by spaces, may appear in an element's start tag.
> """
> 
>> if not, we still have a very bad message error (EOF in middle of
>> construct !?)
> 
> HTMLParser can deal with some errors e.g. lack of ending tags,
> but it can't handle many other problems.
> 
>> I have to use HTMLParser because I want use only python 2.4 standard , I
>> have to install the scripts in many machines.
>> And I have to parse many different sites, I just want extract the links,
>> so with a clean up before parse solve very quickly my problem.
> 
> In Python 2.4 you have to use some third party module. There is no
> other option for _invalid_ HTML. IMHO BeautifulSoup is the best among
> them.
> 

Many thanks Rob , you have been clear has water thanks, 

> --
> HTH,
> Rob

-- 
Best regards,
--
Sérgio M. B. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: stftime %z time conversion character

2007-06-20 Thread sergio
Evan Klitzke wrote:

> Although it is not present in ANSI C, the GNU version of stftime
> supports the conversion character %z, which is a time offset from GMT.
> The four digit time offset is required in RFC 2822 dates/times, and is
> used by a number of other programs as well. I need to convert times
> that use this convention to python time representations, and because
> Python does not support the %z time conversion character I cannot
> simply use the time.strptime function.
> 
> What solutions have people used for this? I'm currently thinking of
> creating a dict that maps four digit time offsets to the time zone
> name and then use the %Z token on that. Is there another (or better)
> way?
> 

I had a similar problem, currently I had solved with a system call 

#The Linux Date Command: TZ=WET date -d "20070823" +%:z 
#example 
timezone = "WET"
year = 2007
month = 2
day = 27
#end of example
cmd="TZ=%s /bin/date -d %.4d%.2d%.2d +%%z" % (timezone,year,month,day) 
print "DEBUG cmd=%s" % cmd
handler=os.popen(cmd, 'r', 1) 
output = "".join(handler.readlines()).strip() 
tz=output[:3]+":"+output[3:] 
handler.close() 
print "DEBUG timezone=%sXX" % tz

 
before I test timezone of my machines like this : 
import time
tzstr=time.strftime("%Z",time.localtime()) 
if tzstr == "WEST" :
do something 

Hope that can help something 

Best regards,
--
Sérgio M. B. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: urllib interpretation of URL with ".."

2007-06-26 Thread sergio
John Nagle wrote:

>  In Python, of course, "urlparse.urlparse", which is
> the main function used to disassemble a URL, has no idea whether it's
> being used by a client or a server, so it, reasonably enough, takes option
> 1.

>>> import urlparse
>>> base="http://somesite.com/level1/";
>>> path="../page.html"
>>> urlparse.urljoin(base,path)
'http://somesite.com/page.html'
>>> base="http://somesite.com/";
>>> urlparse.urljoin(base,path)
'http://somesite.com/../page.html'

For me this is a bug and is very annoying because I can't simply trip ../
from path because base could have a level.


-- 
Best regards,
--
Sérgio M. B. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: urllib interpretation of URL with ".."

2007-06-27 Thread sergio
Gabriel Genellina wrote:

> En Tue, 26 Jun 2007 17:26:06 -0300, sergio <[EMAIL PROTECTED]>
> escribió:
> 
>> John Nagle wrote:
>>
>>>  In Python, of course, "urlparse.urlparse", which is
>>> the main function used to disassemble a URL, has no idea whether it's
>>> being used by a client or a server, so it, reasonably enough, takes
>>> option
>>> 1.
>>
>>>>> import urlparse
>>>>> base="http://somesite.com/level1/";
>>>>> path="../page.html"
>>>>> urlparse.urljoin(base,path)
>> 'http://somesite.com/page.html'
>>>>> base="http://somesite.com/";
>>>>> urlparse.urljoin(base,path)
>> 'http://somesite.com/../page.html'
>>
>> For me this is a bug and is very annoying because I can't simply trip ../
>> from path because base could have a level.
> 
> I'd say it's an annoyance, not a bug. Write your own urljoin function with
> your exact desired behavior - since all "meaningful" .. and . should have
> been already processed by urljoin, a simple url =
> url.replace("/../","/").replace("/./","/") may be enough.
> 

I had exactly the same though the solution is simply this:

urlparse.urljoin(base,path).replace("/../","/")


Many thanks,
--
Sérgio M. B. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: convivenza

2008-01-20 Thread Sergio
crxor 666 wrote:
> 
>> Evidentemente equivocherò sul termine "potenza di un linguaggio", ma 
>> dubito che io possa scrivere un device driver in Python, 
>> indipendentemente dalla potenza processore o dall'esistenza di un 
>> compilatore Python (ho preso per esempio il Python ma potevo usare molti
>> altri linguaggi).
> E perchè? In particolare questa è una questione di libreria più che di
> linguaggio. Questo oggetto per dire ti fa scrivere driver per oggetti
> USB in Python:
> 
Per prima cosa non è scritta in Python ma in C, ma in ogni caso mi pare 
una libreria per l'accesso a dispositivi USB, non una libreria per 
scrivere driver in Python, che sono due cose ben diverse.
Il fatto che le librerie Python (come quelle di altri linguaggi) siano 
scritte per la maggior parte in un linguaggio diverso non dipende solo 
da questioni prestazionali, ma anche dal fatto che certe cose sono 
impossibili in Python.

> 
Come sopra, il kernel non è in Python.

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


I couldn't use the sign funcion inside of another function

2012-04-23 Thread Julio Sergio
I want to use the sign function. When I use it in in-line mode works pretty 
well:

   : sign(-20)
   : -1

However, I wrote the following code in a file, say, pp.py

def tst(x):
s = sign(x)
return(s)

Then I tried to import into my session:

  : from pp import *

When I try to use tst, this is what I get:

  
  Traceback (most recent call last):
File "", line 1, in 
File "pp.py", line 9, in tst
  s = sign(x)
  NameError: global name 'sign' is not defined


Do you have any idea why is this happening?


Thanks,

 -- Sergio.


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


Interprocess comunication

2012-06-07 Thread Julio Sergio
I'm trying to call an external process to filter some of my data, i.e., I'm 
trying to pass some information to the called process, and have this 
information 
back transformed. I started testing with the linux 'cat' command, in this way:


->>> import subprocess as sp
->>> p = sp.Popen(["cat"],stdin=sp.PIPE,stdout=sp.PIPE,close_fds=True)
->>> (fi,fo) = (p.stdin, p.stdout)
->>> fi.write("SOMETHING\n")
->>> fi.flush()
->>> fo.readline()
'SOMETHING\n'
->>> fi.write("OTHER\n")
->>> fi.flush()
->>> fo.readline()
'OTHER\n'
->>> fi.write("NEXT\n")
->>> fi.flush()
->>> fo.readline()
'NEXT\n'
->>> fi.write("NEXT1\n")
->>> fi.flush()
->>> s = fo.readline()
->>> s
'NEXT1\n'

Up to this point it worked as expected. However, when I tryied with the methods 
that write and read several lines, apparently the process got stalled:

->>> fi.writelines(["uno\n","dos\n","tres\n"])
->>> fi.flush()
->>> s = fo.readlines()
.
.
.

Do you have any comments on this?

Thanks,

 --Sergio


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


Re: Interprocess comunication

2012-06-07 Thread Julio Sergio
MRAB  mrabarnett.plus.com> writes:

> 
> I believe it's waiting for the end of the input, i.e. for the pipe to
> close.
> 
> Have you tried calling fo.readline() 3 times instead?
> 

yeah! It worked!...
A question remains: what is then the purpose of fo.readlines(...)?

Thanks,
--Sergio




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


Re: Interprocess comunication

2012-06-07 Thread Julio Sergio
J. Cliff Dyer  sdf.lonestar.org> writes:

> 
> readlines() reads all the lines from the filehandle, but the filehandle
> hasn't signalled that it is done writing lines, so fo is waiting until
> fi is complete.  You either need to keep reading one line at a time, and
> manually release control when there's nothing more to read, or you need
> to do an fi.close() before you try to use fo.readlines().
> 
> 

Thanks... It worked as you said. Here is how I coded it:

->>> fi.writelines(["uno\n","dos\n","tres\n"])
->>> fi.close()
->>> l = fo.readlines()
->>> l
['uno\n', 'dos\n', 'tres\n']


--Sergio

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


About a list comprehension to transform an input list

2012-06-08 Thread Julio Sergio
>From a sequence of numbers, I'm trying to get a list that does something to 
>even 
numbers but leaves untouched the odd ones, say:

[0,1,2,3,4,...] ==> [100,1,102,3,104,...]

I know that this can be done with an auxiliary function, as follows:

->>> def filter(n):
... if (n%2 == 0):
... return 100+n
... return n
... 
->>> L = range(10)
->>> [filter(n) for n in L]
[100, 1, 102, 3, 104, 5, 106, 7, 108, 9]

I wonder whether there can be a single list comprehension expression to get 
this 
result without the aid of the auxiliary function.

Do you have any comments on this?

Thanks,
--Sergio.



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


using identifiers before they are defined

2012-06-12 Thread Julio Sergio
I'm puzzled with the following example, which is intended to be a part of a 
module, say "tst.py":

  a = something(5)

  def something(i):
  return i



When I try: 

->>> import tst

The interpreter cries out:

Traceback (most recent call last):
  File "", line 1, in 
  File "tst.py", line 11, in 
a = something(5)
NameError: name 'something' is not defined

I know that changing the order of the definitions will work, however there are 
situations in which referring to an identifier before it is defined is 
necessary, e.g., in crossed recursion. 

So I modified my module:

  global something

  a = something(5)


  def something(i):
  return i


And this was the answer I got from the interpreter:

->>> import tst

Traceback (most recent call last):
  File "", line 1, in 
  File "tst.py", line 12, in 
a = something(5)
NameError: global name 'something' is not defined


Do you have any comments?

Thanks,

--Sergio.




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


Re: using identifiers before they are defined

2012-06-12 Thread Julio Sergio
Jose H. Martinez  gmail.com> writes:

> 
> 
> You should define the function first and then call it.
> 
> 
>  def something(i):     return i
> 
> 
> a = something(5)
> 
> 
> If you want a reference to the function somewhere else you can do this:
> 

I know that. That was what I meant by "changing the order of the definitions 
will work" in my original message.

And I insist in the issue, which is not trivial... In my message I mentioned 
"crossed recursion", and I delve into it here:

Suppose I have to define two functions, aa, and, bb that are designed to call 
each other:

  def aa():
 ...
 ... a call of bb() somewhere in the body of aa
 ...

  def bb():
 ...
 ... a call of aa() somewhere in the body of bb
 ...


Whatever the order of definition of aa and bb the problem remains, one of the 
two identifiers is not known ...

Most of computer languages have mechanisms to deal with this issue. Is there 
any 
in Python or it is in disadvantage with respect to other languages like C++, 
Java, Perl, PHP, etc.?




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


Re: using identifiers before they are defined

2012-06-12 Thread Julio Sergio
Ethan Furman  stoneleaf.us> writes:

> 
> 
> No.  The reply from MRAB explains this.
> 
> ~Ethan~
> 

Thanks, you're right!
I was confusing statemens with declarations.





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


python3 - No module named 'html5lib'

2016-04-14 Thread Sergio Spina
I'm running a python3 program that requires html5lib but I receive the error No 
module named 'html5lib'.

Here are two session of terminal:

sam@pc ~ $ python
Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
>>> import html5lib
>>> html5lib.__file__
'/usr/local/lib/python2.7/dist-packages/html5lib/__init__.pyc'
>>> quit()

sam@pc ~ $ python3
Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
>>> import html5lib
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named 'html5lib'

Where can be the problem?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python3 - No module named 'html5lib'

2016-04-15 Thread Sergio Spina
Il giorno giovedì 14 aprile 2016 17:54:00 UTC+2, Wildman ha scritto:
> On Thu, 14 Apr 2016 02:31:59 -0700, Sergio Spina wrote:
> 
> > I'm running a python3 program that requires html5lib but I receive the 
> > error No module named 'html5lib'.
> > 
> > Here are two session of terminal:
> > 
> > sam@pc ~ $ python
> > Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
> > [GCC 4.9.2] on linux2
> > >>> import html5lib
> > >>> html5lib.__file__
> > '/usr/local/lib/python2.7/dist-packages/html5lib/__init__.pyc'
> > >>> quit()
> > 
> > sam@pc ~ $ python3
> > Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
> > [GCC 4.9.1] on linux
> > >>> import html5lib
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named 'html5lib'
> > 
> > Where can be the problem?
> 
> apt-get install python3-html5lib
> 
> -- 
>  GNU/Linux user #557453
> The cow died so I don't need your bull!

It works, many thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


ReST: link bookmark

2016-04-17 Thread Sergio Spina
I would know what is the way to implement in ReST a link bookmark like in this 
example:

> 
> 
>
> This text stand for an example of text containing
> a bookmarked target bookmark.
>
> So let's go all together to visit the bookmarked target
> clicking on this link.
>
> 
> 

The string that is the name of the anchor is produced by an algorithm and 1) 
cannot be left away and 2) cannot be seen in the printed document.

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


Re: ReST: link bookmark

2016-04-17 Thread Sergio Spina
Il giorno domenica 17 aprile 2016 12:04:38 UTC+2, Sergio Spina ha scritto:
> I would know what is the way to implement in ReST a link bookmark like in 
> this example:
> 
> > 
> > 
> >
> > This text stand for an example of text containing
> > a bookmarked target bookmark.
> >
> > So let's go all together to visit the bookmarked target
> > clicking on this link.
> >
> > 
> > 
> 
> The string that is the name of the anchor is produced by an algorithm and 1) 
> cannot be left away and 2) cannot be seen in the printed document.
> 
> Thanks.

The correct example is:

> 
> 
>
> This text stand for an example of text containig
> a target bookmark.
>
> So let's go all together to visit the target clicking
> on this link.
>
> 
> 

Sorry for the mispelling.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ReST: link bookmark

2016-04-19 Thread Sergio Spina
Il giorno domenica 17 aprile 2016 12:14:57 UTC+2, Sergio Spina ha scritto:
> Il giorno domenica 17 aprile 2016 12:04:38 UTC+2, Sergio Spina ha scritto:
> > I would know what is the way to implement in ReST a link bookmark like in 
> > this example:
> > 
> > > 
> > > 
> > >
> > > This text stand for an example of text containing
> > > a bookmarked target bookmark.
> > >
> > > So let's go all together to visit the bookmarked target
> > > clicking on this link.
> > >
> > > 
> > > 
> > 
> > The string that is the name of the anchor is produced by an algorithm and 
> > 1) cannot be left away and 2) cannot be seen in the printed document.
> > 
> > Thanks.
> 
> The correct example is:
> 
> > 
> > 
> >
> > This text stand for an example of text containig
> > a target bookmark.
> >
> > So let's go all together to visit the target clicking
> > on this link.
> >
> > 
> > 
> 
> Sorry for the mispelling.

I've tried some experiments looking for a hint:

# file: test.htm




This text stand for an example of text containing
a bookmarked target bookmark.

So let's go all together to visit the bookmarked target
clicking on this link.




First try:

# test.htm converted at http://www.siafoo.net/html.xml

This text stand for an example of text containig a `target <>`_ bookmark.

So let's go all together to visit the target clicking on `this
link <#B3Pa9-5ZRIx-1>`_ .

that is not what I'm looking for;

# pandoc -f html test.htm -s -o test.rst

This text stand for an example of text containig a target bookmark.

So let's go all together to visit the target clicking on `this
link <#B3Pa9-5ZRIx-1>`__.

that is not what I'm looking for;

# html2rst.py taken from 
http://docutils.sourceforge.net/sandbox/cliechti/html2rst/html2rst.py
# python html2rst.py test.htm > test.rst

This text stand for an example of text containig a target bookmark.

So let's go all together to visit the target clicking on `this
link`_.

.. _this link: #B3Pa9-5ZRIx-1

Not a good try.

Is there a better way ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Help for a complex RE

2016-05-08 Thread Sergio Spina
In the following ipython session:

> Python 3.5.1+ (default, Feb 24 2016, 11:28:57) 
> Type "copyright", "credits" or "license" for more information.
>
> IPython 2.3.0 -- An enhanced Interactive Python.
>
> In [1]: import re
>
> In [2]: patt = r"""  # the match pattern is:
> ...: .+  # one or more characters
> ...: [ ] # followed by a space
> ...: (?=[@#D]:)  # that is followed by one of the
> ...: # chars "@#D" and a colon ":"
> ...:"""
> 
> In [3]: pattern = re.compile(patt, re.VERBOSE)
> 
> In [4]: m = pattern.match("Jun@i Bun#i @:Janji")
> 
> In [5]: m.group()
> Out[5]: 'Jun@i Bun#i '
> 
> In [6]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji")
> 
> In [7]: m.group()
> Out[7]: 'Jun@i Bun#i @:Janji '
> 
> In [8]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji #:Junji")
> 
> In [9]: m.group()
> Out[9]: 'Jun@i Bun#i @:Janji D:Banji '

Why the regex engine stops the search at last piece of string?
Why not at the first match of the group "@:"?
What can it be a regex pattern with the following result?

> In [1]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji #:Junji")
> 
> In [2]: m.group()
> Out[2]: 'Jun@i Bun#i '



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


Re: Help for a complex RE

2016-05-08 Thread Sergio Spina
Il giorno domenica 8 maggio 2016 18:16:56 UTC+2, Peter Otten ha scritto:
> Sergio Spina wrote:
> 
> > In the following ipython session:
> > 
> >> Python 3.5.1+ (default, Feb 24 2016, 11:28:57)
> >> Type "copyright", "credits" or "license" for more information.
> >>
> >> IPython 2.3.0 -- An enhanced Interactive Python.
> >>
> >> In [1]: import re
> >>
> >> In [2]: patt = r"""  # the match pattern is:
> >> ...: .+  # one or more characters
> >> ...: [ ] # followed by a space
> >> ...: (?=[@#D]:)  # that is followed by one of the
> >> ...: # chars "@#D" and a colon ":"
> >> ...:"""
> >> 
> >> In [3]: pattern = re.compile(patt, re.VERBOSE)
> >> 
> >> In [4]: m = pattern.match("Jun@i Bun#i @:Janji")
> >> 
> >> In [5]: m.group()
> >> Out[5]: 'Jun@i Bun#i '
> >> 
> >> In [6]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji")
> >> 
> >> In [7]: m.group()
> >> Out[7]: 'Jun@i Bun#i @:Janji '
> >> 
> >> In [8]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji #:Junji")
> >> 
> >> In [9]: m.group()
> >> Out[9]: 'Jun@i Bun#i @:Janji D:Banji '
> > 
> > Why the regex engine stops the search at last piece of string?
> > Why not at the first match of the group "@:"?
> > What can it be a regex pattern with the following result?
> > 
> >> In [1]: m = pattern.match("Jun@i Bun#i @:Janji D:Banji #:Junji")
> >> 
> >> In [2]: m.group()
> >> Out[2]: 'Jun@i Bun#i '
> 
> Compare:
> 
> >>> re.compile("a+").match("").group()
> ''
> >>> re.compile("a+?").match("").group()
> 'a'
> 
> By default pattern matching is "greedy" -- the ".+" part of your regex 
> matches as many characters as possible. Adding a ? like in ".+?" triggers 
> non-greedy matching.

>  In [2]: patt = r"""  # the match pattern is:
>  ...: .+  # one or more characters
>  ...: [ ] # followed by a space
>  ...: (?=[@#D]:)  # ONLY IF is followed by one of the <<< please note
>  ...: # chars "@#D" and a colon ":"
>  ...:""" 

>From the python documentation

>  (?=...)
>  Matches if ... matches next, but doesn't consume any of the string.
>  This is called a lookahead assertion. For example,
>  Isaac (?=Asimov) will match 'Isaac ' only if it's followed by 'Asimov'.

I know about greedy and not-greedy, but the problem remains.

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


Anonymous hyperlinks in restructuredtext

2016-05-28 Thread Sergio Spina
>From the "restructuredtext markup specification":

>Anonymous hyperlink targets consist of an explicit markup
>start (".. "), two underscores, a colon, whitespace, and a
>link block; there is no reference name:
>
>.. __: anonymous-hyperlink-target-link-block
>
>An alternate syntax for anonymous hyperlinks consists of two
>underscores, a space, and a link block:
>
>__ anonymous-hyperlink-target-link-block

Ok. I got the file "test.rst"

==file test.rst==

Nunc ante nulla, porttitor vitae massa eu, mollis tristique
urna. Duis bibendum arcu est, elementum.

.. __: link1

Curabitur sed ultrices ex. Integer.

.. __: link2

Quisque ornare mollis risus eu fringilla. Sed eros mauris,
auctor.

Now I put a reference to link1_ and another to link2_

==end of file=

Let's try to pass it to docutils:

$ rst2latex test.rst > tests.tex
  test.rst:11: (ERROR/3) Anonymous hyperlink mismatch: 0 references
but 2 targets.
  See "backrefs" attribute for IDs.
  test.rst:10: (ERROR/3) Unknown target name: "link1".
  test.rst:10: (ERROR/3) Unknown target name: "link2".

Ok, I retry with the alternate syntax:

==file test.rst==

Nunc ante nulla, porttitor vitae massa eu, mollis tristique
urna. Duis bibendum arcu est, elementum.

__ link1

Curabitur sed ultrices ex. Integer.

__ link2

Quisque ornare mollis risus eu fringilla. Sed eros mauris,
auctor.

Now I put a reference to link1_ and another to link2_

==end of file=

Same error

$ rst2latex test.rst > test.tex
  test.rst:14: (ERROR/3) Anonymous hyperlink mismatch: 0 references
but 2 targets.
  See "backrefs" attribute for IDs.
  test.rst:13: (ERROR/3) Unknown target name: "link1".
  test.rst:13: (ERROR/3) Unknown target name: "link2".

Now, where is the error? How can I correctly set an internal
anonymous kyperlink?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Anonymous hyperlinks in restructuredtext

2016-05-28 Thread Sergio Spina
Il giorno sabato 28 maggio 2016 14:37:21 UTC+2, Ned Batchelder ha scritto:
> On Saturday, May 28, 2016 at 8:28:35 AM UTC-4, Sergio Spina wrote:
> > From the "restructuredtext markup specification":
> > 
> > >Anonymous hyperlink targets consist of an explicit markup
> > >start (".. "), two underscores, a colon, whitespace, and a
> > >link block; there is no reference name:
> > >
> > >.. __: anonymous-hyperlink-target-link-block
> > >
> > >An alternate syntax for anonymous hyperlinks consists of two
> > >underscores, a space, and a link block:
> > >
> > >__ anonymous-hyperlink-target-link-block
> > 
> > Ok. I got the file "test.rst"
> > 
> > ...
> > 
> > Now I put a reference to link1_ and another to link2_
> 
> The docs say, "there is no reference name", so you cannot put a reference
> to them.  You can use an anonymous syntax:
> 
> Jump to `my blog`__.
> 
> __ http://myblog.com
> 
> or you can use a named syntax:
> 
> Jump to `my blog`_.
> 
> .. _my blog: http://myblog.com
> 
> The ReST syntax can be arcane...
> 
> --Ned.

I need INTERNAL hyperlink targets, not external...
-- 
https://mail.python.org/mailman/listinfo/python-list


xmlrcp register classes

2005-09-05 Thread Sergio Rua
Hello,

I have a structured program with several classes which I would like to
export using a xmlrpc server. I'm doing this

Server = SimpleXMLRPCServer (('127.0.0.1',8080))

Server.register_instance(MyClass1())
Server.register_instance(MyClass2())
Server.register_instance(MyClass3())

What is seems to happen is that only the last class I register it is the
only one being exported. How can I register all the classes? Thanks.

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


Re: xmlrcp register classes

2005-09-05 Thread Sergio Rua
Hello,

> class MyCombinedClass(MyClass1, MyClass2, MyClass3):
> pass
> 
> Server.register_instance(MyCombinedClass())

That was easy :) Thanks a lot.

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


Re: HMAC encription issue

2013-08-31 Thread Sergio Sanchez
El sábado, 31 de agosto de 2013 16:39:08 UTC+2, Roy Smith  escribió:
> In article <3479e08e-d435-492b-b2a0-a1c18678f...@googlegroups.com>,
> 
>  sergio7...@gmail.com wrote:
> 
> 
> 
> > key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A3035"
> 
> > key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A303$
> 
> 
> 
> To start with, your keys are not the same (the JS one ends in "35", the 
> Python one ends in "3$",
> 
> and I don't know what to make of the fact that your Python key isn't 
> terminated with a quote.


Sorry, that was a problem with the cut & paste. The two sentences 
key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A3035"
 are just the same in Python and Javascript.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HMAC encription issue

2013-08-31 Thread Sergio Sanchez
El sábado, 31 de agosto de 2013 16:48:53 UTC+2, Sergio Sanchez  escribió:
> El sábado, 31 de agosto de 2013 16:39:08 UTC+2, Roy Smith  escribió:
> 
> > In article <3479e08e-d435-492b-b2a0-a1c18678f...@googlegroups.com>,
> 
> > 
> 
> >  sergio7...@gmail.com wrote:
> 
> > 
> 
> > 
> 
> > 
> 
> > > key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A3035"
> 
> > 
> 
> > > key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A303$
> 
> > 
> 
> > 
> 
> > 
> 
> > To start with, your keys are not the same (the JS one ends in "35", the 
> > Python one ends in "3$",
> 
> > 
> 
> > and I don't know what to make of the fact that your Python key isn't 
> > terminated with a quote.
> 
> 
> 
> 
> 
> Sorry, that was a problem with the cut & paste. The two sentences 
> key="4545453030303743303134462035343733373432363420323031332D30382D33312031343A33353A3035"
>  are just the same in Python and Javascript.



Solved:

key must be converted to binary with the function unhexlify(hexstr)

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


PYTHONPATH not working on Windows XP (?)

2007-09-02 Thread Sergio Correia
Hi,

I'm trying to add a personal folder to the path used by python in
searching for packages and modules. This folder, "C:\docs\utils" , has
some packages not yet ready for "site-packages".

First, I tried sys.path.append("C:\docs\utils") BUT this only lasts
for the current python session.

Then, I read about PYTHONPATH and went to Control Panel - System -
Advanced - Enviromental Variables, and created a new variable
(PYTHONPATH) containing the folder. However, sys.path does not detects
it.. keeps printing the same old files:

>>> import sys; import pprint; pprint.pprint(sys.path)

['C:\\Program Files\\AutoHotkey',
 'C:\\Program Files\\Python25\\Lib\\idlelib',
 'C:\\WINDOWS\\system32\\python25.zip',
 'C:\\Program Files\\Python25\\DLLs',
 'C:\\Program Files\\Python25\\lib',
 'C:\\Program Files\\Python25\\lib\\plat-win',
 'C:\\Program Files\\Python25\\lib\\lib-tk',
 'C:\\Program Files\\Python25',
 'C:\\Program Files\\Python25\\lib\\site-packages']

(By the way, how did that AutoHotkey folder got there? Can I remove it
from sys.path?)

After my second failure, I went to the registry
HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.5\PythonPath

and added my folder there. Still nothing on sys.path , and my imports fail.

Any suggestions for adding my path to sys.path permanently? I'm
running out of ideas

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


Re: PYTHONPATH not working on Windows XP (?)

2007-09-03 Thread Sergio Correia
Thanks!

It worked straightforward, and it's easier than messing with the
enviromental variables or the registry.

BTW, I'm still wondering how did Autohotkey got included in sys.path
(there are no other .pht files on my PC)

Regards,
Sergio

On 9/3/07, olivier <[EMAIL PROTECTED]> wrote:
> Hi,
>
> > Any suggestions for adding my path to sys.path permanently?
>
> You can write a file in Lib/site-packages with a 'pth' extension (the
> name itself doesn't matter) containing the path you want to add.
>
> Example:
> MyCustomLib.pth:
> C:/docs/utils
>
> And be careful with path separator on win32. It should be "/" or "\\",
> never "\".
>
> Regards,
>
>  Olivier
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Can you use -getattr- to get a function in the current module?

2007-09-03 Thread Sergio Correia
This works:

# Module spam.py

import eggs

print getattr(eggs, 'omelet')(100)

That is, I just call the function omelet inside the module eggs and
evaulate it with the argument 100.

But what if the function 'omelet' is in the module where I do the
getattr (that is, in spam.py).  If I do any of this

print getattr(spam, 'omelet')(100)
print getattr('','omelet')(100)
print getattr('omelet')(100)

It wont work. Any ideas?

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


Re: Can you use -getattr- to get a function in the current module?

2007-09-03 Thread Sergio Correia
Alex, Gabriel,

Thanks for the reply. Works great!

On 9/3/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Mon, 03 Sep 2007 20:13:43 -0300, Sergio Correia
> <[EMAIL PROTECTED]> escribi�:
>
> > # Module spam.py
> >
> > import eggs
> >
> > print getattr(eggs, 'omelet')(100)
> >
> > That is, I just call the function omelet inside the module eggs and
> > evaulate it with the argument 100.
> >
> > But what if the function 'omelet' is in the module where I do the
> > getattr (that is, in spam.py).  If I do any of this
>
> Use globals():
>
> print globals()['omelet'](100)
>
> (Of course this only makes sense when using a variable instead of
> 'omelet'...)
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-06 Thread Sergio Correia
Hi, I'm kinda new to Python (that means, I'm a total noob here), but
have one doubt which is more about consistency that anything else.

Why if PEP 8 says that "Almost without exception, class names use the
CapWords convention", does the most basic class, object, is lowercase?

I found a thread about this:
http://mail.python.org/pipermail/python-list/2007-April/437365.html
where its stated that -object- is actually a type, not a class; but
the idea still doesn't convince me.

If i create a class Spam using -object- as a parent class, I would
expect -object- to be a class, not a type as in type(object) (what is
the difference between both btw?). But, on the other hand, if I do
help(object), I get:

>>> help(object)
Help on class object in module __builtin__:

class object
 |  The most base type

So is this a class? No...

>>> object


My doubts get compounded when strange stuff starts to happen:

>>> class Eggs(object):
def __init__(self):
self.x = 1
>>> type(Eggs)


Type 'type'? What is that supposed to mean?

Hope this makes any sense ;),

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


Re: Why 'class spam(object)' instead of class spam(Object)' ?

2007-09-08 Thread Sergio Correia
Thanks for the replies, very instructive!

On 9/7/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Carl Banks wrote:
> > On Fri, 07 Sep 2007 01:30:00 -0500, Sergio Correia wrote:
> >> Hi, I'm kinda new to Python (that means, I'm a total noob here), but
> >> have one doubt which is more about consistency that anything else.
> >>
> >> Why if PEP 8 says that "Almost without exception, class names use the
> >> CapWords convention", does the most basic class, object, is lowercase?
> >
> > It said "almost".  :)
> >
> Indeed it did, and never forget that most of PEP 8 was derived from an
> essay by Guido whose original title was "A Foolish Consistency is the
> Hobgoblin of Little Minds" ...
> >
> >> I found a thread about this:
> >> http://mail.python.org/pipermail/python-list/2007-April/437365.html
> >> where its stated that -object- is actually a type, not a class; but the
> >> idea still doesn't convince me.
> >
> You don't have to be convinced. You just have to do what the PEP says
> yourself and ignore the people who *haven't* done what it says
> (particularly if they are core Python developers).
>
> > There's a false dichotomy there: it's not an either-or situation.  Almost
> > everyone would agree that new-style classes, defined by the Python class
> > statement, are both classes and types.  Some might squabble over whether
> > object is class, but it has nothing to do with why object is spelled in
> > lower-case.
> >
> > The reason why "object" is lower case is because built-in types are
> > spelled in lower-case.  Why are built-in types lower case?  Because many
> > built-in types were originially functions.  For example, "int" and "str"
> > were once functions.  When these symbols became the names of their
> > respective types, they kept the lower-case spelling, and it became
> > convention for built-in types to be spelled lower-case.
> >
> In other words: "Get over it" ;-)
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd   http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting external IP address

2007-03-06 Thread Sergio Correia
The above suggestions seem nice, but I find this one easier:

import urllib2
ext_ip = urllib2.urlopen('http://whatismyip.org/').read()
print ext_ip

The nice thing about the above code is that http://whatismyip.org/
only contains exactly what you want (the ip, nothing more, nothing
less), so no parsing is necessary

Best,
Sergio

On 3/6/07, Cousin Stanley <[EMAIL PROTECTED]> wrote:
>
> > I have a PC behind a firewall, and I'm trying to programmatically
> > determine the IP address visible from outside the firewall.
> > 
>
> Steven 
>
>   Following is another alternative that might at least
>   be worth consideration 
>
>   I use the  lynx  command shown as a command-line alias
>   under Debian linux 
>
> >>>
> >>> import os
> >>>
> >>> pipe_in = os.popen( 'lynx --dump http://checkip.dyndns.org' )
> >>>
> >>> ip_addr = pipe_in.readlines()
> >>>
> >>> for this in ip_addr :
> ... print this
> ...
>
>
>Current IP Address: 65.39.92.38
>
>
> --
> Stanley C. Kitching
> Human Being
> Phoenix, Arizona
>
>
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Best place for a function?

2007-03-07 Thread Sergio Correia
I'm writing a class, where one of the methods is kinda complex. The
method uses a function which I know for certain will not be used
anywhere else. This function does not require anything from self, only
the args passed by the method.

Where should I put the function?

a) Inside the module but outside the class (to avoid cluttering it;
besides the function does not require to access any property or method
of the class).

# mymodule.py

def  _myfunction():
 ...

class myclass(object):
 def mymethod(self):
  ...
  spam = _myfunction()
...


b) Inside the class but outside the method

# mymodule.py

class myclass(object):
 def  _myfunction(self):
 ...

 def mymethod(self):
  ...
  spam = self._myfunction()
...

c) Inside the method:

# mymodule.py

class myclass(object):
 ...
 def mymethod(self):
 def  _myfunction(self):
   ...
 ...
 spam = self._myfunction()
 ...


I'm new to python (and couldn't find anything about this in PEP 8).
What would you suggest me?

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


Re: Best place for a function?

2007-03-07 Thread Sergio Correia
I also found out I can't use `unittest` with nested functions :-(

Thank you all for the responses,

Best,
Sergio

On 7 Mar 2007 14:57:54 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Diez B. Roggisch:
> > If it really has no other use as in this class, put it as an
> > instancemethod in there. Alternatively, you _could_ nest it like this:
>
> Using an instancemethod may be the most formally correct solution for
> that problem, but often nested function are the simpler solution. A
> downside of nested functions is that you can't give them a doctest (in
> a simple way).
>
> Bye,
> bearophile
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
Hi,

I'm looking for an easy way to flatten a two level list like this

spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Into something like
eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

There are *no* special cases (no empty sub-lists).

I have found two ways:

1) Accumulator
eggs = []
for x in eggs:
   eggs.extend(x)

2) Reduce
eggs = reduce(lambda x, y: x+y, spam)

I feel the 1st way is too cumbersome (three lines), and although I
like the 2nd way (except for the lambda part), I understand reduce is
discouraged by Guido so I want to know if there is a "Better Way"(TM)
?

Any ideas?

Thanks,
Sergio

PS: Why does `sum` works only with numbers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
I forgot to say: I've already checked the discussions about
recursive/iterative/etc flatten() functions that can sweep through a
list of arbitrary length, but that's really overkill for what I want.

However, "sum(eggs, [])" or itertools seem to do it w/out the need for
a new function.

Thanks a lot!

Sergio

On 3/7/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 07 Mar 2007 21:14:43 -0300, Sergio Correia
> <[EMAIL PROTECTED]> escribió:
>
> > I'm looking for an easy way to flatten a two level list like this
>
> Try google.
>
> > PS: Why does `sum` works only with numbers?
>
> Try google.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
 O_o

List comprehensions never cease to amaze me.

Thanks,


On 3/7/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 07 Mar 2007 21:41:16 -0300, Sergio Correia
> <[EMAIL PROTECTED]> escribió:
>
> > I forgot to say: I've already checked the discussions about
> > recursive/iterative/etc flatten() functions that can sweep through a
> > list of arbitrary length, but that's really overkill for what I want.
> >
> > However, "sum(eggs, [])" or itertools seem to do it w/out the need for
> > a new function.
> >
> > Thanks a lot!
>
> Just for being (a little!) constructive, given your preconditions on the
> list, you can use:
> eggs = [item for sublist in spam for item in sublist]
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


How to open a txt file from the same folder as my module (w/out changing the working dir)

2007-04-04 Thread Sergio Correia
I have  a program in 'C:\Python25\Lib\site-packages\spam\spam.py'

Importing and everything works fine:
>>> from spam import spam

But the program calls a file located on the same folder (that is:
C:\Python25\Lib\site-packages\spam\).

How do i do that?

>>> spam.eggs()

Traceback (most recent call last):
  File "", line 1, in 
datita = spam.eggs()
  File "C:\Python25\lib\site-packages\spam\spam.py", line 149, in JustDoIt
config = open("configuration.txt", "rb").read().split('\r\n')
IOError: [Errno 2] No such file or directory: 'configuration.txt'

My last resort is to hard code the path for that file, but it's ugly,
and I want to know if I'm missing something. Am I?

Thanks a lot,
Sergio
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to open a txt file from the same folder as my module (w/out changing the working dir)

2007-04-04 Thread Sergio Correia
Larry, Gabriel

Thanks for the replies. Both ways work great.

Sergio

On 4/4/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 04 Apr 2007 20:14:37 -0300, Larry Bates <[EMAIL PROTECTED]>
> escribió:
>
> > Sergio Correia wrote:
> >> I have  a program in 'C:\Python25\Lib\site-packages\spam\spam.py'
> >>
> >> Importing and everything works fine:
> >>>>> from spam import spam
> >>
> >> But the program calls a file located on the same folder (that is:
> >> C:\Python25\Lib\site-packages\spam\).
> >>
> >> How do i do that?
> >
> > The problem is that C:\Python25\Lib\site-packages\spam is not
> > the current working directory when you run the program.  If it were,
> > and if configuration.txt is in that directory it WILL find it.  If
> > you are running this from a shortcut make the working directory
> > C:\Python25\Lib\site-packages\spam
>
> If changing the working directory is not possible/convenient, use the
> module __file__ attribute (spam.__file__) to obtain the directory where
> spam.py resides.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple threading example freezes IDLE?

2007-09-26 Thread Sergio Correia
I think the -print- command, as used in IDLE, is not thread-safe. I
was bitten by an issue like that today, and the problem ended up being
the -print- command I used.

On the cmd line, it works per-fect-ly.. but IDLE seems to be the culprit.
A possible answer seems to be to write a wrapper for print that makes
it thread safe (with the help of a lock.

On 9/19/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> hey all,
>
> For my study I'm writing a simple threaded webcrawler and I am trying
> to do this in python. But somehow, using threads causes IDLE to crash
> on Windows XP (with the latest python distribution 2.5.1). Even a
> simple example such as this:
>
> import thread, time
>
> def doSomething():
>   print "something"
>
> for i in range(2):
>   thread.start_new(doSomething, ())
>
> causes IDLE to freeze when I type it in the interpreter. Using the
> python command line everything works just fine. Using IDLE on Debian
> linux also does not cause anything to crash. What am I overlooking?
>
> regards, Writser Cleveringa
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple threading example freezes IDLE?

2007-09-26 Thread Sergio Correia
I think I have pinpointed the error:

When the -print- command fills the screen, IDLE crashes. That is, if i
have 30 empty lines before I start to push the current screen upwards,
when the last of those lines is used, and its time to push the screen
upwards, IDLE crashes.

I'm using IDLE 1.2.1, Python 2.5.1, and Tk 8.4. Does anyone has any
idea of why is this happening?

Thanks,
Sergio

Example code   --->  http://pastebin.com/f21868e26

import time
import Queue
import threading

class Worker(threading.Thread):

def __init__(self,  inQueue, **kwds):
threading.Thread.__init__(self, **kwds)
self.inQueue = inQueue
self.setDaemon(True)
self.start()

def run(self):
while True:
item = self.inQueue.get()
print item
self.inQueue.task_done()
time.sleep(0.1)

qSymbols = Queue.Queue()
symbols = range(50)
for symbol in sorted(symbols):
qSymbols.put_nowait(symbol)

Worker(qSymbols) # Start thread
qSymbols.join()
print "The End..."




On 9/26/07, Sergio Correia <[EMAIL PROTECTED]> wrote:
> I think the -print- command, as used in IDLE, is not thread-safe. I
> was bitten by an issue like that today, and the problem ended up being
> the -print- command I used.
>
> On the cmd line, it works per-fect-ly.. but IDLE seems to be the culprit.
> A possible answer seems to be to write a wrapper for print that makes
> it thread safe (with the help of a lock.
>
> On 9/19/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > hey all,
> >
> > For my study I'm writing a simple threaded webcrawler and I am trying
> > to do this in python. But somehow, using threads causes IDLE to crash
> > on Windows XP (with the latest python distribution 2.5.1). Even a
> > simple example such as this:
> >
> > import thread, time
> >
> > def doSomething():
> >   print "something"
> >
> > for i in range(2):
> >   thread.start_new(doSomething, ())
> >
> > causes IDLE to freeze when I type it in the interpreter. Using the
> > python command line everything works just fine. Using IDLE on Debian
> > linux also does not cause anything to crash. What am I overlooking?
> >
> > regards, Writser Cleveringa
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Sorting Countries by Region

2007-11-16 Thread Sergio Correia
Just a few notes:

1) get_countries_list

What is the purpose of that function? Besides a few errors (an
argument named list, no value returned), it seems you just want to
remove duplicates from a list called countries. You can do that
transforming the list to a 'set'.

new_countries =  list( set(countries) )

2) I would suggest using countries.sort(...) or sorted(countries,...),
specifying cmp or key options too sort by region instead.

3) Instead of doing this:

for country in unique_countries:
   matrix.write(n,1, country)
   n = n+1

Do something like

for i, cou in enumerate(unique_countries):
   matrix.write(1+i, 1, cou)

(so you dont need to increment the 'i' variable manually)


On Nov 16, 2007 2:13 PM,  <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm analyzing some data that has a lot of country data.  What I need
> to do is sort through this data and output it into an excel doc with
> summary information.  The countries, though, need to be sorted by
> region, but the way I thought I could do it isn't quite working out.
> So far I can only successfully get the data alphabetically.
>
> Any ideas?
>
> import xlrd
> import pyExcelerator
>
> def get_countries_list(list):
> countries_list=[]
> for country in countries:
> if country not in countries_list:
> countries_list.append(country)
>
> EU = ["Austria","Belgium", "Cyprus","Czech Republic",
> "Denmark","Estonia", "Finland"]
> NA = ["Canada", "United States"]
> AP = ["Australia", "China", "Hong Kong", "India", "Indonesia",
> "Japan"]
> Regions_tot = {'European Union':EU, 'North America':NA, 'Asia
> Pacific':AP,}
>
> path_file = "c:\\1\country_data.xls"
> book = xlrd.open_workbook(path_file)
> Counts = book.sheet_by_index(1)
> countries= Counts.col_values(0,start_rowx=1, end_rowx=None)
>
> get_countries_list(countries)
>
> wb=pyExcelerator.Workbook()
> matrix = wb.add_sheet("matrix")
>
> n=1
> for country in unique_countries:
> matrix.write(n,1, country)
> n = n+1
>
> wb.save('c:\\1\\matrix.xls')
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Sorting Countries by Region

2007-11-16 Thread Sergio Correia
About the sort:

Check this (also on http://pastebin.com/f12b5b6ca )

def make_regions():

# Values you provided
EU = ["Austria","Belgium", "Cyprus","Czech Republic",
"Denmark","Estonia", "Finland"]
NA = ["Canada", "United States"]
AP = ["Australia", "China", "Hong Kong", "India", "Indonesia",
"Japan"]
regions = {'European Union':EU, 'North America':NA, 'Asia Pacific':AP}

ans = {}
for reg_name, reg in regions.items():
for cou in reg:
ans[cou] = reg_name
return ans

def cmp_region(cou1, cou2):
ans = cmp(regions[cou1], regions[cou2])
if ans: # If the region is the same, sort by country
return cmp(cou1, cou2)
else:
return ans

regions = make_regions()
some_countries = ['Austria', 'Canada', 'China', 'India']

print 'Old:', some_countries
some_countries.sort(cmp_region)
print 'New:', some_countries


Why that code?
Because the first thing I want is a dictionary where the key is the
name of the country and the value is the region. Then, I just make a
quick function that compares considering the region and country.
Finally, I sort.

Btw, the code is just a quick hack, as it can be improved -a lot-.


About the rest of your code:
- martyw's example is much more useful than you think. Why? because
you can just iterate across your document, adding the values you get
to the adequate object property. That is, instead of using size or
pop, use the variables you are interested in.

Best, and good luck with python,
Sergio

On Nov 16, 2007 5:15 PM,  <[EMAIL PROTECTED]> wrote:
> Great, this is very helpful.  I'm new to Python, so hence the
> inefficient or nonsensical code!
>
> >
> > 2) I would suggest using countries.sort(...) or sorted(countries,...),
> > specifying cmp or key options too sort by region instead.
> >
>
> I don't understand how to do this.  The countries.sort() lists
> alphabetically and I tried to do a lambda x,y: cmp() type function,
> but it doesn't sort correctly.  Help with that?
>
> For martyw's example, I don't need to get any sort of population
> info.  I'm actually getting the number of various types of documents.
> So the entry is like this:
>
> Argentina   Food and Consumer Products  Food Additives  Color
> Additives   1
> Argentina   Food and Consumer Products  Food Additives  Flavors   
>   1
> Argentina   Food and Consumer Products  Food Additives
> General 6
> Argentina   Food and Consumer Products  Food Additives  labeling  
>   1
> Argentina   Food and Consumer Products  Food Additives  Prohibited
> Additives   1
> Argentina   Food and Consumer Products  Food ContactCellulose 
>   1
> Argentina   Food and Consumer Products  Food ContactFood
> Packaging   1
> Argentina   Food and Consumer Products  Food ContactPlastics  
>   4
> Argentina   Food and Consumer Products  Food Contact
> Waxes   1
> Belize
> etc...
>
> So I'll need to add up all the entries for Food Additives and Food
> contacts, the other info like Color Additives isn't important.
>
> So I will have an output like this
>   Food AdditivesFood Contact
> Argentina 107
> Belize
> etc...
>
> Thanks so much for the help!
> --
>
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-11-20 Thread Sergio Correia
Let's see:

> 1) Should I put my unittests in a subdirectory? Does the subdirectory
> have to be a package?

Sure, to avoid cluttering put the tests in a folder called 'tests'
(and any input the tests require, like mock files, output files used
to test if the output is correct, etc etc, should be put in that
folder or in a subfolder of 'tests'.

I like this setup:

myproject
../ package1
 ../../ tests
../../../ mock_files
../package2

and so on

If you want to be able to import the tests from python (say, 'from
myproject.tests import test_all'), then yes, you need to make the
tests folder a subpackage (just drop an empty __init__.py file)

> 2) Does the main folder /myproject have to be a package? Should I put
> my modules directly under /myproject, or should I create a subfolder,
> for example /myproject/modules

Of course... make /myproject a package. Now, if your modules are kinda
small you can just dump them in /myproject, but if what you are doing
is fairly complex, it's better to move each module to its own folder.

> Does anyone have any "best practices" as to how to manage your code?

I want 'best practices' too... anyone?

Sergio


PS: Casey, neat idea with the 'alltests.py'. Btw, I think relative
imports can be helpful:
http://www.python.org/dev/peps/pep-0328/#guido-s-decision
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Formatting question.

2007-11-20 Thread Sergio Correia
Hey Mike,
Welcome to Python!

About your first issue, just change the line
outfile.write( "'%s'," % (LoL[x][y]))
With
outfile.write( "'%s'," % (LoL[x][y][:-1]))

Why? Because when you do the line.split, you are including the '\n' at
the end, so a new line is created.

Now, what you are doing is not very pythonic (batteries are included
in python, so you could just use the CSV module). Also, the for x in
range(len(somelist)) is not recommended, you can just do something
like:


import csv

infile = open("mydata.txt", "rb")
outfile = open("out.txt", "wb")

reader = csv.reader(infile, delimiter='\t')
writer = csv.writer(outfile, quotechar=None, delimiter = "\\")

for row in reader:
data = "'" + "', '".join(row) + "'"
base = " ( Insert NBUSER.Grochamber Values %s, )"
writer.writerow([base % data])

infile.close()
outfile.close()

The above lines works like your program, writing exactly what you asked.
Again, all lists are iterable, you don't need to iterate an integer
from 1 to len(list). (isn't python wonderful?)

HTH,
Sergio


On Nov 20, 2007 6:11 PM, mike5160 <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> My input file looks like this : ( the data is separated by tabs )
>
> 11/26/2007  56.366  898.90  -10.086 23.11   1212.3
> 11/26/2007  52.25   897.6   -12.5   12.61.5
> 11/26/2007  52.25   897.6   -12.5   12.6133.5
>
> The output I'm trying to get is as follows :
>
>  ( Insert NBUSER.Grochamber Values
> '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', )
>  ( Insert NBUSER.Grochamber Values
> '11/26/2007','52.25','897.6','-12.5','12.6','1.5', )
>  ( Insert NBUSER.Grochamber Values
> '11/26/2007','52.25','897.6','-12.5','12.6','133.5', )
>
> The following is the program i have written so far :
>
>
> LoL = []
>
> for line in open('mydata.txt'):
> LoL.append(line.split("\t"))
>
> print "read from a file: ", LoL,
>
> outfile = open("out.dat", "w")
>
> lilength = len(LoL)
> liwidelength = len(LoL[1])
>
>
> print "length of list is " , lilength, "long"
> print "length of list is " , liwidelength, "long"
>
> for x in range(lilength):
> outfile.write(" ( ")
> outfile.write('Insert NBUSER.Grochamber Values ')
> for y in range(liwidelength):
> outfile.write( "'%s'," % (LoL[x][y]))
> outfile.write(" ) \n")
>
> outfile.close()
>
>
> I have 3 questions :
>
> 1. The formatting in the first line comes out wrong all the time. I m
> using windows python 2.5.1. The last part of the first line is always
> on the second line.
>
> 2. How do I avoid the "," symbol after the last entry in the line?
> (this are supposed to be sql-queries - importing excel based tabbed
> data to sql database)
>
> 3. What do I do when the data is missing? Like missing data?
>
> Thanks for all your help!
>
> Mike
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-11-20 Thread Sergio Correia
As a side note, I find much easier to drop a PTH file than messing
with pythonpath. If you are not familiar with PTH files, what I do is
this

1) Go to "C:\Program Files\Python25\Lib\site-packages" or whatever is
appropiate in your case.
2) Create a text file, name it something like "MyProjects.PTH" (note
the extension!)
3) in the file, just write the path of the folder that contains all
your projects (in my case, C:/docs/python)

The idea is to keep the main python installation separated from the
modules you are currently developing. Your python installation goes to
"program files/python" or "bin/python", and your personal projects go
somewhere else (usually inside your 'user' folder). This smooths many
things, like working with different versions of a package you are
developing.

On Nov 20, 2007 11:34 PM, Ben Finney <[EMAIL PROTECTED]> wrote:
> Jens <[EMAIL PROTECTED]> writes:
>
> > On 21 Nov., 04:16, Jens <[EMAIL PROTECTED]> wrote:
> > > On 21 Nov., 01:46, [EMAIL PROTECTED] wrote:
> > > dummy/
> > >   dummy_package/
> > > __init__.py
> > > moduleA.py
> > > tests/
> > >__init__.py
> > >test.py
>
> To avoid confusion, the directory that is the package should be named
> as you want the imports to appear; e.g. if you want to 'import
> foo.module_a', then name the directory containing 'module_a.py' as
> 'foo/'.
>
> This often results in::
>
> foo/
>   setup.py
>   foo/
> __init__.py
> module_a.py
>   test/
> __init__.py
> test_module_a.py
>
> That is, the *project* directory (containing all the files) is named
> 'foo/'; the *package* directory (where all the implementation code is
> found) is named 'foo/foo/', and the unit tests are found in the
> directory 'foo/test/'.
>
> That's normal, though if it confuses you you might want to rename the
> project directory. I'm often doing development on multiple
> version-control branches, so each project directory is named for the
> branch it contains; within each of those, the same 'foo/' name is used
> for the package directory.
>
> > > I'm using Python 2.5.1. When I'm trying to call a function in
> > > 'moduleA' from 'test' it won't work unless I make the 'dummy'
> > > folder a package as well. That's pretty weird. Does
> > > 'dummy_package' have to be in my pythonpath or something? How do I
> > > reference moduleA from test?
>
> You should install the package into a place where Python's import path
> will find it. Read up on using the standard library 'distutils'
> mechanism for this; it involves writing a 'setup.py' file to define
> the parameters for installation of your package.
>
> > > I would like to avoid making 'dummy' into a package as well.
>
> Yes. The top-level directory is used for containing a number of files,
> including 'setup.py', that should not be part of the installed
> package.
>
> > Problem solved. I added 'dummy' to the PYTHONPATH. (Do I really have
> > to do that for every project I create?) Anyway, it works the way I'd
> > like it to now.
>
> I hope the above makes it clearer what I prefer for this situation.
>
> --
>  \ "True greatness is measured by how much freedom you give to |
>   `\  others, not by how much you can coerce others to do what you |
> _o__) want."  --Larry Wall |
> Ben Finney
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function stopping a function

2007-11-22 Thread Sergio Correia
If you are talking about events and all that, I suppose you are using
(or should be using) threads.

Why don't try running the length_function as  a Thread that on every
loop checks a semaphore and if the condition is met, exits itself?
Kinda like this:
http://mail.python.org/pipermail/python-list/2006-January/362138.html

HTH, Sergio

PS: Note the "try..." in my reply. I've never done this, so I'm not
sure it's going to work. Wiser people in the list will probably give
you better replies.


On Nov 22, 2007 11:30 PM, Sorin Schwimmer <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> We all know that a function can launch the execution
> of another function. How can a function stop the
> execution of another function?
>
> For instance, lenghty_function() executes, when an
> external event triggers cancel(), which is supposed to
> abruptly stop lengthy_function(), reset some variables
> and exit immediately.
>
> Thanks for your advice
> SxN
>
>
>   
> 
> Be a better sports nut!  Let your teams follow you
> with Yahoo Mobile. Try it now.  
> http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert escaped HTML into a string?

2007-11-23 Thread Sergio Correia
This may help:

http://effbot.org/zone/re-sub.htm#strip-html

You should take care that there are several issues about going from html to txt

1)  What should wedo aboutthis?
You need to strip all tags..

2) ", &, <, and >... and I could keep going.. we need to
convert all those

3) we need to remove all whitespace.. tab, new lines, etc. (Maybe
breaks should be considered as new lines in the new text?)

The link above solve several of this issues, it can serve as a good
starting point.

Best,
Sergio


On Nov 24, 2007 12:42 AM, Just Another Victim of the Ambient Morality
<[EMAIL PROTECTED]> wrote:
> I've done a google search on this but, amazingly, I'm the first guy to
> ever need this!  Everyone else seems to need the reverse of this.  Actually,
> I did find some people who complained about this and rolled their own
> solution but I refuse to believe that Python doesn't have a built-in
> solution to what must be a very common problem.
> So, how do I convert HTML to plaintext?  Something like this:
>
>
> Thisisastring.
>
>
> ...into:
>
>
> This is a string.
>
>
> Actually, the ideal would be a function that takes an HTML string and
> convert it into a string that the HTML would correspond to.  For instance,
> converting:
>
>
> This &that
> or the other thing.
>
>
> ...into:
>
>
> This & that or the other thing.
>
>
> ...since HTML seems to convert any amount and type of whitespace into a
> single space (a bizarre design choice if I've ever seen one).
> Surely, Python can already do this, right?
> Thank you...
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-11-26 Thread Sergio Correia
Bluebird:

If you are using python 2.5, relative imports are no longer an issue:
http://docs.python.org/whatsnew/pep-328.html

That problem solved, what you sometimes want is to change the version
of your package. I just change the text in the PTH file, to point to
another version, and voilá (no need to move files around or to mess
with the code in the package itself). Probably you can write a script
that changes the PTH file from python itself.

Albert:

Thanks, that looks useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Show this file in explorer"

2007-12-01 Thread Sergio Correia
Although I'm a python fan; for that kind of stuff, I use autohotkey (
http://www.autohotkey.com/download/ )

Best,
Sergio

On Dec 1, 2007 3:30 AM, farsheed <[EMAIL PROTECTED]> wrote:
> I have a big problem. I have a list of files that my script find and
> list them in a little gui.
> I need this function:
>
> when i d-click on each item, I want explorer opens and selects that
> item inside windows explorer.
> like that beautiful buttom in iTunes.
>
> Thanks in advane.
>
> Farshid Ashouri.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping the semicolon?

2007-12-04 Thread Sergio Correia
On Dec 4, 2007 10:40 AM, Nick <[EMAIL PROTECTED]> wrote:


> Is this expected behavior?
>
> >>> s = '123;abc'
> >>> s.replace(';', '\;')
> '123\\;abc'
>

Everything is Ok. It's still a single backslash. Try:

>>> print  s.replace(';', '\;')

Or
>>> x = s.replace(';', '\;')
>>> print x

Best,
Sergio
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Timeout test hangs IDLE

2007-12-05 Thread Sergio Correia
I once made a small app that used threads on IDLE.

There was a strange error when using 'print' & threads. When what I printed
filled the entire screen, instead of moving all the text up, IDLE just
hanged. Try running your code from the shell instead, to see if the problem
is in IDLE.

HTH,
Sergio

On Dec 5, 2007 5:07 PM, <[EMAIL PROTECTED]> wrote:

> On Dec 5, 10:37 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote:
> > > > On Dec 5, 6:00 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote:
> > > > > I'm trying to integrate the timeout function from
> > > > herehttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/47
> > > > 3878into a
> > > > > long running automation script and the following code
> > > > causes IDLE after
> > > > > 20 or 30 iterations in countTest.
> >
> > > > > This is in 2.5, XP and there's no traceback.
> >
> > > > > Could someone point me at the user error?
> >
> > > > > Thanks in advance.
> >
> > > > > def countTest():
> > > > > for i in xrange(1000):
> > > > > print i
> > > > > return True
> >
> > > > > def timeout(func, args=(), kwargs={}, timeout_duration=1,
> > > > default=None):
> > > > > import threading
> > > > > class InterruptableThread(threading.Thread):
> > > > > def __init__(self):
> > > > > threading.Thread.__init__(self)
> > > > > self.result = None
> >
> > > > > def run(self):
> > > > > try:
> > > > > self.result = func(*args, **kwargs)
> > > > > except:
> > > > > self.result = default
> >
> > > > > it = InterruptableThread()
> > > > > it.start()
> > > > > it.join(timeout_duration)
> > > > > if it.isAlive():
> > > > > return default
> > > > > else:
> > > > > return it.result
> >
> > > > > def runTest():
> > > > > timeout(countTest, timeout_duration=5)
> >
> > > > > if __name__ == "__main__":
> > > > > runTest()
> >
> > > > I'm confused. What does it cause IDLE to do? I tried running the
> > > > script and it ran fine. I killed it 17346 since I have no
> > > intention of
> > > > letting it tie up my work for your extraordinary large iteration
> > > > number.
> >
> > > > I'm using Python 2.4 on Windows XP.
> >
> > > > Mike
> >
> > > Sorry, I need a better proof-reader.
> >
> > > When I run that code, the output gets to ~26 and then IDLE (or the
> > > shell, I'm not sure which) hangs and there's  zero CPU activity in the
> > > pythonw.exe process.
> >
> > Also, I should say that the the idea is that the huge iteration should
> > timeout after 5 seconds. I only gave it a 1000 range because I
> > didn't know how fast it would get through the loop. Perhaps you stopped
> > it before the timeout triggered?
> >
> > Cheers,
> >
> > Drea
>
> No...I ran it for at least 30-60 seconds. Making a thread stop on
> command is a pain though.
>
> This link taught me one way to do it, but I cannot vouch how will it
> works as I've never aborted any of my threads:
>
> http://wiki.wxpython.org/LongRunningTasks
>
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Job Offer: Python Ninja or Pirate!

2007-12-10 Thread Sergio Correia
> import sys, xml, urllib
>
> dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num in
> set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for city in
> ((xml.dom.minidom.parseString(urllib.urlopen('
> http://api.etsy.com/feeds/xml_user_details.php?id='
> + str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda
> t: (setattr(t, 'data', 'no city'),
> t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace('  ', ' ') for id
> in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])]
>


Is that python or perl?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why this apparent assymetry in set operations?

2008-01-15 Thread Sergio Correia
Both of you are correct.

>>> x = set([1,2,3])
>>> y = set([4,5])
>>> x |= y
>>> x
set([1, 2, 3, 4, 5])


On Jan 15, 2008 11:07 AM, Skip Montanaro <[EMAIL PROTECTED]> wrote:
> > > Why is that?  Doesn't the |= operator essentially map to an update() call?
> >
> > No, according to 3.7 Set Types, s | t maps to s.union(t).
>
> I was asking about the |= assignment operator which according to the
> docs *does* map to the update method.
>
> Skip
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I don't understand what is happening in this threading code

2008-01-18 Thread Sergio Correia
This is what's happening:

 1) The chef thread releases the sema
 2) While the chef thread is saying "Andiamo", decreasing "i", and
ending the while loop, the waiter thread SERVES the dish and RUNS to
reacquire the lock
 3) Back in the main loop, chef.join() is run, and then the waiter's
variable is changed.

But it's already too late. The waiter is already locked. He'll wait
and wait forever for another dish, which will never come. So you will
have to kill him. All for a race condition.

---
I've just read Carl's post (just b4 hitting submit).

I agree with him, rewrite the logic. IMO, the objects should be the
key, THEY are the ones that should be joined. You should run the chef
and waiter as daemons, and just do something like

orders.join()
dishes.join()

And when the chefs finishes with the orders and the waiter finishes
serving them, the program ends.

HTH,
Sergio


On Jan 18, 2008 7:43 PM, Matthew Wilson <[EMAIL PROTECTED]> wrote:
> In this code, I tried to kill my thread object by setting a variable on it
> to False.
>
> Inside the run method of my thread object, it checks a different
> variable.
>
> I've already rewritten this code to use semaphores, but I'm just curious
> what is going on.
>
> Here's the code:
>
> import logging, threading, time
> logging.basicConfig(level=logging.DEBUG,
> format="%(threadName)s: %(message)s")
>
> class Waiter(threading.Thread):
> def __init__(self, hot_food):
> super(Waiter, self).__init__()
> self.should_keep_running = True
> self.hot_food = hot_food
>
> def run(self):
> while self.should_keep_running:
> logging.debug("Inside run, the id of should_keep_running is %s."
>   % id(self.should_keep_running))
> self.hot_food.acquire()
>
> def cook_food(hot_food):
> i = 5
> while i >= 0:
> logging.debug("I am cooking food...")
> time.sleep(1)
> hot_food.release()
> logging.debug("Andiamo!")
> i -= 1
>
> def main():
>
> hot_food = threading.Semaphore(value=0)
>
> chef = threading.Thread(name="chef", target=cook_food, args=(hot_food, ))
> chef.start()
>
> w = Waiter(hot_food)
> logging.debug("Initially, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
> w.start()
> logging.debug("After start, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
>
> # Wait for the chef to finish work.
> chef.join()
>
> # Now try to kill off the waiter by setting a variable inside the waiter.
> w.should_keep_running = False
> logging.debug("Now, the id of w.should_keep_running is %s."
>   % id(w.should_keep_running))
>
> if __name__ == "__main__":
> main()
>
> And here's what I get when I execute it.  I have to suspend the process
> with CTRL=Z and then kill -9 it.
>
> $ python foo.py
> MainThread: Initially, the id of w.should_keep_running is 135527852.
> MainThread: After start, the id of w.should_keep_running is 135527852.
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> chef: I am cooking food...
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> chef: Andiamo!
> Thread-1: Inside run, the id of should_keep_running is 135527852.
> MainThread: Now, the id of w.should_keep_running is 135527840.
>
> [1]+  Stopped python foo.py
>
> $ kill -9 %1
>
> [1]+  Stopped python foo.py
>
> The memory address of should_keep_running seems to change when I set it
> from True to False, and inside the run method, I keep checking the old
> location.
>
> I am totally baffled what this means.
>
> Like I said earlier, I already rewrote this code to use semaphores, but
> I just want to know what is going on here.
>
> Any explanation is welcome.
>
> TIA
>
> Matt
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

2008-01-30 Thread Sergio Correia
is this some kind of joke?
if you get no answers, then the answer is no

On Jan 30, 2008 7:40 PM, Blubaugh, David A. <[EMAIL PROTECTED]> wrote:
> I do not understand why no one has answered the following question:
>
> Has anybody worked with Gene Expression Programming
>
>
> David Blubaugh
>
>
>
>
>
>
>
>
> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED] On Behalf
> Of [EMAIL PROTECTED]
> Sent: Wednesday, January 30, 2008 6:10 PM
> To: python-list@python.org
> Subject: Python-list Digest, Vol 52, Issue 437
>
> Send Python-list mailing list submissions to
> python-list@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> http://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
> [EMAIL PROTECTED]
>
> You can reach the person managing the list at
> [EMAIL PROTECTED]
>
> When replying, please edit your Subject line so it is more specific than
> "Re: Contents of Python-list digest..."
>
> This e-mail transmission contains information that is confidential and may be 
> privileged.   It is intended only for the addressee(s) named above. If you 
> receive this e-mail in error, please do not read, copy or disseminate it in 
> any manner. If you are not the intended recipient, any disclosure, copying, 
> distribution or use of the contents of this information is prohibited. Please 
> reply to the message immediately by informing the sender that the message was 
> misdirected. After replying, please erase it from your computer system. Your 
> assistance in correcting this error is appreciated.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Has Anyone Worked with Gene Expression Programming ???????????????????????????

2008-01-30 Thread Sergio Correia
Try contacting "Ryan O'Neil ryanjoneil at gmail.com". He is the author
of pygep http://code.google.com/p/pygep/ , and is probably working
here: http://www.gepsoft.com/

If you don't get an answer, it means that THEY found him first.
This message will self destruct in ... range(3, 0, -1) ...

On Jan 22, 2008 10:53 AM, Blubaugh, David A. <[EMAIL PROTECTED]> wrote:
>
>
>
> To Anyone,
>
>
>
> Has anyone worked with Gene Expression Programming???  Specifically, has
> anyone out there worked with pygep software package???  I have a few
> questions
>
>
> David Blubaugh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing Pubic Hair Methods

2008-01-30 Thread Sergio Correia
So in this case it is REALLY better to ask for permission rather than
forgiveness?

On Jan 30, 2008 10:30 PM, Ben Finney <[EMAIL PROTECTED]> wrote:
> MRAB <[EMAIL PROTECTED]> writes:
>
> > On Jan 31, 12:57 am, Asun Friere <[EMAIL PROTECTED]> wrote:
> > > Ouch!! If on the other hand 'females' is populated by instances of
> > > (or merely includes instances of) class 'Human', I suggest you
> > > test for female.consent somewhere in your code!
> > >
> > The Pythonic approach would be to try the action and catch a
> > NoConsentException.
>
> You're making the classic Pythonista mistake: you behave as though
> EAFP applies everywhere. I assure you, in the above situation, it does
> not apply.
>
> --
>  \ "He may look like an idiot and talk like an idiot but don't let |
>   `\  that fool you. He really is an idiot." —Groucho Marx |
> _o__)  |
> Ben Finney
> --
>
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: small problem with re.sub

2008-01-30 Thread Sergio Correia
See this:
http://www.regular-expressions.info/python.html
(the Search and Replace part)

You are referring to the group as "(?P=id)", when you should be using
r"\g".

HTH,
Sergio


On Jan 30, 2008 10:01 PM, Astan Chee <[EMAIL PROTECTED]> wrote:
> Hi,
> I have a html text stored as a string. Now I want to go through this
> string and find all 6 digit numbers and make links from them.
> Im using re.sub and for some reason its not picking up the previously
> matched condition. Am I doing something wrong? This is what my code
> looks like:
> htmlStr = re.sub('(?P\d{6})',' href=\"http://linky.com/(?P=id).html\">(?P=id)',htmlStr)
> It seems that it replaces it alright, but it replaces it literally. Am I
> not escaping certain characters?
> Thanks again for the help.
> Cheers
>
> Animal Logic
> http://www.animallogic.com
>
> Please think of the environment before printing this email.
>
> This email and any attachments may be confidential and/or privileged. If you 
> are not the intended recipient of this email, you must not disclose or use 
> the information contained in it. Please notify the sender immediately and 
> delete this document if you have received it in error. We do not guarantee 
> this email is error or virus free.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-19 Thread Sergio Correia
I don't get this thread. At all. I want my 15 minutes back.

(OTOH, some of your replies were quite funny or interesting, including
- as usual - Gabriel and Steve's)

On Feb 19, 2008 11:29 PM, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-02-19, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > What is a a homile?
>
> It's a misspelling of homily. :)
>
> --
> Grant Edwards   grante Yow!  It's hard being
>   at   an ARTIST!!
>visi.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Financial Modeling with Python by Shayne Fletcher, Christopher Gardner

2008-04-22 Thread Sergio Correia
Searched on google and couldn't find anything :S

On Mon, Apr 21, 2008 at 11:28 AM,  <[EMAIL PROTECTED]> wrote:
> Just saw at amazon.com reference to the following book that might be
>  available later this year:
>
>  Financial Modeling with Python [IMPORT] (Hardcover)
>  by Shayne Fletcher (Author), Christopher Gardner (Author)
>
>  Availability: Sign up to be notified when this item becomes available.
>
>  Product Details
>
> * Hardcover: 352 pages
> * Publisher: John Wiley and Sons Ltd (November 10, 2008)
> * ISBN-10: 0470987847
> * ISBN-13: 978-0470987841
> * Shipping Weight: 1.7 pounds
>
>  Would be nice if the authors or publisher could post to this group an
>  outline or draft table of contents of the book.
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Python declarative

2014-01-15 Thread Sergio Tortosa Benedito
Hi I'm developing a sort of language extension for writing GUI programs
called guilang, right now it's written in Lua but I'm considreing Python
instead (because it's more tailored to alone applications). My question
it's if I can achieve this declarative-thing in python. Here's an
example:

Window "myWindow" {
title="Hello world";
Button "myButton" {
label="I'm a button";
onClick=exit
}
}
print(myWindow.myButton.label)

Of course it doesn't need to be 100% equal. Thanks in advance

Sergio


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


Re: Want to learn Python

2007-06-15 Thread Sergio Monteiro Basto
On Fri, 2007-06-15 at 11:41 +, Amol wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all
> 
Books : 
Learning Python 2nd Edition (ISBN 0-596-00281-5) or above
Python in a nutshell (I guess).
both O'Reilly (r) 
-- 
Sérgio M. B.


smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list

HTMLParser.HTMLParseError: EOF in middle of construct

2007-06-18 Thread Sergio Monteiro Basto
Hi,
Can someone explain me, what is wrong with this site ?

python linkExtractor3.py http://www.noticiasdeaveiro.pt > test

HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173,
column 1

at line 1173 of test file is perfectly normal .

I like to know what I have to clean up before parse the html page 
I send in attach the python code .

thanks in advance 
-- 
Sérgio M. B.
import urllib
import urlparse
import re
from HTMLParser import HTMLParser, HTMLParseError

class ParserExtractor(HTMLParser):
def __init__(self, base, content):
HTMLParser.__init__(self)

self.__content  = content

self.__base  = base
self.__links = []

def links(self):
self.feed(self.__content)
self.close()
return self.__links

def handle_starttag(self, tag, attr):
attr = dict(attr)

if 'a' == tag:
self.start_a(attr)
if 'base' == tag:
self.start_base(attr)

def start_a(self, attr):
l = attr.get('href')
if l:
self.__links.append( urlparse.urljoin(self.__base, l) )

def start_base(self, attr):
l = attr.get('href')
if l:
self.__base = l

def getLinks(url):
content = None
base = url
content = urllib.urlopen(url).read(-1)
# clean scripts and comments
p = re.compile('',re.S|re.I)
content = p.sub('', content)
p = re.compile('',re.S)
content = p.sub('', content)
print content

links = []
parser = ParserExtractor(url, content)
links  = parser.links()

return links

if __name__ == '__main__':
from sys import argv

for l in getLinks(argv[1]):
print l


smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: csv search and print

2007-06-18 Thread Sergio Monteiro Basto
On Mon, 2007-06-18 at 13:11 -0700, John Machin wrote: 
> On Jun 19, 4:12 am, [EMAIL PROTECTED] wrote:
> > I have a csv file containing lot of rows & columns. I wanted to search thru 
> > the
> > heading for each column for a string and then print all the headings and the
> > corresponding rows if a match is found.
> >
> > Any advise?

you can put cvs in a MySql DB
mysql -e 'CREATE TABLE table2(col1 VARCHAR(255), col2 VARCHAR(255), col3
VARCHAR(255), col4 VARCHAR(255), col5 VARCHAR(255), col6 VARCHAR(255),
col7 VARCHAR(255), col8 VARCHAR(255), col9 VARCHAR(255), col10
VARCHAR(255), col11 VARCHAR(255), col12 VARCHAR(255), col13
VARCHAR(255), col14 VARCHAR(255))' table2

in mysql:
load data infile '/home/sergio/pesquisa/table2.txt' into table table2
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

and work with python and mysql 
http://dustman.net/andy/python/python-and-mysql

> 
> 1. Clarify your requirements: "corresponding rows" ... corresponding
> to what? How many rows/columns is a "lot"? "I have a csv file" ...
> only one? "search thru the heading for each column for a string" is
> open to misinterpretation of various kinds :-)
> 2. Write your script.
> 3. Ask a specific question if you have a problem.
> 
-- 
Sérgio M. B.


smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Sqlite format string

2009-08-29 Thread Sergio Charpinel Jr.
Hi,
I have this statement cursor.execute("SELECT * from session_attribute WHERE
sid=%s", ( user ))
and I'm receiving this error :

TypeError: not all arguments converted during string formatting

What is wrong ?
-- 
Sergio Roberto Charpinel Jr.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sqlite format string

2009-08-30 Thread Sergio Charpinel Jr.
Thank you very much.

2009/8/30 Cameron Simpson 

> On 29Aug2009 17:27, Sergio Charpinel Jr. 
> wrote:
> | Hi,
> | I have this statement cursor.execute("SELECT * from session_attribute
> WHERE
> | sid=%s", ( user ))
> | and I'm receiving this error :
> |
> | TypeError: not all arguments converted during string formatting
> |
> | What is wrong ?
>
> This:
>
>  ( user )
>
> is not a tuple containing the element user. It's just user.
>
> This:
>
>  ( user, )
>
> is what you want.
> --
> Cameron Simpson  DoD#743
> http://www.cskk.ezoshosting.com/cs/
>
> [Alain] had been looking at his dashboard, and had not seen me, so I
> ran into him. - Jean Alesi on his qualifying prang at Imola '93
>



-- 
Sergio Roberto Charpinel Jr.
-- 
http://mail.python.org/mailman/listinfo/python-list