Single-event-mode plotting

2013-04-25 Thread priisdk
I have some questions on the example below. My intention is to replace the y 
values with data from some sensor connected to the computer, and to make it 
work in what could be called 'single-event-mode' which means that I only want 
to plot and store data whenever the mouse is clicked.
I have made the plotting with VPython, and I have also considered matplotlib.
However, with either of these modules I cannot see how to answer the questions 
1 and 2 below.
Is there some other graphical module that will be better suited?
Notice, that I use Python 3.2.

1) Can I modify the program so that the clicks should be done in the 
testdisplay window on not in the scene window?

2) In the testdisplay I only want to see the actual blue point together with 
the hitherto stored green points. And not only that: I want to free all earlier 
blue points from memory. How can I do that? 



Poul Riis



from time import *
import visual.graph as visualgraph
from visual import *

scene=display(x=0, y=0, width=300, height=100,foreground=color.black,
  background=color.white)
ch=''
txt=''
inputtext='tmax: '
labeltext=label(pos=(0,0,0),text=inputtext)
while ch!='\n':
ch=scene.kb.getkey()
txt=txt+ch
if ch!='\n':
labeltext.text=inputtext+txt
tmax=eval(txt)
#labeltext.visible=0


testdisplay=visualgraph.gdisplay(title='Test', xtitle='x', ytitle='y',
   x=0, y=75, width=500, 
height=500,foreground=color.black,
   background=color.white)
testcurve = visualgraph.gcurve(color=color.blue,display=testdisplay)
testdots = visualgraph.gdots(color=color.red,display=testdisplay,size=5)
mousedots = visualgraph.gdots(color=color.green,display=testdisplay,size=10)
finalcurve = visualgraph.gcurve(color=color.magenta,display=testdisplay)

tarray=[]
yarray=[]
tstart=time()
t=time()-tstart
while t1:
mousedots.plot(pos=(t,y))
scene.mouse.events = 0
tarray.append(t)
yarray.append(y)
for i in range(0,len(tarray)):
finalcurve.plot(pos=(tarray[i],yarray[i]))
-- 
http://mail.python.org/mailman/listinfo/python-list


Guess the Number Repeat

2013-04-25 Thread eschneider92
How do I make the following program play the 'guess the number game' twice?

import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.') 
guess = input()
guess = int(guess)
print('You have ' + str(5 - guessesTaken) + ' guesses left.')
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken 
+ ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Guess the Number Repeat

2013-04-25 Thread Peter Otten
eschneide...@comcast.net wrote:

> How do I make the following program play the 'guess the number game'
> twice?
> 
> import random
> guessesTaken = 0
> print('Hello! What is your name?')
> myName = input()
> number = random.randint(1, 20)
> print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
> while guessesTaken < 6:
> print('Take a guess.')
> guess = input()
> guess = int(guess)
> print('You have ' + str(5 - guessesTaken) + ' guesses left.')
> guessesTaken = guessesTaken + 1
> if guess < number:
> print('Your guess is too low.')
> if guess > number:
> print('Your guess is too high.')
> if guess == number:
> break
> if guess == number:
> guessesTaken = str(guessesTaken)
> print('Good job, ' + myName + '! You guessed my number in ' +
> guessesTaken + ' guesses!')
> if guess != number:
> number = str(number)
> print('Nope. The number I was thinking of was ' + number)


If you put everything needed to guess once into a function like in the 
following example. Once you have reorganised

#first version -- flat
guess = int(input("guess my number: "))
if guess == 42:
 print("congrats")
else:
 print("sorry, you're wrong")

into

#second version -- using a function
def guess_number():
guess = int(input("guess my number: "))
if guess == 42:
 print("congrats")
else:
 print("sorry, you're wrong")

guess_number()

you can easily modify the script to invoke the guess_number() function 
inside a loop:

#third version -- calling the function from within a loop
def guess_number():
guess = int(input("guess my number: "))
if guess == 42:
 print("congrats")
else:
 print("sorry, you're wrong")

for i in range(2):
print("round", i+1)
guess_number()




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


Libroffice PMT equivalent in python

2013-04-25 Thread ஆமாச்சு
Hi,

Are there equivalent in any Python libraries that could match function
like PMT in libreoffice?

Refer: https://help.libreoffice.org/Calc/Financial_Functions_Part_Two#PMT

--

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


Re: Libroffice PMT equivalent in python

2013-04-25 Thread Terry Jan Reedy

On 4/25/2013 6:46 AM, ஆமாச்சு wrote:

Hi,

Are there equivalent in any Python libraries that could match function
like PMT in libreoffice?

Refer: https://help.libreoffice.org/Calc/Financial_Functions_Part_Two#PMT


try the packages listed at
https://pypi.python.org/pypi?%3Aaction=search&term=finance&submit=search


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


Re: Libroffice PMT equivalent in python

2013-04-25 Thread Vlastimil Brom
2013/4/25 ஆமாச்சு 

> Hi,
>
> Are there equivalent in any Python libraries that could match function
> like PMT in libreoffice?
>
> Refer: https://help.libreoffice.org/Calc/Financial_Functions_Part_Two#PMT
>
> --
>
> Amachu
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
you may check numpy
http://www.numpy.org/

http://docs.scipy.org/doc/numpy/reference/generated/numpy.pmt.html

>>> import numpy
>>> numpy.pmt(1.99/100/12,36,25000)
-715.95533443739942
>>>

(The input in percent is to be divided by 100 and the output could be
rounded separately, if needed.)

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


Re: Pythonic way to count sequences

2013-04-25 Thread Serhiy Storchaka

25.04.13 08:26, Chris Angelico написав(ла):

So you can count them up directly with a dictionary:

count = {}
for sequence_tuple in list_of_tuples:
 count[sequence_tuple] = count.get(sequence_tuple,0) + 1


Or alternatives:

count = {}
for sequence_tuple in list_of_tuples:
 if sequence_tuple] in count:
  count[sequence_tuple] += 1
 else:
  count[sequence_tuple] = 1

count = {}
for sequence_tuple in list_of_tuples:
 try:
  count[sequence_tuple] += 1
 except KeyError:
  count[sequence_tuple] = 1

import collections
count = collections.defaultdict(int)
for sequence_tuple in list_of_tuples:
 count[sequence_tuple] += 1

But of course collections.Counter is a preferable way now.


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


Re: epiphany

2013-04-25 Thread Roy Smith
In article <5178b1db$0$29977$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> The semantics of NotImplemented is that it is a signal for one object to 
> say "I don't know how to do this, let somebody else try".

That's precisely the logic here.  The rule says, "I don't know how to 
tell you if this is OK or not, ask another rule".

> Since rules apparently take no arguments, either:
> 
> 1) they rely on global state, which is a nasty design; or
> 
> 2) rules actually have a fixed return result, in which case why make them 
> functions in the first place?

Yes, rules take arguments.  I elided them from the original description 
since it wasn't germane to what I was trying to show.

> Since both possibilities seem stupid, and I do not believe that Roy 
> actually is stupid,

I am honored that you have such a high opinion of me :-)

Here's what the docs say about NotImplemented:

> This type has a single value. There is a single object with this 
> value. This object is accessed through the built-in name 
> NotImplemented. Numeric methods and rich comparison methods may 
> return this value if they do not implement the operation for the 
> operands provided. (The interpreter will then try the reflected 
> operation, or some other fallback, depending on the operator.) Its 
> truth value is true.

