Re: [ANN] IPython 0.13 is officially out!

2012-07-01 Thread Leo
On 2012-07-01 01:55 +0800, Fernando Perez wrote:
> - ~6 months of work.
> - 373 pull requests merged.
> - 742 issues closed (non-pull requests).
> - contributions from 62 authors.
> - 1760 commits.
> - a diff of 114226 lines.

Thank you for the hard work.

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


webbrowser.open always opens up Safari on Lion

2012-02-25 Thread Leo
Hello,

On Lion and with its stock python version 2.7.1 r271:86832,
webbrowser.open('file://localhost/nonexistingfile') always opens up
Safari. Is this a bug?

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


Re: webbrowser.open always opens up Safari on Lion

2012-02-25 Thread Leo
On 2012-02-26 11:36 +0800, Steven D'Aprano wrote:
> What part of this do you think is the bug, and why? What part of the 
> behaviour actually experienced contradicts the documented behaviour of 
> webbrowser.open()?
>
> http://docs.python.org/library/webbrowser.html

If you have the default browser set to Chrome, it still opens up Safari.

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


Re: webbrowser.open always opens up Safari on Lion

2012-02-25 Thread Leo
On 2012-02-26 15:04 +0800, Cameron Simpson wrote:
> On the suppostion that "the default browser" is actually multiple
> settings, one for each of several URL (URI?) schemes, what do these two
> shell commands do for you? From a shell prompt in a Terminal:
>
>   open file://localhost/nonexistingfile
> and 
>   open http://www.python.org/
>
> Do they both open Chome for you?

The first one prints: The file /nonexistingfile does not exist.
No browser is opened.

The second one opened Chrome.

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


Algorithm of ordering in Python using recursion

2017-09-13 Thread Leo
Can anyone help me find the error of this implementation in Python what am I 
doing with this TBiS algorithm?

Algorithm:

Function b = TBiSort(a, n, k, dir)
if n == 1 then
b = a;
else 
h1 = TBiSort(a(1:n/2), n/2, k, dir);
h2 = TBiSort(a(n/2+1:n),n/2,k, -dir);
b = TBiMerge( [h1,h2], n, k, dir)


Function b = TBiMerge(hh, n, k, dir)
[hmin, hmax] = minmax(hh(1:n/2),hh(1+n/2:n));
bmin= TBiMerge(hmin, n2, k, dir);
if n == 2k then
b = bmin;
else
bmax = TBiMerge(hmax, n/2, k, dir);
if dir == 'up'
then
b = [bmin,bmax];
else
b = [bmax,bmin];


For conceptual clarity we present the algorithm in recursion fashion. Wecomment 
on the truncation. The TBiSort recursion goes downward first portioning the 
initial data list a all the way to the base level (sublist length 1), then goes 
upward with monotonic merges. In TBiMerge, the min max function renders the 
minimal and maximal between each element pair on the two input lists. The 
truncation begins at, and continues from, the point where the monotonic 
sublists reach in size to k. At each merge step, bmax, the upper part of the 
merged list is purged, and the total data is reduce d by half. By TBiMerge, the 
merged sublists never exceed k in size. 

Implementation:

def TBiSort(a, n, k, direction):
if n == 1:
b = a
else:
h1 = TBiSort(a[0:n/2], n/2, k, direction)
h2 = TBiSort(a[n/2:n], n/2, k, -direction)
print h1
print h2
b = TBiMerge(h1 + h2, n, k, direction)
return b

def TBiMerge(hh, n, k, direction):
p1 = [ min(hh[0:n/2]), max(hh[0:n/2]) ]
print p1
p2 = [ min(hh[n/2:n+1]), max(hh[n/2:n+1]) ]
print p2
bmin = TBiMerge(p1, n/2, k, direction)
if n == 2 * k:
b = bmin
else:
bmax = TBiMerge(p2, n/2, k, direction)
if direction == 1:
b = bmin + bmax
else:
b = bmax + bmin
return b

a = [3,7,4,8,6,2,1,5]
k = 4
direction = 1
teste = TBiSort(a, len(a), k, direction)

print teste

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


Re: mapLast, mapFirst, and just general iterator questions

2022-06-20 Thread Leo
On Wed, 15 Jun 2022 04:47:31 +1000, Chris Angelico wrote:

> Don't bother with a main() function unless you actually need to be
> able to use it as a function. Most of the time, it's simplest to
> just have the code you want, right there in the file. :) Python
> isn't C or Java, and code doesn't have to get wrapped up in
> functions in order to exist.

Actually a main() function in Python is pretty useful, because Python
code on the top level executes a lot slower. I believe this is due to
global variable lookups instead of local.

Here is benchmark output from a small test.

```
Benchmark 1: python3 test1.py
  Time (mean ± σ): 662.0 ms ±  44.7 ms
  Range (min … max):   569.4 ms … 754.1 ms
 
Benchmark 2: python3 test2.py
  Time (mean ± σ): 432.1 ms ±  14.4 ms
  Range (min … max):   411.4 ms … 455.1 ms
 
Summary
  'python3 test2.py' ran
1.53 ± 0.12 times faster than 'python3 test1.py'
```

Contents of test1.py:

```
l1 = list(range(5_000_000))
l2 = []

while l1:
l2.append(l1.pop())

print(len(l1), len(l2))
```

Contents of test2.py:

```
def main():
l1 = list(range(5_000_000))
l2 = []

while l1:
l2.append(l1.pop())

print(len(l1), len(l2))
main()
```

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


Re: How would one scrap property listing website like this?

2022-09-23 Thread Leo
On Thu, 22 Sep 2022 09:36:47 -0700 (PDT), tripd...@gmail.com wrote:

> https://nigeriapropertycentre.com/
> Has anyone scrap something like this before?
> probably i should try power bi first to see if it can?

You can try something like this.

import urllib.request
from bs4 import BeautifulSoup

URL = "https://nigeriapropertycentre.com/for-rent/lagos";
UA = "Mozilla/5.0 (X11; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/
105.0"

def fetch_url(url):
headers = {"User-Agent": UA}
req = urllib.request.Request(url, headers={"User-Agent": UA})
resp = urllib.request.urlopen(req)
return resp.read().decode("utf-8")

html = fetch_url(URL)
soup = BeautifulSoup(html, "html.parser")

for item in soup.find_all(itemtype="https://schema.org/ListItem";):
row = {}
row["name"] = item.find(itemprop="name").text
row["url"] = item.find(itemprop="url").get("href", "")
row["image"] = item.find(itemprop="image").get("src", "")
row["content-title"] = item.find(class_="content-title").text
row["address"] = item.find("address").text.strip()
row["description"] = item.find(itemprop="description").text.strip()
row["added-on"] = item.find("span", class_="added-on").text.strip()
row["price"] = item.find("span", class_="price").parent.text.strip()

row["aux"] = []

for li in item.find("ul", class_="aux-info").find_all("li"):
row["aux"].append(li.text.strip())

print(row)
-- 
https://mail.python.org/mailman/listinfo/python-list


Exception raising, and performance implications.

2005-10-03 Thread leo
Hello all -

I was wondering about the performance implications of explicitly
raising exceptions to get information about the current frame.
Something like what the inspect module does, with:

---
def currentframe():
"""Return the frame object for the caller's stack frame."""
try:
raise 'catch me'
except:
return sys.exc_traceback.tb_frame.f_back
---

I come from a java background, where Exceptions are a big Avoid Me, but
are the performance implications the same in Python? We're expecting a
big load on our app (100,000 users/hour) , so we'd like to be as tuned
as possible.

Thanks,
leo

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


Re: Exception raising, and performance implications.

2005-10-04 Thread leo
> However, I think the functionality you're asking for is available as
> inspect.currentframe(), and if the implementation is in "C" it may have a tiny
> performance advantage over the Python version.

You're absolutely right, in fact the code snippet from my OP was taken
directly from inspect.currentframe. We're intending on using this in
production, and I'm trying to gauge what the implications may be.

> Python uses exceptions internally, using StopIteration to terminate the
> iterator in a for: loop.

Wow, I was unaware of this. If Python internally uses exceptions, maybe
they aren't as detrimental as I thought.

That said, I will be judiciously profiling my code and measuring as
much as possible, I just wanted to throw this question out to the NG in
case anyone had done this before (and so I can put off learning the
profiler a little bit longer :) )

Thanks all for the replies.

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


interpreter frame

2005-08-10 Thread Leo
Why is it not possible to get the frame from the interpreter using the
inspect library? IOW, why does this code:

>>> from inspect import *
>>> stack()

produce:

[(, '', 1, '?', None, None)]

instead of:

[(, '', 1, '?', '\tstack()', 0)]

?

I must be missing something. The motivating question is:

How can I get the interpreter line that triggered the current actions?

TIA,
Leo.

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


Re: interpreter frame

2005-08-10 Thread Leo
Good try, but that doesn't seem to work either. Maybe I should have
emphasized that what I really want is the line of code, as opposed to
the entire frame. Here is the output of sys._getframe() on my system:

Python 2.3.4 (#1, Feb  2 2005, 12:11:53)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._getframe()

>>> from inspect import *
>>> getframeinfo(sys._getframe())
('', 1, '?', None, None)

Is it different in 2.4? Maybe there is something else in sys.* that I
am having trouble finding?

TIA,
Leo.

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


command history behavior in windows and linux

2005-08-29 Thread Leo
Does someone know if there is a setting in the python Unix world to
make the command history behave as it does in the Windows intepreter?
Specifically, I like the fact that the command history remembers which
of a sequence of commands is the one that I last issued. For example,
suppose that I typed the following lines into the interpreter:

import foo
for e in foo.container:
   print e

In Unix, I would have to tap up arrow 3 times for each line:

up up up gives me "import foo". I press enter.
up up up gives me "for...". I press enter.
up up up gives me "   print...". I press enter.

In Windows, I get this behavior I like better:

up up up gives me "import foo". I press enter.
down gives me "for...". I press enter.
down gives me "   print...". I press enter.

How do I get the second behavior to take place in all the platforms I
use? Also, the windows version remembers my commands across sections.
How do I enable that in the python version?

I tried editing the inputrc file that controls the readline library by
adding the following lines:

$if python
set history-preserve-point on
$endif

but this did not seem to work.

TIA,
Leo.

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


Python Requests script to login to a phpbb forum

2014-02-19 Thread Leo

Hi there,

I have decided to jump in at the deep end to try and learn python. I 
have been able to get requests to pull the login page off the server 
and I think send the login request. I don't get logged in though. 
Please let me know if I would be better off asking in a phpBB related 
group or forum.


Here is my code without username and password included:
import requests

payload = {'username': 'username', 'password': 'password'}
r = 
requests.post("http://www.tt-forums.net/ucp.php?mode=login",data=payload)

sidStart = r.text.find("sid")+4
sid = r.text[sidStart:sidStart+32]
parameters = {'mode': 'login', 'sid': sid}
r = 
requests.post("http://www.tt-forums.net/ucp.php",params=parameters,data=payload)

if "Logout" in r.text: print("We are in")

Thank you

--
ClassicVB Users Regroup! comp.lang.basic.visual.misc
Free usenet access at http://www.eternal-september.org


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


python compile code object -- reverse how to

2006-07-19 Thread leo
Hi,
following is the python scripts:
import marshal
script = """
print 'hello'
"""
code = compile(script, "

Re: python compile code object -- reverse how to

2006-07-19 Thread leo
Hi, all,
i mean to convert
'c\000\000\000\000\001\000\000\000s\017\000\000\00
> 0\177\000\000\177\002\000d\000\000GHd\001\000S(\00
> 2\000\000\000s\005\000\000\000helloN(\000\000\000\
> 000(\000\000\000\000s\010\000\000\000

doctest + swig example

2006-07-26 Thread Leo
Could someone please spare a .i file with an example doctest that
works? I tried as follows and it fails:

1) I have an osi.i file that generates osi.py and _osi.so. At the very
end I added:
...
%pythoncode %{
def _test():
import doctest
doctest.testfile('testOsi.txt')

if __name__ == "__main__":
_test()
%}
---

2) I have a testOsi.txt file, whose contents are taken from the output
that works on the terminal, plus some docstring stuff:
...
>>> import osi
>>> cbc = osi.OsiCbcSolverInterface()
>>> cbc.readMps('stein15.mps') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Coin0001I At line 15 NAME  STEIN15 ...
Coin0008I STEIN15 read with 0 errors
0
...


but the result I get is:
**
File "testOsi.txt", line 15, in testOsi.txt
Failed example:
cbc.readMps('stein15.mps') # doctest: +ELLIPSIS,
+NORMALIZE_WHITESPACE
Exception raised:
Traceback (most recent call last):
  File "/usr/lib/python2.4/doctest.py", line 1243, in __run
compileflags, 1) in test.globs
  File "", line 1, in ?
cbc.readMps('stein15.mps') # doctest: +ELLIPSIS,
+NORMALIZE_WHITESPACE
  File "/home/leolopes/research/poams/code/swimpy/osi.py", line
144, in readMps
def readMps(*args): return
_osi.OsiCbcSolverInterface_readMps(*args)
NotImplementedError: No matching function for overloaded
'OsiCbcSolverInterface_readMps'
**

Thanks!
Leo.

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


what is the data from loads()

2006-08-24 Thread leo
Hi,

Following is the python scripts:



import marshal

exec(marshal.loads('c\000\000\000\000\001\000\000\000s\017\000\000\000\177\000\000\177\002\000d\000\000GHd\001\000S(\002\000\000\000s\005\000\000\000helloN(\000\000\000\000(\000\000\000\000s\010\000\000\000

marshal and unmarshal

2006-08-26 Thread leo
Hi,
following is marshal and unmarshal script

import marshal
strng = """
print 'hello world'
"""
code = compile(strng, "", "exec")
data = marshal.dumps(code)
strng0 = marshal.loads(data)
print repr(data)
print "-"*100
print strng0

###Result:
'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello
 
worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00'

", line 2>

Question:
1.  why  unmarshal data is
 ", line 2>
 not
'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello
 
worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00'

2.  how safe is the compiled and serialize data.
'c\x00\x00\x00\x00\x01\x00\x00\x00s\x0f\x00\x00\x00\x7f\x00\x00\x7f\x02\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00s\x0b\x00\x00\x00hello
 
worldN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00s\x01\x00\x00\x00?\x02\x00s\x00\x00\x00\x00'
 


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


Re: and [True,True] --> [True, True]?????

2009-04-23 Thread Leo
Steven D'Aprano wrote:

> On Mon, 20 Apr 2009 15:13:15 -0500, Grant Edwards wrote:
> 
> 
>> I fail to see the difference between "length greater than 0" and "list
>> is not empty".  They are, by definition, the same thing, aren't they?
> 
> For built-in lists, but not necessarily for arbitrary list-like sequences.
> 
> There's also the performance issue. I might have a sequence-like
> structure where calling len() takes O(N**2) time, (say, a graph) but
> calling __nozero__ might be O(1). Why defeat the class designer's
> optimizations?
Is that true?
Calling len() actually traverses the whole list?
> 
> 


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


python shell crashing on paste

2010-02-23 Thread Leo
I just upgraded to Windows 7 (yes, I know) and I've been having a
really strange problem with running python (2.6.4, installed from the
python.org installer) from the command line.

If I open the interpreter, and then paste in a long string,
conhost.exe crashes. This doesn't happen when pasting the string just
in the command line so its something with the python interpreter.

Here's the details of the windows crash:

Log Name:  Application
Source:Application Error
Event ID:  1000
Task Category: (100)
Level: Error
Keywords:  Classic
Description:
Faulting application name: conhost.exe, version: 6.1.7600.16385, time
stamp: 0x4a5bc271
Faulting module name: conhost.exe, version: 6.1.7600.16385, time
stamp: 0x4a5bc271
Exception code: 0xc005
Fault offset: 0x48ca
Faulting process id: 0x1aa8
Faulting application start time: 0x01cab4e450b97766
Faulting application path: C:\Windows\system32\conhost.exe
Faulting module path: C:\Windows\system32\conhost.exe
Report Id: 9c6afd6c-20d7-11df-bbd8-e390d387a902

Has anyone else seen anything like this? Any suggestions on how to
even start figuring this out?

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


Re: python shell crashing on paste

2010-03-01 Thread Leo
Thanks for responding Michel. It looks like its an issue with
pyreadline - http://ipython.scipy.org/moin/PyReadline/Intro - causing
the crash. I'm working with the author of it on trying to get the
issue figured out.

It's not related to UAC.

--
--Leo

On Feb 23, 10:41 pm, "Michel Claveau -
MVP" wrote:
> Hi!
>
> Where (directory) are you, when the problem come?
> Have you try with UAC disabled?
>
> @+
> --  
> MCI

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


Re: Convert '165.0' to int

2011-07-21 Thread Leo Jay
On Thu, Jul 21, 2011 at 5:31 PM, Frank Millman  wrote:
>
> Hi all
>
> I want to convert '165.0' to an integer.
>
> The obvious method does not work -
>
>>>> x = '165.0'
>>>> int(x)
>
> Traceback (most recent call last):
>  File "", line 1, in 
> ValueError: invalid literal for int() with base 10: '165.0'
>
> If I convert to a float first, it does work -
>
>>>> int(float(x))
>
> 165
>>>>
>
> Is there a short cut, or must I do this every time (I have lots of them!) ? I 
> know I can write a function to do this, but is there anything built-in?
>
> Thanks
>
> Frank Millman
>

How about int(x[:-2])?

--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error 0*80070570

2016-04-21 Thread Allan Leo
When running the  setup for your 3.5.1(32-bit version), the setup
experiences error 0*80070570 and tells me to check the log file. What could
be the problem and whats the solution.
On Apr 21, 2016 7:05 AM, "Allan Leo"  wrote:

> When running the setup for your 3.5.1(32-bit version) the setup
> experiences  error 0*80070570 and tells me to checkout the log file. What
> could be the problem and whats the resolution.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Re: Error 0*80070570

2016-04-21 Thread Allan Leo
I need help with this setup error.
-- Forwarded message --
From: "Allan Leo" 
Date: Apr 21, 2016 10:06 AM
Subject: Re: Error 0*80070570
To: 
Cc:

When running the  setup for your 3.5.1(32-bit version), the setup
experiences error 0*80070570 and tells me to check the log file. What could
be the problem and whats the solution.
On Apr 21, 2016 7:05 AM, "Allan Leo"  wrote:

> When running the setup for your 3.5.1(32-bit version) the setup
> experiences  error 0*80070570 and tells me to checkout the log file. What
> could be the problem and whats the resolution.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Learn Python + Swift 3 by creating a comprehensive system with web app and iOS app

2016-07-05 Thread Leo Trieu
Guys, we're from Code4Startup team and we're running a KickStarter campaign for 
the next awesome course to bring best value to Python and Swift community.

In this course, you will learn how to use Python and Swift 3 by cloning cool 
startup apps like UberEats, Doordash or Postmates.

In case you're interested and want to learn more, check it out here: 
http://kck.st/29NjAtR

Feel free to comment here with any questions.

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


Just starting to learn Python, and encounter a problem

2016-07-22 Thread Zagyen Leo
yeah, it may be quite simple to you experts, but hard to me.

In one of exercises from the Tutorial it said: "Write a program that asks the 
user their name, if they enter your name say "That is a nice name", if they 
enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), 
otherwise tell them "You have a nice name."

And i write so:

name = input("Enter your name here: ")
if name == "John Cleese" or "Michael Palin":
print("Sounds like a gentleman.")
else:
print("You have a nice name.")

But strangely whatever I type in (e.g. Santa Claus), it always say "Sounds like 
a gentleman.", not the result I want.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread Zagyen Leo
I got it! Thank you.

Hope in one day I could help other newbies as you do.
-- 
https://mail.python.org/mailman/listinfo/python-list


How to decompile an exe file compiled by py2exe?

2005-09-23 Thread Leo Jay
Dear All,

I lost my source code because of my incaution.
so anyone can tell me how to decompile the exe file compiled by py2exe?

Thanks.

--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to decompile an exe file compiled by py2exe?

2005-09-24 Thread Leo Jay
Thanks for all of your replies.

but my problem is not how to decompile .pyo or .pyc files.

i used py2exe to compile my source file `hjparser.py' into
`hjparser.exe' and other files. but i deleted the `hjparser.py' file
by misoperation.(of cause, i tried to recover, but failed)

I opened the `hjparser.exe' file in UltraEdit(a hex editor), and found
some partial statements and comments but not complete.

so, my problem is i'm sure that the source code is in `hjparser.exe'
but i don't know how to decompile the executable file `hjparser.exe'
into `hjparser.py',
i don't care about how to decompile .pyo or .pyc files.

Thanks


On 9/24/05, Ivan Voras <[EMAIL PROTECTED]> wrote:
> It is - py2exe embeds python bytecodes. It seems it does it in the
> "library.zip" file (if I'm reading
> http://starship.python.net/crew/theller/moin.cgi/Py2Exe correctly).
> Bytecode files extracted should be decompilable to something resembling
> original python code by a python decompiler (quick Googling finds
> "decompyle": http://www.crazy-compilers.com/).
> --
> http://mail.python.org/mailman/listinfo/python-list
>



--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing an HTML a tag

2005-09-24 Thread Leo Jay
you may define a start_a in MyHTMLParser.

e.g.
import htmllib
import formatter

class HTML_Parser(htmllib.HTMLParser):
def __init__(self):
htmllib.HTMLParser.__init__(self,
formatter.AbstractFormatter(formatter.NullWriter()))

def start_a(self, args):
for key, value in args:
if key.lower() == 'href':
print value


html = HTML_Parser()
html.feed(open(r'a.htm','r').read())
html.close()


On 24 Sep 2005 10:13:30 -0700, George <[EMAIL PROTECTED]> wrote:
> How can I parse an HTML file and collect only that the A tags. I have a
> start for the code but an unable to figure out how to finish the code.
> HTML_parse gets the data from the URL document. Thanks for the help
>
> def HTML_parse(data):
>  from HTMLParser import HTMLParser
>  parser = MyHTMLParser()
>
>  parser.feed(data)
>
>  class MyHTMLParser(HTMLParser):
>
>  def handle_starttag(self, tag, attrs):
>
>  def handle_endtag(self, tag):
>
> def read_page(URL):
>  "this function returns the entire content of the specified URL
> document"
>  import urllib
>  connect = urllib.urlopen(url)
>  data = connect.read()
>  connect.close()
>  return data
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


about install wxPython in Redhat Linux AS 4

2005-09-28 Thread Leo Jay
Dear All,

I'd like to install wxPython in my Redhat AS 4,
I have downloaded both
wxPython-common-gtk2-unicode-2.6.1.0-fc2_py2.4.i386.rpm and 
wxPython2.6-gtk2-unicode-2.6.1.0-fc2_py2.4.i386.rpm packages from
www.wxpython.org.

After I installed these two packages successfully, what should i do now?

i tried to import wx in python, but python just returned an error:
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named wx

Anyone can help me, please?

Thanks


--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about install wxPython in Redhat Linux AS 4

2005-09-28 Thread Leo Jay
On 9/28/05, Martin Franklin <[EMAIL PROTECTED]> wrote:
> Leo,
>
> I don't have AS 4 but fedora core 4 has wx in it's YUM repositories I
> assume RedHat has too, so perhaps you need to use the officially
> sanctioned version.  If you want to use the latest and greatest then you
> will most likely need to build them from source (which means installing
> the -devel packages for python & GTK)
>
> Martin
>

Thanks for your reply,

AS 4 don't have neither yum nor apt-get.
and i tried to build the wxpython from scratch,
but, after building wxwindow correctly, i encountered
dozens of errors when installing wxpython.
i'm just a rookie that i have no idea about how to handle these errors.


--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


how to get rate of pop3 receiving progress?

2005-07-14 Thread Leo Jay
when i use POP3.retr() in poplib module, the retr() function will not
return until the  receiving progress is finished

so, is there any way to get the rate of receiving progress?

Thanks

-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question about lists

2005-07-20 Thread Leo Jay
you may use the decimal module which was introduced in Python2.4


>>> from decimal import *
>>> li = [Decimal(".25"), Decimal(".10"), Decimal(".05"), Decimal(".01")]
>>> print li
[Decimal("0.25"), Decimal("0.10"), Decimal("0.05"), Decimal("0.01")]
>>>

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


Re: Newbie question about lists

2005-07-20 Thread Leo Jay
IMO, python should use the decimal for default.
.25 is right for Decimal(".25").
isn't that better?

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


how to get the return value of a thread?

2005-09-09 Thread Leo Jay
Dear all,

i would like to get the return value of all threads

e.g.
def foo(num):
if num>10:
return 1
elif num>50:
return 2
else
return 0


after i invoked 
t = thread.start_new_thread(foo,(12,))
how to get the return value of `foo'?

Thanks

-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Why doesn't join() call str() on its arguments?

2005-02-16 Thread Leo Breebaart
I've tried Googling for this, but practically all discussions on
str.join() focus on the yuck-ugly-shouldn't-it-be-a-list-method?
issue, which is not my problem/question at all.

What I can't find an explanation for is why str.join() doesn't
automatically call str() on its arguments, so that e.g.
str.join([1,2,4,5]) would yield "1245", and ditto for e.g.
user-defined classes that have a __str__() defined.

All I've been able to find is a 1999 python-dev post by Tim
Peters which would seem to indicate he doesn't understand it
either:

"string.join(seq) doesn't currently convert seq elements to
 string type, and in my vision it would. At least three of us
 admit to mapping str across seq anyway before calling
 string.join, and I think it would be a nice convenience
 [...]"

But now it's 2005, and both string.join() and str.join() still
explicitly expect a sequence of strings rather than a sequence of
stringifiable objects.

I'm not complaining as such -- sep.join(str(i) for i in seq) is
not *that* ugly, but what annoys me is that I don't understand
*why* this was never changed. Presumably there is some
counter-argument involved, some reason why people preferred the
existing semantics after all. But for the life of me I can't
think what that counter-argument might be...

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't join() call str() on its arguments?

2005-02-16 Thread Leo Breebaart

John Machin <[EMAIL PROTECTED]> writes:


> On 16 Feb 2005 18:47:21 GMT, Leo Breebaart <[EMAIL PROTECTED]> wrote:
> 
> >What I can't find an explanation for is why str.join() doesn't
> >automatically call str() on its arguments, so that e.g.
> >str.join([1,2,4,5]) would yield "1245", and ditto for e.g.
> >user-defined classes that have a __str__() defined.
> 
> For a start, I think you meant ''.join([1,2,4,5]) to yield
> "1245".

Yep. Sorry. Bad example.
 

> Secondly, concatenating arbitrary types with a null separator doesn't
> appear to be a good use case.
> E.g.
> >>> ''.join([str(x) for x in [1,2,1./3,4]])
> '120.4'

Okay:

>>> ', '.join(str(x) for x in [1,2,1./3,4])
'1, 2, 0., 4'

Isn't that better?

I am not claiming that *all* uses of calling join() on arbitrary
types are useful. But then neither are *all* uses of calling
join() on actual strings, or all uses of adding arbitrarily typed
elements to a list, or...

It's just that in my experience so far, whenever I have felt a
need for the 'join()' function, it has *always* been in a
situation where I also have to do the str(x) thing. That suggests
to me an "obvious default" of the kind that exists elsewhere in
Python as well.

It is entirely possible that my experience is not shared (or not
to the same extent) by others, but part of my reason for asking
this question here is investigating precisely that.


> Some possible explanations:
> 
> 1. Explicit is better than implicit.

Sure. But it's always a tradeoff -- list comprehensions are more
implicit than for loops...


> 2. It would only be a good "trick" IMHO with a non-null
> separator and types with a 'clean' str() result (unlike float)
> -- like int; I can't think of more at the moment.

I don't agree that the str() result for a float isn't clean.
Sometimes it can be exactly what you need, or even just
sufficient. If you want more control, then pure join() isn't what
you need, anyway. Right?


> 3. It would be one step on the slippery downwards path to
> perlishness.

I think you're exaggerating, and I really would prefer to have
this discussion without gratuitous swipes against other
languages, please?


> 4. For consistency, would you like "1" + 2 to produce "12"?

No. A foolish consistency etc. etc. I sincerely do like the fact
that Python does not try to second-guess the programmer, I do
value explicit over implicit, and I have no desire to open the
can of worms that would be the changing the semantics of +.


I think my main dissatisfaction with your four possible
explanations stems from the fact that a join() function that
would be a bit more type-agnostic strikes me as *more* Pythonic,
not *less*. Isn't that what duck typing is about? Why does join()
care that its arguments should be actual strings only? If the
function of join() is to produce a string, why isn't it
sufficient for its arguments to have a string representation --
why do they have to *be* strings? Isn't that sort of thing
exactly how we are taught *not* to write our own argument
handling when we learn Python?

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't join() call str() on its arguments?

2005-02-16 Thread Leo Breebaart

"Delaney, Timothy C (Timothy)" <[EMAIL PROTECTED]> writes:

> John Roth wrote:
> 
> > result = "".join([str(x) for x in list])
> 
> As of 2.4, you should use a generator expression here instead (unless
> you require backwards-compatibility with 2.3).
> 
> result = ''.join(str(x) for x in iterable)
> 
> Easier to read, more memory-efficient, potentially faster (depending on
> performance characteristics of building large lists).

Stop me if I sound too whiney, but in my original post that
started this thread just a couple of hours ago, I did in fact get
this right, so I'm not entirely sure who the two of you are
actually talking to...

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


How to name Exceptions that aren't Errors

2005-04-07 Thread Leo Breebaart
I've recently become rather fond of using Exceptions in Python to
signal special conditions that aren't errors, but which I feel
are better communicated up the call stack via the exception
mechanism than via e.g. return values.

For instance, I'm thinking of methods such as:


def run(self):
""" Feed the input file to the simulator. """

for linenr, line in enumerate(self.infile):
try:
current_values = self.parse_line(linenr, line)
==> except CommentLineException:
continue
results = self.do_one_simulation_step(current_values)
self.process_simulation_results(results)


which I use in order to discard comments from a file I'm parsing
line-by-line.

My question is twofold. First, I know that many programmers are
violently opposed to using exceptions in this fashion, i.e. for
anything other than, well, exceptional circumstances. But am I
correct in thinking that in Python this usage is actually
considered quite normal, and not frowned upon? Is my snippet
above indeed sufficiently Pythonic?

Second, purely as a question of aesthetics, I was wondering if
the folks here might have any opinions about actual naming
conventions for the exception classes used in this fashion.

'CommentLineError' would clearly be wrong, but using the
'Exception' prefix seems a bit redundant and pointless too. I
suppose I could just call the exception "CommentLine" and leave
it at that, but I don't know, maybe there's something better I'm
overlooking.

Any suggestions?

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to name Exceptions that aren't Errors

2005-04-07 Thread Leo Breebaart
Max <[EMAIL PROTECTED]> writes:

> LOOK EVERYONE, it's Leo Breebart. You are the same Leo
> Breebart, right?

Breeb*aa*rt. But otherwise, yeah -- I do frequent more than just
one newsgroup. :-)


> This guys famous in the alternative universe of
> alt.fan.pratchett.

I doubt anybody here cares! Who was it that said: "On the
Internet, everyone's famous to fifteen other people"...?

Anyways, regardless of any feeble claims to notoriety I may have
in alternate universes, here in Python country I am but a humble
grasshopper wot has only been programming in Python for slightly
over a year now.

*Dutch* grasshopper, though. Does that help any?

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: word replacing in a paragraph

2014-01-06 Thread leo kirotawa
Since it is for a template you can round the keyword to be replaced ,
something like $data$ and then just  string.replace('$data','1234')




On Mon, Jan 6, 2014 at 12:01 PM, Frank Cui  wrote:

> Hey guys,
>
> I'm trying to automate a process by initially creating a standard template
> and then replace some text fields with variable values.
>
> [for example, "DATE" in the paragraph will be replaced by the current date
> value. it doesn't have to be a literal word of "DATE", "DATE" in "TESTDATE"
> can also be replaced.]
>
> Is there some lightweight built-in or 3rd party  libraries which are good
> for such kind of work ?
>
> Thanks
> Frank
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>


-- 
--
Leônidas S. Barbosa (Kirotawa)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-04 Thread leo kirotawa
You'll find some explanation here:
http://stackoverflow.com/questions/1708292/meaning-of-using-commas-and-underscores-with-python-assignment-operator

On Wed, Feb 4, 2015 at 12:08 PM, ast  wrote:
> hello
>
> I dont understand why there is a comma just after line in the following
> command:
>
> line, = plt.plot(x, np.sin(x), '--', linewidth=2)
>
>
> I never saw that before
>
> Found here:
> http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
>
> thanks
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

--
Leônidas S. Barbosa (Kirotawa)
blog: corecode.wordpress.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: file handling issues

2013-09-06 Thread leo . carnovale
On Friday, 6 September 2013 20:20:02 UTC+10, leo.ca...@gmail.com  wrote:
> I am making this little game and I am trying to make some sort of script that 
> does the following:
> 
> >Checks to see if a file exists
> 
>  >If it does, check the numbers in it
> 
>  >If it doesn't, make one and fill it with some numbers
> 
> >Sorts out if the numbers in the file are in the right format
> 
>  >If they are, then store them
> 
>  >If not, remake it again
> 
> >THEN, check if there is a pass.
> 
>  >If there is, check if it fits the key and go on if so
> 
>  >If not, ask for a new one, check it, go on if its correct.
> 
> 
> 
> Every time I run it, it says the key is 0!?
> 
> I can not for the life of me figure out what it is doing.
> 
> 
> 
> The code:
> 
> <https://docs.google.com/document/d/1_Qo4bgmNhRer3fAt3EAtPNSei4N2q58f_q4_9r6OHbw/edit?usp=sharing>
> 
> 
> 
> Thanks
> 
> 
> 
> Leo

Probably should also mention this,
The KEY is what the user is presented with, and to use the program, they must 
enter a corresponding PASS which is created with a special manipulator that I 
made.
-- 
https://mail.python.org/mailman/listinfo/python-list


file handling issues

2013-09-06 Thread leo . carnovale
I am making this little game and I am trying to make some sort of script that 
does the following:
>Checks to see if a file exists
 >If it does, check the numbers in it
 >If it doesn't, make one and fill it with some numbers
>Sorts out if the numbers in the file are in the right format
 >If they are, then store them
 >If not, remake it again
>THEN, check if there is a pass.
 >If there is, check if it fits the key and go on if so
 >If not, ask for a new one, check it, go on if its correct.

Every time I run it, it says the key is 0!?
I can not for the life of me figure out what it is doing.

The code:
<https://docs.google.com/document/d/1_Qo4bgmNhRer3fAt3EAtPNSei4N2q58f_q4_9r6OHbw/edit?usp=sharing>

Thanks

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


Re: file handling issues

2013-09-06 Thread Leo Carnovale
On Saturday, 7 September 2013 02:17:03 UTC+10, Piet van Oostrum  wrote:
> leo.carnov...@gmail.com writes:
> 
> 
> 
> > I am making this little game and I am trying to make some sort of script 
> > that does the following:
> 
> >>Checks to see if a file exists
> 
> >  >If it does, check the numbers in it
> 
> >  >If it doesn't, make one and fill it with some numbers
> 
> >>Sorts out if the numbers in the file are in the right format
> 
> >  >If they are, then store them
> 
> >  >If not, remake it again
> 
> >>THEN, check if there is a pass.
> 
> >  >If there is, check if it fits the key and go on if so
> 
> >  >If not, ask for a new one, check it, go on if its correct.
> 
> >
> 
> > Every time I run it, it says the key is 0!?
> 
> > I can not for the life of me figure out what it is doing.
> 
> >
> 
> > The code:
> 
> > <https://docs.google.com/document/d/1_Qo4bgmNhRer3fAt3EAtPNSei4N2q58f_q4_9r6OHbw/edit?usp=sharing>
> 
> >
> 
> 
> 
> What a mess is that code. First that messing around with the key is
> 
> crazy. You probably want to do some crypto on it, but why don't you just
> 
> use some standard crypto algorithm?
> 
> 
> 
> The you have defined T as True and F as False, but sometimes you use T
> 
> and sometimes True, and as far as I can see you never use F. Just stay
> 
> with True and false as it makes the code more readable.
> 
> 
> 
> Once you use "with open('Key')", all other case you use
> 
> f = open('Key',...)
> 
> f.read() or f.write()
> 
> f.close()
> 
> 
> 
> Be consistenst and use always "with open..."
> 
> 
> 
> There are at least three palces where you write a key to the file. Make
> 
> a function for this; it makes your code more structured.
> 
> 
> 
> And please, put spaces aroud the = signs.
> 
> 
> 
> Now the real problem:
> 
> 
> 
> if newpas:
> 
> f=open("Key","w")
> 
> print("No pass found!")
> 
> print("Your wonderful key is: ",int(keys[0]))
> 
> pasw=input("What is your pass?   : ")
> 
> elif newkey:
> 
> f=open("Key","w")
> 
> 
> 
> Here you open the file for writing but you never write anything to it.
> 
> This makes the file empty. And apparently you do not check this the next
> 
> time you open it. If you would have used a function to write a key to
> 
> the file, this probably would not have occurred.
> 
> 
> 
> if mess_with(keys[0])==pasw:
> 
> hesin=1
> 
> print("Your in!")
> 
> f=open("Key","w")
> 
> 
> 
> Here you open the file again with the same variable. This causes the old
> 
> value to be lost and the file probably to be closed. Just messy.
> 
> 
> 
> print("writing %s" % str(keys[0])+pasw)
> 
> f.write(str(keys[0])+pasw)
> 
> f.close()
> 
> else:
> 
> hesin=0
> 
> 
> 
> And how are people supposed to guess an 8 character password? Are they
> 
> supposed to do that weird calculation on their calculators or some such?
> 
> 
> 
> -- 
> 
> Piet van Oostrum 
> 
> WWW: http://pietvanoostrum.com/
> 
> PGP key: [8DAE142BE17999C4]

Yes the code is a mess, I have been tempted to re write the whole thing...
The reason for the messiness is firstly because I am relatively new to 
programming and because this is the result of me tinkering around with previous 
code, which was still messy, but cleaner than this.

So the open("key","w") clears the file straight away? That helps a lot, thanks, 
this will definitely save me a lot of time in the future. Also the user doesn't 
guess the pass, I would give it to them. After they enter it, they go on to the 
guessing game (not shown in the code).

Thanks for the help!

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


Re: file handling issues

2013-09-06 Thread Leo Carnovale
On Saturday, 7 September 2013 13:03:14 UTC+10, Leo Carnovale  wrote:
> On Saturday, 7 September 2013 02:17:03 UTC+10, Piet van Oostrum  wrote:
> 
> > leo.carnov...@gmail.com writes:
> 
> > 
> 
> > 
> 
> > 
> 
> > > I am making this little game and I am trying to make some sort of script 
> > > that does the following:
> 
> > 
> 
> > >>Checks to see if a file exists
> 
> > 
> 
> > >  >If it does, check the numbers in it
> 
> > 
> 
> > >  >If it doesn't, make one and fill it with some numbers
> 
> > 
> 
> > >>Sorts out if the numbers in the file are in the right format
> 
> > 
> 
> > >  >If they are, then store them
> 
> > 
> 
> > >  >If not, remake it again
> 
> > 
> 
> > >>THEN, check if there is a pass.
> 
> > 
> 
> > >  >If there is, check if it fits the key and go on if so
> 
> > 
> 
> > >  >If not, ask for a new one, check it, go on if its correct.
> 
> > 
> 
> > >
> 
> > 
> 
> > > Every time I run it, it says the key is 0!?
> 
> > 
> 
> > > I can not for the life of me figure out what it is doing.
> 
> > 
> 
> > >
> 
> > 
> 
> > > The code:
> 
> > 
> 
> > > <https://docs.google.com/document/d/1_Qo4bgmNhRer3fAt3EAtPNSei4N2q58f_q4_9r6OHbw/edit?usp=sharing>
> 
> > 
> 
> > >
> 
> > 
> 
> > 
> 
> > 
> 
> > What a mess is that code. First that messing around with the key is
> 
> > 
> 
> > crazy. You probably want to do some crypto on it, but why don't you just
> 
> > 
> 
> > use some standard crypto algorithm?
> 
> > 
> 
> > 
> 
> > 
> 
> > The you have defined T as True and F as False, but sometimes you use T
> 
> > 
> 
> > and sometimes True, and as far as I can see you never use F. Just stay
> 
> > 
> 
> > with True and false as it makes the code more readable.
> 
> > 
> 
> > 
> 
> > 
> 
> > Once you use "with open('Key')", all other case you use
> 
> > 
> 
> > f = open('Key',...)
> 
> > 
> 
> > f.read() or f.write()
> 
> > 
> 
> > f.close()
> 
> > 
> 
> > 
> 
> > 
> 
> > Be consistenst and use always "with open..."
> 
> > 
> 
> > 
> 
> > 
> 
> > There are at least three palces where you write a key to the file. Make
> 
> > 
> 
> > a function for this; it makes your code more structured.
> 
> > 
> 
> > 
> 
> > 
> 
> > And please, put spaces aroud the = signs.
> 
> > 
> 
> > 
> 
> > 
> 
> > Now the real problem:
> 
> > 
> 
> > 
> 
> > 
> 
> > if newpas:
> 
> > 
> 
> > f=open("Key","w")
> 
> > 
> 
> > print("No pass found!")
> 
> > 
> 
> > print("Your wonderful key is: ",int(keys[0]))
> 
> > 
> 
> > pasw=input("What is your pass?   : ")
> 
> > 
> 
> > elif newkey:
> 
> > 
> 
> > f=open("Key","w")
> 
> > 
> 
> > 
> 
> > 
> 
> > Here you open the file for writing but you never write anything to it.
> 
> > 
> 
> > This makes the file empty. And apparently you do not check this the next
> 
> > 
> 
> > time you open it. If you would have used a function to write a key to
> 
> > 
> 
> > the file, this probably would not have occurred.
> 
> > 
> 
> > 
> 
> > 
> 
> > if mess_with(keys[0])==pasw:
> 
> > 
> 
> > hesin=1
> 
> > 
> 
> > print("Your in!")
> 
> > 
> 
> > f=open("Key","w")
> 
> > 
> 
> > 
> 
> > 
> 
> > Here you open the file again with the same variable. This causes the old
> 
> > 
> 
> > value to be lost and the file probably to be closed. Just messy.
> 
> > 
> 
> > 
> 
> > 
> 
> > print("writing %s" % str(keys[0])+pasw)
> 
> > 
> 
> > f.write(str(keys[0])+pasw)
> 
> > 
> 
> > f.close()
> 
> > 
> 
> > else:
> 
> > 
> 
> > hesin=0
> 
> > 
> 
> > 
> 
> > 
> 
> > And how are people supposed to guess an 8 character password? Are they
> 
> > 
> 
> > supposed to do that weird calculation on their calculators or some such?
> 
> > 
> 
> > 
> 
> > 
> 
> > -- 
> 
> > 
> 
> > Piet van Oostrum 
> 
> > 
> 
> > WWW: http://pietvanoostrum.com/
> 
> > 
> 
> > PGP key: [8DAE142BE17999C4]
> 
> 
> 
> Yes the code is a mess, I have been tempted to re write the whole thing...
> 
> The reason for the messiness is firstly because I am relatively new to 
> programming and because this is the result of me tinkering around with 
> previous code, which was still messy, but cleaner than this.
> 
> 
> 
> So the open("key","w") clears the file straight away? That helps a lot, 
> thanks, this will definitely save me a lot of time in the future. Also the 
> user doesn't guess the pass, I would give it to them. After they enter it, 
> they go on to the guessing game (not shown in the code).
> 
> 
> 
> Thanks for the help!
> 
> 
> 
> Leo

Ah and one other thing!
What is this crypto algorithm you speak of? I desperately need some sort of 
encryption as at the moment anyone can simply open the text file and change the 
numbers to numbers that work! 
Where can I learn more about it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: file handling issues

2013-09-06 Thread Leo Carnovale
On Saturday, 7 September 2013 13:58:43 UTC+10, Michael Torrie  wrote:
> On 09/06/2013 09:05 PM, Leo Carnovale wrote:
> 
> > Ah and one other thing! What is this crypto algorithm you speak of? I
> 
> > desperately need some sort of encryption as at the moment anyone can
> 
> > simply open the text file and change the numbers to numbers that
> 
> > work! Where can I learn more about it?
> 
> 
> 
> There are two kinds of cryptography, generally.  Symmetric and
> 
> asymmetric.  Your needs will dictate which system you use.  Symmetric
> 
> cryptography means that the sake encryption key that was used to encrypt
> 
> the data is used to decrypt it.  Asymmetric cryptography basically means
> 
> one key is used to encrypt a message and another key is used to decrypt
> 
> the message.
> 
> 
> 
> In your case, perhaps symmetric encryption is most logical, though I'm
> 
> not at all clear what you are doing.  However you'll have to embed the
> 
> encryption key in your python source code, which isn't hidden at all.
> 
> And actually any program that embeds a symmetric key in its code can be
> 
> cracked rather easily.
> 
> 
> 
> Python has many libraries to support encryption.  Some are in the
> 
> standard library.  Search for python and crypto to see what docs are
> 
> available.  You might want to read up on basic cryptography principles
> 
> as well.

Thanks! Obviously, I need to do a lot of research. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-11 Thread leo kirotawa
assign using () creates tuple not a list. Tuples have not .sort() method.
correct would be:
ncount = [key,val]

On Tue, Aug 11, 2015 at 9:01 PM, Ltc Hotspot  wrote:
> Hi Everyone,
>
>
> What is the list equivalent to line 12: ncount.sort(reverse=True)
>
>
> count = dict()
> fname = raw_input("Enter file name: ")#
> handle = open (fname, 'r')#
> for line in handle:
> if line.startswith("From "):
> address = line.split()[5]
> line = line.rstrip()
> count[address] = count.get(address, 0) + 1
>
> for key,val in count.items():
> ncount = (key,val)
> ncount.sort(reverse=True)
> print key,val
>
>
> Error message, reads: AttributeError, line 12, below : 'tuple' object has no 
> attribute 'sort'
>
> Raw data code, available at http://tinyurl.com/ob89r9p
> Embedded data code, available at http://tinyurl.com/qhm4ppq
> Visualization URL link, available at http://tinyurl.com/ozzmffy
>
>
> Regards,
> Hal
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

--
Leônidas S. Barbosa (Kirotawa)
blog: corecode.wordpress.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Vaga Java (Belgica, com tudo pago)

2015-08-13 Thread leo kirotawa
Wondering why a position for Java/JS was sent to this list...just wondering...

On Thu, Aug 13, 2015 at 11:59 AM,   wrote:
> https://walljobs.typeform.com/to/uWpUqj
>
> We seek a software developer with experience in web application development.
>
> Should you have the passion to work in the start-up environment and the 
> willingness to evolve in a fast-paced environment, then we'd like to get in 
> touch.
>
> We are located in Brussels, Belgium, in the center of Europe. You should be 
> able to work in an international team, show passion and commitment to towards 
> the project, and be able to adapt to challenging European working standards.
>
> Responsibilities
>
> Understand design documents, giving feedback when necessary, and implement 
> the required changes in the code base.
>
> Interact with an existing large software implementation and independently 
> perform the required actions
>
> Review code from peers
>
> Develop automated tests and other quality assurance techniques
>
> Interact with the marketing, psychology and business teams giving advice and 
> feedback
>
> Adapt and adjust to a fast pacing environment
>
> https://walljobs.typeform.com/to/uWpUqj
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

--
Leônidas S. Barbosa (Kirotawa)
blog: corecode.wordpress.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: First time I looked at Python was(...)

2014-06-10 Thread leo kirotawa
Gzz,

Guys I'm from Brazil too, and I'm ashamed for this troll. And sorry by
his terrible taste in music.
Wondering now about moderation , have we one?

[]'s

On Tue, Jun 10, 2014 at 5:07 PM, Carlos Anselmo Dias
 wrote:
>
>
> Terry Jan Reedy ...
>
> https://www.youtube.com/watch?v=HbGHq2aUXDU (yhis one is portuguese ...
>
> I'm someone who did very probably more webpages than you in your entire life
> ...
>
> Do you exist?
>
>
>
>
>
> On 06/10/2014 08:57 PM, Terry Reedy wrote:
>>
>> On 6/10/2014 1:19 PM, Carlos Anselmo Dias wrote:
>>>
>>> Let me finish with this ...
>>>
>>> https://www.youtube.com/watch?
>>
>>
>> Yes, do finish with that. People, please quit responding to 'carlos' from
>> premium-sponsor.com (which apparently exists but has no web page).
>>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

--
Leônidas S. Barbosa (Kirotawa)
blog: corecode.wordpress.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Distributing python applications as a zip file

2014-07-23 Thread Leo Jay
On Wed, Jul 23, 2014 at 12:23 PM, Steven D'Aprano  wrote:
> A little known feature of Python: you can wrap your Python application in
> a zip file and distribute it as a single file. The trick to make it
> runnable is to put your main function inside a file called __main__.py
> inside the zip file. Here's a basic example:
>
> steve@runes:~$ cat __main__.py
> print("NOBODY expects the Spanish Inquisition!!!")
>
> steve@runes:~$ zip appl __main__.py
>   adding: __main__.py (stored 0%)
> steve@runes:~$ rm __main__.py
> steve@runes:~$ python appl.zip
> NOBODY expects the Spanish Inquisition!!!
>
>
> On Linux, you can even hack the zip file to include a shebang line!
>
>
> steve@runes:~$ cat appl
> #!/usr/bin/env python
> # This is a Python application stored in a ZIP archive.
> steve@runes:~$ cat appl.zip >> appl
> steve@runes:~$ chmod u+x appl
> steve@runes:~$ ./appl
> NOBODY expects the Spanish Inquisition!!!
>
>
> It's not quite self-contained, as you still need to have Python
> installed, but otherwise it's a good way to distribute a Python
> application as a single file that users can just copy and run.
>

But if you use windows and you happen to use multiprocessing,
please be aware of this bug I encountered several years ago.
https://mail.python.org/pipermail/python-dev/2011-December/115071.html

-- 
Best Regards,
Leo Jay
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting a list of all modules

2014-07-30 Thread Leo Jay
On Wed, Jul 30, 2014 at 3:43 PM, Steven D'Aprano  wrote:
> I'm looking for a programmatic way to get a list of all Python modules
> and packages. Not just those already imported, but all those which
> *could* be imported.
>

If you don't actually import it, how can you know it could be imported?
Not all .so files are valid python modules.
Not all .py files could be imported by all python interpreters.

> I have a quick-and-dirty function which half does the job:
>
>
> def get_modules():
> extensions = ('.py', '.pyc', '.pyo', '.so', '.dll')
> matches = set()
> for location in sys.path:
> if location == '': location = '.'
> if os.path.isdir(location):
> for name in os.listdir(location):
> base, ext = os.path.splitext(name)
> if ext in extensions:
> matches.add(base)
> return sorted(matches)
>
>
>
> but I know it's wrong (it doesn't handle packages correctly, or zip
> files, doesn't follow .pth files, has a very naive understanding of cross-
> platform issues, fails to include built-in modules that don't live in the
> file system, and probably more).
>
> Is this problem already solved? Can anyone make any suggestions?
>
>
>
> --
> Steven
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Best Regards,
Leo Jay
-- 
https://mail.python.org/mailman/listinfo/python-list


Cannot use multiprocessing and zip together on windows

2011-12-11 Thread Leo Jay
Hi All,

I have a file p.zip, there is a __main__.py in it, and the content of
__main__.py is:

from multiprocessing import Process
import os

def f():
   print 'in f, pid:', os.getpid()

if __name__ == '__main__':
   print 'pid:', os.getpid()
   p = Process(target=f)
   p.start()
   p.join()


On linux, I can get expected result for running "python p.zip"
But on windows xp, I got:

Traceback (most recent call last):
 File "", line 1, in 
 File "C:\python27\lib\multiprocessing\forking.py", line 346, in main
   prepare(preparation_data)
 File "C:\python27\lib\multiprocessing\forking.py", line 454, in prepare
   assert main_name not in sys.modules, main_name
AssertionError: __main__

It seems that the situation described here is similar:
http://bugs.python.org/issue10128

But the patch doesn't work for me.

Anybody knows how to fix this?
Thanks.

-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Data Tree urgent help!!!!!!

2013-02-20 Thread Leo Breebaart
Peter Otten <__pete...@web.de> writes:

> >>> class Name(str):
> ... def __repr__(self):
> ... return self
> ... 
> >>> apple, pear, dog, cat, fork, spoon = map(Name, "apple pear dog cat fork 
> >>> spoon".split())

Is there any reason why you introduced the Name class? In Python
2.7 this works equally well if I just do:

>>> apple, pear, dog, cat, fork, spoon = map(str, "apple pear dog cat fork 
>>> spoon".split())

So I was wondering why you used Name.

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


Re: Question on for loop

2013-03-04 Thread leo kirotawa
In fact this code is already doing what you want, but if the second
character, by example, is not in secrectWord it'll jump out of the for and
return. If you want that interact through the all characters and  maybe
count how many them are in the secrectWord, just take of the return there
or do some list comprehension like: [ r for r in secrecWord if r in
lettersGuessed] .



[]'s



On Mon, Mar 4, 2013 at 9:18 AM, newtopython  wrote:

> Hi all,
>
> I'm super new to python, just fyi.
>
> In the piece of code below, secretWord is a string and lettersGuessed is a
> list. I'm trying to find out if ALL the characters of secretWord are
> included in lettersGuessed, even if there are additional values in the
> lettersGuessed list that aren't in secretWord.
>
> What this code is doing is only checking the first character of secretWord
> and then returning True or False. How do I get it to iterate through ALL of
> the characters of secretWord?
>
> for character in secretWord:
> if character not in lettersGuessed:
> return True
> return False
>
> Thanks!
>
> Ro
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Leônidas S. Barbosa (Kirotawa)

Engenheiro de Software - IBM (LTC - Linux Technology Center)
MsC Sistemas e Computação
Bacharel em Ciências da Computação.

blog nerd: corecode.wordpress.com/

User linux : #480879

"Mais sábio é aquele que sabe que não sabe" (Sócrates)
"smile and wave" - =D + o/ (Penguins of Madagascar)

日本語の学生です。
コンピュータサイエンスの学位.
-- 
http://mail.python.org/mailman/listinfo/python-list


is there any lib can split string in this way?

2006-01-08 Thread Leo Jay
I want to split a string like this:
'abc  def  "this is a test"  ok'
into:
['abc', 'def', 'this is a test', 'ok']

is there any lib meet my need?

thanks

--
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


how to use python com server in c++?

2006-08-19 Thread Leo Jay
dear all,
i have a python com server like this:

import win32com.server.register

class HelloWorld:
_reg_clsid_ = "{B0EB5AAB-0465-4D54-9CF9-04ADF7F73E4E}"
_reg_desc_  = 'Python test com server'
_reg_progid_= "Leojay.ComServer"
_public_methods_= ['Add', 'Mul']

def Add(self, a, b):
return a+b
def Mul(self, a, b):
return a*b


if __name__ == '__main__':
win32com.server.register.UseCommandLine(HelloWorld)


after registering the com server, i can use it in visual basic .net:
Dim a As Integer = 5
Dim b As Integer = 8
Dim h As Object = CreateObject("Leojay.ComServer")
MsgBox(h.Add(a, b).ToString() + " " + h.Mul(a, b).ToString())

but i don't know how to use it in visual c++.

who has any idea about using this com server in viusal c++?
a detailed sample of early binding would be better, thanks.



-- 
Best Regards,
Leo Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: does raw_input() return unicode?

2006-10-10 Thread Leo Kislov

Theerasak Photha wrote:
> On 10/10/06, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Theerasak Photha schrieb:
> > >> At the moment, it only returns unicode objects when invoked
> > >> in the IDLE shell, and only if the character entered cannot
> > >> be represented in the locale's charset.
> > >
> > > Why only IDLE? Does urwid or another console UI toolkit avoid this 
> > > somehow?
> >
> > I admit I don't know what urwid is; from a shallow description I find
> > ("a console user interface library") I can't see the connection to
> > raw_input(). How would raw_input() ever use urwid?
>
> The other way around: would urwid use raw_input() or other Python
> input functions anywhere?
>
> And what causes Unicode input to work in IDLE alone?

Other applications except python are actually free to implement unicode
stdin. python cannot do it because of backward compatibility. You can
argue that python interactive console could do it too, but think about
it this way: python interactive console deliberately behaves like a
running python program would.

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


Re: does raw_input() return unicode?

2006-10-10 Thread Leo Kislov

Duncan Booth wrote:
> "Stuart McGraw" <[EMAIL PROTECTED]> wrote:
>
> > So, does raw_input() ever return unicode objects and if
> > so, under what conditions?
> >
> It returns unicode if reading from sys.stdin returns unicode.
>
> Unfortunately, I can't tell you how to make sys.stdin return unicode for
> use with raw_input. I tried what I thought should work and as you can see
> it messed up the buffering on stdin. Does anyone else know how to wrap
> sys.stdin so it returns unicode but is still unbuffered?

Considering that all consoles are ascii based, the following should
work where python was able to determine terminal encoding:

class ustdio(object):
def __init__(self, stream):
self.stream = stream
self.encoding = stream.encoding
def readline(self):
return self.stream.readline().decode(self.encoding)

sys.stdin = ustdio(sys.stdin)

answer = raw_input()
print type(answer)

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


Re: People's names (was Re: sqlite3 error)

2006-10-10 Thread Leo Kislov
John J. Lee wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
> [...]
> > > There would also need to be a flag field to indicate the canonical
> > > ordering
> > > for writing out the full name: e.g. family-name-first, given-names-first.
> > > Do we need something else for the Vietnamese case?
> >
> > You'd think some standards body would have worked on this, wouldn't
> > you. I couldn't think of a Google search string that would lead to
> > such information, though. Maybe other, more determined, readers can do
> > better.
>
> I suppose very few projects actually deal with more than a handful of
> languages or cultures, but it does surprise me how hard it is to find
> out about this kind of thing -- especially given that open source
> projects often end up with all kinds of weird and wonderful localised
> versions.
>
> On a project that involved 9 localisations, just trying to find
> information on the web about standard collation of diacritics
> (accented characters) in English, German, and Scandinavian languages
> was more difficult than I'd expected.

As far as I understand unicode.org has become the central(?) source of
locale information: http://unicode.org/cldr/Did you use it?

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


Re: How to find number of characters in a unicode string?

2006-10-10 Thread Leo Kislov

Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Marc 'BlackJack'
> Rintsch wrote:
>
> > In <[EMAIL PROTECTED]>,
> > Preben Randhol wrote:
> >
> >> Is there a way to calculate in characters
> >> and not in bytes to represent the characters.
> >
> > Decode the byte string and use `len()` on the unicode string.
>
> Hmmm, for some reason
>
> len(u"C\u0327")
>
> returns 2.

If python ever provide this functionality it would be I guess
u"C\u0327".width() == 1. But it's not clear when unicode.org will
provide recommended fixed font character width information for *all*
characters. I recently stumbled upon Tamil language, where for example
u'\u0b95\u0bcd', u'\u0b95\u0bbe', u'\u0b95\u0bca', u'\u0b95\u0bcc'
looks like they have width 1,2,3 and 4 columns. To add insult to injury
these 4 symbols are all considered *single* letter symbols :) If your
email reader is able to show them, here they are in all their glory:
க், கா, கொ, கௌ.

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

Re: Need a Regular expression to remove a char for Unicode text

2006-10-13 Thread Leo Kislov


On Oct 13, 4:44 am, [EMAIL PROTECTED] wrote:
> శ్రీనివాస wrote:
> > Hai friends,
> > Can any one tell me how can i remove a character from a unocode text.
> > కల్‌&హార is a Telugu word in Unicode. Here i want to
> > remove '&' but not replace with a zero width char. And one more thing,
> > if any whitespaces are there before and after '&' char, the text should
> > be kept as it is. Please tell me how can i workout this with regular
> > expressions.
>
> > Thanks and regards
> > Srinivasa Raju DatlaDon't know anything about Telugu, but is this the 
> > approach you want?
>
> >>> x=u'\xfe\xff & \xfe\xff \xfe\xff&\xfe\xff'
> >>> noampre = re.compile('(? >>> noampre('', x)

He wants to replace & with zero width joiner so the last call should be
noampre(u"\u200D", x)

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

Re: Need a Regular expression to remove a char for Unicode text

2006-10-13 Thread Leo Kislov
On Oct 13, 4:55 am, "Leo Kislov" <[EMAIL PROTECTED]> wrote:
> On Oct 13, 4:44 am, [EMAIL PROTECTED] wrote:
>
> > శ్రీనివాస wrote:
> > > Hai friends,
> > > Can any one tell me how can i remove a character from a unocode text.
> > > కల్‌&హార is a Telugu word in Unicode. Here i want to
> > > remove '&' but not replace with a zero width char. And one more thing,
> > > if any whitespaces are there before and after '&' char, the text should
> > > be kept as it is. Please tell me how can i workout this with regular
> > > expressions.
>
> > > Thanks and regards
> > > Srinivasa Raju DatlaDon't know anything about Telugu, but is this the 
> > > approach you want?
>
> > >>> x=u'\xfe\xff & \xfe\xff \xfe\xff&\xfe\xff'
> > >>> noampre = re.compile('(? > >>> noampre('', x)

> He wants to replace & with zero width joiner so the last call should be
> noampre(u"\u200D", x)

Pardon my poor reading comprehension, OP doesn't want zero width
joiner. Though I'm confused why he mentioned it at all.

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

Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 15, 10:25 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I just want to send a very simple email from within python.
>
> I think the standard module of smtpd in python can do this, but I
> haven't found documents about how to use it after googleing. Are there
> any examples of using smtpd ? I'm not an expert,so I need some examples
> to learn how to use it.

smtpd is for relaying mail not for sending. What you need it a dns
toolkit (search cheeseshop) to map domain name to list of incoming mail
servers, and then using stdlib smtplib try to submit the message to
them.

> Or maybe there is a better way to to this?

This won't work if you're behind a strict corporate firewall or if ISP
is blocking port 25 outgoing connections. In those cases you _have_ to
use an external mail server.

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


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 16, 12:31 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Rob Wolfe wrote:
> > [EMAIL PROTECTED] wrote:
>
> >> Hi,
>
> >> I just want to send a very simple email from within python.
>
> >> I think the standard module of smtpd in python can do this, but I
> >> haven't found documents about how to use it after googleing. Are there
> >> any examples of using smtpd ? I'm not an expert,so I need some examples
> >> to learn how to use it.
>
> > See standard documentation:
>
> >http://docs.python.org/lib/SMTP-example.html
>
> > HTH,
> > RobI have read the example and copied the code and save as send.py, then I
> run it. Here is the output:
> $ python send.py
> From: [EMAIL PROTECTED]
> To: [EMAIL PROTECTED]
> Enter message, end with ^D (Unix) or ^Z (Windows):
> just a test from localhost
> Message length is 82
> send: 'ehlo [202.127.19.74]\r\n'
> reply: '250-WebMail\r\n'
> reply: '250 AUTH plain\r\n'
> reply: retcode (250); Msg: WebMail
> AUTH plain
> send: 'mail FROM:<[EMAIL PROTECTED]>\r\n'
> reply: '502 negative vibes\r\n'
> reply: retcode (502); Msg: negative vibes
> send: 'rset\r\n'
> reply: '502 negative vibes\r\n'
> reply: retcode (502); Msg: negative vibes
> Traceback (most recent call last):
>  File "send.py", line 26, in ?
>server.sendmail(fromaddr, toaddrs, msg)
>  File "/usr/lib/python2.4/smtplib.py", line 680, in sendmail
>raise SMTPSenderRefused(code, resp, from_addr)
> smtplib.SMTPSenderRefused: (502, 'negative vibes', '[EMAIL PROTECTED]')
>
> Do I have to setup a smtp server on my localhost ?

You need to use login method
. And by the way, the
subject of your message is very confusing, you are posting log where
you're sending email using external server.

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


Re: How to send E-mail without an external SMTP server ?

2006-10-16 Thread Leo Kislov


On Oct 16, 2:04 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> It's not safe if I have to use login method explicitly by which I have
> to put my username and password in the script. I have also tried the
> Unix command 'mail', but without success, either. I could use 'mail' to
> send an E-mail to the user on the server, but I couldn't send an E-mail
> to an external E-mail server. I realized that it may because the port 25
> outgoing connections are blocked, so I gave up. I will have to login
> periodically to check the status of the jobs:-(

Using username password is safe as long as you trust system admin, you
just need to make your script readable only to you. Or even better put
the username and password in a separate file. There is also a way to
limit damage in case you don't trust admin, you just need to get auth
token. Start smtp session and set debug level(True), use login method
and see the token:

send: 'AUTH PLAIN \r\n'
reply: '235 2.7.0 Accepted\r\n'
reply: retcode (235); Msg: 2.7.0 Accepted

Then put the token in a file readable only to you, and from now on
instead of login() method use docmd('AUTH PLAIN',"). If the token is stolen, the thief can only send mail from your
account but won't be able to login with password.

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


Re: Alphabetical sorts

2006-10-16 Thread Leo Kislov


On Oct 16, 2:39 pm, Tuomas <[EMAIL PROTECTED]> wrote:
> My application needs to handle different language sorts. Do you know a
> way to apply strxfrm dynamically i.e. without setting the locale?

Collation is almost always locale dependant. So you have to set locale.
One day I needed collation that worked on Windows and Linux. It's not
that polished and not that tested but it worked for me:

import locale, os, codecs

current_encoding = 'ascii'
current_locale = ''

def get_collate_encoding(s):
'''Grab character encoding from locale name'''
split_name = s.split('.')
if len(split_name) != 2:
return 'ascii'
encoding = split_name[1]
if os.name == "nt":
encoding = 'cp' + encoding
try:
codecs.lookup(encoding)
return encoding
except LookupError:
return 'ascii'

def setup_locale(locale_name):
'''Switch to new collation locale or do nothing if locale
   is the same'''
global current_locale, current_encoding
if current_locale == locale_name:
return
current_encoding = get_collate_encoding(
locale.setlocale(locale.LC_COLLATE, locale_name))
current_locale = locale_name

def collate_key(s):
'''Return collation weight of a string'''
return locale.strxfrm(s.encode(current_encoding, 'ignore'))

def collate(lst, locale_name):
'''Sort a list of unicode strings according to locale rules.
   Locale is specified as 2 letter code'''
setup_locale(locale_name)
return sorted(lst, key = collate_key)


words = u'c ch f'.split()
print ' '.join(collate(words, 'en'))
print ' '.join(collate(words, 'cz'))

Prints:

c ch f
c f ch

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


Re: right curly quote and unicode

2006-10-18 Thread Leo Kislov
On 10/17/06, TiNo <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I am trying to compare my Itunes Library xml to the actual files on my
> computer.
> As the xml file is in UTF-8 encoding, I decided to do the comparison of the
> filenames in that encoding.
> It all works, except with one file. It is named 'The Chemical
> Brothers-Elektrobank-04 - Don't Stop the Rock (Electronic Battle Weapon
> Version).mp3'. It goes wrong with the apostrophe in Don't. That is actually
> not an apostrophe, but ASCII char 180: ´

It's actually Unicode char #180, not ASCII. ASCII characters are in
0..127 range.

> In the Itunes library it is encoded as: Don%E2%80%99t

Looks like a utf-8 encoded string, then encoded like an url.

> I do some some conversions with both the library path names and the folder
> path names. Here is the code:
> (in the comment I dispay how the Don't part looks. I got this using print
> repr(filename))
> -
> #Once I have the filenames from the library I clean them using the following
> code (as filenames are in the format '
> file://localhost/m:/music/track%20name.mp3')
>
> filename = urlparse.urlparse(filename)[2][1:]  # u'Don%E2%80%99t' ; side
> question, anybody who nows a way to do this in a more fashionable way?
> filename = urllib.unquote (filename) # u'Don\xe2\x80\x99t'

This doesn't work for me in python 2.4, unquote expects str type, not
unicode. So it should be:

filename = urllib.unquote(filename.encode('ascii')).decode('utf-8')


> filename = os.path.normpath(filename) # u'Don\xe2\x80\x99t'
>
> I get the files in my music folder with the os.walk method and then
> I do:
>
> filename = os.path.normpath(os.path.join (root,name))  # 'Don\x92t'
> filename = unicode(filename,'latin1') # u'Don\x92t'
> filename = filename.encode('utf-8') # 'Don\xc2\x92t'
> filename = unicode(filename,'latin1') # u'Don\xc2\x92t'

This looks like calling random methods with random parameters :)
Python is able to return you unicode file names right away, you just
need to pass input parameters as unicode strings:

>>> os.listdir(u"/")
[u'alarm', u'ARCSOFT' ...]

So in your case you need to make sure the start directory parameter
for walk function is unicode.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: characters in python

2006-10-18 Thread Leo Kislov


On Oct 18, 11:50 am, Stens <[EMAIL PROTECTED]> wrote:
> Stens wrote:
> > Can python handle this characters: c,c,ž,d,š?
>
> > If can how"I wanna to change some characters in text (in the file) to the
> characters at this address:
>
> http://rapidshare.de/files/37244252/Untitled-1_copy.png.html

You need to use unicode, see any python unicode tutorial, for example
this one http://www.amk.ca/python/howto/unicode or any other you can
find with google.

Your script can look like this:

# -*- coding: PUT-HERE-ENCODING-OF-THIS-SCRIPT-FILE -*-
import codecs
outfile = codecs.open("your output file", "w", "encoding of the output
file"):
for line in codecs.open("your input file", "r", "encoding of the input
file"):
outfile.write(line.replace(u'd',u'd'))

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


Re: characters in python

2006-10-18 Thread Leo Kislov

Leo Kislov wrote using google groups beta:
> On Oct 18, 11:50 am, Stens <[EMAIL PROTECTED]> wrote:
> > Stens wrote:
> > > Can python handle this characters: c,c,ž,d,š?

[snip]

> outfile.write(line.replace(u'd',u'd'))

I hope you'll do better than google engeers who mess up croatian
characters in new google groups. Of course the last 'd' should be latin
d with stroke. I really typed it but google swallowed the stroke.

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


Re: codecs.EncodedFile

2006-10-18 Thread Leo Kislov

Neil Cerutti wrote:

> It turns out to be troublesome for my case because the
> EncodedFile object translates calls to readline into calls to
> read.
>
> I believe it ought to raise a NotImplemented exception when
> readline is called.
>
> As it is it silently causes interactive applications to
> apparently hang forever, and breaks the line-buffering
> expectation of non-interactive applications.

Does it work if stdin is a pipe? If it works then raising
NotImplemented doesn't make sense.

> If raising the exception is too much to ask, then at least it
> should be documented better.

Improving documentation is always a good idea. Meanwhile see my
solution how to make readline method work:
http://groups.google.com/group/comp.lang.python/msg/f1267dc612314657

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


Re: Flexible Collating (feedback please)

2006-10-19 Thread Leo Kislov
Ron Adam wrote:

> locale.setlocale(locale.LC_ALL, '')  # use current locale settings

It's not current locale settings, it's user's locale settings.
Application can actually use something else and you will overwrite
that. You can also affect (unexpectedly to the application)
time.strftime() and C extensions. So you should move this call into the
_test() function and put explanation into the documentation that
application should call locale.setlocale


>  self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE)

[snip]

>  if NUMERICAL in self.flags:
>  slist = self.numrex.split(s)
>  for i, x in enumerate(slist):
>  try:
>  slist[i] = float(x)
>  except:
>  slist[i] = locale.strxfrm(x)

I think you should call locale.atof instead of float, since you call
re.compile with re.LOCALE.

Everything else looks fine. The biggest missing piece is support for
unicode strings.

  -- Leo.

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


Re: Type discrepancy using struct.unpack

2006-10-19 Thread Leo Kislov

Pieter Rautenbach wrote:
> Hallo,
>
> I have a 64 bit server with CentOS 4.3 installed, running Python.
>
> [EMAIL PROTECTED] pymsnt-0.11.2]$ uname -a
> Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT
> 2006 x86_64 x86_64 x86_64 GNU/Linux
>
> Consider the following two snippets, issuing a struct.unpack(...) using
> Python 2.3.4 and Python 2.5 respectively.
>
> [EMAIL PROTECTED] pymsnt-0.11.2]$ python
> Python 2.5 (r25:51908, Oct 17 2006, 10:34:59)
> [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import struct
> >>> print type(struct.unpack(">L", "")[0])
> 
> >>>
>
> [EMAIL PROTECTED] pymsnt-0.11.2]$ /usr/bin/python2.3
> Python 2.3.4 (#1, Feb 17 2005, 21:01:10)
> [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import struct
> >>> print type(struct.unpack(">L", "")[0])
> 
> >>>
>
> I would expect  in both cases. Why is this not so?

http://mail.python.org/pipermail/python-dev/2006-May/065199.html

  -- Leo.

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


Re: Flexible Collating (feedback please)

2006-10-20 Thread Leo Kislov
Ron Adam wrote:
> Leo Kislov wrote:
> > Ron Adam wrote:
> >
> >> locale.setlocale(locale.LC_ALL, '')  # use current locale settings
> >
> > It's not current locale settings, it's user's locale settings.
> > Application can actually use something else and you will overwrite
> > that. You can also affect (unexpectedly to the application)
> > time.strftime() and C extensions. So you should move this call into the
> > _test() function and put explanation into the documentation that
> > application should call locale.setlocale
>
> I'll experiment with this a bit, I was under the impression that local.strxfrm
> needed the locale set for it to work correctly.

Actually locale.strxfrm and all other functions in locale module work
as designed: they work in C locale before the first call to
locale.setlocale. This is by design, call to locale.setlocale should be
done by an application, not by a 3rd party module like your collation
module.

> Maybe it would be better to have two (or more) versions?  A string, unicode, 
> and
> locale version or maybe add an option to __init__ to choose the behavior?

I don't think it should be two separate versions. Unicode support is
only a matter of code like this:

# in the constructor
self.encoding = locale.getpreferredencoding()

# class method
def strxfrm(self, s):
if type(s) is unicode:
return locale.strxfrm(s.encode(self.encoding,'replace')
return locale.strxfrm(s)

and then instead of locale.strxfrm call self.strxfrm. And similar code
for locale.atof

> This was the reason for using locale.strxfrm. It should let it work with 
> unicode
> strings from what I could figure out from the documents.
>
> Am I missing something?

strxfrm works only with byte strings encoded in the system encoding.

  -- Leo

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


Re: comparing Unicode and string

2006-10-20 Thread Leo Kislov

[EMAIL PROTECTED] wrote:
> Thanks, John and Neil, for your explanations.
>
> Still I find it rather difficult to explain to a Python beginner why
> this error occurs.
>
> Suggestion: shouldn't an error raise already when I try to assign s2? A
> normal string should never be allowed to contain characters that are
> not codable using the system encoding. This test could be made at
> compile time and would render Python more didadic.

This is impossible because of backward compatibility, your suggestion
will break a lot of existing programs. The change is planned to happen
in python 3.0 where it's ok to break backward compatibility if needed.

  -- Leo.

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


Re: right curly quote and unicode

2006-10-20 Thread Leo Kislov
On 10/19/06, TiNo <[EMAIL PROTECTED]> wrote:
> Now I know where the problem lies. The character in the actual file path is
> u+00B4 (Acute accent) and in the Itunes library it is u+2019 (a right curly
> quote). Somehow Itunes manages to make these two the same...?
>
> As it is the only file that gave me trouble, I changed the accent in the
> file to an apostrophe and re-imported it in Itunes. But I would like to hear
> if there is a solution for this problem?

I remember once I imported a russian mp3 violating tagging standard by
encoding song name in windows-1251 encoding into itunes and itunes
converted the name without even asking me into standard compliant
utf-8. So there is some magic going on. In your case u+00B4 is a
compatibility character from unicode.org point of view and they
discourage usage of such characters. Perhaps itunes is eager to make
u+00B4 character history as soon as possible. Googling for "itunes
replaces acute with quote" reveals that char u+00B4 is not alone. Read
the first hit. I'm afraid you will have to reverse engeneer what
itunes is doing to some characters.

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


Re: encoding of sys.argv ?

2006-10-23 Thread Leo Kislov

Jiba wrote:
> Hi all,
>
> I am desperately searching for the encoding of sys.argv.
>
> I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. 
> sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is 
> "utf-8". However, sys.argv is neither in ASCII (since I can pass French 
> accentuated character), nor in UTF-8. It seems to be encoded in "latin-1", 
> but why ?

Your system is misconfigured, complain to your distribution. On UNIX
sys.getfilesystemencoding(), sys.stdin.encoding, sys.stdout.encoding,
locale.getprefferedencoding and the encoding of the characters you type
should be the same.

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


Re: encoding of sys.argv ?

2006-10-23 Thread Leo Kislov

Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, Jiba wrote:
>
> > I am desperately searching for the encoding of sys.argv.
> >
> > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem.
> > sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is
> > "utf-8". However, sys.argv is neither in ASCII (since I can pass French
> > accentuated character), nor in UTF-8. It seems to be encoded in
> > "latin-1", but why ?
>
> There is no way to determine the encoding.  The application that starts
> another and sets the arguments can use any encoding it likes and there's
> no standard way to find out which it was.

There is standard way: nl_langinfo function
<http://www.opengroup.org/onlinepubs/009695399/functions/nl_langinfo.html>
The code in pythonrun.c properly uses it find out the encoding. The
other question if Linux or *BSD distributions confirm to the standard.

  -- Leo.

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


Re: How to identify generator/iterator objects?

2006-10-25 Thread Leo Kislov

Kenneth McDonald wrote:
> I'm trying to write a 'flatten' generator which, when give a
> generator/iterator that can yield iterators, generators, and other data
> types, will 'flatten' everything so that it in turns yields stuff by
> simply yielding the instances of other types, and recursively yields the
> stuff yielded by the gen/iter objects.
>
> To do this, I need to determine (as fair as I can see), what are
> generator and iterator objects. Unfortunately:
>
>  >>> iter("abc")
> 
>  >>> def f(x):
> ... for s in x: yield s
> ...
>  >>> f
> 
>  >>> f.__class__
> 
>
> So while I can identify iterators, I can't identify generators by class.

But f is not a generator, it's a function returning generator:

>>> def f():
... print "Hello"
... yield 1
...
>>> iter(f)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iteration over non-sequence
>>> iter(f())

>>> type(f())

>>> 

Notice, there is no side effect of calling f function.

  -- Leo

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


Re: How to identify generator/iterator objects?

2006-10-25 Thread Leo Kislov

Michael Spencer wrote:
> Kenneth McDonald wrote:
> > I'm trying to write a 'flatten' generator which, when give a
> > generator/iterator that can yield iterators, generators, and other data
> > types, will 'flatten' everything so that it in turns yields stuff by
> > simply yielding the instances of other types, and recursively yields the
> > stuff yielded by the gen/iter objects.
> >
> > To do this, I need to determine (as fair as I can see), what are
> > generator and iterator objects. Unfortunately:
> >
> >  >>> iter("abc")
> > 
> >  >>> def f(x):
> > ... for s in x: yield s
> > ...
> >  >>> f
> > 
> >  >>> f.__class__
> > 
> >
> > So while I can identify iterators, I can't identify generators by class.
> >
> > Is there a way to do this? Or perhaps another (better) way to achieve
> > this flattening effect? itertools doesn't seem to have anything that
> > will do it.
> >
> > Thanks,
> > Ken
> I *think* the only way to tell if a function is a generator without calling it
> is to inspect the compilation flags of its code object:
>
>   >>> from compiler.consts import CO_GENERATOR
>   >>> def is_generator(f):
>   ... return f.func_code.co_flags & CO_GENERATOR != 0
>   ...
>   >>> def f1(): yield 1
>   ...
>   >>> def f2(): return 1
>   ...
>   >>> is_generator(f1)
>   True
>   >>> is_generator(f2)
>   False
>   >>>

It should be noted that this checking is completely irrelevant for the
purpose of writing flatten generator. Given

def inc(n):
yield n+1

the following conditions should be true:

list(flatten([inc,inc])) == [inc,inc]
list(flatten([inc(3),inc(4)]) == [4,5]

  -- Leo

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


Re: my first software

2006-10-26 Thread Leo Kislov

[EMAIL PROTECTED] wrote:
> I am a beginner of programming and started to learn Python a week ago.
> last 3 days, i write this little tool for Renju.if you have any advice
> on my code,please tell me

> s = ''
>
> for i in range (0,len(done) - 1):
> s = s +str(done[i][0]) + str(done[i][1]) + '\n'
> s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1])
>
>

This is easier to do with a generator comprehension and join method:

s = '\n'.join(str(item[0]) + str(item[1]) for item in done)


> for i in range (0, len(s)):
> x = s[i][0]
> .
> if i%2 == 0:
> 

There is a builtin function enumerate for this case, IMHO it's slightly
easier to read:

for i, item in enumerate(s)
x = item[0]
...
if not i%2:
...

> if len(done) != 0 and beensaved == 0 and askyesno(...):
> saveasfile()

It's a personal matter, but usually python programmers treats values in
boolean context directly without comparison:

if done and not beensaved and askyesno(...):

The rules are documented here: http://docs.python.org/lib/truth.html .

  -- Leo

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


Re: subprocess cwd keyword.

2006-10-26 Thread Leo Kislov

Ivan Vinogradov wrote:
> Dear All,
>
> I would greatly appreciate a nudge in the right direction concerning
> the use of cwd argument in the call function from subprocess module.
>
> The setup is as follows:
>
> driver.py <- python script
> core/ <- directory
>   main<- fortran executable in the core directory
>
>
> driver script generates some input files in the core directory. Main
> should do its thing and dump the output files back into core.
> The problem is, I can't figure out how to do this properly.
>
> call("core/main") works but uses .. of core for input/output.
>
> call("core/main",cwd="core") and call("main",cwd="core") both result in
[snip exception]

Usually current directory is not in the PATH on UNIX. Try
call("./main",cwd="core") 

  -- Leo

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


Re: gettext on Windows

2006-10-28 Thread Leo Kislov

[EMAIL PROTECTED] wrote:
> Martin v. Löwis wrote:
> > [EMAIL PROTECTED] schrieb:
> > > Traceback (most recent call last):
> > >   File "panicbutton.py", line 36, in ?
> > > lan = gettext.GNUTranslations (open (sLang, "rb"))
> > >   File "C:\Python24\lib\gettext.py", line 177, in __init__
> > > self._parse(fp)
> > >   File "C:\Python24\lib\gettext.py", line 280, in _parse
> > > raise IOError(0, 'File is corrupt', filename)
> > > IOError: [Errno 0] File is corrupt: 'locale\\fr_FR.mo'
> >
> > If it says so, it likely is right. How did you create the file?
>
> I only get the "File is corrupt" error when I changed
>
> lan = gettext.GNUTranslations (open (sLang))

This code definately corrupts .mo files since on windows files are
opened in text mode by default.

> to
>
> lan = gettext.GNUTranslations (open (sLang, "rb"))
>
> Without the "rb" in the open () I get a "struct.error : unpack str size
> does not match format" error (see original post).

struct.error usually means input data doesn't correspond to expected
format.

> The .mo files were created using poEdit (www.poedit.org), and I get the
> same error with various translations, all created by different people.

Try msgunfmt
http://www.gnu.org/software/gettext/manual/html_node/gettext_128.html#SEC128
to see if it can convert your files back to text.

  -- Leo

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


Re: subprocess decoding?

2006-10-29 Thread Leo Kislov

MC wrote:
> Hi!
>
> On win-XP (french), when I read subprocess (stdout), I must use
> differents decoding (cp1252,cp850,cp437, or no decoding), depending of
> the "launch mode" of the same Python's script:
>   - from command-line
>   - from start+run
>   - from icon
>   - by Python-COM-server
>   - etc.
>
> (.py & .pyw can also contribute)
>
>
> How to know, on the fly, the encoding used by subprocess?

You can't. Consider a Windows equivalent of UNIX "cat" program. It just
dump content of a file to stdout. So the problem of finding out the
encoding of stdout is equal to finding out encoding of any file. It's
just impossible to do in general. Now, you maybe talking about
conventions. AFAIK since Windows doesn't have strong command line
culture, it doesn't such conventions.

  -- Leo

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


Re: Lookuperror : unknown encoding : utf-8

2006-10-29 Thread Leo Kislov

Sachin Punjabi wrote:
> Hi,
>
> I wanted to read a file encoded in utf-8 and and using the following
> syntax in my source which throws me an error specifying Lookuperror :
> unknown encoding : utf-8. Also I am working on Python version 2.4.1.
>
> import codecs
> fileObj = codecs.open( "data.txt", "r", "utf-8" )
>
> Can anyone please guide me how do I get utf-8 activated in my codecs or
> any setting needs to be done for the same before using codecs.

What OS? Where did you get your python distribution? Anyway, I believe
utf-8 codec was in the python.org distribution since the introduction
of unicode (around python 2.0). If you can't use utf-8 codec right out
of the box, something is really wrong with your setup.

  -- Leo

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


Re: Lookuperror : unknown encoding : utf-8

2006-10-30 Thread Leo Kislov

Sachin Punjabi wrote:
> On Oct 30, 1:29 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> > Sachin Punjabi wrote:
> > > The OS is Windows XPthen your installation is seriously broken.  where 
> > > did you get the
> > installation kit?  have you removed stuff from the Lib directory ?
> >
> > 
>
> It was already installed on my PC and I have no clue how it was
> installed or any changes has been done.

Then it's a distribution of your PC manufacturer. They could omit some
modules like utf-8 codec.

> I am just downloading newer
> version from python.org and will install and check it. I think there
> should be problem with installation itself.

That's a right idea, I'd also recommend to leave the manufacturer's
python distribution alone. Do not remove it, do not upgrade it. Some
programs provided by the manufacturer can stop working. If the
preinstalled python was installed into c:\python24 directory, choose
some other directory when you install python from python.org.

  -- Leo

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


Re: Lookuperror : unknown encoding : utf-8

2006-10-30 Thread Leo Kislov

Sachin Punjabi wrote:
> I installed it again but it makes no difference. It still throws me
> error for LookUp Error: unknown encoding : utf-8.

Most likely you're not using the new python, you're still running old
one. 

  -- Leo

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


Re: How to test python extension modules during 'make check' / 'make distcheck'?

2006-11-02 Thread Leo Kislov

Mark Asbach wrote:
> Hi pythonians,
>
> I'm one of the maintainers of an open source image processing toolkit
> (OpenCV) and responsible for parts of the autotools setup. The package
> mainly consists of four shared libraries but is accompanied by a python
> package containing some pure python code and of course extension modules
> for the four libraries.
>
> Now during the last month we were preparing a major release which means
> testing, fixing, testing, fixing, ... in the first degree. Typical
> functionality of the shared libraries is verified during 'make check'
> and 'make distcheck' by binaries that are linked against the libraries
> (straight forward) and are listed in the 'TESTS' automake primary.
>
> Unfortunately, many problems with the python wrappers arose from time to
> time. Currently we have to build and install before we can run any
> python-based test routines. When trying to integrate python module
> testing into the automake setup, there are some problems that I couldn't
> find a solution for:
>
> a) the extension modules are built in different (other) subdirectories -
> so they are not in the local path where python could find them

As I understand it's not python that cannot find them but dynamic
linker. On ELF UNIX systems you can set LD_LIBRARY_PATH to help linker
find dependencies, on Windows -- PATH. If you need details, you can
find them in dynamic linker manuals.

> b) the libraries and extension modules are built with libtool and may
> have rpaths compiled in (is this problematic)?

libtools seems to have some knobs to cope with rpath:
http://sourceware.org/ml/bug-glibc/2000-01/msg00058.html

> c) a different version of our wrappers might be installed on the testing
> machine, somewhere in python/site-packages. How can I make sure that
> python only finds my 'new' local generated modules?

Set PYTHONPATH to the directory where locally generated modules are
located. They will be found before site packages.

  -- Leo

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


Re: Erronous "unsupported locale setting" ?

2006-11-06 Thread Leo Kislov
robert wrote:
> Why can the default locale not be set by its true name? but only by '' ? :

Probably it is just not implemented. But since locale names are system
specific (For example windows accepts 'ch' as Chinese in Taiwan, where
as IANA <http://www.iana.org/assignments/language-subtag-registry>
considers it Chamorro) setlocale should probably grow an additional
keyword parameter: setlocale(LC_ALL, iana='de-DE')

  -- Leo

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


Re: Erronous "unsupported locale setting" ?

2006-11-06 Thread Leo Kislov

robert wrote:
> Leo Kislov wrote:
> > robert wrote:
> >> Why can the default locale not be set by its true name? but only by '' ? :
> >
> > Probably it is just not implemented. But since locale names are system
> > specific (For example windows accepts 'ch' as Chinese in Taiwan, where
> > as IANA <http://www.iana.org/assignments/language-subtag-registry>
> > considers it Chamorro) setlocale should probably grow an additional
> > keyword parameter: setlocale(LC_ALL, iana='de-DE')
>
> that'd be another fat database to blow up the python core(s).
>
> I just wonder why locale.setlocale(locale.LC_ALL,"de_DE") doesn't accept the 
> name, which
> >>> locale.getlocale() / getdefaultlocale()
> ('de_DE', 'cp1252')
> already deliver ?

It is documented that those functions return cross platform RFC 1766
language code. This code sometimes won't be compatible with OS specific
locale name. Cross platform code can useful if you want to create your
own locale database for example cross platform language packs.

Right now we have:

setlocale(category) -- get(it's not a typo) OS locale name
getlocale(category) -- get cross platform locale name
setlocale(category,'') -- enable default locale, return OS locale name
getdefaultlocale()  -- get cross platform locale name

I agree it's very confusing API, especially setlocale acting like
getter, but that's what we have. Improvement is welcome.

  -- Leo

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


Re: comparing Unicode and string

2006-11-10 Thread Leo Kislov
Neil Cerutti wrote:
> On 2006-11-10, Steve Holden <[EMAIL PROTECTED]> wrote:
> >>> But I don't insist on my PEP. The example just shows just
> >>> another pitfall with Unicode and why I'll advise to any
> >>> beginner: Never write text constants that contain non-ascii
> >>> chars as simple strings, always make them Unicode strings by
> >>> prepending the "u".
> >>
> >> That doesn't do any good if you aren't writing them in unicode
> >> code points, though.
> >
> > You tell the interpreter what encoding your source code is in.
> > It then knows precisely how to decode your string literals into
> > Unicode. How do you write things in "Unicode code points"?
>
> for = u"f\xfcr"

Unless you're using unicode unfriendly editor or console, u"f\xfcr" is
the same as u"für":

>>> u"f\xfcr" is u"für"
True

So there is no need to write unicode strings in hexadecimal
representation of code points.

  -- Leo

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

Re: str.title question after '

2006-11-13 Thread Leo Kislov

Antoon Pardon wrote:
> I have a text in ascii. I use the ' for an apostroph. The problem is
> this gives problems with the title method.  I don't want letters
> after a ' to be uppercased. Here are some examples:
>
>argument   result  expected
>
>   't smidje   'T Smidje   't Smidje
>   na'ama  Na'Ama  Na'ama
>   al pi tnu'atAl Pi Tnu'AtAl Pi Tnu'at
>
>
> Is there an easy way to get what I want?

def title_words(s):
words = re.split('(\s+)', s)
return ''.join(word[0:1].upper()+word[1:] for word in words)

>
> Should the current behaviour condidered a bug?

I believe it follows definition of \w from re module.

> My would be inclined to answer yes, but that may be
> because this behaviour would be wrong in Dutch. I'm
> not so sure about english.

The problem is more complicated. First of all, why title() should be
limited to human languages? What about programming languages? Is
"bar.bar.spam" three tokens or one in a foo programming language? There
are some problems with human languages too: how are you going to
process "out-of-the-box" and "italian-american"?

  -- Leo

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


Re: Character Encodings and display of strings

2006-11-13 Thread Leo Kislov

JKPeck wrote:
> It seemed to me that this sentence
>
> For many types, this function makes an attempt to return a string that
> would yield an object with the same value when passed to eval().
>
> might mean that the encoding setting of the source file might influence
> how repr represented the contents of the string.  Nothing to do with
> Unicode.  If a source file could have a declared encoding of, say,
> cp932 via the # coding comment, I thought there was a chance that eval
> would respond to that, too.

Not a chance :) Encoding is a property of an input/output object
(console, web page, plain text file, MS Word file, etc...). All
input/output object have specific rules determining their encoding,
there is absolutely no connection between encoding of the source file
and any other input/output object.

repr escapes bytes 128..255 because it doesn't know where you're going
to output its result so repr uses the safest encoding: ascii.

  -- Leo

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


Re: Problem reading with bz2.BZ2File(). Bug?

2006-11-15 Thread Leo Kislov
Clodoaldo Pinto Neto wrote:
> Fredrik Lundh wrote:
> > Clodoaldo Pinto Neto wrote:
> >
> > > The offending file is 5.5 MB. Sorry, i could not reproduce this problem
> > > with a smaller file.
> >
> > but surely you can post the repr() of the last two lines?
>
> This is the output:
>
> $ python bzp.py
> line number: 588317
> '\x07'
> ''

Confirmed on windows with 2.4 and 2.5:

C:\p>\Python24\python.exe bzp.py
line number: 588317
'\x1e'
''

C:\p>\Python25\python.exe bzp.py
line number: 588317
'\x1e'
''

Looks like one byte of garbage is appended at the end of file. Please
file a bug report. As a workaround "rU" mode seems to work fine for
this file.

  -- Leo

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


Re: how to print pdf with python on a inkjet printer.

2006-11-17 Thread Leo Kislov

krishnakant Mane wrote:
> hello all.
> I am developing an ncurses based python application that will require
> to create pdf reports for printing.
> I am not using py--qt or wx python.
> it is a consol based ui application and I need to make a pdf report
> and also send it to a lazer or ink jet printer.
> is it possible to do so with python?
> or is it that I will have to use the wxpython library asuming that
> there is a print dialog which can open up the list of printers?
> if wx python and gui is the only way then it is ok but I will like to
> keep this application on the ncurses side.

Assuming you are on a UNIX-like system, you really need to setup CUPS
<http://www.cups.org/> (or may be your system already provides CUPS).
PDF seems to be the future intermediate format for UNIX printing
<http://www.linux.com/article.pl?sid=06/04/18/2114252> and CUPS already
supports printing PDF files, just run "lp your_file.pdf" to print a
file. CUPS only have command line interface:
<http://www.cups.org/documentation.php/options.html>

  -- Leo

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


Re: how to print pdf with python on a inkjet printer.

2006-11-17 Thread Leo Kislov
Leo Kislov wrote:
> CUPS only have command line interface:
> <http://www.cups.org/documentation.php/options.html>

My mistake: CUPS actually has official C API
<http://www.cups.org/documentation.php/api-cups.html> and unofficial
python bindings <http://freshmeat.net/projects/pycups/>.

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


Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?

2006-11-17 Thread Leo Kislov

Martin v. Löwis wrote:
> gabor schrieb:
> >> All this code will typically work just fine with the current behavior,
> >> so people typically don't see any problem.
> >>
> >
> > i am sorry, but it will not work. actually this is exactly what i did,
> > and it did not work. it dies in the os.path.join call, where file_name
> > is converted into unicode. and python uses 'ascii' as the charset in
> > such cases. but, because listdir already failed to decode the file_name
> > with the filesystem-encoding, it usually also fails when tried with
> > 'ascii'.
>
> Ah, right. So yes, it will typically fail immediately - just as you
> wanted it to do, anyway; the advantage with this failure is that you
> can also find out what specific file name is causing the problem
> (whereas when listdir failed completely, you could not easily find
>  out the cause of the failure).
>
> How would you propose listdir should behave?

How about returning two lists, first list contains unicode names, the
second list contains undecodable names:

files, troublesome = os.listdir(separate_errors=True)

and make separate_errors=True by default in python 3.0 ?

  -- Leo

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

Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?

2006-11-17 Thread Leo Kislov

gabor wrote:
> Martin v. Löwis wrote:
> > gabor schrieb:
> >> i also recommend this approach.
> >>
> >> also, raising an exception goes well with the principle of the least
> >> surprise imho.
> >
> > Are you saying you wouldn't have been surprised if that had been
> > the behavior?
>
>
> yes, i would not have been surprised. because it's kind-of expected when
> dealing with input, that malformed input raises an unicode-exception.
> and i would also expect, that if os.listdir completed without raising an
> exception, then the returned data is correct.

The problem is that most programmers just don't want to deal with
filesystem garbage but they won't be happy if the program breaks
either.

> > How would you deal with that exception in your code?
>
> depends on the application. in the one where it happened i would just
> display an error message, and tell the admins to check the
> filesystem-encoding.
>
> (in other ones, where it's not critical to get the correct name, i would
> probably just convert the text to unicode using the "replace" behavior)
>
> what about using flags similar to how unicode() works? strict, ignore,
> replace and maybe keep-as-bytestring.
>
> like:
> os.listdir(dirname,'strict')

That's actually an interesting idea. The error handling modes could be:
'mix' -- current behaviour, 'ignore' -- drop names that cannot be
decoded, 'separate' -- see my other message. 

  -- Leo

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


Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?

2006-11-18 Thread Leo Kislov
Martin v. Löwis wrote:
> Leo Kislov schrieb:
> > How about returning two lists, first list contains unicode names, the
> > second list contains undecodable names:
> >
> > files, troublesome = os.listdir(separate_errors=True)
> >
> > and make separate_errors=True by default in python 3.0 ?
>
> That would be quite an incompatible change, no?

Yeah, that was idea-dump. Actually it is possible to make this idea
mostly backward compatible by making os.listdir() return only unicode
names and os.binlistdir() return only binary directory entries.
Unfortunately the same trick will not work for getcwd.

Another idea is to map all 256 bytes to unicode private code points.
When a file name cannot be fully decoded the undecoded bytes will be
mapped to specially allocated code points. Unfortunately this idea
seems to leak if the program later wants to write such unicode string
to a file. Python will have to throw an exception since we don't know
if it is ok to write broken string to a file. So we are back to square
one, programs need to deal with filesystem garbage :(

  -- Leo

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

  1   2   3   >