Re: A simple single line, triple-quoted comment is giving syntax error. Why?

2015-03-28 Thread Tim Roberts
Aditya Raj Bhatt  wrote:

>On Wednesday, March 18, 2015 at 1:04:39 PM UTC-5, Laurent Pointal wrote:
>> > Can someone also provide a sort of a 'guide' to triple-quoted
>> > comments in general?
>> 
>> A triple ' or " string is a Python string, allowing line-return in
>> string.
>
>What do you mean by line-return in string? Is it newline? Does it mean I
>can write -
>
>'''first part
>second part'''
>
>?
> 
>> If it is in an expression (like a = 5 '''a comment'''), then it must
>> be a 
>> valid expression (and here it is not).
>
>What is not a valid expression here?

Were you ever able to extract the Real Answer to your original question
from the froth that resulted?  Your basic misunderstanding is that the
triple-quote thing is NOT a comment marker.  It is a string literal,
exactly like a single-quoted string, except that it allows embedded
newlines.  So, your statement
a = 5 '''a comment'''
is invalid for exactly the same reason that the statement
a = 5 "a comment"
is invalid.  Neither one of those statement have any comments.

There is a CONVENTION to embed a literal string as the first line in a
function, to allow for automatic documentation.  Whether the literal string
is single-quoted or triple-quoted is irrelevant.  That is, these two things
are equivalent:

def func(a):
"This is a function"
return a*2

def func(a):
"""This is a function"""
return a*2
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.4.1 on W2K?

2014-10-11 Thread Tim Roberts
Michael Torrie  wrote:
>
>That's really interesting.  I looked briefly at the page.  How does your
>python extension work with xywrite?  Does it manipulate xywrite
>documents or does it tie in at runtime with Xywrite somehow?  If so, how
>does it do this?  Crossing the divide into a 16-bit app is pretty
>impressive.

Actually, Microsoft made it pretty easy to call 32-bit DLLs in a 16-bit
process and vice versa.  That's why many of us were surprised when they did
not provide the same capability in the 32/64 transition.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: very lightweight gui for win32 + python 3.4

2014-09-22 Thread Tim Roberts
Wolfgang Keller  wrote:
>
>> wxPython and Qt are well known but they are not exactly lightweight.
>
>wxPython not lightweight?
>
>It's just a wrapper of win32.

That's not really accurate.  wxWidgets does expose the Win32 APIs, but the
wrapping is not all that transparent.  And wxPython adds significant
functionality on the top of that.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: binario - simple work with binary files

2014-09-06 Thread Tim Roberts
Rustom Mody  wrote:

>On Tuesday, September 2, 2014 6:05:19 AM UTC+5:30, Tim Roberts wrote:
>> Rustom Mody wrote:
>
>> >On Tuesday, August 26, 2014 6:58:42 AM UTC+5:30, Tim Roberts wrote:
>
>> >> To the equivalent code with struct:
>> >>   import struct
>> >>   dscrp = "H?fs5B"
>> >>   f = open('file.dat')
>> >>   stuff = struct.unpack( dscrp, f.read() )
>> >>   print stuff
>> >> In both cases, you have to KNOW the format of the data beforehand.  If you
>> >> do a read_short where you happen to have written a float, disaster ensues.
>> >> I don't really see that you've added very much.
>> >I thought much the same.
>> >However notice your f.read(). Its type is string.
>> >What if file.dat is a 1GB wav file?
>
>>   f.seek(512000)
>>   stuff = struct.unpack( dscrp, f.read(128) )
>
>And what if the struct you are (trying to) unpack is greater or less
>than 128 bytes?

stuff = struct.unpack( dscrp, f.read(struct.calcsize(dscrp)) )

>But its not enough. One can write a generator that yields one char
>at a time.  How to feed that to struct.unpack??

I think you have lost track of the discussion here, because your question
is irrelevant.  His binario package couldn't do that, either, since it only
accepts filenames.  But at least with struct.unpack, I can suck from the
generator into a string, and feed that string into struct.unpack.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: binario - simple work with binary files

2014-09-01 Thread Tim Roberts
Rustom Mody  wrote:

>On Tuesday, August 26, 2014 6:58:42 AM UTC+5:30, Tim Roberts wrote:

>> To the equivalent code with struct:
>
>>   import struct
>
>>   dscrp = "H?fs5B"
>
>>   f = open('file.dat')
>>   stuff = struct.unpack( dscrp, f.read() )
>
>>   print stuff
>
>> In both cases, you have to KNOW the format of the data beforehand.  If you
>> do a read_short where you happen to have written a float, disaster ensues.
>
>> I don't really see that you've added very much.
>
>I thought much the same.
>However notice your f.read(). Its type is string.
>
>What if file.dat is a 1GB wav file?

  f.seek(512000)
  stuff = struct.unpack( dscrp, f.read(128) )

The point is that files already know how to position themselves.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANN: binario - simple work with binary files

2014-08-25 Thread Tim Roberts
bwa...@gmail.com wrote:
>
>binario is the Python package that lets an application read/write primitive 
>data types from an underlying input/output file as binary data.
>
>Package on PyPI: https://pypi.python.org/pypi/binario
>Package on GitHub: https://github.com/asaskevich/binario
>Docs: http://binarios-docs.readthedocs.org/en/latest/
>
>Package still in Alpha, and I need some help with testing, new features and 
>docs :)

I hope you will accept constructive criticism.

The documentation says it lets an application read/write binary data from
an "underlying input/output stream".  That's not really accurate.  "Stream"
implies something very general, but your constructors will only accept
filenames.  Your code ONLY works with files.  If I have a stream of data in
memory, or an already open file, your code can't be used.

This is why packages like "struct" (which is basically a more compact
version of what you are doing) read from a string or a buffer, and leave
the file-like behavior to things that already know how to behave like
files.

Compare your sample code:

  >>> import binario
  >>> r = binario.Reader("file.dat")
  >>> r.read_short()
  2014
  >>> r.read_bool()
  True
  >>> r.read_float()
  3.1415
  >>> r.read_string()
  "Hello, world!"
  >>> r.read(5)
  b'\x80\x14\n\xff\x00'

To the equivalent code with struct:

  import struct

  dscrp = "H?fs5B"

  f = open('file.dat')
  stuff = struct.unpack( dscrp, f.read() )

  print stuff

In both cases, you have to KNOW the format of the data beforehand.  If you
do a read_short where you happen to have written a float, disaster ensues.

I don't really see that you've added very much.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Very basic question. How do I start again?

2014-08-21 Thread Tim Roberts
Seymore4Head  wrote:
>
>I want to give the computer 100 tries to guess a random number between
>1 and 100 picked by the computer.

If it takes more than 7, you're doing it wrong...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3 is killing Python

2014-07-16 Thread Tim Roberts
MRAB  wrote:
>On 2014-07-16 00:53, Rick Johnson wrote:
>> On Tuesday, July 15, 2014 5:40:29 PM UTC-5, Abhiram R wrote:
>>
>> ...or some pretentious line
>> about "this was sent from my i-phone" -- send that crap to the
>> bitbucket!
>>
>"This was sent from my iPhone" == "I have an iPhone!"

Please note that iPhones come configured from the factory to say that. Some
users probably don't even know it is happening.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3 is killing Python

2014-07-16 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>For what little it is worth, if any one country won World War Two, it was 
>the USSR.

I don't think that's quite accurate.  It is certainly true that the USSR
suffered vastly more casualties than any participant in the war,
essentially losing one entire generation of young men.  It is also true
that the USSR faced the Germans head-on for longer than any other
combatant.

But it is is not at all clear that the USSR could have defeated Germany on
its own.  The enormous industrial capacity of the United States was an
extremely significant factor that helped turn the tide in what otherwise
would have been an ugly war of attrition, much like WWI.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Success with subprocess communicate on Windows?

2014-07-01 Thread Tim Roberts
Terry Reedy  wrote:
>
>It does not work on Windows. As I reported on 
>http://bugs.python.org/issue8631, msg222053,
> >>> subprocess.check_output("pyflakes -h")
>works in the interpreter and Idle shell, while
> >>> s.check_output("pyflakes c:\programs\python34\lib\turtle.py")
>gives bizarre output in the interpreter and hangs in the idle shell, as 
>does the code above.