It gives an example of a use by numeric methods.  It doesn't say that's 
the only thing it can be used for.

It also says, "Its truth value is true".  Why would they document that 
fact if you weren't supposed to use it as a boolean operand?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the source of an exception in a python multiprocessing program

2013-04-25 Thread Neil Cerutti
On 2013-04-24, William Ray Wing  wrote:
> On Apr 24, 2013, at 4:31 PM, Neil Cerutti  wrote:
>
>> On 2013-04-24, William Ray Wing  wrote:
>>> When I look at the pool module, the error is occurring in
>>> get(self, timeout=None) on the line after the final else:
>>> 
>>>def get(self, timeout=None):
>>>self.wait(timeout)
>>>if not self._ready:
>>>raise TimeoutError
>>>if self._success:
>>>return self._value
>>>else:
>>>raise self._value
>> 
>> The code that's failing is in self.wait. Somewhere in there you
>> must be masking an exception and storing it in self._value
>> instead of letting it propogate and crash your program. This is
>> hiding the actual context.
>
> I'm sorry, I'm not following you.  The "get" routine (and thus
> self.wait) is part of the "pool" module in the Python
> multiprocessing library. None of my code has a class or
> function named "get".

Oops! I failed to notice it was part of the pool module and not
your own code. 

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


Re: epiphany

2013-04-25 Thread Steven D'Aprano
On Thu, 25 Apr 2013 08:36:34 -0400, Roy Smith wrote:

> In article <5178b1db$0$29977$c3e8da3$54964...@news.astraweb.com>,
>  Steven D'Aprano  wrote:
> 
>> The semantics of NotImplemented is that it is a signal for one object
>> to say "I don't know how to do this, let somebody else try".
> 
> That's precisely the logic here.  The rule says, "I don't know how to
> tell you if this is OK or not, ask another rule".

Sounds good to me then. It looks like your design is actually much closer 
to what I believe the standard Python semantics are intended to be than 
it appeared at first.



[...]
> Here's what the docs say about NotImplemented:
> 
>> This type has a single value. There is a single object with this value.
>> This object is accessed through the built-in name NotImplemented.
>> Numeric methods and rich comparison methods may return this value if
>> they do not implement the operation for the operands provided. (The
>> interpreter will then try the reflected operation, or some other
>> fallback, depending on the operator.) Its truth value is true.
> 
> It gives an example of a use by numeric methods.  It doesn't say that's
> the only thing it can be used for.

Right. You can do a lot of things in Python, including shooting your foot 
off :-) but that doesn't mean you should. The further away from standard 
Python conventions you get, the more wary you should be. That's all.


> It also says, "Its truth value is true".  Why would they document that
> fact if you weren't supposed to use it as a boolean operand?

You can use *anything* in Python in a boolean context. That's a language 
feature: all objects are either truthy or falsey. As for why it is 
documented for NotImplemented, I guess that's because some people might 
guess that it is falsey, like None.



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


Re: IPython in Emacs

2013-04-25 Thread Seb
On Wed, 24 Apr 2013 21:38:04 -0700 (PDT),
rusi  wrote:

> There were some ipython+emacs+windows bugs:
> https://bugs.launchpad.net/ipython/+bug/290228

> Last I tried nearly 2 years, they were still there
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/36e757567f28368e

On Debian here, so not a problem.

Thanks,
-- 
Seb

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


Re: epiphany

2013-04-25 Thread Roy Smith
In article <51792710$0$29977$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> > It also says, "Its truth value is true".  Why would they document that
> > fact if you weren't supposed to use it as a boolean operand?
> 
> You can use *anything* in Python in a boolean context. That's a language 
> feature: all objects are either truthy or falsey. As for why it is 
> documented for NotImplemented, I guess that's because some people might 
> guess that it is falsey, like None.

That was part of what added the epiphanality to the experience.  My 
first guess was exactly as you say, that bool(NotImplemented) would be 
false.  Once I discovered that it was true, the rest immediately fell 
into place and many lines of code got replaced by the simple:

return all(r(...) for r in rules)
  ^
  |
  + stuff that I'm not showing goes here :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Efficient way of looging in python

2013-04-25 Thread maitreymishra23
Hi,

I need an efficient way of logging using python.
My problem statemnt:
1. I have multiple processes using the same logging file.
I need solutions to the following:
a) If multiple processes are trying to write to the same file, I need to 
prevent that. Otherwise, the logging messages will be puzzling to the user as 
he would see logging messages from one module than may be some other following 
it.

Please let me know if there is an efficient way to do it.

Thanks!

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


Re: Efficient way of looging in python

2013-04-25 Thread Skip Montanaro
> a) If multiple processes are trying to write to the same file, I need to 
> prevent that.

Two things: Use some sort of file locking.  You can get the lockfile
module from PyPI. Include at least the process id as one of the
logging fields in your formatter.  I haven't don't enough with the
logging module to know it it supports some sort of "name" field, which
would make the different messages more easily distinguished, but if
so, that would be a better alternative to the process id.

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


Re: IPython in Emacs

2013-04-25 Thread rusi
On Apr 25, 6:01 pm, Seb  wrote:
> On Wed, 24 Apr 2013 21:38:04 -0700 (PDT),
>
> rusi  wrote:
> > There were some ipython+emacs+windows bugs:
> >https://bugs.launchpad.net/ipython/+bug/290228
> > Last I tried nearly 2 years, they were still there
> >http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> On Debian here, so not a problem.

Ok me too :-)

A quick try of your startup code did not work for me.
There is a perennial clash in emacs between python.el and python-
mode.el -- I guess its that.
Which do you use?

What are your commands for eval-buffer and start-interpreter?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient way of looging in python

2013-04-25 Thread Roozbeh
You can also add several handlers to your logger with different levels, so that 
one Filehandler passes the errors to a log file and StreamHandler passes 
messages with a different level to the output stream.
Also by setting the basicConfig of the logger you can format the log messages 
so that you would see where the messages are originating from.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2013-04-25 Thread Roozbeh
You need to handle the cookie that comes with the server response. Example code:

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/";)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison Style

2013-04-25 Thread llanitedave
On Wednesday, April 24, 2013 10:57:49 PM UTC-7, Chris Angelico wrote:
> On Thu, Apr 25, 2013 at 3:49 PM, llanitedave  wrote:
> 
> > Given that
> 
> >
> 
> > s = some static value
> 
> > i = a value incremented during a loop
> 
> >
> 
> > I'm used to comparing them as
> 
> >
> 
> > if i == s:
> 
> > # some code
> 
> >
> 
> > But for some unknown reason I did a switch
> 
> >
> 
> > if s == i:
> 
> > # same code
> 
> >
> 
> > It didn't seem to make any difference at first glance, so I just got to 
> > wondering --
> 
> 
> 
> It won't make any difference in any sort of sane code. If there's any
> 
> situation in which == is not reflexive, something seriously nasty is
> 
> going on.
> 
> 
> 
> > Is there a standard for comparison order?  Is there any kind of performance 
> > difference?  Is there even a tradition for one or the other?  Are there any 
> > gotchas?
> 
> 
> 
> It's conventional to compare variables to constants, not constants to
> 
> variables (even in C where there's the possibility of mucking up the
> 
> operator, most people still compare variables to constants). I'd
> 
> normally use "i == s" there, treating s as a constant for the purpose
> 
> of the loop. Unless you're deliberately being poetical, language such
> 
> as "Three is the number thou shalt count" is distinctly abnormal, so
> 
> saying "if (5 == i)" is equally awkward. It's nothing major; mostly
> 
> it's like the algebraic convention of putting the more-known elements
> 
> earlier in a term (eg 2πix - 2 is known, 3.14159 is mostly known,
> 
> i is imaginary but at least it's constant, and x is unknown).
> 
> 



Thanks, Chris.  That's kind of along the lines of what I was thinking.  
Visually, the code just looked wrong, and I figure if for no other reasons than 
readability it's preferable in the traditional way.

It's nice to know, though, that the next time dyslexia strikes it's not 
necessarily a horrible thing.

> 
> > Do I need to get a hobby?
> 
> 
> 
> I thought programming WAS a hobby?
> 

I meant a safer, easier, and more mainstream hobby, like base jumping or 
motorcycle aerobatics or something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient way of looging in python

2013-04-25 Thread Jean-Michel Pichavant
- Original Message -
> Hi,
> 
> I need an efficient way of logging using python.
> My problem statemnt:
> 1. I have multiple processes using the same logging file.
> I need solutions to the following:
> a) If multiple processes are trying to write to the same file, I need
> to prevent that. Otherwise, the logging messages will be puzzling to
> the user as he would see logging messages from one module than may
> be some other following it.
> 
> Please let me know if there is an efficient way to do it.
> 
> Thanks!
> 
> Br,
> Maitrey
> --
> http://mail.python.org/mailman/listinfo/python-list

Everything you need should be explained here
http://docs.python.org/release/3.2/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes

Most of the concepts are applicable to any version of python I've done it with 
python 2.5. I used some Vinay's code posted on the net to implement a logging 
server, all my processes are logging to that server which is responsible for 
writing the file.

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to return list of lists

2013-04-25 Thread eternaltheft
Hi guys, I'm having a lot of trouble with this.

My understanding of python is very basic and I was wondering how I can return 
this table as a list of lists.

1   2   3   4   5
3   4   5   6
5   6   7
7   8
9

The function is 
def Table(n): 
Then how would I make it that when the value of n is 4 it returns [[1, 2, 3], 
[3, 4], [5]].

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


Guppy-PE/Heapy 0.1.10

2013-04-25 Thread sverker nilsson
I am happy to announce Guppy-PE 0.1.10

Guppy-PE is a library and programming environment for Python,
currently providing in particular the Heapy subsystem, which supports
object and heap memory sizing, profiling and debugging. It also
includes a prototypical specification language, the Guppy
Specification Language (GSL), which can be used to formally specify
aspects of Python programs and generate tests and documentation from a
common source.

The main news in this release:

o Support for Python 2.7
  However, there are still some problems with the tests
  that I haven't been able to sort out.

o Some minor bug fixes

License: MIT

Guppy-PE 0.1.10 is available in source tarball format on the Python
Package Index (a.k.a. Cheeseshop):

http://pypi.python.org/pypi/guppy/0.1.10

The project homepage is on Sourceforge:

http://guppy-pe.sourceforge.net

Enjoy,

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


Re: How to return list of lists

2013-04-25 Thread Wolfgang Maier
  gmail.com> writes:

> 
> Hi guys, I'm having a lot of trouble with this.
> 
> My understanding of python is very basic and I was wondering how I can
return this table as a list of lists.
> 
> 1 2   3   4   5
> 3 4   5   6
> 5 6   7
> 7 8
> 9
> 
> The function is 
> def Table(n): 
> Then how would I make it that when the value of n is 4 it returns [[1, 2,
3], [3, 4], [5]].
> 
> Thank you 
> 

First of all, state your question precisely!
I have no idea why with n=4 you would want to return that!
Second, the solution of this sort of problem lies in list comprehensions
combined with range(). Read up on those topics! Especially comprehensions
are so fundamental to the language that you have know about them before you
embark on any serious programming efforts.
Best,
Wolfgang

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


Re: How to return list of lists

2013-04-25 Thread Eternaltheft
On Thursday, April 25, 2013 11:29:31 PM UTC+8, Wolfgang Maier wrote:
>  gmail.com> writes:
> 
> 
> 
> > 
> 
> > Hi guys, I'm having a lot of trouble with this.
> 
> > 
> 
> > My understanding of python is very basic and I was wondering how I can
> 
> return this table as a list of lists.
> 
> > 
> 
> > 1   2   3   4   5
> 
> > 3   4   5   6
> 
> > 5   6   7
> 
> > 7   8
> 
> > 9
> 
> > 
> 
> > The function is 
> 
> > def Table(n): 
> 
> > Then how would I make it that when the value of n is 4 it returns [[1, 2,
> 
> 3], [3, 4], [5]].
> 
> > 
> 
> > Thank you 
> 
> > 
> 
> 
> 
> First of all, state your question precisely!
> 
> I have no idea why with n=4 you would want to return that!
> 
> Second, the solution of this sort of problem lies in list comprehensions
> 
> combined with range(). Read up on those topics! Especially comprehensions
> 
> are so fundamental to the language that you have know about them before you
> 
> embark on any serious programming efforts.
> 
> Best,
> 
> Wolfgang

Ah sorry the task is to make a function for this:
def tTable(n): 
tTable(n),even n, returns the initial triangular n-1 x n-1(triangular table i 
posted before) table as a list of lists. For example, tTable(4) returns [[1, 2, 
3], [3, 4], [5]].

Sorry if i was a bit vague, but i don't know how to explain it any better :(. 
And thanks for the tips! I will definitely read up on it when i get the time. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread rusi
On Apr 25, 8:29 pm, Wolfgang Maier  wrote:
>   gmail.com> writes:
>
>
>
> > Hi guys, I'm having a lot of trouble with this.
>
> > My understanding of python is very basic and I was wondering how I can
>
> return this table as a list of lists.
>
>
>
> > 1  2       3       4       5
> > 3  4       5       6
> > 5  6       7
> > 7  8
> > 9
>
> > The function is
> > def Table(n):
> > Then how would I make it that when the value of n is 4 it returns [[1, 2,
> 3], [3, 4], [5]].
>
> > Thank you
>
> First of all, state your question precisely!
> I have no idea why with n=4 you would want to return that!
> Second, the solution of this sort of problem lies in list comprehensions
> combined with range(). Read up on those topics! Especially comprehensions
> are so fundamental to the language that you have know about them before you
> embark on any serious programming efforts.
> Best,
> Wolfgang

As Wolfgang says -- dunno why the 4 (my code below works for 3)
And I wonder whether you are making us do your homework.
Still heres something to start you off

def row(max,n): return range(2*n-1, max+n)
def tri(max): return [row(max,i) for i in range(1,max+1)]
 >>> tri(3)
[[1, 2, 3], [3, 4], [5]]
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread Eternaltheft
Definitely not, like i said I'm having trouble doing it, you didn't have to 
write a code for me, i just need an explanation on how to do it. sorry if it 
felt like i was trying to get my homework done 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread Wolfgang Maier
Eternaltheft  gmail.com> writes:

>
> Ah sorry the task is to make a function for this:
> def tTable(n): 
> tTable(n),even n, returns the initial triangular n-1 x n-1(triangular
table i posted before) table as a
> list of lists. For example, tTable(4) returns [[1, 2, 3], [3, 4], [5]].
> 
> Sorry if i was a bit vague, but i don't know how to explain it any better
:(. And thanks for the tips! I will
> definitely read up on it when i get the time. 
> 

So if you posted this before, why are you asking again?
Could you provide a link to the post? Otherwise, I guess I'll look for it
when I get the time ;)



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


Re: How to return list of lists

2013-04-25 Thread Eternaltheft
On Friday, April 26, 2013 12:05:32 AM UTC+8, Eternaltheft wrote:
> Haha i'm confused? im guessing you mean the triangular table i said i posted 
> before? its this one 
> 
> 
> 
> 12345 
> 
> 3456 
> 
> 567 
> 
> 78 
> 
> 9 
> 
> 
> 
> this was the table in my original post
omg im an idiot, i didn't mention that the original table is the triangular 
table..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread Eternaltheft
Haha i'm confused? im guessing you mean the triangular table i said i posted 
before? its this one 

12345 
3456 
567 
78 
9 

this was the table in my original post 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison Style

2013-04-25 Thread Chris Angelico
On Fri, Apr 26, 2013 at 12:19 AM, llanitedave  wrote:
> On Wednesday, April 24, 2013 10:57:49 PM UTC-7, Chris Angelico wrote:
>> I thought programming WAS a hobby?
>>
>
> I meant a safer, easier, and more mainstream hobby, like base jumping or 
> motorcycle aerobatics or something.

Good point. With the sort of thinking you're demonstrating here, you
should consider a job working with Spike Milligna (the well-known
typing error). I believe there ought to be an office cubicle available
for you in one of the excellent organizations devoted to Milliganesque
thinkers and computer programmers - the walls are nicely padded...

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


HTC ChaCha review

2013-04-25 Thread 23alagmy
HTC ChaCha review
http://natigtas7ab.blogspot.com/2012/10/htc-chacha-review.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread Steven D'Aprano
On Thu, 25 Apr 2013 08:01:09 -0700, eternaltheft wrote:

> Hi guys, I'm having a lot of trouble with this.
> 
> My understanding of python is very basic and I was wondering how I can
> return this table as a list of lists.
> 
> 1 2   3   4   5
> 3 4   5   6
> 5 6   7
> 7 8
> 9


Do you know how to build lists of numbers?

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6]
c = [5, 6, 7]
d = [7, 8]
e = [9]


Now put them in a list:

table = [a, b, c, d, e]
print table


Got that so far? Now let's see how you might do the same thing without 
typing up the inner lists by hand. For that, you want the range() 
function.

a = range(1, 6)  # 1 is included, 6 is excluded.
b = range(3, 7)
c = range(5, 8)
# etc.


Now let's do it without the temporary variables a, b, c, d, e.

This time, start with the outer list, only with nothing in it. Then fill 
it using the range function.

table = []
table.append(range(1, 6))
table.append(range(3, 7))
# etc.


Now let's put this in a function:


def table(n):
# Returns a triangular table (list of lists).
# So far, we ignore n and hard-code the table. We'll fix this later.
table = []
table.append(range(1, 6))
table.append(range(3, 7))
# etc.
return table


You're about halfway there now. The easy half. You get to do the hard 
half :-)


You need to think about how to turn a series of repeated appends into a 
loop, either a while loop or a for loop. I recommend you use a for-loop. 

Start by answering these questions:

* if the argument to the function, n, is 4, how many rows and how many 
columns will the table have?

* if n is 5, how many rows and columns will the table have?

* in general, for some value of n, what will be the first row?

* turn that into a call to range. Remember that if you call range with 
two arguments, the first argument is included, the second is excluded:
range(5, 9) => [5, 6, 7, 8]

* what will the second row be? Hint: the *first* number in the second row 
will be the first number of the first row PLUS TWO; the *last* number in 
the second row will be ... what?

* turn that into a call to range. Can you see the pattern for how each 
call to range will vary from the last?

* this suggests you want a for loop:

for row number 1, 2, 3, ... 
table.append(make a row)

Obviously that's not real Python code. You need to write the Python code.


Write some code, and if you run into trouble, come back and ask for help.



Good luck! 


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


Re: Comparison Style

2013-04-25 Thread Steve Simmons
Chris Angelico  wrote:

With the sort of thinking you're demonstrating here, you
should consider a job working with Spike Milligna (the well known typing error).

Errr ,  I think you'll find that he's joined the choir invisibule. Mind you,  
he did say he was ill! 

Sent from a Galaxy far far away
-- 
http://mail.python.org/mailman/listinfo/python-list


Python platform/framework for new RESTful web app

2013-04-25 Thread Eric Frederich
If I wanted to create a new web application (RESTful) today with Python
what are my options given the following requirements.

* Google Account authentication
* Facebook authentication
* Managed hosting (like Google App Engine or Heroku) but with the ability
to be self-hosted later down the road.

I am familiar with Django (well I was a 3 years ago).
I have played a little with web.py and like the ideas there.

I like the idea of using something like GAE but don't want to be locked in.

Is Django the answer?
I think you can run Django on GAE (and obviously you can self-host it).
I see there is a Django REST framework.  Is this a good framework?
Are there good Google and Facebook authentication extensions?

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


Re: Comparison Style

2013-04-25 Thread llanitedave
On Thursday, April 25, 2013 11:31:04 AM UTC-7, Steve Simmons wrote:
> Chris Angelico  wrote:
> 
> 
> 
> With the sort of thinking you're demonstrating here, you
> 
> should consider a job working with Spike Milligna (the well known typing 
> error).
> 
> 
> 
> Errr ,  I think you'll find that he's joined the choir invisibule. Mind you,  
> he did say he was ill! 
> 
> 
> 
> Sent from a Galaxy far far away


Did you ever hear him sing?  He's better off in the choir inaudible.

As am I...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison Style

2013-04-25 Thread Neil Cerutti
On 2013-04-25, llanitedave  wrote:
>> Errr ,  I think you'll find that he's joined the choir
>> invisibule. Mind you,  he did say he was ill! 
>> 
>> Sent from a Galaxy far far away
>
> Did you ever hear him sing?  He's better off in the choir
> inaudible.

Well I've never heard either one.

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


Re: Comparison Style

2013-04-25 Thread Steve Simmons
llanitedave  wrote:

>On Thursday, April 25, 2013 11:31:04 AM UTC-7, Steve Simmons wrote:
>> Chris Angelico  wrote:
>> 
>> 
>> 
>> With the sort of thinking you're demonstrating here, you
>> 
>> should consider a job working with Spike Milligna (the well known
>typing error).
>> 
>> 
>> 
>> Errr ,  I think you'll find that he's joined the choir invisibule.
>Mind you,  he did say he was ill! 
>> 
>> 
>> 
>> Sent from a Galaxy far far away
>
>
>Did you ever hear him sing?  He's better off in the choir inaudible.
>
>As am I...
>-- 
>http://mail.python.org/mailman/listinfo/python-list

The Ying Tong song -  a classic of its time. But eminently suited to the 
chorally challenged. 

Sent from a Galaxy far far away-- 
http://mail.python.org/mailman/listinfo/python-list


Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread yuyaxuan0
Hey guys,

I have a python script that will call an external exe file. Code is kind of 
like this:

import sys
import os
from helper_functions import strContains

if (len(sys.argv) != 4):
print('Usage of script: export_mirax_data  
 ')
else:
print('Script to export mirax data')
print('---')

# default parameters for exporting
zoomLevel = 0 # 0 (original) - 9 (whole slide on one image)
tileHeight = 2048 # has to be a multiple of 256
tileWidth = 2048  # has to be a multiple of 256
fileFormat = "png"# jpg, png and bmp are allowed
mapFileFormat = "png" # xml, png and bmp are allowed

# implicitly needed parameters
MiraxSlideExporter = "MrxSlideExport.exe"

slicePath = sys.argv[1]
pathToResultData = sys.argv[2]
tileHeight = sys.argv[3]
tileWidth = sys.argv[3]
  
# slices = os.listdir(pathToSourceMiraxData)

# sys.argv[1]
# sys.argv[2]

# create command-line for system-call of mirax-slide-exporter
# -e exports the slide
# -i saves slide information in outputfolder
# -a optional
# -n only tiles which contain information are exported
# -s + pathToSourceMiraxData + \
cmdForExportingSlicesToTiles = \
MiraxSlideExporter + \
" -i " + \
" -e " + \
" -z " + str(zoomLevel) + \
" -t " + str(tileHeight) + " " + str(tileWidth) + \
" -f " + str(fileFormat) + \
" -m " + str(mapFileFormat) + \
" "

#cmd = "D:\\programs\\MIRAX_SlideAC_SDK\\Bin\\MrxSlideExport.exe -s 
D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Slides\\L10 -e -o 
D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Output\\L10 -z 5 -f png"
#os.system(cmd)
#msg = os.popen(cmd, mode='r', buffering=-1) # does not work
#print(msg)

# run through slices in given source-path


cmd = cmdForExportingSlicesToTiles + " -s " + slicePath + " -o " + 
pathToResultData
print(cmd)
os.system(cmd)



So the problem is that is says it doesn't have sufficient memory. 

The weired thing is that if I just ran the exe file directly in cmd console, 
it's working without any memory problem. I am wondering whether if it's some 
kind of python issue limits the memory that we can use??
-- 
http://mail.python.org/mailman/listinfo/python-list


baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Alastair Thompson
I am completely baffled by the behavior of this code with regards to the
evaluation order of namespaces when assigning the class attributes.  Both
classes are nested within a function I called whywhywhy.

I assumed that example1 and example2 classes would look first at their own
namespace, then object, then the whywhywhy func namespace then global, and
maybe module.  It seems this is not the case.

def whywhywhy(first, second, third):
def print_stuff():
print("func: first=", first)
print("func: second=", second)
print("func: third=", third)
print_stuff()

class example1(object):
print("1cls: first=", first)
print("1cls: second=", second)
print("1cls: third=", third)

second = second
foo = third

class example2(object):
print("2cls: first=", first)
print("2cls: second=", second)
print("2cls: third=", third)

second = second
third = third

def second():
pass

whywhywhy(1,2,3)


The code above produces the following output
"""
func: first= 1
func: second= 2
func: third= 3
1cls: first= 1
1cls: second= 
1cls: third= 3
2cls: first= 1
2cls: second= 
Traceback (most recent call last):
  File "error.py", line 29, in 
whywhywhy(1,2,3)
  File "error.py", line 18, in whywhywhy
class example2(object):
  File "error.py", line 21, in example2
print("2cls: third=", third)
NameError: name 'third' is not defined
"""

In particular:

print_stuff behaves as I would expect
1cls: second #<--- Why does this look at the global namespace for second
and not the whywhywhy func namespace first.
2cls: second #<--- Why can this no longer find third, it surely hasn't hit
the line third=third

Thanks for any help you can provide. :)
Alastair
-- 
http://mail.python.org/mailman/listinfo/python-list


Preavviso 291601-443382

2013-04-25 Thread Pay


La fattura deve essere pagato fino alla prossima settimana.
   
Dettagli possono essere trovati all'indirizzo:
http://gtslawnservices.com/Progetto.zip




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


Re: Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread Dave Angel

On 04/25/2013 05:18 PM, yuyaxu...@gmail.com wrote:

Hey guys,

I have a python script that will call an external exe file. Code is kind of 
like this:



This is a perfect example where you can simplify the problem down to a 
few lines that fail for you, and actually document the environment and 
the results.





 #cmd = "D:\\programs\\MIRAX_SlideAC_SDK\\Bin\\MrxSlideExport.exe -s 
D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Slides\\L10 -e -o 
D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Output\\L10 -z 5 -f png"
 #os.system(cmd)
 #msg = os.popen(cmd, mode='r', buffering=-1) # does not work


That's a useless statement.  What you really should be saying is:  I ran 
exactly xxx, and it formatted my neighbor's D: drive.  Or you should 
skip that, and just concentrate on the ancient os.system() you're asking 
about.  BTW, any reason you're not using the multiprocess module?  It 
can simplify a lot of things, for example, bypassing the shell, so you 
know what the child program is really getting as parameters.



 cmd = cmdForExportingSlicesToTiles + " -s " + slicePath + " -o " + 
pathToResultData
 print(cmd)
 os.system(cmd)

So the problem is that is says it doesn't have sufficient memory.


Who says?  At what point do they say it?  Show us a transcript of 
exactly what you do to see this message, and actually show the message.



You probably could simplify this to 5 lines:

import os
cmd = "some literal string with lots of options"
print "About to launch program"
print cmd
os.system(cmd)

Then you run it from the cmd line, and copy/paste the results into your 
mnext message.


C:\Somedir\ > python  myprog.py
About to launch program
some literal...

Some message that might mention running out of memory...

Naturally, you should specify your Python version, your OS version, and 
any other variables you can think of.


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


Re: Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread Steven D'Aprano
On Thu, 25 Apr 2013 14:18:58 -0700, yuyaxuan0 wrote:

> Hey guys,
> 
> I have a python script that will call an external exe file. Code is kind
> of like this:

"Kind of like"? So it might be different? How much different?

[snip irrelevant code]

Please try to cut your code down to the minimum necessary to demonstrate 
the problem.


> #cmd = "D:\\programs\\MIRAX_SlideAC_SDK\\Bin\\MrxSlideExport.exe -s
> D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Slides\\L10 -e
> -o D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Output\\L10
> -z 5 -f png" 

You can simplify Windows pathnames by using forward slashes.


> #os.system(cmd)
> #msg = os.popen(cmd, mode='r', buffering=-1) # does not work
> #print(msg)

Of course it does not work. You have commented it out.


> # run through slices in given source-path
> cmd = cmdForExportingSlicesToTiles + " -s " + slicePath + " -o " +
> pathToResultData 
> print(cmd)
> os.system(cmd)
> 
> So the problem is that is says it doesn't have sufficient memory.

What says "it" doesn't have sufficient memory? What's "it"? You may have 
seen the error, but we haven't. Please COPY AND PASTE the exact error 
message, IN FULL, and describe where it comes from:

* is it a Python traceback?

* something printed directly to the terminal but not a traceback?

* Blue Screen of Death?

* a message in a GUI alert?

* something else?



> The weired thing is that if I just ran the exe file directly in cmd
> console, it's working without any memory problem. I am wondering whether
> if it's some kind of python issue limits the memory that we can use??

No.



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


Re: baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Bas
On Thursday, April 25, 2013 11:27:37 PM UTC+2, Alastair Thompson wrote:
> I am completely baffled by the behavior of this code with regards to the 
> evaluation order of namespaces when assigning the class attributes.  Both 
> classes are nested within a function I called whywhywhy.
[snip weird namespace problem]

Hi,

I am not a namespace expert, but I think the following example shows the same 
problem in an easier way without any classes, and gives a more helpful error 
message:

In [1]: a = 123
In [2]: def f():
   ...: print a
   ...: b = 456

In [3]: f()
123

In [4]: def g():
   ...: print a
   ...: a = 456

In [5]: g()
---
UnboundLocalError Traceback (most recent call last)
/home/xxx/ in ()
> 1 g()

/home/xxx/ in g()
  1 def g():
> 2 print a
  3 a = 456
  4 

UnboundLocalError: local variable 'a' referenced before assignment


My guess is that in f(), the compiler sees no definition of a, so it assumes is 
must come from the outer namespace. In g(), however, it sees on the second line 
that a is uses as an assignment target, so it makes the variable a local. When 
it is executed, it rightfully complains that the local variable is not yet 
defined. A smarter compiler might prevent this problem, but then again a 
smarter programmer would not have local and global variables with the same name.

In your example, something similar is probably happening, since you assign 
something to third inside example2, thereby making it 'local'. Since you are 
dealing with classes, the error message is probably not so clear (but whywhywhy 
would you define a class inside a function?) Does that make sense?

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


Re: Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread yuyaxuan0
OK...

1."Memory is not enough..." is giving from the exe program.
2. If I run the exe program directly using cmd console, it's working good.
3. I am using Windows 7, 4GB memory python 2.7 the program is a image 
processing program.

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


Re: IPython in Emacs

2013-04-25 Thread Seb
On Thu, 25 Apr 2013 06:54:33 -0700 (PDT),
rusi  wrote:

> On Apr 25, 6:01 pm, Seb  wrote:
>> On Wed, 24 Apr 2013 21:38:04 -0700 (PDT),

>> rusi  wrote:
>> > There were some ipython+emacs+windows bugs:
>> >https://bugs.launchpad.net/ipython/+bug/290228 > Last I tried nearly
>> 2 years, they were still there
>> >http://groups.google.com/group/comp.lang.python/browse_thread/thread/...

>> On Debian here, so not a problem.

> Ok me too :-)

> A quick try of your startup code did not work for me.  There is a
> perennial clash in emacs between python.el and python- mode.el -- I
> guess its that.  Which do you use?

The first.  I don't have anything python-related in ~/.emacs other than
what I showed.  Works fine for me, except for weird things like multiple
input prompts in the IPython shell at startup, which seem to come from
each statement in the variables I showed.  Similar things happen when
sending code from the script buffer.


> What are your commands for eval-buffer and start-interpreter?

I don't understand what you're asking.  I evaluate the script buffer
with `python-shell-send-buffer' and start IPython with `run-python'.


-- 
Seb

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


Re: baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Alastair Thompson
Thats a good pointer to what is going on. Thank you Bas.

I am familiar with error such as

x=1
def foo():
x = 2
def erm():
print(x)
x=3
erm()
foo()
UnboundLocalError: local variable 'x' referenced before assignment.

It seems a bit different for classes (below), as it jumps out to get the
value from the global name space, where it didn't for functions (above).

x=1
def foo():
x = 2
class erm():
print(x)
x = 3
foo()  # This evaluates == 1

But you certainly have explained why  "NameError: name 'third' is not
defined" occurs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to count sequences

2013-04-25 Thread Denis McMahon
On Wed, 24 Apr 2013 22:05:52 -0700, CM wrote:

> I have to count the number of various two-digit sequences in a list such
> as this:
> 
> mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4) sequence
> appears 2 times.)
> 
> and tally up the results, assigning each to a variable.  The inelegant
> first pass at this was something like...
> 
> # Create names and set them all to 0 alpha = 0 beta = 0 delta = 0 gamma
> = 0 # etc...
> 
> # loop over all the tuple sequences and increment appropriately for
> sequence_tuple in list_of_tuples:
> if sequence_tuple == (1,2):
> alpha += 1
> if sequence_tuple == (2,4):
> beta += 1
> if sequence_tuple == (2,5):
> delta +=1
> # etc... But I actually have more than 10 sequence types.
> 
> # Finally, I need a list created like this:
> result_list = [alpha, beta, delta, gamma] #etc...in that order
> 
> I can sense there is very likely an elegant/Pythonic way to do this, and
> probably with a dict, or possibly with some Python structure I don't
> typically use.  Suggestions sought.  Thanks.

mylist = [ (3,3), (1,2), "fred", ("peter",1,7), 1, 19, 37, 28.312, 
("monkey"), "fred", "fred", (1,2) ]

bits = {}

for thing in mylist:
if thing in bits:
bits[thing] += 1
else:
bits[thing] = 1

for thing in bits:
print thing, " occurs ", bits[thing], " times"

outputs:

(1, 2)  occurs  2  times
1  occurs  1  times
('peter', 1, 7)  occurs  1  times
(3, 3)  occurs  1  times
28.312  occurs  1  times
fred  occurs  3  times
19  occurs  1  times
monkey  occurs  1  times
37  occurs  1  times

if you want to check that thing is a 2 int tuple then use something like:

for thing in mylist:
if isinstance( thing, tuple ) and len( thing ) == 2 and isinstance
( thing[0], ( int, long ) ) and isinstance( thing[1], ( int, long) ):
if thing in bits:
bits[thing] += 1
else:
bits[thing] = 1

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


TCP reassembly

2013-04-25 Thread Hasil Sharma
Hi everyone , 
How to reassemble the TCP data packets into objects viz. html , css , js image 
files etc . I have no idea how to implement it using python , please help ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TCP reassembly

2013-04-25 Thread Andrew Berg
On 2013.04.25 18:35, Hasil Sharma wrote:
> Hi everyone , 
> How to reassemble the TCP data packets into objects viz. html , css , js 
> image files etc . I have no idea how to implement it using python , please 
> help ?
TCP packets don't need to be reassembled. If your application receives TCP 
packets out of order, there is a problem with your networking
equipment (or possibly the TCP stack in your OS). I suspect that you actually 
mean that you want distinct bytes objects that represent
specific data. Sockets will give you a stream of bytes; how the data is 
separated is defined by the protocol. If you are dealing with HTTP,
it is much better to use an HTTP client library than raw sockets. In fact, 
there are many libraries available for many different protocols,
which are a better choice than dealing with sockets directly for all but the 
simplest protocols. You'll get a better answer if you tell us
what the problem is and what you are trying to accomplish.

-- 
CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to count sequences

2013-04-25 Thread Modulok
On 4/25/13, Denis McMahon  wrote:
> On Wed, 24 Apr 2013 22:05:52 -0700, CM wrote:
>
>> I have to count the number of various two-digit sequences in a list such
>> as this:
>>
>> mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4) sequence
>> appears 2 times.)
>>
>> and tally up the results, assigning each to a variable.
...

Consider using the ``collections`` module::


from collections import Counter

mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]
count = Counter()
for k in mylist:
count[k] += 1

print(count)

# Output looks like this:
# Counter({(2, 4): 2, (4, 5): 1, (3, 4): 1, (2, 1): 1})


You then have access to methods to return the most common items, etc. See more
examples here:

http://docs.python.org/3.3/library/collections.html#collections.Counter


Good luck!
-Modulok-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return list of lists

2013-04-25 Thread Eternaltheft
Thank you so much for the help, I get it now :D. I really appreciate you taking 
the time to explain it into detail for me
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to count sequences

2013-04-25 Thread Matthew Gilson


A Counter is definitely the way to go about this.  Just as a little more 
information.  The below example can be simplified:


from collections import Counter
count = Counter(mylist)

With the other example, you could have achieved the same thing (and been 
backward compatible to python2.5) with


   from collections import defaultdict
   count = defaultdict(int)
   for k in mylist:
count[k] += 1



On 4/25/13 9:16 PM, Modulok wrote:

On 4/25/13, Denis McMahon  wrote:

On Wed, 24 Apr 2013 22:05:52 -0700, CM wrote:


I have to count the number of various two-digit sequences in a list such
as this:

mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4) sequence
appears 2 times.)

and tally up the results, assigning each to a variable.

...

Consider using the ``collections`` module::


 from collections import Counter

 mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]
 count = Counter()
 for k in mylist:
 count[k] += 1

 print(count)

 # Output looks like this:
 # Counter({(2, 4): 2, (4, 5): 1, (3, 4): 1, (2, 1): 1})


You then have access to methods to return the most common items, etc. See more
examples here:

http://docs.python.org/3.3/library/collections.html#collections.Counter


Good luck!
-Modulok-


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


Re: Pythonic way to count sequences

2013-04-25 Thread CM
Thank you, everyone, for the answers.  Very helpful and knowledge-
expanding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison Style

2013-04-25 Thread Chris Angelico
On Fri, Apr 26, 2013 at 12:37 PM, Dennis Lee Bieber
 wrote:
> On Thu, 25 Apr 2013 15:57:49 +1000, Chris Angelico 
> declaimed the following in gmane.comp.python.general:
>> It's conventional to compare variables to constants, not constants to
>> variables (even in C where there's the possibility of mucking up the
>> operator, most people still compare variables to constants).
>
> The main reason for /literal/ first is to trap C/C++ assignment as
> expression.
>
> if (x = 5)
>
> ends up assigning x the value 5 and THEN, since 5 is "true" executing
> the "then" part.
>
> if (5 = x)
>
> OTOH is a compiler error.
>

Aware of this. My point is that, even though there's a good reason for
putting the constant first, it's still FAR more common to put the
variable first. Also, this protection helps only when the "constant"
is actually something the compiler knows is a constant - it doesn't
work in a search function, for instance:

char *strchr(char *string, char findme) {
while (*string) {
if (*string==findme) return string;
++string;
}
return 0;
}

If you switch the order of operands in that, the compiler won't help
you. Plus it "reads" wrong. So the convention is still
variable==constant.

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


Re: TCP reassembly

2013-04-25 Thread Dave Angel

On 04/25/2013 07:35 PM, Hasil Sharma wrote:

Hi everyone ,
How to reassemble the TCP data packets into objects viz. html , css , js image 
files etc . I have no idea how to implement it using python , please help ?




TCP reassembly has a specific meaning, and I doubt if that's what you 
mean.  If you reach down below the tcp layer in your OS, and get raw IP 
packets, then you have to do the reassembly yourself.  But if you open a 
TCP connection, the OS will already do any reordering, retrying, and 
reassembly for you.


Give a specific example of what you're trying, and what piece of it is 
failing for you.


tcpdump or wireshark can be used to examine low level protocol issues, 
if you really have such.  And python + scapy can generate pretty 
arbitrary packets.  But I rather doubt that's what you want.



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


Re: Comparison Style

2013-04-25 Thread Dave Angel

On 04/25/2013 10:48 PM, Chris Angelico wrote:




Also, this protection helps only when the "constant"
is actually something the compiler knows is a constant - it doesn't
work in a search function, for instance:

char *strchr(char *string, char findme) {
 while (*string) {
 if (*string==findme) return string;
 ++string;
 }
 return 0;
}


Sure, but if I were coding in C again, I'd have made that function signature

char *strchr(char *string, const char findme) {
   or maybe
char *strchr(const char *string, const char findme) {



If you switch the order of operands in that, the compiler won't help
you.


Yes, it would.


Plus it "reads" wrong. So the convention is still
variable==constant.


In my case, after having it drilled in that you're "supposed" to put the 
constant first, I realized that I never had any problem with using =, 
because as soon as I questioned the order, I just double-checked that I 
was using ==.  At that point, there was no longer any benefit to making 
the order backwards.



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


Re: IPython in Emacs

2013-04-25 Thread rusi
On Apr 26, 3:18 am, Seb  wrote:
>
> I don't understand what you're asking.  I evaluate the script buffer
> with `python-shell-send-buffer' and start IPython with `run-python'.


There are two emacs python modes -- one which comes builtin with emacs
-- python.el, one which (used to?) come with python -- python-mode.el.

My impression is that most pythonistas preferred the python-mode
earlier. Not so sure now.
You can get it from https://launchpad.net/python-mode/

Heres a minimal setup for python-mode +ipython (everything's probably
not working)

(add-to-list 'load-path "~/.emacs.d/downloads/python-mode")  ;; Or
whatever is your path for python-mode.el
(autoload 'python-mode "python-mode" "Python Mode." t)
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
(add-to-list 'interpreter-mode-alist '("python" . python-mode))

;; A first cut at replicating your settings of ipython for python-mode
(setq py-python-command "ipython"  ; python-shell-interpreter
  py-python-command-args '(""); python-shell-interpreter-args
; Should it be -i?
  py-shell-input-prompt-1-regexp "In \\[[0-9]+\\]: "
  ; Other variables dont exist or cant find
  ; Not really explored ipython.el
)


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


PCAP Files

2013-04-25 Thread Hasil Sharma
I m having network dumps in the form of pcap files and I want to extract the 
html,css, image files etc etc all that can be extracted from those pcap files , 
can anyone please tell me how to accomplish such a task in python ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread rusi
On Apr 26, 3:11 am, yuyaxu...@gmail.com wrote:
> OK...
>
> 1."Memory is not enough..." is giving from the exe program.
> 2. If I run the exe program directly using cmd console, it's working good.
> 3. I am using Windows 7, 4GB memory python 2.7 the program is a image 
> processing program.

It may be good to go thruogh http://sscce.org/
Your earlier data was too long
Now its not self-contained (and not an example)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Peter Otten
Alastair Thompson wrote:

> I am completely baffled by the behavior of this code with regards to the
> evaluation order of namespaces when assigning the class attributes.  Both
> classes are nested within a function I called whywhywhy.
> 
> I assumed that example1 and example2 classes would look first at their own
> namespace, then object, then the whywhywhy func namespace then global, and
> maybe module.  It seems this is not the case.
> 
> def whywhywhy(first, second, third):
> def print_stuff():
> print("func: first=", first)
> print("func: second=", second)
> print("func: third=", third)
> print_stuff()
> 
> class example1(object):
> print("1cls: first=", first)
> print("1cls: second=", second)
> print("1cls: third=", third)
> 
> second = second
> foo = third
> 
> class example2(object):
> print("2cls: first=", first)
> print("2cls: second=", second)
> print("2cls: third=", third)
> 
> second = second
> third = third
> 
> def second():
> pass
> 
> whywhywhy(1,2,3)
> 
> 
> The code above produces the following output
> """
> func: first= 1
> func: second= 2
> func: third= 3
> 1cls: first= 1
> 1cls: second= 
> 1cls: third= 3
> 2cls: first= 1
> 2cls: second= 
> Traceback (most recent call last):
>   File "error.py", line 29, in 
> whywhywhy(1,2,3)
>   File "error.py", line 18, in whywhywhy
> class example2(object):
>   File "error.py", line 21, in example2
> print("2cls: third=", third)
> NameError: name 'third' is not defined
> """
> 
> In particular:
> 
> print_stuff behaves as I would expect
> 1cls: second #<--- Why does this look at the global namespace for second
> and not the whywhywhy func namespace first.
> 2cls: second #<--- Why can this no longer find third, it surely hasn't hit
> the line third=third
> 
> Thanks for any help you can provide. :)
> Alastair

A class body is basically a function body that is executed once. To allow an 
assignment

>>> x = 42
>>> class A:
... x = x
... 

which is not possible inside a function

>>> def f():
... x = x
... 
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment

it uses one opcode, LOAD_NAME, that looks into the local and falls back to 
the global namespace, but knows nothing about closures:

>>> code = compile("class A:\n  x = x", "", "exec")
>>> code.co_consts
(", line 1>, 'A', None)
>>> import dis
>>> dis.dis(code.co_consts[0])
  1   0 LOAD_FAST0 (__locals__) 
  3 STORE_LOCALS 
  4 LOAD_NAME0 (__name__) 
  7 STORE_NAME   1 (__module__) 

  2  10 LOAD_NAME2 (x) 
 13 STORE_NAME   2 (x)  
   
 16 LOAD_CONST   0 (None)   
   
 19 RETURN_VALUE
   

For functions on the other side the compiler determines the scope of the 
name:

>>> def g():
... y = "outer"
... def h():
... return x, y, z
... z = 42
... return h
... 
>>> dis.dis(g())
  4   0 LOAD_GLOBAL  0 (x) # global var
  3 LOAD_DEREF   0 (y) # closure
  6 LOAD_FAST0 (z) # local
  9 BUILD_TUPLE  3 
 12 RETURN_VALUE 

  5  13 LOAD_CONST   1 (42) 
 16 STORE_FAST   0 (z) 

As you can see there are three different opcodes for global, closure, and 
local namespace.

However, while the above gives some technical background it doesn't explain 
why this scheme was chosen. My guess is that when Python got closures nobody 
was willing to do the extra work to make class bodies namespace-aware.
The alternative, disallowing x = x in classes, would have seriously broken 
backwards-compatibility.


-- 
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: baffled classes within a function namespace. Evaluation order.

2013-04-25 Thread Steven D'Aprano
On Fri, 26 Apr 2013 07:39:32 +0200, Peter Otten wrote:

> A class body is basically a function body that is executed once. To
> allow an assignment
> 
 x = 42
 class A:
> ... x = x
> ...
> 
> which is not possible inside a function


As far as I can tell, the documentation says that this assignment should 
also be impossible inside a class. Unless I'm missing something, I think 
this is a bug.

http://docs.python.org/3/reference/executionmodel.html


[...]
> However, while the above gives some technical background it doesn't
> explain why this scheme was chosen. My guess is that when Python got
> closures nobody was willing to do the extra work to make class bodies
> namespace-aware. The alternative, disallowing x = x in classes, would
> have seriously broken backwards-compatibility.

Not so. x = x was not allowed in classes before there were closures:


[steve@ando ~]$ python1.5
Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 
4.1.2-52)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
>>>
>>> def f():
... x = 1
... class Test:
... x = x
... return Test
...
>>> T = f()
Traceback (innermost last):
  File "", line 1, in ?
  File "", line 3, in f
  File "", line 4, in Test
NameError: x



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


Re: Weird python behavior

2013-04-25 Thread rusi
On Apr 26, 11:04 am, Tim Roberts  wrote:
> 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.

Yes…
When it comes to keywords it is reasonable to expect the programmer to
know all the keywords and if he uses one for a function/variable the
error will be immediate.

When it comes to modules it is less reasonable to expect the
programmer to know all available modules.
To present these kind of errors, Erlang has a concept of sticky
modules -- those that come from the system -- for which special
efforts need to be made to 'unstick' them if one wants them
overridden.  This is helpful because the default which is to raise an
error, is in most cases a more sound option than to silently override
a builtin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Quesion about running a exe file in Python(Not enough memory)

2013-04-25 Thread Chris Angelico
On Fri, Apr 26, 2013 at 8:00 AM, Steven D'Aprano
 wrote:
> On Thu, 25 Apr 2013 14:18:58 -0700, yuyaxuan0 wrote:
>> #cmd = "D:\\programs\\MIRAX_SlideAC_SDK\\Bin\\MrxSlideExport.exe -s
>> D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Slides\\L10 -e
>> -o D:\\fit\\projects\\bayer\\KidneyLiver\\MiraxScanner\\Output\\L10
>> -z 5 -f png"
>
> You can simplify Windows pathnames by using forward slashes.

These paths are being given to an external tool, so I wouldn't
guarantee that forward slashes will work. But you can use a raw string
literal to avoid doubling them all up.

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


Warning in python file when i m using pychecker.

2013-04-25 Thread Avnesh Shakya
hi,
   I am trying to run my file using pychecker, but it's showing warning. I am 
unable to get these warning. Please help me, how to remove these warning. I am 
using pychecker first time.

avin@HP:~/github/UdacitySiteData$ pychecker udacity_to_jsonFinal.py
Processing module udacity_to_jsonFinal (udacity_to_jsonFinal.py)...

Warnings...

[system path]/dist-packages/bs4/__init__.py:206: Parameter (successor) not used
[system path]/dist-packages/bs4/__init__.py:209: Parameter (successor) not used
[system path]/dist-packages/bs4/__init__.py:213: Local variable (tag) not used

[system path]/dist-packages/bs4/element.py:306: Parameter (kwargs) not used
[system path]/dist-packages/bs4/element.py:507: (id) shadows builtin
[system path]/dist-packages/bs4/element.py:791: (next) shadows builtin
[system path]/dist-packages/bs4/element.py:903: Invalid arguments to 
(__repr__), got 2, expected 1

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


Re: PCAP Files

2013-04-25 Thread Cameron Simpson
On 25Apr2013 21:55, Hasil Sharma  wrote:
| I m having network dumps in the form of pcap files and I want to
| extract the html,css, image files etc etc all that can be extracted
| from those pcap files , can anyone please tell me how to accomplish
| such a task in python ?

I would reassemble the TCP packets into data streams and then handle
them to an HTTP or MIME parser. For the first part, have you tried
a google search? Like this:

  https://www.google.com.au/search?q=reassemble+pcap+files+into+tcp+streams

Looks promising, particularly the "streams" and "tcpreplay" stuff.
Or even search the Python Package Index for "pcap", even indirectly via google:

  
https://www.google.com.au/search?q=pypi+pcap&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-beta&channel=fflb

Then just handle the data streams to a normal Python MIME parser
to figure out what's in them.

Cheers,
-- 
Cameron Simpson 

I have come here to chew bubblegum and kick ass, and I'm all out of
bubblegum.  - Roddy Piper
-- 
http://mail.python.org/mailman/listinfo/python-list