Right.  What do you think \t is in a string?  (Hint: it's only one byte.)

You need to use
s.check_output("pyflakes c:\\programs\\python34\\lib\\turtle.py")
or
s.check_output(r"pyflakes c:\programs\python34\lib\turtle.py")
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help with executing DB query in two different places in a test

2014-05-19 Thread Tim Roberts
Sunitha Byju  wrote:
>
>I am trying to automate an ecom website. I need to run DB query after
>placing each order.  I don't know how to run different queries after
>each order.  Can someone help me out with having queries after each
>order submission or test?  

Well, what's your primary key?  After each test, you need to fetch the
record that should have been created, and verify that the fields contain
the information you provided.  For example, if you're doing a shopping
cart, then you must have some kind of key associated with this session. So,
you could just fetch all of the record for the session after each
transaction, and make sure the contents match what you expect.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Psycopg2 : error message.

2014-05-19 Thread Tim Roberts
dandrigo  wrote:
>
>I'm writing a python script for a web service. I have to connect to my
>postgres/postgis databases via Psycopg2. 
>
>I writed a little first script just to connect to my pg/postgis db and drop
>a test db. 
>
>But when i execute the python file, i have several error messages. 

Really, this wouldn't have been so hard to figure out if you had read the
documentation.

 conn=psycopg2.connect("dbname='busard_test' user='laurent'
host='localhost' password='cactus'")

Psycopg2 has two ways to specify the parameters.  You can either do them as
individual Python parameters, in which case each parameter is a string that
needs to be quited, OR you can use a single connection string, in which
case you do NOT quote the individual parameters.

So, you can either do this:

conn=psycopg2.connect("dbname=busard_test user=laurent host=localhost
password=cactus")

or do this:

 conn=psycopg2.connect(database='busard_test', user='laurent',
host='localhost', password='cactus'")
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Two Questions about Python on Windows

2014-04-05 Thread Tim Roberts
maxerick...@gmail.com wrote:
>
>You can also edit the PATHEXT environment variable to include .py/.pyw,
>making the python source files executable (as long as the types are 
>properly registered with Windows; if double clicking runs them they
>should be properly registered).

Let me clarify that just a bit.

There are several ways to run Python scripts from a Windows command line.
You can invoke the interpreter specifically by name:
C:\Apps\Python27\python xxx.py
C:\Apps\Python27\python xxx.pyw

Or, if the Python directory is in your path:
python xxx.py
python xxx.pyw

If the .py and .pyw extension are registered using assoc and ftype (which
the Windows installer does), then you can invoke them by file name:
xxx.py
xxx.pyw

If you add those extensions to PATHEXT, then you do not even need to
provide the extension, so they will look just like any other automatically
executable program:
    xxx
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: numpy.where() and multiple comparisons

2014-01-18 Thread Tim Roberts
Peter Otten <__pete...@web.de> wrote:

>John Ladasky wrote:
>
>> On Friday, January 17, 2014 6:16:28 PM UTC-8, duncan smith wrote:
>> 
>>>  >>> a = np.arange(10)
>>>  >>> c = np.where((2 < a) & (a < 7))
>>>  >>> c
>>> (array([3, 4, 5, 6]),)
>> 
>> Nice!  Thanks!
>> 
>> Now, why does the multiple comparison fail, if you happen to know?
>
>2 < a < 7
>
>is equivalent to
>
>2 < a and a < 7
>
>Unlike `&` `and` cannot be overridden (*)

And just in case it isn't obvious to the original poster, the expression "2
< a" only works because the numpy.array class has an override for the "<"
operator.  Python natively has no idea how to compare an integer to a
numpy.array object.

Similarly, (2 < a) & (a > 7) works because numpy.array has an override for
the "&" operator.  So, that expression is compiled as

numpy.array.__and__(
numpy.array.__lt__(2, a),
numpy.array.__lt__(a, 7)
)

As Peter said, there's no way to override the "and" operator.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python declarative

2014-01-18 Thread Tim Roberts
serto...@gmail.com wrote:
>
>First, I don't like that all parenthesis, I like to differentiate 
>which type of delimiter is, this is not so bad if using spaces but 
>anyways it's a little more difficult.  Second, In regard, to using
>something like myWindow=Window rather than Window "myWindow", at 
>first I didn't liked it that much, but in the end it does tell the 
>user that the attributes can be accesed just like anything else. 

Well, this all depends on whether you want this code to BE Python code, or
just to be READ BY Python code.  That's a huge difference.  If you want
your layout to BE Python code, then you have little alternative except to
use the suggestions offered.  But if you simply want your scripts to be
interpreted by a Python program, then you can do whatever you want.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: min max from tuples in list

2013-12-14 Thread Tim Roberts
Dennis Lee Bieber  wrote:
>
>>
>>Well "performant" is performant enough for the purposes of communicating
>>on the python list I think :D
>
>   Most probably could figure it out as being stylistically similar to
>"conformant", which I believe IS used in English 
>
>conformant => something that conforms
>performant => something that performs

Yes, I suspect it comes from people expecting too much consistency.  If
something that has "conformance" is "conformant", then something that has
good "performance" must be "performant".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is It Bug?

2013-12-07 Thread Tim Roberts
Mahan Marwat  wrote:
>
>Why this is not working.
>
>>>> 'Hello, World'.replace('\\', '\\')
>
>To me, Python will interpret '' to '\\'. 

It's really important that you think about the difference between the way
string literals are written in Python code, and the way the strings
actually look in memory.

The Python literal 'Hello, World' contains exactly 2 backslashes.  We
have to spell it with 4 backslashes to get that result, but in memory there
are only two.

Similarly, the Python literal '\\' contains exactly one character.

So, if your goal is to change 2 backslashes to 1, you would need
'Hello, World'.replace('','\\')

However, REMEMBER that if you just have the command-line interpreter echo
the result of that, it's going to show you the string representation, in
which each backslash is shown as TWO characters.  Observe:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'Hello, \\\\World'
>>> s
'Hello, World'
>>> print s
Hello, \\World
>>> s = s.replace('','\\')
>>> s
'Hello, \\World'
>>> print s
Hello, \World
>>>
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why is there no natural syntax for accessing attributes with names not being valid identifiers?

2013-12-03 Thread Tim Roberts
Piotr Dobrogost  wrote:
>
>Attribute access syntax being very concise is very often preferred 
>to dict's interface. 

It is not "very concise".  It is slightly more concise.

x = obj.value1
x = dct['value1']

You have saved 3 keystrokes.  That is not a significant enough savings to
create new syntax.  Remember the Python philosophy that there ought to be
one way to do it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pypix

2013-11-19 Thread Tim Roberts
Ajay Kumar  wrote:
>
>Hi Guys, i have created a site for Python Tutorials. here is the link 
>http://pypix.com/python/get-started-python-web-development/ . I would like to 
>have your opinion like what tutorials would you love to see.

Are you making a site for Python Tutorials, or tutorials for creating web
sites with Python?

Also, allow me to make one editorial note.  You say:

 Python is a general purpose programming language and is quickly
 becoming a must-have tool in the arsenal of any self-respecting
 programmer.

That statement was true in 1998.  Today, Python is a well-established and
mature programming tool.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: sendmail library ?!

2013-11-17 Thread Tim Roberts
Tamer Higazi  wrote:
>
>I am looking for a python library that does mailing directly through
>"sendmail".
>
>When I look into the docs, I see only an "smtlip" library but nothing
>that could serve with sendmail or postfix.
>
>Any ideas ?!

Remember that
   import smtplib
   s = smtplib.SMTP("localhost")
usually communicates directly with the local server, whether it be sendmail
or postfix or whatever.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Algorithm that makes maximum compression of completly diffused data.

2013-11-07 Thread Tim Roberts
Mark Janssen wrote:
>>> Well let me try to explain why it is working and i have implemented one.
>>> I only need to refresh my memory it was almost 15 years ago.
>>> This is not the solution but this is why it is working.
>>> 65536=256^2=16^4=***4^8***=2^16
>>
>> I think the idea is that you could take any arbitrary input sequence,
>> view it as a large number, and then find what exponential equation can
>> produce that result.  The equation becomes the "compression".

Interesting -- I hadn't noticed that.  Of course, now you have the
problem of expressing 4^8 in a compact way.

-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

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


Re: Algorithm that makes maximum compression of completly diffused data.

2013-11-07 Thread Tim Roberts
jonas.thornv...@gmail.com wrote:
>
>Well let me try to explain why it is working and i have implemented one.
>I only need to refresh my memory it was almost 15 years ago.
>This is not the solution but this is why it is working.
>65536=256^2=16^4=***4^8***=2^16

All of those values are indeed the same, and yet that is completely
unrelated to compression.  Did you honestly believe this was actually
explaining anything?

>Yes i am aware that 256 is a single byte 8 bits, but the approach is valid 
>anyway.

This whole post is a most amazing collection of non sequiturs.  If you
would like to describe your compression scheme, there really are people
here who would be interested in reading it (although that number gets less
and less as this thread goes on).
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Algorithm that makes maximum compression of completly diffused data.

2013-11-02 Thread Tim Roberts
jonas.thornv...@gmail.com wrote:
>
>Well then i have news for you.

Well, then, why don't you share it?

Let me try to get you to understand WHY what you say is impossible.  Let's
say you do have a function f(x) that can produce a compressed output y for
any given x, such that y is always smaller than x.  If that were true, then
I could call f() recursively:
f(f(...f(f(f(f(f(x)...))
and eventually the result get down to a single bit.  I hope it is clear
that there's no way to restore a single bit back into different source
texts.

Here's another way to look at it.  If f(x) is smaller than x for every x,
that means there MUST me multiple values of x that produce the same f(x).
Do you see?  If x is three bits and f(x) is two bits, that means there are
8 possible values for x but only 4 values for f(x).  So, given an f(x), you
cannot tell which value of x it came from.  You have lost information.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: First day beginner to python, add to counter after nested loop

2013-11-02 Thread Tim Roberts
jonas.thornv...@gmail.com wrote:
>
>I certainly do not like the old bracket style it was a catastrophe, but 
>in honesty the gui editor of python should have what i propose, a parser
>that indent automaticly at loops, functions and end.

Many editors do that.  Vim, which is what I use, certainly does.

>I promise you it will save millions of hours of bug searching all over 
>world in a month.

I suspect you meant "dozens" rather than "millions"...

Look, both schemes have their pitfalls.  With an "end" requirement, it's
easy to have code where the indenting doesn't match the actual nesting, and
that causes human confusion.  Without the "end" requirement, it's not hard
to type code where you forget to dedent.  Those are just two manifestations
of the exact same problem.  Neither scheme is provably superior to the
other.  It's just a choice that a language designer has to make.

I happen to like Python's choice.  You'll get used to it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: First day beginner to python, add to counter after nested loop

2013-10-30 Thread Tim Roberts
jonas.thornv...@gmail.com wrote:
>
>Why did Python not implement end... The end is really not necessary for
>the programming language it can be excluded, but it is a courtesy to
>the programmer and could easily be transformed to indents automaticly,
>that is removed before the compiliation/interpretation of code.  

You only say that because your brain has been poisoned by languages that
require some kind of "end".  It's not necessary, and it's extra typing. 99%
of programmers do the indentation anyway, to make the program easy to read,
so why not just make it part of the syntax?  That way, you don't
accidentally have the indentation not match the syntax.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: converting letters to numbers

2013-10-19 Thread Tim Roberts
Steven D'Aprano  wrote:
>On Sun, 13 Oct 2013 20:13:32 -0700, Tim Roberts wrote:
>
>> def add(c1, c2):
>>  % Decode
>>...
>Python uses # for comments, not %, as I'm sure you know. What language 
>were you thinking off when you wrote the above?


Psssht, I know better than that.

I've been reading through MATLAB code, which uses %, but I have CERTAINLY
not written enough MATLAB to excuse that.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing the terminal title bar with Python

2013-10-19 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>You might find this useful, or just for fun, but on POSIX systems (Linux, 
>Unix, Apple Mac, but not Windows) you can change the title of the 
>terminal window from Python. 

Just for completeness, this is also possible in Windows, assuming you have
installed py32win, which virtually every Windows Python user does:

import win32console
win32console.SetConsoleTitle(msg)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: converting letters to numbers

2013-10-13 Thread Tim Roberts
kjaku...@gmail.com wrote:
>
>Transfer it to an uppercase letter if it's a letter, if it's not then an error.
>This isn't right, I know, just testing around
>
>def add(c1, c2):
>ans = ''
>for i in c1 + c2:
>ans += chrord(i)-65))%26) + 65)
>return ans

It's close.  I think you're overthinking it.  Take it step by step. Decode,
process, encode.  That means convert the inputs to integers, add the
integers, convert the result back.

def add(c1, c2):
 % Decode
 c1 = ord(c1) - 65
 c2 = ord(c2) - 65
 % Process
 i1 = (c1 + c2) % 26
 % Encode
 return chr(i1+65)

Or, as a one-liner:

A = ord('A')
def add(c1, c2):
 return chr((ord(c1)-A + ord(c2)-A) % 26 + A)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: card dealer

2013-09-28 Thread Tim Roberts
Antoon Pardon  wrote:
>
>Op 28-09-13 12:31, Ned Batchelder schreef:
>>
>> I've thought that way about it too: there are so many shuffles any way,
>> it won't be a problem.  But think about it like this:  if you shuffle a
>> deck of 52 cards with a default Python random object, then once you have
>> dealt out only 28 cards, the entire rest of the deck is completely
>> determined.  That is, given the sequence of the first 28 cards, there's
>> only one choice for how the remaining 24 will be dealt.  Depending on
>> what you need from your deck of cards, that could be a complete disaster.
>
>I don't see it. Unless given those 28 cards you can actually predict
>those 24 other cards or at least can devise some betting strategy that
>will allow you to beat the odds I don't see how this could lead to a
>disaster.

That's exactly the problem.  Because the number of permutations is limited,
once you know the first 28 cards, you can uniquely identify the permutation
you started with, and that's enough to get the entire sequence.

Now, it's going to take a hell of a lot of memory to store that
information, so I'm not sure it is a disaster in a practical sense.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Newbie question related to Boolean in Python

2013-09-05 Thread Tim Roberts
skwyan...@gmail.com wrote:
>
># This is just to show my understanding of Boolean. In line 8-9, if 
>my input is "taunt bear", the result is true and true, which will 
>continue the loop.
>
> So what confused me is line 12-13. if my input is taunt bear, is it
>suppose to be taunt bear == "taunt bear" and bear_moved which is 
>true and true? which means the loop will continue instead of cancelling it.

I'm not quite sure what you're expecting.  There is nothing in any of the
cases that will exit the loop.  The loop is infinite.  I assume (with no
evidence) that the "dead" function calls sys.exit, which kills the program.
In that case, this makes a little bit of sense.  The first time you type
"taunt bear", bear_moved is set True and the loop runs again.  If you type
"taunt bear" a second time, then the bear is pissed off and you call
dead().
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to split with "\" character, and licence copyleft mirror of �

2013-09-05 Thread Tim Roberts
random...@fastmail.us wrote:
>
>Of course, in 99% of situations where you can use a windows pathname in
>Python, you are free to use it with a forward slash instead of a
>backslash.

This is actually worth repeating, because it's not well known.

ALL Windows APIs handle forward and backward slashes interchangably.  It is
only the command interpreter that requires the backslash.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to split with "\" character, and licence copyleft mirror of �

2013-09-01 Thread Tim Roberts
materil...@gmail.com wrote:

>Hello everybody
>I'm trying to run this: 
>
>
>>>> a = 'E:\Dropbox\jjfsdjjsdklfj\sdfjksdfkjslkj\flute.wav'
>>>> a.split('\')
>
>SyntaxError: EOL while scanning string literal
>
>
>I think that the character '\' is the problem, but unfortunately I'm
>developing a small app for windows and I need to show only the name
>of the .wav file, in this case 'flute.wav'.

I assume you know that backslash has a special meaning in string constants.
For example the string '\n\r' contains exactly two characters, and no
backslashes.

When you want to use an actual backslash in an ordinary string constant,
you have to double it.  So, you could have written your code as:
a = 'E:\\Dropbox\\jjfsdjjsdklfj\\sdfjksdfkjslkj\\flute.wav'
a.split('\\')

Another altrnative is to use "raw" strings, in which backslashes are not
interpreted:
a = r'E:\Dropbox\jjfsdjjsdklfj\sdfjksdfkjslkj\flute.wav'
a.split(r'\')

I assume your filename is actually input to your program, and not as a
constant in your code, so that may not be a problem.  However, there is an
API to do exactly what you're asking:

  >>> import os
  >>> a=r'E:\Dropbox\one\two\three\flute.wav'
  >>> os.path.split(a)
  ('E:\\Dropbox\\one\\two\\three', 'flute.wav')
  >>> os.path.split(a)[1]
  'flute.wav'
  >>>
  
>I also want to know how to mirror a character, in my case this one ©,
>because I'll use the Copyleft http://en.wikipedia.org/wiki/Copyleft
>to distribute my app.

You can't "mirror" a character.  That is an invented glyph that is not
present in Unicode.  Fortunately, the character doesn't have any legal
meaning, so you can just include explanatory text in your description that
identifies your license.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: must be dicts in tuple

2013-07-29 Thread Tim Roberts
Tanaya D  wrote:
>
>I am using Python with Bots(EDI translator)
>
>But i am getting the following error:
>MappingFormatError: must be dicts in tuple: get((({'BOTSID': 'HEADER'},),))
>
>Can anyone pls help me with it.

Possible hint: the error says you're supposed to have dicts in a tuple.
What you have is a dict in a tuple in a tuple.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get the OS System Font Directory(Cross-Platform) in python?

2013-07-12 Thread Tim Roberts
Metallicow  wrote:
>
>If the OS doesn't *have* a dedicated system fonts dir that is accessable 
>by the user, then I am not that much interested in dealing with it. 

Really?  Because Windows is the ONLY one of the major operating systems
that actually has a dedicated system fonts directory.  Linux doesn't even
have a dedicated windowing system.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hex dump w/ or w/out utf-8 chars

2013-07-12 Thread Tim Roberts
Joshua Landau  wrote:
>
>Isn't a superscript "c" the symbol for radians?

That's very rarely used.  More common is "rad".  The problem with a
superscript "c" is that it looks too much like a degree symbol.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Geo Location extracted from visitors ip address

2013-07-05 Thread Tim Roberts
? Gr33k  wrote:
>
>Is there a way to extract out of some environmental variable the Geo 
>location of the user being the city the user visits out website from?
>
>Perhaps by utilizing his originated ip address?

It is possible to look up the geographic region associated with a block of
IP addresses.  That does not necessarily bear any resemblence to the actual
location of the user.  It tells you the location of the Internet provider
that registered the IP addresses.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell Script to use pythonw.exe ?

2013-07-02 Thread Tim Roberts
goldtech  wrote:
>
>I just changed the file extension of the script file from .py to .pyw
>and it uses pythonw.exe. I didn't read it anywhere, just intuited it
>and tried it. Python has some very smart people working the language...

While your statement is true, that's not what happened here.

Windows has long had the ability to associate a file extension with a
handler.  If you start a command shell, the "assoc" command tells you the
program type associated with an extension, and the "ftype" command tells
you the command line that will be executed for that program type.  On my
box:

C:\tmp>assoc .py
.py=Python

C:\tmp>ftype Python
Python="C:\Apps\Python27\Python.exe" "%1" %*

C:\tmp>assoc .pyw
.pyw=Python.NoConFile

C:\tmp>ftype Python.NoConFile
Python.NoConFile="C:\Apps\Python27\Pythonw.exe" "%1" %*

You can create your own, if you want.  If you want files with a .script
extension to run PythonW, you can type:

assoc .script=Python.NoConFile
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-18 Thread Tim Roberts
Nick the Gr33k  wrote:
>
>On 16/6/2013 4:55 ??, Tim Roberts wrote:
>
>> Nick the Gr33k  wrote:
>> Because Python lets you use arbitrary values in a Boolean context, the net
>> result is exactly the same.
>
>What is an arbitrary value? don even knwo what arbitrary means literally 
>in English.

Basically, it means "any".  In Python, you can use ANY value where a
Boolean is expected.  All types have a Boolean meaning.  For integers, 0 is
false, anything else is true.  For strings, an empty string "" is false,
anything else is true.  For lists, an empty list [] is false, anything else
is true.  For tuples, an empty tuple () is false, anything else is true.
For dicts, an empty dict {} is false, anything else is true.

>The argument being returned in an "and" or "or" expression is the one 
>that *determined' the evaluation of the expression.

That's not exactly how I'd put it, but the statement is correct.  The last
thing it had to evaulate is the result of the expression.

>And actually what's being returned is not the argument itself but the 
>argument's value.

But this is no different than any other programming language.  Expressions
always use the value of their operands, and they always return a value.

The name vs value thing is critical to understanding Python, in my opinion,
and it can be a stumbling block when you're coming from another language.
Here's how I think about it.

Python had two distinct spaces: there is a space for names, and there is a
space for objects (which are values).  Objects live in a nameless, faceless
object cloud.

A name is always bound to some object (which might be the "None" object). A
name always knows its object, but an object never knows what names it is
bound to.

The only things that can be used in expressions and function arguments are
objects.  Names are merely the way we specify which objects to be used.

a = [3]

That creates a nameless list containing a single integer object with the
value 3.  It then binds the name "a" to that list.  Note that the list has
no clue that it is bound to any names.

b = a

That binds "b" to the same list.  "b" and "a" are not related in any way,
except that they happen to be bound to the same object.  Note that there is
still only one list.

a.append(4)

That modifies the list so that it now contains [3,4].  b is bound to the
same list, so if you 
print(b)
you'll see [3,4]

Now, let's say I do this:

a = [5]

Here's where people get tripped up.  This does not change our original
list.  Instead, it creates a new nameless list containing 5, and binds the
name a to that list.  a and b are no longer bound to the same object.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-15 Thread Tim Roberts
Nick the Gr33k  wrote:
>
>but i'm doing this all day long i just dont comprehend why it works this 
>way.
>it doesn't make any sense to me.

It's just a rule you'll have to learn.  The "and" and "or" operators in
Python simply do not return a boolean value.  The expression "a or b" is
evaluated as:
if a is true then return a otherwise return b

It's true that in many languages, "or" returns a Boolean value, so the
result is:
if a is true then return True otherwise return bool(b)

Because Python lets you use arbitrary values in a Boolean context, the net
result is exactly the same.  However, the Python is a lot more flexible,
because it lets you simulate the C ternary ?: operator.

Similarly, "a and b" is evaluated as:
if a is false then return a otherwise return b

In a long series separated by "or", the expression is true as soon as one
of the subexpressions is true.  So, as a short-circuit, Python simply
returns the first one that has a "true" value.  So, for example, these all
return 'abcd':

'abcd' or 'defg' or 'hjkl'   ==> 'abcd'
0 or 'abcd' or 'defg' or 'hjkl'  ==> 'abcd'
0 or None or 'abcd' or 'defg' or 'hjkl'  ==> 'abcd'

Similarly, "and" returns the first "false" value, or if they're all true,
the last value.  Why?  Because it can't know whether the whole expression
is true unless it looks at every value.  So:

0 and 1 and 'what'   ==>  0
1 and 0 and 'what'   ==>  0
1 and None and 0 ==>  None
1 and 1 and 'what'   ==> 'what'
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an integer from a sequence of bytes

2013-06-13 Thread Tim Roberts
Fábio Santos  wrote:

>On 5 Jun 2013 06:23, "Tim Roberts"  wrote:
>> A single machine word was 60 bits, so a single register read got you 10
>> characters.
>
>10 characters! Now that sounds like it's enough to actually store a word.
>However long words can inadverten be cropped.

Well, Cybers weren't often used for heavy text processing.  Most of the
time, a "word" was limited to 7 characters, so you could fit an 18-bit
address in the bottom of the register.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-11 Thread Tim Roberts
 ??  wrote:
>
>[code]
>   if not re.search( '=', name ) and not re.search( '=', month ) 
> and not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE clientsID = 
> (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and 
> YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
>   elif not re.search( '=', month ) and not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE 
> MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', 
> (month, year) )
>   elif not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE 
> YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year )

There is so much you didn't tell us here, including which database you are
using.

With most Python database adapters, the second parameter of the "execute"
method must be a tuple.  "year" is not a tuple.  My guess is that this will
work fine:
cur.execute( 
"SELECT * FROM works WHERE YEAR(lastvisit)=%s ORDER BY lastvisit",
(year,) )

It seems silly to fire up a regular expression compiler to look for a
single character.  
if name.find('=') < 0 and month.find('=') < 0 and year.find('=') < 0:
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an integer from a sequence of bytes

2013-06-04 Thread Tim Roberts
Grant Edwards  wrote:

>On 2013-06-03, Dan Stromberg  wrote:
>>
>> When I was a Freshman in college, I used a CDC Cyber a lot; it had 6 bit
>> bytes and 60 bit words.  This was in 1985.
>
>But you couldn't address individual 6-bit "hextets" in memory could
>you?  My recollection is that incrementing a memory address got you
>the next 60-bit chunk -- that means that by the older terminology a
>"byte" was 60 bits.  A "character" was 6 bits, and a single register
>or memory location could hold 6 characters.

A single machine word was 60 bits, so a single register read got you 10
characters.  There were three sets of registers -- the X registers were 60
bits, the A and B registers were 18 bits, which was the size of the largest
possible address.

CDC didn't actually use the term "byte".  That was IBM's domain.

When ASCII became unavoidable, most programs changed to using 5x 12-bit
"bytes" per word.

Ah, memories.  I spent 10 years working for Control Data.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encodign issue in Python 3.3.1 (once again)

2013-05-26 Thread Tim Roberts
? ???33?  wrote:
>
>This is the code that although correct becaus it works with englisg(standARD 
>ASCII letters) it wont with Greek:
>...
>if( log ):
>   name = log
>   # print specific client header info
>   cur.execute('''SELECT hits, money FROM clients WHERE name = %s''', 
> (name,) )
>   data = cur.fetchone()
>===
>
>The following is the live output of: tail -F /usr/local/apache/logs/error_log &
>...
>   File "/opt/python3/lib/python3.3/site-packages/pymysql/cursors.py", line 
> 108, in execute, referer: http://superhost.gr/cgi-bin/pelatologio.py
> query = query.encode(charset), referer: 
> http://superhost.gr/cgi-bin/pelatologio.py
> UnicodeEncodeError: 'latin-1' codec can't encode characters in position 
> 46-52: ordinal not in range(256), referer: 
> http://superhost.gr/cgi-bin/pelatologio.py
>
>I can udnerstand that this is an encoding issue but i dont knwo how to fix 
>this.
>please help.

While the other responders have a good laugh at your expense, let me
actually point you toward a solution.

The traceback line I left above is the key.  It shows that the pymysql
module is trying to encode your Unicode string into an 8-bit character set
in order to send it to the MySQL server.  It is THAT conversion that
failed; this has nothing to do with the server (yet).

So, why did it choose 'latin-1'?  Because that's the default character set
for pymysql.  You could have learned this yourself -- you have the full
source code for pymysql on your machine.

You can override the default character set:

    con = pymysql.connect( db = 'metrites', host = 'localhost', user =
'me', passwd = 'somepass', charset='utf-8', init_command='SET NAMES UTF8' )
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scope of a class..help???

2013-05-23 Thread Tim Roberts
lokeshkopp...@gmail.com wrote:
>
>ok Peter Otten,
>but how to make a Class global??

Your class IS global.  I still don't think you understand what you did
wrong.  You've tripped into a strange little quirk of scoping.  Here is
your code with some unimportant lines removes.

class Node:
def __init__(self, value=None):
self.value = value
self.next = None

## OK, at this point, you have a global called "Node", which is a class.

def number_to_LinkedList(numbers):
  pass
  list_numbers = list(numbers)
  head_node = Node()
  # ... 
  current_node.next = None
  while Node:
print Node.data

Python actually does a first scan through your function before it starts to
compile it.  When it does the scan, it sees you use the name "Node" as a
local variable.  At that point, it remembers that "in this function scope,
'Node' is a local name".  Now, it codes to compile the class.  When it
encounters Node() for the first time, it sees that "Node" is not defined
locally, even though it was supposed to be a local name.

You are assuming that the first Node() in that function will automatically
refer to the global class.  It won't.  The only way to solve this dilemma
is to change the name you use in the "while" loop.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write fast into a file in python?

2013-05-19 Thread Tim Roberts
Carlos Nepomuceno  wrote:

>Python really writes '\n\r' on Windows. Just check the files.

It actually writes \r\n, but it's not Python that's doing it.  It's the C
runtime library.

And, of course, you can eliminate all of that by opening the file in binary
mode open(name,'wb').
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Collision of Two Rect

2013-05-04 Thread Tim Roberts
Alex Gardner  wrote:
>
>When rect A collides with rect B they stick when I am wanting A to bounce off 
>of B.  I have tried different methods, but none seem to work.  My source is 
>here:  http://pastebin.com/CBYPcubL
>
>The collision code itself is below:
>--
># Bounce off of the paddle
>if paddle_rect.colliderect(ball_rect):
>y_vel*=-1
>x_vel*=-1

I haven't looked at the rest of your code, but the lines you have here are
going to send the ball back in exactly the direction it came from -- a 180
degree reversal.  When a ball hits a paddle at an angle other than head on,
only ONE of the velocities is reversed.  When you hit a horizontal paddle,
only the Y velocity is negated.  The ball continues in the same X
direction:

\O
 \  /
  \/
   

See?  The X velocity continues unchanged until it hits a vertical wall.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File Read issue by using module binascii

2013-04-27 Thread Tim Roberts
Jimmie He  wrote:

>When I run the readbmp on an example.bmp(about 100k),the Shell is become to 
>"No respose",when I change f.read() to f.read(1000),it is ok,could someone 
>tell me the excat reason for this?
>Thank you in advance!
>
>Python Code as below!!
>
>import binascii
>
>def read_bmp():
>f = open('example.bmp','rb')
>rawdata = f.read()   #f.read(1000) is ok
>hexstr = binascii.b2a_hex(rawdata)   #Get an HEX number
>bsstr = bin (int(hexstr,16))[2:]

I suspect the root of the problem here is that you don't understand what
this is actually doing.  You should run this code in the command-line
interpreter, one line at a time, and print the results.

The "read" instruction produces a string with 100k bytes.  The b2a_hex then
produces a string with 200k bytes.  Then, int(hexstr,16) takes that 200,000
byte hex string and converts it to an integer, roughly equal to 10 to the
240,000 power, a number with some 240,000 decimal digits.  You then convert
that integer to a binary string.  That string will contain 800,000 bytes.
You then drop the first two characters and print the other 799,998 bytes,
each of which will be either '0' or '1'.

I am absolutely, positively convinced that's not what you wanted to do.
What point is there in printing out the binary equavalent of a bitmap?

Even if you did, it would be much quicker for you to do the conversion one
byte at a time, completely skipping the conversion to hex and then the
creation of a massive multi-precision number.  Example:

f = open('example.bmp','rb')
rawdata = f.read()
bsstr = []
for b in rawdata:
bsstr.append( bin(ord(b)) )
    bsstr = ''.join(bsstr)

or even:
f = open('example.bmp','rb')
bsstr = ''.join( bin(ord(b))[2:] for b in f.read() )
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird python behavior

2013-04-25 Thread Tim Roberts
Forafo San  wrote:
>
>OK, lesson learned: Take care not to have module names that conflict with 
>python's built ins. Sorry for being so obtuse.

You don't have to apologize.  We've all been bitten by this at least once.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get JSON values and how to trace sessions??

2013-04-23 Thread Tim Roberts
webmas...@terradon.nl wrote:
> 
>But now i am wondering how to trace sessions? it is needed for a
>multiplayer game, connected to a webserver. How do i trace a PHP-session?
>I suppose i have to save a cookie with the sessionID from the webserver?

Yes.  The server will send a Set-Cookie: header with your first response.
You just need to return that in a Cookie: header with every request you
make after that.

>Are their other ways to keep control over which players sends the gamedata?

Not sure what you mean.  If the web site requires cookies, this is what you
have to do.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusing Algorithm

2013-04-23 Thread Tim Roberts
RBotha  wrote:
>
>I'm facing the following problem:
>
>"""
>In a city of towerblocks, Spiderman can 
>“cover” all the towers by connecting the 
>first tower with a spider-thread to the top 
>of a later tower and then to a next tower 
>and then to yet another tower until he 
>reaches the end of the city. ...
>
>-Example:
>List of towers: 1 5 3 7 2 5 2
>Output: 4
>"""
>
>I'm not sure how a 'towerblock' could be defined. How square does a shape have 
>to be to qualify as a towerblock? Any help on solving this problem?

Here's your city;

  [  ]
  [  ]
  [  ][  ][  ]
  [  ][  ][  ]
  [  ][  ][  ][  ]
  [  ][  ][  ][  ][  ][  ]
  [  ][  ][  ][  ][  ][  ][  ]
 --
   A   B   C   D   E   F   G

Once you see the picture, you can see that you'd thread from B to D without
involving C.  I think you'll go A to B to D to F to G -- 4 threads.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encoding NaN in JSON

2013-04-18 Thread Tim Roberts
Miki Tebeka  wrote:
>
>>> I'm trying to find a way to have json emit float('NaN') as 'N/A'.
>> No.  There is no way to represent NaN in JSON.  It's simply not part of the
>> specification.
>
>I know that. I'm trying to emit the *string* 'N/A' for every NaN.

You understand that this will result in a chunk of text that is not JSON?
Other JSON readers won't be able to read it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encoding NaN in JSON

2013-04-16 Thread Tim Roberts
Miki Tebeka  wrote:
>
>I'm trying to find a way to have json emit float('NaN') as 'N/A'.
>I can't seem to find a way since NaN is a float, which means overriding 
>"default" won't help.
>
>Any simple way to do this?

No.  There is no way to represent NaN in JSON.  It's simply not part of the
specification.  From RFC 4627 section 2.4:

   Numeric values that cannot be represented as sequences of digits
   (such as Infinity and NaN) are not permitted.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling python script in dos and passing arguments

2013-04-16 Thread Tim Roberts
Chris Rebert  wrote:
>
>2. Glob/wildcard ("*") expansion is done by the shell, but
>subprocess.Popen does not use the shell by default (for good reason!).

This is only true in Linux.  In Windows, the wildcard characters are passed
to the program, so each app must do its own glob expansion.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting USB volume serial number from inserted device on OSX

2013-04-04 Thread Tim Roberts
John Nagle  wrote:
>
>   That would be useful to have as a portable function for all USB
>devices.  Serial port devices are particularly annoying, because their
>port number is somewhat random when there's more than one, and changes
>on hot-plugging.

There is no portable solution.  Every operating system handles this kind of
this very differently.  Remember, the operating system abstractions are all
designed to hide this from you.  When you open a serial port or an audio
device or use a file system, you aren't supposed to KNOW that there is a
USB device behind it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PSF News: Guido van Rossum quitting Python to develop new, more difficult to learn, language.

2013-04-01 Thread Tim Roberts
Pierre O'Dee  wrote:
>
>Guido went on to say that he's now working on a new language
>called Giddy-up-and-Go which will take the worst features of C++,
>Java, and French combined with elements of both PHP and Klingon
>syntax.

This would seem like the ideal programming language in which to implement
an open source version of the ill-fated Microsoft Bob project.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a simple stand alone python app I can use on my Kindle fire?

2013-04-01 Thread Tim Roberts
ah  wrote:
>
>I'm enjoying learning python, and would like to be able to study and practice 
>on the go, using my kindle fire reader. (wifi enabled).
>
>Amazon does have an app, Qpython lite, but requires a  live wifi connection
>to the internet to run. I'm looking for a simple python app, stand alone 
>that i can run on my kindle, without an internet connection,  just to 
>practice while i learn. (Just a simple terminal, and text editor, and
>python? like ubuntu offers.)

You have identified the ingredients: you need a shell, you need an editor,
and you need the Python interpreter.

Your Kindle is an Android device, which means it runs Linux, but I don't
know whether you have access to the general Android app store.  There
certainly are Android terminal applications available that will bring up a
shell for you.  The one you have is probably enough.

There is also an implemention of Vim for Android that even supports touch
commands.  If you've played with Ubuntu, then you probably already know
Vim.

After that, you'll need Python itself.  Your machine has an ARM processor,
so you'll want to find a Python built for Linux ARM.  I know such things
are available, but you may have to do some creative searching.

Just like Ubuntu, you cannot run Windows applications.  You also cannot run
any x86 or amd64 applications.  You must have ARM binaries.  If you want to
go really crazy, you can get a "cross compiler" for your Ubuntu system that
lets you build ARM binaries.  From there, you could build Python from
source.


>I've tried downloading portable python, and couldnt' get it to run 
>('can't run in DOS mode?'), 

Of course not.  Portable Python is a Windows product.  Your Kindle doesn't
run Windows.


>I've tried downloading ubuntu to my kindle and couldn't, 

Did you download the x86 version?  That will not work.  There are Ubuntu
distributions available for the Kindle Fire, but it's going to require
getting your hands dirty.  Google is your friend here.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does 1**2**3**4**5 raise a MemoryError?

2013-04-01 Thread Tim Roberts
morphex  wrote:
>
>While we're on the subject, wouldn't it be nice to have some cap there so
>that it isn't possible to more or less block the system with large 
>exponentiation?

There IS a cap.  It's called the "MemoryError" exception.

But, seriously, what would you have it do instead?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Separate Rows in reader

2013-03-28 Thread Tim Roberts
Jiewei Huang  wrote:
>
>Hi the output is:
>
>[('John Cleese,Ministry of Silly Walks,421,27-Oct',), ('Stacy 
>Kisha,Ministry of Man Power,1234567,17-Jan',)]
>
>how to make it to
>
>[CODE][('John Cleese', 'Ministry of Silly Walks' , '421', '27-Oct'), 
>('Stacy Kisha', 'Ministry of Man Power', '1234567,17-Jan')][/CODE]
>
>i need ' ' in all the row and the , to be remove after the date

Do you have any intention of doing ANY of this work on your own?  Or are
you going to steal it all?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how does the % work?

2013-03-24 Thread Tim Roberts
leonardo  wrote:
>
>thank you all!

So, what was the problem?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how does the % work?

2013-03-22 Thread Tim Roberts
leonardo selmi  wrote:
>
>i wrote this example :
>
>name = raw_input("What is your name?")
>quest = raw_input("What is your quest?")
>color = raw_input("What is your favorite color?")
>
>print """Ah, so your name is %s, your quest is %s, 
>and your favorite color is %s."""  % (name, quest, color)

No, you didn't.  You wrote:

print('''Ah, so your name is %s, your quest is %s, and your
favorite color is %s.''') % (name, quest, color)

>but i get this error:  Traceback (most recent call last):
>  File "/Users/leonardo/print.py", line 5, in 
>favourite color is %s.''') % (name, quest, color)
>TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
>
>how can i solve it?

You are using Python 3.  In Python 3, "print" is a function that returns
None.  So, the error is exactly correct.  To fix it, you need to have the %
operator operate on the string, not on the result of the "print" function:

print('''Ah, so your name is %s, your quest is %s, and your
favorite color is %s.''' % (name, quest, color))
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changes on windows registry doesn�t take effect immediately

2013-03-14 Thread Tim Roberts
iMath  wrote:
>
>changes on windows registry doesn’t take effect immediately

Well, that's not exactly the issue.  The registry is being changed
immediately.  The issue is that IE doesn't check for proxy settings
continuously.

>but the changes on windows registry doesn’t take effect immediately, so
>is there some way to change the windows registry and let the changes
>take effect immediately without restarting IE ?

No.  This is an IE issue, not a registry issue.  Other browsers might
behave differently.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First attempt at a Python prog (Chess)

2013-02-18 Thread Tim Roberts
Chris Hinsley  wrote:
>
>Is a Python list as fast as a bytearray ?

Python does not actually have a native array type.  Everything in your
program that looked like an array was actually a list.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First attempt at a Python prog (Chess)

2013-02-13 Thread Tim Roberts
Chris Hinsley  wrote:

>New to Python, which I really like BTW.
>
>First serious prog. Hope you like it. I know it needs a 'can't move if 
>your King would be put into check' test. But the weighted value of the 
>King piece does a surprising emergent job.

It looks a little like a C program ported line-by-line to Python.  For
example, in Python, there's no reason not to keep the board as an 8x8 array
instead of a 64-element list.  That by itself would make the code easier to
read.  It would also let you replace this:
for row in range(8):
for col in range(8):

with the more Pythonic:
for row in board:
for cell in row:

I would probably replace the piece_type function with a map that maps the
piece number directly to the piece 
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call shell?

2013-02-11 Thread Tim Roberts
contro opinion  wrote:
>
>>>> import os
>>>> os.system("i=3")
>0
>>>> os.system("echo $i")
>
>0
>>>>
>why i can't get the value of i ?

Each invocation of os.system creates a brand new shell that starts, runs,
and terminates.  Your first command adds a variable "i" to the environment
for that shell, but the variable is deleted when the shell procsess
terminates.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python programming language?

2013-02-09 Thread Tim Roberts
Grant Edwards  wrote:
>
>IMO, a "scripting language" is used to automate tasks that would
>otherwise be done by a human sitting at a keyboard typing commands.
>[Perhaps that definition should be extended to include tasks that
>would otherwise by done by a human sitting and clicking on a GUI.]

I think that definition is a little too neat and clean.  

Most people would call bash a "scripting language", but it is also clearly
a programming language.  It has syntax, variables and expressions.  I
suspect it is Turing-complete, although I haven't seen a proof of that.

I would assert that scripting languages are a proper subset of programming
languages, not a separate category.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal 0**0

2013-02-06 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>Does anyone have an explanation why Decimal 0**0 behaves so differently from
>float 0**0?
>...
>I am familiar with the arguments for treating 0**0 as 0, or undefined, but
>thought that except for specialist use-cases, it was standard practice for
>programming languages to have 0**0 return 1. According to Wikipedia, the
>IEEE 754 standard is for "pow" to return 1, although languages can define a
>separate "powr" function to return a NAN.
>
>http://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero
>
>I suspect this is a bug in Decimal's interpretation of the standard. Can
>anyone comment?

I don't think Decimal ever promised to adhere to IEEE 754, did it?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-21 Thread Tim Roberts
Ferrous Cranus  wrote:
>
>Renames and  moves are performed, either by shell access or either by cPanel 
>access by website owners.
>
>That being said i have no control on HOW and WHEN users alter their html pages.

Right, and that makes it impossible to solve this problem.

Think about some scenarios.  Let's say I have a web site with two pages:
~/web/page1.html
~/web/page2.html

Now let's say I use some editor to make a copy of page1 called page1a.html.
~/web/page1.html
~/web/page1a.html
~/web/page2.html

Should page1a.html be considered the same page as page1.html?  What if I
subsequently delete page1.html?  What if I don't?  How long will you wait
before deciding they are the same?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-21 Thread Tim Roberts
Ferrous Cranus  wrote:
>
>No, it is difficult but not impossible.
>It just cannot be done by tagging the file by:
>
>1. filename
>2. filepath
>3. hash (math algorithm producing a string based on the file's contents)
>
>We need another way to identify the file WITHOUT using the above attributes.

Think about it this way.  Say that YOU, as a human being, were inserted
into the web server.  You are handed the path and the contents of a page
about to be served.  How would YOU solve this problem?

If you can't describe in words how YOU would recognize these altered files,
then there is absolutely no way to teach a computer how to do it.  It IS
impossible.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Tim Roberts
Dave Angel  wrote:
>
>As Adnan has pointed out, Python is case insensitive. 

That's not really what you meant to say...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to download internet files by python ?

2013-01-09 Thread Tim Roberts
iMath  wrote:
>
>There is also a httplib2 module 
>https://code.google.com/p/httplib2/
>
>which one is more pythonic and powerful ?

Both are Pythonic, and power is irrelevant for this.  Your code is going to
spend 90% of its time waiting for the network.  Just solve the problem.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: got stuck in equation

2013-01-01 Thread Tim Roberts
usamazo...@gmail.com wrote:
> 
>i know very litle about programing. still learning from tutorials. u can call 
>me a beginner.
>now i need to solve this equation so that i can put this in python but the 
>formula of design is very complex 
> 
>Formula is :
> 
>log(W18) = (Z)(S)+9.36log(SN+1) 
>-2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr-)-8.07
> 
>every thing is constant except this SN. . i want to seperate SN like SN= 
>rest of the stuff. how can i seprate it because manualy its impossible to
>take SN out.

Right.  Algebraically, it isn't practical to solve this for SN.  That
probably means you're going to need a iterative solution.  That is, you
start with a guess, see how far off you are, and refine the guess until you
narrow in on a solution.  That means you'll have to figure out whether
raising SN gets you closer or farther away from a solution.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: the class problem

2013-01-01 Thread Tim Roberts
contro opinion  wrote:
>
>here is my haha  class
>class  haha(object):
>  def  theprint(self):
>print "i am here"
>
>>>> haha().theprint()
>i am here
>>>> haha(object).theprint()
>Traceback (most recent call last):
>  File "", line 1, in 
>TypeError: object.__new__() takes no parameters
>
>why   haha(object).theprint()  get wrong output?

It doesn't -- that's the right output.  What did you expect it to do?

The line "class haha(object)" says that "haha" is a class that happens to
derive from the "object" base class.  The class is still simply called
"haha", and to create an instance of the class "haha", you write "haha()".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2013-01-01 Thread Tim Roberts
Omer Korat  wrote:
>
>I am using the nltk.classify.MaxEntClassifier. This object has a set of 
>labels, and a set of probabilities: P(label | features). It modifies 
>this probability given data. SO for example, if you tell this object 
>that the label L appears 60% of the time with the feature F, then 
>P(L | F) = 0.6. 
>
>The point is, there is no way to access the probabilities directly. 
>The object's 'classify' method uses these probabilities, but you can't
>call them as an object property. 

Well, you have the source code, so you can certainly go look at the
implementation and see what the data is based on.

>In order to adjust probabilities, you have to call the object's 'train' 
>method, and feed classified data in.

The "train" method is not actually an object method, it's a class method.
It doesn't use any existing probabilities -- it returns a NEW
MaxEntClassifier based entirely on the training set.

>So is there any way to save a MaxEntClassifier object, with its 
>classification probabilities, without having to call the 'train' method?

If you haven't called the "train" method, there IS no MaxEntClassifier
object.  Once you have called "train", you should be able to pickle the new
MaxEntClassifier and fetch it back with its state intact.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2012-12-28 Thread Tim Roberts
Omer Korat  wrote:
>
>So it means pickle doesn't ever save the object's values, only how it was 
>created? 

You say that as though there were a difference between the two.  There
isn't.  An object is just a dictionary of values.  If you set an object
member to a string, then that object's dictionary for that member name
contains a string.  It doesn't contain some alternative packed binary
representation of a string.

>Say I have a large object that requires a lot of time to train on data. It
>means pickle doesn't save its values, so you have to train it every time
>anew? Is there no way to save its trained values?

When you say "train on data", what do you mean?  If your training creates
computed data in other members, those members and their values should also
be saved in the pickle.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-28 Thread Tim Roberts
Abhas Bhattacharya  wrote:
>
>Now, for your questions:
>If i call one() and two() respectively, i would like to see "one" and "two".
>I dont have much knowledge of lambda functions, neither am i going to use
>them, so that's something I cant answer.

My point is not that these are special cases to consider, but rather that
all of these are the GENERAL case.  A function, now matter how it was
created, is an anonymous object that lives out in object space.  Like all
objects, a function object can be bound to many different names.  An object
doesn't know just one name, and when a function object is invoked, it has
NO IDEA what name was used to invoke it.  The information is simply not
available.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am facing an issue while decoding json string using json.loads

2012-12-26 Thread Tim Roberts
sajuptpm  wrote:
>
>I am facing an issue while decoding json string using json.loads(jstring).
>Its working, if i do json.dumps(eval(jstring)) before json.loads(jstring).
>I could not figure out the issue. I want to avoide use of "eval" here.

The problem is that your string contains two instances of an escaped right
bracket  \]  .  That's not one of the characters you're allowed to escape
in JSON.  The rules are very strict.  There are only 8 allowed escape
codes, plus the \u construct.

Note that you cannot just replace \] with ], because your string also
contains one instance of \\] .

Who is doing the JSON encoding?  It appears to be doing it incorrectly.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-26 Thread Tim Roberts
Abhas Bhattacharya  wrote:
>
>While I am defining a function, how can I access the name (separately as
>string as well as object) of the function without explicitly naming 
>it(hard-coding the name)?
>For eg. I am writing like:
>def abc():
>#how do i access the function abc here without hard-coding the name?

Why?  Of what value would that be?

Note that I'm not merely being obstructionist here.  What you're asking
here is not something that a Python programmer would normally ask.  The
compiled code in a function, for example, exists as an object without a
name.  That unnamed object can be bound to one or more function names, but
the code doesn't know that.  Example:

def one():
print( "Here's one" )

two = one

That creates one function object, bound to two names.  What name would you
expect to grab inside the function?

Even more obscure:

two = lamba : "one"
one = two

Which one of these is the "name" of the function?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python USB control on Windows 7?

2012-12-22 Thread Tim Roberts
Duncan Booth  wrote:
>
>In this year's Christmas Raffle at work I won a 'party-in-a-box' including 
>USB fairy lights.
>
>They sit boringly on all the time, so does anyone know if I can toggle the 
>power easily from a script? My work PC is running Win7.

Not easily, no.  It's not really a USB device -- I'm betting it doesn't
even enumerate.  It's just sucking power from the USB wires.  There's
nothing to control.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does dead code costs time?

2012-12-05 Thread Tim Roberts
Bruno Dupuis  wrote:

>On Wed, Dec 05, 2012 at 05:40:51PM +0100, Bruno Dupuis wrote:
> 
>> Good point! I didn't even noticed that. It's weird... Maybe the
>> difference comes from a peehole optim on f which is not possible on g as
>> g is to complex.
>
>Neil, you were right, thanks. I patched peehole.c to remove this optim, and
>now the figures are the same. I investigate to find out why the latter
>function is not optimized the same way (and if it can be, I'll propose a
>patch for that)

At the risk of being labeled a prude, please be careful about spelling (and
pronouncing) the whole word "peephole".  The word as you have spelled it
here (twice) is a vulgarity.

Now, I'm all in favor of the occasional vulgarity, but if this is a
misunderstanding, you could find yourself as the butt of some awkward jokes
at some future optimization conference...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen and the subprocess module

2012-11-28 Thread Tim Roberts
Andrew  wrote:
>
>I'm working on a script that will run an executable obtaine the output  
> from the executable
>and do some analysis on the output. Essentially the script runs the  
>executable analyses
>the data.
>I'm looking into os.popen and the subprocess module, implementing os.popen  
>is easy but i hear
>it is depreciating  however I'm finding the implemantation of subprocess  
>daunting can anyone help

One of my favorite things about the subprocess module is that the
introductory comments have examples of how to use subprocess to replace
almost every use case for os.system and os.popen.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing process name

2012-11-19 Thread Tim Roberts
andrea crotti  wrote:

>I have very long processes to spawn which I want to lauch as separate
>processes (and communicate with ZeroMQ), but now the problem is that the
>forked process appears in "ps" with the same name as the launcher
>process.

http://code.google.com/p/py-setproctitle/
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subprocess puzzle and two questions

2012-11-13 Thread Tim Roberts
w...@mac.com wrote:
>...
>However, if I try the same operation in the python interpreter using 
>subprocess.Popen like so:
>
>>>> import subprocess
>>>> result = subprocess.Popen(['time', 'nslookup', 'www.es.net', '8.8.4.4'], 
>>>> shell = False, stdout = subprocess.PIPE, stderr = 
>>>> subprocess.PIPE).communicate()
>>>> print result
>('Server:\t\t8.8.4.4\nAddress:\t8.8.4.4#53\n\nNon-authoritative 
>answer:\nwww.es.net\tcanonical name = 
>www3.es.net.\nName:\twww3.es.net\nAddress: 128.55.22.201\n\n', '0.06 
>real 0.00 user 0.00 sys\n')
>
>And the timing information I'm after has been truncated to two digits after 
>the decimal.  It appears that Popen is applying a default format. 

No, that's silly.  A few minutes thought should have told you that.  In
your standalone test, you are getting the "time" command that is built in
to bash.  In the subprocess example, you've specified "shell = False", so
you are using the external "time" command (/usr/bin/time in my system), and
that command has a different output format.  The csh "time" command is
different yet again.

>1) how can I recover that third digit from the subprocess?

Do you actually believe that the third decimal place has any meaning at
all?  It doesn't.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: awk like usage in python

2012-11-09 Thread Tim Roberts
Rudra Banerjee  wrote:
>
>Friends,
>I am in process learning python.
>I basically use shell scripts for text formatting and trying my hand on
>python.
>where I am fighting is awk's functionality in python. 
>Say, one of my real tiny code looks like:
>#!/bin/bash
>TMP=store
>for i in $1/MnBi_EOS_*
>do
>#  echo $i
>  grep -A 15 "T(est)" $i/out-Dy-eos2 >$TMP
>  var_T=`awk '/T\(est\)/{printf $2}' $TMP`
>  var_s1=`awk '/s1,torque/{print $6;exit}' $TMP`
>  var_t=`awk '/s1,torque/{print $7;exit}' $TMP`
>  echo  $var_T  $var_s1  $var_t >>tfl
>#  echo ""
>#  echo ""
>done
>sort -n tfl >$2
>rm -i $TMP tfl

Well, describe your program in words.  Then, you can convert it to Python.

For every directory in the given directory whose name starts with
MnBi_EOS_:
extract the 15 lines starting with T(est) from the file out-Dy-eos2 to
a temporary file
extract the 2nd field from the line with T(est) in it
extract the 6th field from the first line with "s1,torque"
extract the 7th field from the first line with "s1,torque"
print those three fields to a file
sort that file
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Listen for changes in variable (alsaaudio.Mixer(x, x).getvolume(x)

2012-10-24 Thread Tim Roberts
Muffinman  wrote:
>
>I'm new to Python (running 2.6.6 but if necessary 3.x should also be
>fine). I have a little idea I hope to accomplish with Python. I want to
>listen for changes in Alsa sound volume level and base some actions on
>that. With the few lines below I can check the current volume level. 
...
>
>volumes = mixer.getvolume(1)

Now, do you understand that this is just fetching the current setting of
the volume control for the microphone?  It's not telling you anything about
the actual level of the sounds being captured.

The fact that you're talking about real-time response makes me think you
might be misunderstanding this.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pls help me with this prog

2012-10-20 Thread Tim Roberts
inshu chauhan  wrote:
>
>but i want to calculate it for every 3 points not the whole data, but
>instead of giving me centre for every 3 data the prog is printing the
>centre 3 times...
>
>def main (data):
>j = 0
>for  i in data[:3]:
>while j != 3:
> centre = CalcCentre(data)
> j += 1
> print centre

This loop doesn't do what you think it does.  Think about the problem you
have to solve.  You have a set of data.  You want to operate on the whole
set, 3 points at a time.  What this loop does is grab the first three
points (only), then calculates the center on the entire list three times.

You want something like:

# As long as there is data in the list:
while data:
# Split the list into two parts: first 3 and the rest.
first3, data = data[3:],data[3:]
# Operate on the first three.
print CalcCenter( first3 )

To make it a little more resilient, you might make sure that len(data) is a
multiple of 3, or at least stop when it is shorter than 3.

To be more clever, you can write a function that returns 3 at a time:

def N_at_a_time( iter, n ):
while len(iter) >= n:
yield iter[:n]
iter = iter[n:]

Now you can do this:

def main(data):
for first3 in N_at_a_time(data, 3):
print CalcCenter(first3)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding http proxies

2012-10-14 Thread Tim Roberts
Olive  wrote:
>
>it seems when I read the code above that the proxy acts mostly as an
>orinary server with respect to the client except that it is supposed to
>receive the full URL instead of just the path. Am I right? Is there any
>documentation on what an http proxy is supposed to implement.

Consider the ways HTTP could have been implemented.  Say we have a request
to get http://www.bigsite.com/pictures/index.html .

One way HTTP could have been implemented is by sending this request to the
server at www.bigsite.com:

GET /pictures/index.html HTTP/1.0

If that were how HTTP were done, you could not implement a proxy, because
there isn't enough information for any intermediates to know where the
request had to end up.

Instead, http looks like this:

GET /pictures/index.html HTTP/1.1
Host: www.bigsite.com

Now, even if this is sent to someone who is not "www.bigsite.com", that
receipient can tell exactly who is supposed to get the message.

So, a web proxy receives requests intended for other sites, and forwards
them on, possibly after restricting or modifying them.  That's it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating C++ code

2012-10-10 Thread Tim Roberts
Jean-Michel Pichavant  wrote:
>
>I'm trying to generate C++ code from an XML file. I'd like to use a template 
>engine, which imo produce something readable and maintainable.
>My google search about this subject has been quite unsuccessful, I've been 
>redirected to template engine specific to html mostly.
>
>Does anybody knows a python template engine for generating C++ code ?

I'm a big fan of Cheetah.  It's simple but flexible enough to be useful.
Besides the many web projects I've done with it, I also I use it in one
project to generate PHP code (it generates data access objects from a live
database schema).
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Experimental Python-based shell

2012-10-02 Thread Tim Roberts
Jonathan Hayward  wrote:
>
>I've made an experimental Python-based Unix/Linux shell at:
>
>http://JonathansCorner.com/cjsh/
>
>An experimental Unix/Linux command line shell, implemented in Python 3,
>that takes advantage of some more recent concepts in terms of usability
>and searching above pinpointing files in heirarchies.
>
>I invite you to try it.

Without intending to detract from your work in any way, are you familiar
with the IPython project?

http://ipython.org/

You may find some interesting synergy with them.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who's laughing at my responses, and who's not?

2012-09-24 Thread Tim Roberts
Dwight Hutto  wrote:
>
>Been getting slammed by a few for some insignificant things, so who's
>laughing at me, and who takes me seriously. I don't claim to be the
>best, just trying to help.
>
>So who doesn't want me around?

Who cares?  There are probably hundreds of thousands of people reading this
forum.  A few of those people probably don't like you.  So what?

Illegitemi non carborondum -- don't let the bastards wear you down.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to limit CPU usage in Python

2012-09-24 Thread Tim Roberts
Paul Rubin  wrote:
>
>Tim Roberts: reasons to want to do this might involve a shared host
>where excessive cpu usage affects other users;

That's what priorities are for.

>...or a computer with
>limited power consumption, where prolonged high cpu activity causes
>thermal or other problems.

OK, I grant that.  However, statistically speaking, it is much more likely
that the OP merely has a misunderstanding.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exact integer-valued floats

2012-09-22 Thread Tim Roberts
True.  Seymour wanted all of the integer instructions to be combinatorial 
logic, rather than iterative.  Fortunately, since the floating point binary 
point was to the right, it was trivial to pack integers to float, do a floating 
computation, then unpack back to integer.

Apologize in advance for top-posting.  My Xoom makes bottom-posting awkward.
--
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

Dave Angel  wrote:


On 09/22/2012 05:05 PM, Tim Roberts wrote:
> Dennis Lee Bieber  wrote:
>> On 22 Sep 2012 01:36:59 GMT, Steven D'Aprano wrote:
>>> For non IEEE 754 floating point systems, there is no telling how bad the
>>> implementation could be :(
>>  Let's see what can be found...
>>
>>  IBM 360: Same as Sigma-6 (no surprise; hearsay is the Sigma was
>> designed by renegade IBM folk; even down to using EBCDIC internally --
>> but with a much different interrupt system [224 individual interrupt
>> vectors as I recall, vs the IBM's 7 vectors and polling to find what
>> device]).
> The Control Data 6000/Cyber series had sign bit and 11-bit exponent, with
> either a 48-bit mantissa or a 96-bit mantissa, packed into one or two
> 60-bit words.  Values were not automatically normalized, so there was no
> assumed 1 bit, as in IEEE-754.

And it's been a long time (about 39 years), but as I recall the CDC 6400
(at least) had no integer multiply or divide.  You had to convert to
float first.  The other oddity about the CDC series is it's the last
machine I've encountered that used ones-complement for ints, with two
values for zero.


--

DaveA

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


Re: Exact integer-valued floats

2012-09-22 Thread Tim Roberts
Dennis Lee Bieber  wrote:
>
>On 22 Sep 2012 01:36:59 GMT, Steven D'Aprano wrote:
>> 
>> For non IEEE 754 floating point systems, there is no telling how bad the 
>> implementation could be :(
>
>   Let's see what can be found...
>
>   IBM 360: Same as Sigma-6 (no surprise; hearsay is the Sigma was
>designed by renegade IBM folk; even down to using EBCDIC internally --
>but with a much different interrupt system [224 individual interrupt
>vectors as I recall, vs the IBM's 7 vectors and polling to find what
>device]).

The Control Data 6000/Cyber series had sign bit and 11-bit exponent, with
either a 48-bit mantissa or a 96-bit mantissa, packed into one or two
60-bit words.  Values were not automatically normalized, so there was no
assumed 1 bit, as in IEEE-754.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to limit CPU usage in Python

2012-09-22 Thread Tim Roberts
Rolando Cañer Roblejo  wrote:
>
>Is it possible for me to put a limit in the amount of processor usage (% 
>CPU) that my current python script is using?

Why?  That's an odd request.  It's natural to want to reduce your priority
if you want other processes handled first, but an idle CPU is a wasted
resource.  You want it to be busy all of the time.

>Some people recommend to use nice and cpulimit unix 
>tools, but those are external to python and I prefer a python solution. 

Scheduling and CPU priority are, by their very nature, operating system
concepts.  You will not find generic mechanisms wrapping them.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine (using ssh ?)

2012-09-19 Thread Tim Roberts
ashish  wrote:
>
>Here is my situation
>
>1. I have two machines. Lets call them 'local' & 'remote'.
>Both run ubuntu & both have python installed
>
>2. I have a python script, local.py, running on 'local' which needs to pass
>arguments ( 3/4 string arguments, containing whitespaces like spaces, etc )
>to a python script, remote.py running on 'remote' (the remote machine).

You haven't provided very many details, so it's possible ssh is the
low-impact solution, but don't discard the possibility of using a TCP
socket for this.  It's easy in Python.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Tim Roberts
David Smith  wrote:
>
>I'm converting windows bat files little by little to Python 3 as I find 
>time and learn Python.
>The most efficient method for some lines is to call Python like:
>python -c "import sys; sys.exit(3)"
>
>How do I "indent" if I have something like:
>if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else 
>sys.exit(3)
>
>My sole result in many attempts is "Syntax Error."

The other responses asking "why" are excellent, but this will do that
specific job:

sys.exit( {'Cope':1,'Perform':2}.get(sR,3) )

The best way to convert a batch file to Python is to convert the whole file
to a Python script.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending USB commands with Python

2012-08-30 Thread Tim Roberts
"Adam W."  wrote:
>
>You are correct about the 2 being the number of bytes written.  However when I 
>issue a read command I get:
>
>>>> ep.write('\x1BA')
>4
>>>> ep.read(1)
>usb.core.USBError: [Errno None] b'libusb0-dll:err [_usb_setup_async] invalid 
>endpoint 0x02\n'

USB endponts only go in one direction.  There will be one endpoint for
outoging data, and one endpoint for incoming data.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending USB commands with Python

2012-08-28 Thread Tim Roberts
"Adam W."  wrote:
>
>So I'm trying to get as low level as I can with my Dymo label printer, 
>and this method described the PDF 
>http://sites.dymo.com/Documents/LW450_Series_Technical_Reference.pdf 
>seems to be it.
>
>I'm unfamiliar with dealing with the USB interface and would greatly
>appreciate it if someone could tell me how to send and receive these
>commands with Python.  Perhaps if you were feeling generous and 
>wanted to write a bit of sample code, sending the "Get Printer 
>Status" command and receiving the response (page 17 of the PDF) 
>would be perfect to get me on my way.

Well, it's more than "a bit of sample code".  You would essentially be
writing a device driver.

Which operating system are you using?  If you are on Windows, then the
operating system has already loaded a printer driver for this device.  You
can't talk to the USB pipes without uninstalling that driver.  It would be
just about as easy for you to learn to use GDI to write to the printer like
a normal application, and that way the code would work on the NEXT
generation of printer, too.

The libusb or libusbx libraries can be used to talk to USB devices.  There
is a Python binding.  On Windows, you still need to have a driver, but the
libusbx instructions can help you find an install one.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling loaded DLL function expecting POINT * argument

2012-08-26 Thread Tim Roberts
Tim Williams  wrote:

>Hello all,
>
>I'm trying to use the ctypes module to call functions in a DLL. I've
>figured out how to modify my path so the library is found, and I can 
>call LoadLibrary on it, but one of the functions expects an array of
> POINTS. Here is the prototype from the .h file:
>
>
>TRACKER_API HRESULT InitializeMask(HANDLE pHandle, int nWidth, int nHeight, 
>POINT* ptMasks, int nNumPoints);

How is TRACKER_API defined?  You're using ctypes.oledll, which uses the
__stdcall calling convention.  It's possible your DLL is defined as
__cdecl.  Try cdll.LoadLibrary instead of oledll.LoadLibrary.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On-topic: alternate Python implementations

2012-08-04 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>Most people are aware, if only vaguely, of the big Four Python 
>implementations:
>
>CPython, or just Python, the reference implementation written in C.
>IronPython, written in .NET.

Technicality:  .NET is not a language, it is a run-time framework.
IronPython is written in C#.  It generates code that runs in the .NET
Framework.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when an iterable object is exhausted or not

2012-08-04 Thread Tim Roberts
Franck Ditter  wrote:
>
>Two similar iterable objects but with a different behavior :
>
>$$$ i = range(2,5)
>$$$ for x in i : print(x,end=' ')
>
>2 3 4 
>$$$ for x in i : print(x,end=' ')# i is not exhausted   
>
>2 3 4 
>
>- Compare with :
>
>$$$ i = filter(lambda c : c.isdigit(), 'a1b2c3')
>$$$ for x in i : print(x,end=' ')
>
>1 2 3 
>$$$ for x in i : print(x,end=' ')# i is exhausted
>
>$$$ 
>
>IMHO, this should not happen in Py3k.

It's interesting that it DOESN'T happen in Python 2.  The first "i" is of
type list, the second "i" is of type string, and both are restartable.

What's the type of "i" in the second case in Python 3?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >