Re: Continuing indentation

2016-03-05 Thread Steven D'Aprano
On Sat, 5 Mar 2016 08:14 am, sohcahto...@gmail.com wrote:

> I wouldn't call PEP 8 "correct".  I would say that you just simply agree
> with PEP 8's suggestion.
> 
> You guys are spending way too much time fighting over something that is
> clearly subjective.  Nobody is "correct" here.  There's no right and
> wrong, just simple preference.

Your point is taken, but I think there is an objectively better style. Or at
least there may be an objectively better style. 

Of course, coming up with an objective definition of what is meant
by "better", and performing UI testing to determine which style is better,
is a lot of hard work for marginal gain. It's much more fun to just flame
each other :-)



-- 
Steven

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-05 Thread lucasfrank254
On Saturday, December 12, 2015 at 1:05:29 AM UTC-8, Harbey Leke wrote:
> Create a class called BankAccount
> 
> .Create a constructor that takes in an integer and assigns this to a 
> `balance` property.
> 
> .Create a method called `deposit` that takes in cash deposit amount and 
> updates the balance accordingly.
> 
> .Create a method called `withdraw` that takes in cash withdrawal amount and 
> updates the balance accordingly. if amount is greater than balance return 
> `"invalid transaction"`
> 
> .Create a subclass MinimumBalanceAccount of the BankAccount class
> 
> Please i need help on this i am a beginer into python programming.
> 
> 
> Also below is a test case given for this project 
> 
> 
> import unittest
> class AccountBalanceTestCases(unittest.TestCase):
>   def setUp(self):
> self.my_account = BankAccount(90)
> 
>   def test_balance(self):
> self.assertEqual(self.my_account.balance, 90, msg='Account Balance 
> Invalid')
> 
>   def test_deposit(self):
> self.my_account.deposit(90)
> self.assertEqual(self.my_account.balance, 180, msg='Deposit method 
> inaccurate')
> 
>   def test_withdraw(self):
> self.my_account.withdraw(40)
> self.assertEqual(self.my_account.balance, 50, msg='Withdraw method 
> inaccurate')
> 
>   def test_invalid_operation(self):
> self.assertEqual(self.my_account.withdraw(1000), "invalid transaction", 
> msg='Invalid transaction')
>   
>   def test_sub_class(self):
> self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount), msg='No 
> true subclass of BankAccount')

my solution is:

class BankAccount(object):
def __init__(self, initial_balance):
self.balance = initial_balance
def deposit(self, amount):
self.balance +=amount
def withdraw(self, amount):
  if self.balance>= amount:
  self.balance  -=  amount
  else:
return invalid transaction
a1 = BankAccount (90)
a1.deposit(90)
a1.withdraw(40)
a1.withdraw(1000)
class MinimumBalanceAccount(BankAccount):
  def __init__(self):
BankAccount.__init__(self,minimum_balance)
self.minimum_balance = minimum_balance
my_account = BankAccount(90)
my_account.withdraw(40)
print my_account.balance


It keeps alerting me that,"Error running your script".Where might I have gone 
wrong?Please help..
-- 
https://mail.python.org/mailman/listinfo/python-list


Application console for Tkinter program?

2016-03-05 Thread Christian Gollwitzer

Hi all,

is there an easy way to add an application console to a Tkinter program? 
For instance, can you embed IDLE into a program such that when a button 
is pressed, it pops up a REPL window where the running program can be 
examined?


Say, there is a simple program like:


import Tkinter as tk

def runshell():
from idlelib.PyShell import main
main()

root=tk.Tk()
nvar=tk.StringVar(root)
en=tk.Entry(textvariable=nvar)
en.pack()

btn=tk.Button(text="Shell", command=runshell)
btn.pack()

root.mainloop()


I want the button to popup a shell window, and then nvar.get() should 
give me whatever is currently written in the entry. The code above does 
not work as intended, it pops up a shell, but:


1) I can't reach the variables from the main program, i.e. print(nvar) 
gives me a NameError


2) If you click the Shell button twice, it locks up the program, because 
main() obviously starts it's own mainloop



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


Re: Any comment on using ctypesgen package?

2016-03-05 Thread jfong
Chris Angelico at 2016/3/5  UTC+8 1:50:05PM wrote:
> Your conclusion may well be correct. However, the exact issue you're
> looking at here might be easily enough fixed; it looks like it's
> trying to sort things by length, so you can simply use "key=len" (and
> maybe "reverse=True").

After Chris gave this suggestion, I can't withstand the temptation of running 
the setup again. This time, strangely, it reports error on import. Won't the 
import statement easy enough to be handled by 2To3? Here is the result (where 
the whole "ctypesgencore" directory had been processed by 2To3 and the "parser" 
is a sub-directory under it):

--
D:\Patch\ctypesgen-master>python setup.py install
Traceback (most recent call last):
  File "setup.py", line 13, in 
import ctypesgencore
  File "D:\Patch\ctypesgen-master\ctypesgencore\__init__.py", line 55, in 
from . import parser
  File "D:\Patch\ctypesgen-master\ctypesgencore\parser\__init__.py", line 17, in
 
from .datacollectingparser import DataCollectingParser
  File "D:\Patch\ctypesgen-master\ctypesgencore\parser\datacollectingparser.py",
 line 10, in 
from . import ctypesparser
  File "D:\Patch\ctypesgen-master\ctypesgencore\parser\ctypesparser.py", line 15
, in 
from .cparser import *
  File "D:\Patch\ctypesgen-master\ctypesgencore\parser\cparser.py", line 21, in

from . import cgrammar
  File "D:\Patch\ctypesgen-master\ctypesgencore\parser\cgrammar.py", line 25, in
 
from . import ctypesparser
ImportError: cannot import name 'ctypesparser'


Just curious, is there a recursive-import happen on handling the "parser" 
directory?

After checking the files, I had noticed that all the import statements had been 
changed by 2To3. Mostly the changes are, such as, from "import cgrammar" to 
"from . import cgrammar", or "from cparser import *" to "from .cparset import 
*". I can understand the former, but can't figure out the latter:-(

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


Re: [Still off-top] Physics [was Requests author discusses MentalHealthError exception]

2016-03-05 Thread Marko Rauhamaa
Chris Angelico :

> On Sat, Mar 5, 2016 at 1:51 PM, Gregory Ewing
>  wrote:
>> Conservation of energy would be one reason. If you put two particles
>> together and got more energy out than went in, where did the extra
>> energy come from?
>
> You borrowed it from the bank, of course. You have to make loan
> payments periodically, or they'll foreclose on your particles. If
> everyone borrows energy all at once, and then can't make their
> payments, the universe crashes in a "heat death".

Quantum Mechanics works like a corrupt central bank: you have an
unlimited credit line and can borrow energy out of nothing as long as
you repay the loan before the audit.


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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-05 Thread Peter Otten
lucasfrank...@gmail.com wrote:

> On Saturday, December 12, 2015 at 1:05:29 AM UTC-8, Harbey Leke wrote:
>> Create a class called BankAccount
>> 
>> .Create a constructor that takes in an integer and assigns this to a
>> `balance` property.
>> 
>> .Create a method called `deposit` that takes in cash deposit amount and
>> updates the balance accordingly.
>> 
>> .Create a method called `withdraw` that takes in cash withdrawal amount
>> and updates the balance accordingly. if amount is greater than balance
>> return `"invalid transaction"`
>> 
>> .Create a subclass MinimumBalanceAccount of the BankAccount class
>> 
>> Please i need help on this i am a beginer into python programming.
>> 
>> 
>> Also below is a test case given for this project
>> 
>> 
>> import unittest
>> class AccountBalanceTestCases(unittest.TestCase):
>>   def setUp(self):
>> self.my_account = BankAccount(90)
>> 
>>   def test_balance(self):
>> self.assertEqual(self.my_account.balance, 90, msg='Account Balance
>> Invalid')
>> 
>>   def test_deposit(self):
>> self.my_account.deposit(90)
>> self.assertEqual(self.my_account.balance, 180, msg='Deposit method
>> inaccurate')
>> 
>>   def test_withdraw(self):
>> self.my_account.withdraw(40)
>> self.assertEqual(self.my_account.balance, 50, msg='Withdraw method
>> inaccurate')
>> 
>>   def test_invalid_operation(self):
>> self.assertEqual(self.my_account.withdraw(1000), "invalid
>> transaction", msg='Invalid transaction')
>>   
>>   def test_sub_class(self):
>> self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount),
>> msg='No true subclass of BankAccount')
> 
> my solution is:
> 
> class BankAccount(object):
> def __init__(self, initial_balance):
> self.balance = initial_balance
> def deposit(self, amount):
> self.balance +=amount
> def withdraw(self, amount):
>   if self.balance>= amount:
>   self.balance  -=  amount
>   else:
> return invalid transaction
> a1 = BankAccount (90)
> a1.deposit(90)
> a1.withdraw(40)
> a1.withdraw(1000)
> class MinimumBalanceAccount(BankAccount):
>   def __init__(self):
> BankAccount.__init__(self,minimum_balance)
> self.minimum_balance = minimum_balance
> my_account = BankAccount(90)
> my_account.withdraw(40)
> print my_account.balance
> 
> 
> It keeps alerting me that,"Error running your script".Where might I have
> gone wrong?Please help..

When you run the above code as a script on your own machine, i. e. if the 
file is called bank.py you type

python3 bank.py

on the commandline (if you are using Idle, you can hit F5 instead), what 
happens?

The output should give you a hint about what's wrong and where in the script 
the problem occurs. This output is called "traceback", and if you cannot 
make sense of it, come back here to ask, but don't forget to include the 
traceback into your post. Don't paraphrase, use cut and paste.

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


Re: Application console for Tkinter program?

2016-03-05 Thread Terry Reedy

On 3/5/2016 2:52 AM, Christian Gollwitzer wrote:


is there an easy way to add an application console to a Tkinter program?


Right now, you should turn the question around.  Is there an easy way to 
run a tkinter program within an interactive console?  Answer: yes, two 
ways, after removing the runshell stuff and mainloop call*.


1. Call your program mytk.py.  In your system console, run 'python -i 
myth.py'.  When the code ends, control passes to the console running 
python.  Statements like 'print(nvar.get())' will be executed in the 
main namespace of the still running program.


2. Load (or write) the file into an IDLE Editor and hit F5 (Run -> Run 
module on the menu).  This simulates the console command above.


* The tk loop is started with the Tk() call.  Most things work without 
the blocking mainloop() call.  When this is true, the mainloop call 
serves mainly to keep the program running instead of exiting.  The -i 
option does the same.


If you need mainloop(), then add

def quit(): # or quit(self):
root.exit()
b = tk.Button(root, command=quit)
b.grid()  # or pack or place

The root.quit() call ends the blocking mainloop call and allows console 
entry.  I believe a subsequent root.mainloop() in the console will work 
when needed.



For instance, can you embed IDLE into a program such that when a button
is pressed, it pops up a REPL window where the running program can be
examined?


If the REPL window is defined in an imported module, the problem is 
linking the main namespace of the tkinter program with the REPL loop in 
such a way that commands entered into the REPL are executed in the main 
module, not in the REPL module.



Say, there is a simple program like:


import Tkinter as tk

def runshell():
 from idlelib.PyShell import main
 main()

root=tk.Tk()
nvar=tk.StringVar(root)
en=tk.Entry(textvariable=nvar)
en.pack()

btn=tk.Button(text="Shell", command=runshell)
btn.pack()

root.mainloop()


I want the button to popup a shell window, and then nvar.get() should
give me whatever is currently written in the entry. The code above does
not work as intended, it pops up a shell, but:

1) I can't reach the variables from the main program, i.e. print(nvar)
gives me a NameError


This is the linkage problem I mentioned.


2) If you click the Shell button twice, it locks up the program, because
main() obviously starts it's own mainloop


IDLE executes user code in a separate process, linked by sockets, so 
that execution of IDLE GUI code and user code do not interfere with each 
other.  I would like to refactor IDLE so that the Shell window would 
contain a Shell Frame (or LabelledFrame) that could also be used as pane 
in a single-window version of IDLE.  It would be possible to create a 
Shell frame without starting a new mainloop.


It might be possible to adapt such a component as an embedded console. 
An imported frame should not interfere with the main-module code or code 
in other modules.  The main problems are a) namespace linkage (mentioned 
before), b) the need for sys.stdin/out/err to not be None, and c) for 
capturing exceptions in code entered in the console, so as to not crash 
the main program.


--
Terry Jan Reedy

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


Re: Application console for Tkinter program?

2016-03-05 Thread Christian Gollwitzer

Am 05.03.16 um 11:15 schrieb Terry Reedy:

On 3/5/2016 2:52 AM, Christian Gollwitzer wrote:

is there an easy way to add an application console to a Tkinter program?


Right now, you should turn the question around.


so this means no, right?


Is there an easy way to
run a tkinter program within an interactive console?  Answer: yes, two
ways, after removing the runshell stuff and mainloop call*.

1. Call your program mytk.py.  In your system console, run 'python -i
myth.py'.  When the code ends, control passes to the console running
python.  Statements like 'print(nvar.get())' will be executed in the
main namespace of the still running program.


well yes, this does work, but I should have explained why I want it the 
other way round. We have an in-house tool which is used to manipulate 
images. During production use, at some point you think "and now if I 
could just save the image that I see on screen into a PNG file". You 
know exactly that MyViewer.image is the thing that contains what you 
need, if only you had a way to tell it 
'MyViewer.image.save("somewhere.png")'. At this point, you haven't 
started the program from an interactive python. Always running the tool 
from ipython or idle means there are useless windows hanging around, but 
if you close them, your pogram goe away. To make it even more 
complicated, the deployed version of the tool uses pyinstaller to be 
safe from environment changes.


Of course, I could pack some text widget somewhere and fiddle a few 
bindings to make it do this with eval(), but a good REPL has history, 
autocompletion, syntax highlighting you get it. I had simply hoped, 
since idle is written in Tkinter, that it could be reused for that purpose.


For pure Tcl/Tk, there is tkcon which can do exactly this and I use it 
in similar tools writtin in Tcl/Tk. I can run it via Tk.eval(), but I 
couldn't find a way to call back into Python coming from the Tkinter 
interpreter, and obviously autocompletion and syntax highlighting do not 
work well.



For instance, can you embed IDLE into a program such that when a button
is pressed, it pops up a REPL window where the running program can be
examined?


If the REPL window is defined in an imported module, the problem is
linking the main namespace of the tkinter program with the REPL loop in
such a way that commands entered into the REPL are executed in the main
module, not in the REPL module.


I'm happy to pass the main module as an argument to REPLInit().


2) If you click the Shell button twice, it locks up the program, because
main() obviously starts it's own mainloop


IDLE executes user code in a separate process, linked by sockets, so
that execution of IDLE GUI code and user code do not interfere with each
other.


Ahhh - OK this makes sense in the general case, but not for a console 
where you *want* your REPL to perform surgery on the main program.



I would like to refactor IDLE so that the Shell window
...
It might be possible to adapt such a component as an embedded console.
An imported frame should not interfere with the main-module code or code
in other modules.  The main problems are a) namespace linkage (mentioned
before),




b) the need for sys.stdin/out/err to not be None,


tkcon solves this be redirecting stdin/stdout/stderr to functions which 
write to the console window.



and c) for
capturing exceptions in code entered in the console, so as to not crash
the main program.



For Python exceptions I see no problem - the eval must simply be 
properly wrapped in try..except and the traceback is redirected to the 
console. If a C level exception occurs, this will crash everything, but 
that's OK.


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


Re: Any comment on using ctypesgen package?

2016-03-05 Thread Mark Lawrence

On 05/03/2016 08:14, jf...@ms4.hinet.net wrote:

Chris Angelico at 2016/3/5  UTC+8 1:50:05PM wrote:

Your conclusion may well be correct. However, the exact issue you're
looking at here might be easily enough fixed; it looks like it's
trying to sort things by length, so you can simply use "key=len" (and
maybe "reverse=True").


After Chris gave this suggestion, I can't withstand the temptation of running the setup again. This 
time, strangely, it reports error on import. Won't the import statement easy enough to be handled 
by 2To3? Here is the result (where the whole "ctypesgencore" directory had been processed 
by 2To3 and the "parser" is a sub-directory under it):

--
D:\Patch\ctypesgen-master>python setup.py install
Traceback (most recent call last):
   File "setup.py", line 13, in 
 import ctypesgencore
   File "D:\Patch\ctypesgen-master\ctypesgencore\__init__.py", line 55, in 

 from . import parser
   File "D:\Patch\ctypesgen-master\ctypesgencore\parser\__init__.py", line 17, 
in
  
 from .datacollectingparser import DataCollectingParser
   File 
"D:\Patch\ctypesgen-master\ctypesgencore\parser\datacollectingparser.py",
  line 10, in 
 from . import ctypesparser
   File "D:\Patch\ctypesgen-master\ctypesgencore\parser\ctypesparser.py", line 
15
, in 
 from .cparser import *
   File "D:\Patch\ctypesgen-master\ctypesgencore\parser\cparser.py", line 21, in

 from . import cgrammar
   File "D:\Patch\ctypesgen-master\ctypesgencore\parser\cgrammar.py", line 25, 
in
  
 from . import ctypesparser
ImportError: cannot import name 'ctypesparser'


Just curious, is there a recursive-import happen on handling the "parser" 
directory?

After checking the files, I had noticed that all the import statements had been changed by 2To3. Mostly the changes 
are, such as, from "import cgrammar" to "from . import cgrammar", or "from cparser import 
*" to "from .cparset import *". I can understand the former, but can't figure out the latter:-(

--Jach



HTH http://python3porting.com/problems.html

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2016-03-05 Thread Albert Visser

On Sat, 05 Mar 2016 08:41:39 +0100,  wrote:


On Saturday, December 12, 2015 at 1:05:29 AM UTC-8, Harbey Leke wrote:

Create a class called BankAccount

.Create a constructor that takes in an integer and assigns this to a  
`balance` property.


.Create a method called `deposit` that takes in cash deposit amount and  
updates the balance accordingly.


.Create a method called `withdraw` that takes in cash withdrawal amount  
and updates the balance accordingly. if amount is greater than balance  
return `"invalid transaction"`


.Create a subclass MinimumBalanceAccount of the BankAccount class

Please i need help on this i am a beginer into python programming.


Also below is a test case given for this project


import unittest
class AccountBalanceTestCases(unittest.TestCase):
  def setUp(self):
self.my_account = BankAccount(90)

  def test_balance(self):
self.assertEqual(self.my_account.balance, 90, msg='Account Balance  
Invalid')


  def test_deposit(self):
self.my_account.deposit(90)
self.assertEqual(self.my_account.balance, 180, msg='Deposit method  
inaccurate')


  def test_withdraw(self):
self.my_account.withdraw(40)
self.assertEqual(self.my_account.balance, 50, msg='Withdraw method  
inaccurate')


  def test_invalid_operation(self):
self.assertEqual(self.my_account.withdraw(1000), "invalid  
transaction", msg='Invalid transaction')


  def test_sub_class(self):
self.assertTrue(issubclass(MinimumBalanceAccount, BankAccount),  
msg='No true subclass of BankAccount')


my solution is:

class BankAccount(object):
def __init__(self, initial_balance):
self.balance = initial_balance
def deposit(self, amount):
self.balance +=amount
def withdraw(self, amount):
  if self.balance>= amount:
  self.balance  -=  amount
  else:
return invalid transaction
a1 = BankAccount (90)
a1.deposit(90)
a1.withdraw(40)
a1.withdraw(1000)
class MinimumBalanceAccount(BankAccount):
  def __init__(self):
BankAccount.__init__(self,minimum_balance)
self.minimum_balance = minimum_balance
my_account = BankAccount(90)
my_account.withdraw(40)
print my_account.balance


It keeps alerting me that,"Error running your script".Where might I have  
gone wrong?Please help..


Most probably there's extra information available on the "Error running  
your script" message. You should examine that.

Meanwhile, I think the line "return invalid transaction" provides a clue.

--
Vriendelijke groeten / Kind regards,

Albert Visser

Using Opera's mail client: http://www.opera.com/mail/
--
https://mail.python.org/mailman/listinfo/python-list


Re: Reason for not allowing import twice but allowing reload()

2016-03-05 Thread alien2utoo
Steven,

> There are better ways to manage your Python path than to manually insert
> paths into sys.path like that. What version of Python are you using?

I would love to know, apart from PYTHONPATH and sys.path.append() route.

I am using Python 2.7.11 to start with as suggested by my employer.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Still off-top] Physics [was Requests author discusses MentalHealthError exception]

2016-03-05 Thread Oscar Benjamin
On 5 March 2016 at 02:51, Gregory Ewing  wrote:
>  The masslessness of photons comes from an extrapolation
>>
>> that leads to a divide by infinity: strictly speaking it's just
>> undefined.
>
> No, it's not. The total energy of a particle is given by
>
>E**2 == c**2 * p**2 + m**2 * c**4
>
> where p is the particle's momentum and m is its mass.
> For a photon, m == 0. No division by zero involved.
>
> For a massive particle at rest, p == 0 and the above
> reduces to the well-known
>
>E == m * c**2

The distinction I'm drawing is between physical fact and mathematical
convenience. For other particles we can say that the 1st formula above
holds with m taken to be the mass of the particle at rest. We can
extend that formula to the case of photons which are never at rest by
saying that in the case of photons m=0. That's nice and it's
mathematically convenient in the calculations. It's analogous to
extending the natural definition of the factorial function by saying
that 0!=1. We can't prove that 0!=1 but it's useful to define it that
way. It wouldn't be a disaster to simply leave 0! undefined: it would
just make some equations a little more complicated.

Since the generally accepted physical fact is that photons are never
at rest we are free to define their "rest mass" (use any term you
like) to be anything that is mathematically convenient so we define it
as zero because that fits with your equation above. Turning full
circle we can then use the equation above to say that they are
massless since they would hypothetically be massless in some other
situation even though genuinely massless photons are not thought to
exist in physical reality (unless I'm really out of date on this!).

>> Something I don't know is if there's some theoretical reason why the
>> binding energy could never exceed the sum of the energies of the
>> constituent particles (resulting in an overall negative mass).
>
> Conservation of energy would be one reason. If you
> put two particles together and got more energy out than
> went in, where did the extra energy come from?

That's the point: the energy balance would be satisfied by the
negative energy of the bound particles. The binding energy can be
defined as the energy required to unbind the particles (other
definitions such as André's are also possible). From this definition
we see that the binding energy depends on the binding interaction
(electromagnetic or whatever) that binds the particles together.

The only examples I know of where the binding energy is computed
approximately for e.g. a hydrogen atom predict that the binding energy
is proportional to the (rest) mass of the bound particle(s). If it's
guaranteed that the binding energy always somehow comes out
proportional to the mass of the particles with a coefficient
necessarily smaller than 1/c**2 then you could say that the bound
product could never have negative energy. I just can't see off the top
of my head an argument to suggest that this is impossible.

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


Re: ANN: Wing IDE 5.1.10 released

2016-03-05 Thread jumppanen . jussi
On Saturday, March 5, 2016 at 5:55:34 AM UTC+11, Mario R. Osorio wrote:

> your messages area misleading; you should label them as ADVERTISEMENT

The fact the title contains ANN (announce) means pretty much the same thing.
-- 
https://mail.python.org/mailman/listinfo/python-list


Can I find the class of a method in a decorator.

2016-03-05 Thread Antoon Pardon
Using python 3.4/3.5

Suppose I have the following class:

class Tryout:

@extern
def method(self, ...)

Now how can I have access to the Tryout class in
the extern function when it is called with method
as argument

def extern(f):
the_class = 

f.__class doesn't work, if I write the following

def extern(f)
print(f.__class__)

the result is: , so that doesn't work.
Looking around I didn't find an other obvious candidate
to try. Anybody an idea?

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


Re: [Still off-top] Physics [was Requests author discusses MentalHealthError exception]

2016-03-05 Thread Gene Heskett
On Saturday 05 March 2016 08:11:46 Oscar Benjamin wrote:

> On 5 March 2016 at 02:51, Gregory Ewing  
wrote:
> >  The masslessness of photons comes from an extrapolation
> >
> >> that leads to a divide by infinity: strictly speaking it's just
> >> undefined.
> >
> > No, it's not. The total energy of a particle is given by
> >
> >E**2 == c**2 * p**2 + m**2 * c**4
> >
> > where p is the particle's momentum and m is its mass.
> > For a photon, m == 0. No division by zero involved.
> >
> > For a massive particle at rest, p == 0 and the above
> > reduces to the well-known
> >
> >E == m * c**2
>
> The distinction I'm drawing is between physical fact and mathematical
> convenience. For other particles we can say that the 1st formula above
> holds with m taken to be the mass of the particle at rest. We can
> extend that formula to the case of photons which are never at rest by
> saying that in the case of photons m=0. That's nice and it's
> mathematically convenient in the calculations. It's analogous to
> extending the natural definition of the factorial function by saying
> that 0!=1. We can't prove that 0!=1 but it's useful to define it that
> way. It wouldn't be a disaster to simply leave 0! undefined: it would
> just make some equations a little more complicated.
>
> Since the generally accepted physical fact is that photons are never
> at rest we are free to define their "rest mass" (use any term you
> like) to be anything that is mathematically convenient so we define it
> as zero because that fits with your equation above. Turning full
> circle we can then use the equation above to say that they are
> massless since they would hypothetically be massless in some other
> situation even though genuinely massless photons are not thought to
> exist in physical reality (unless I'm really out of date on this!).
>
> >> Something I don't know is if there's some theoretical reason why
> >> the binding energy could never exceed the sum of the energies of
> >> the constituent particles (resulting in an overall negative mass).
> >
> > Conservation of energy would be one reason. If you
> > put two particles together and got more energy out than
> > went in, where did the extra energy come from?
>
> That's the point: the energy balance would be satisfied by the
> negative energy of the bound particles. The binding energy can be
> defined as the energy required to unbind the particles (other
> definitions such as André's are also possible). From this definition
> we see that the binding energy depends on the binding interaction
> (electromagnetic or whatever) that binds the particles together.
>
> The only examples I know of where the binding energy is computed
> approximately for e.g. a hydrogen atom predict that the binding energy
> is proportional to the (rest) mass of the bound particle(s). If it's
> guaranteed that the binding energy always somehow comes out
> proportional to the mass of the particles with a coefficient
> necessarily smaller than 1/c**2 then you could say that the bound
> product could never have negative energy. I just can't see off the top
> of my head an argument to suggest that this is impossible.
>
> --
> Oscar

I've never heard of a massless photon, and they do exert a push on the 
surface they are reflected from, its even been proposed to use it as a 
space drive.  The push is miniscule indeed at normal illumination levels 
but some have calculated how much laser power it would take to move 
something like a solar sail. Practically, the cost of the energy and the 
size of the laser needed are impractical.

Cheers, Gene Heskett
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I find the class of a method in a decorator.

2016-03-05 Thread Chris Angelico
On Sun, Mar 6, 2016 at 2:05 AM, Antoon Pardon
 wrote:
> Using python 3.4/3.5
>
> Suppose I have the following class:
>
> class Tryout:
>
> @extern
> def method(self, ...)
>
> Now how can I have access to the Tryout class in
> the extern function when it is called with method
> as argument
>
> def extern(f):
> the_class = 
>
> f.__class doesn't work, if I write the following
>
> def extern(f)
> print(f.__class__)
>
> the result is: , so that doesn't work.
> Looking around I didn't find an other obvious candidate
> to try. Anybody an idea?

At the time when the function decorator is run, there isn't any class.
You could just as effectively create your function outside the class
and then inject it (Tryout.method = method).

What is it you're trying to do? Would it be a problem to have a class
decorator instead/as well?

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


Photon mass (was: [Still off-top] Physics)

2016-03-05 Thread Thomas 'PointedEars' Lahn
Oscar Benjamin wrote:

> On 5 March 2016 at 02:51, Gregory Ewing 
> wrote:
>>>  The masslessness of photons comes from an extrapolation
>>> that leads to a divide by infinity: strictly speaking it's just
>>> undefined.
>>
>> No, it's not. The total energy of a particle is given by
>>
>>E**2 == c**2 * p**2 + m**2 * c**4
>>
>> where p is the particle's momentum and m is its mass.
>> For a photon, m == 0. No division by zero involved.
>>
>> For a massive particle at rest, p == 0 and the above
>> reduces to the well-known
>>
>>E == m * c**2
> 
> The distinction I'm drawing is between physical fact and mathematical
> convenience.

The physical fact is that as far as we know the photon mass is zero.  That 
is, the upper limit of the photon mass is so close to zero (at the time of 
writing, Adelberger et al. place it at < 10⁻²⁶ eV∕c² ≈ 1.783 × 10⁻⁵⁹ g 
≈ 1.957 × 10⁻³² m_e; see below) that we can assume it to be zero without 
introducing significant error in our *physical* calculations.

;
but also  pp.,
and in general  → “Summary Tables” → “Gauge and Higgs 
Bosons”.

> […]
> Since the generally accepted physical fact is that photons are never
> at rest

ISTM that this is rather a mathematical fact following from that energy–
momentum relation and the assumption that the photon (γ) mass m_γ is zero.  
It follows rather obviously then that E(m = m_γ = 0, p = 0) = 0.  But 
everything that exists has to have some (non-zero) energy.  So photons, and 
in general any objects, that have no mass *and* no momentum relative to a 
frame of reference cannot exist for an observer at rest relative to that 
frame.

> we are free to define their "rest mass" (use any term you
> like) to be anything that is mathematically convenient so we define it
> as zero because that fits with your equation above.

No.  We know that if our present understanding of physics is a sufficiently 
complete/correct description of reality, m_γ = 0 is a requirement.

Several reasons for that can be given; here are some:

1) If m_γ ≠ 0, the speed of light in vacuum could not be c as, according to 
special relativity, nothing that has mass m ≠ 0 can move at c relative to a 
frame of reference ­­– infinite energy in terms of that frame would be 
required for accelerating it to that speed: The kinetic energy of such a 
body is

  Eₖ = E_rel − E₀

where

  E₀ = E(m ≠ 0, p = 0) = mc²

by the energy–momentum relation (see above), and

  lim E_rel(v) = lim mc²∕√(1 − (v∕c)²) = +∞
  v→cv→c

–, and photons are the particles of *light*.  So m = m_γ ≠ 0 would have 
profound and measurable implications on the propagation of light, that would 
*at the very least* be inconsistent with our knowledge of optics that 
precedes special relativity.



2) When one looks into

  E² = (p c)² + (m c²)²

further – which is not just an arbitrary equation that happens to fits 
observations very well, but is derived from the norm of the four-momentum –, 
one realizes that if, and only if,

  m_γ = 0,

then also

  E_γ = E(m = m_γ, p) = p c = ℏk c = ℎc/λ = ℎf

(ℏ = ℎ∕2π, k = ||k⃗|| = 2π∕λ — wavenumber, k⃗ — wave vector), which has been 
experimentally confirmed even *before* the postulation of special relativity 
in observations of the photoelectric effect (the kinetic energy imparted by 
light to electrons in a metal’s surface is proportional to its wavelength 
λ/frequency f).  So if m_γ ≠ 0, this would also have profound and measurable 
implications on the energy transported by light of different 
wavelengths/frequencies/colors that would be inconsistent with our knowledge 
of electromagnetic radiation that precedes special relativity.




Finally,

3) if m_γ ≠ 0, the range of the electromagnetic interaction would not be 
infinite, as because of the uncertainty principle the range r of an 
interaction depends on the mass m of the particle that carries it:

  r(m) ≈ c∆t ≈ ℏ∕2mc.

This would have profound and measurable implications on fundamental 
interactions that would be inconsistent with our experimentally very well 
confirmed (and daily applied) knowledge of quantum mechanics.




X-Post & F'up2 sci.physics.relativity

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Photon mass (was: [Still off-top] Physics)

2016-03-05 Thread Thomas 'PointedEars' Lahn
Gene Heskett wrote:

> I've never heard of a massless photon,

That is unfortunate as it should be common knowledge by now.

> and they do exert a push on the surface they are reflected from, […]

Photons exert a force on surfaces because they carry *momentum* or, as it 
had been understood in terminology that is obsolete now, a non-zero 
“*relativistic* mass” (that had been distinguished from “rest mass”).




F'up2 sci.physics.relativity

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I find the class of a method in a decorator.

2016-03-05 Thread Antoon Pardon
Op 05-03-16 om 16:18 schreef Chris Angelico:
> On Sun, Mar 6, 2016 at 2:05 AM, Antoon Pardon
>  wrote:
>> Using python 3.4/3.5
>>
>> Suppose I have the following class:
>>
>> class Tryout:
>>
>> @extern
>> def method(self, ...)
>>
>> Now how can I have access to the Tryout class in
>> the extern function when it is called with method
>> as argument
>>
>> def extern(f):
>> the_class = 
>>
>> f.__class doesn't work, if I write the following
>>
>> def extern(f)
>> print(f.__class__)
>>
>> the result is: , so that doesn't work.
>> Looking around I didn't find an other obvious candidate
>> to try. Anybody an idea?
> 
> At the time when the function decorator is run, there isn't any class.
> You could just as effectively create your function outside the class
> and then inject it (Tryout.method = method).
> 
> What is it you're trying to do? Would it be a problem to have a class
> decorator instead/as well?
> 
> ChrisA
> 

The idea is that some of these methods will be externally available
and others are not. So that I get an external string and can do
something of the following:

tryout = Tryout()

st = read_next_cmd()

if st in tryout.allowed:
getattr(tryout, st)()
else:
raise ValueError("%s: unallowed cmd string" % st)

And the way I wanted to populate Tryout.allowed as a class attribute
would have been with the decorator extern, which would just have put
the name of the method in the Tryout.allowed set and then return the function.


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


Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
Anybody have the correct method of adding an icon to a
window?  I have found several code examples on the web
but they all result in an error.  Thanks.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I find the class of a method in a decorator.

2016-03-05 Thread Peter Otten
Antoon Pardon wrote:

> Op 05-03-16 om 16:18 schreef Chris Angelico:
>> On Sun, Mar 6, 2016 at 2:05 AM, Antoon Pardon
>>  wrote:
>>> Using python 3.4/3.5
>>>
>>> Suppose I have the following class:
>>>
>>> class Tryout:
>>>
>>> @extern
>>> def method(self, ...)
>>>
>>> Now how can I have access to the Tryout class in
>>> the extern function when it is called with method
>>> as argument
>>>
>>> def extern(f):
>>> the_class = 
>>>
>>> f.__class doesn't work, if I write the following
>>>
>>> def extern(f)
>>> print(f.__class__)
>>>
>>> the result is: , so that doesn't work.
>>> Looking around I didn't find an other obvious candidate
>>> to try. Anybody an idea?
>> 
>> At the time when the function decorator is run, there isn't any class.
>> You could just as effectively create your function outside the class
>> and then inject it (Tryout.method = method).
>> 
>> What is it you're trying to do? Would it be a problem to have a class
>> decorator instead/as well?
>> 
>> ChrisA
>> 
> 
> The idea is that some of these methods will be externally available
> and others are not. So that I get an external string and can do
> something of the following:
> 
> tryout = Tryout()
> 
> st = read_next_cmd()
> 
> if st in tryout.allowed:
> getattr(tryout, st)()
> else:
> raise ValueError("%s: unallowed cmd string" % st)
> 
> And the way I wanted to populate Tryout.allowed as a class attribute
> would have been with the decorator extern, which would just have put
> the name of the method in the Tryout.allowed set and then return the
> function.

A simple alternative would be a flag

class Forbidden(Exception):
pass

def extern(f):
f.published = True
return f

def invoke(obj, command):
try:
method = getattr(obj, command)
if not method.published:
raise Forbidden
except (AttributeError, Forbidden):
raise Forbidden("Forbidden command %r" % command)
return method()

invoke(tryout, "foo")

Or if you need the set of allowed commands:

def make_extern():
allowed = set()
def extern(f):
allowed.add(f.__name__)
return allowed, extern

class Tryout:
allowed, extern = make_extern()
@extern
def method(...): ...

Too much boilerplate? Hide it in a baseclass or metaclass:

class Meta(type):
def __prepare__(*args, **kw):
allowed = set()
def extern(f):
allowed.add(f.__name__)
return dict(allowed=allowed, extern=extern)

class Tryout(metaclass=Meta):
@extern
def foo(self): ...
@extern
def bar(self): ...
def baz(self): ...

assert Tryout.allowed == {"foo", "bar"}



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


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Grant Edwards
On 2016-03-05, Wildman  wrote:

> Anybody have the correct method of adding an icon to a
> window?  I have found several code examples on the web
> but they all result in an error.  Thanks.

You'll have to be a lot more specific about what you mean by "add an
icon to a window".  Do you just want to display an .ico file within a
window?

-- 
Grant






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


Re: Adding Icon To Tkinter Window - Followup

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 10:47:09 -0600, Wildman wrote:

> Anybody have the correct method of adding an icon to a
> window?  I have found several code examples on the web
> but they all result in an error.  Thanks.

I found this and it works in Linux but only with black
and white xbm images (I would prefer color):

root.wm_iconbitmap('@myicon.xbm')

I found some info in a forum that talked about putting
a color icon in a Label on a separate window and passing
that to the main window as the icon.  But there were no
code examples or explanations.  So far I have not been
able to figure it out.  I would appreciate any help.

-- 
 GNU/Linux user #557453
"Be at war with your vices, at peace with your neighbors,
and let every new year find you a better man."
  -Benjamin Franklin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Mark Lawrence

On 05/03/2016 16:47, Wildman via Python-list wrote:

Anybody have the correct method of adding an icon to a
window?  I have found several code examples on the web
but they all result in an error.  Thanks.



Would you please be kind enough to read this 
http://www.catb.org/esr/faqs/smart-questions.html.  Then tell us exactly 
what you are trying to achieve, how you are trying to achieve it and the 
error that you get, including the complete traceback if there is one.


TIA.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Adding Icon To Tkinter Window - Followup

2016-03-05 Thread Christian Gollwitzer

Am 05.03.16 um 19:10 schrieb Wildman:

On Sat, 05 Mar 2016 10:47:09 -0600, Wildman wrote:


Anybody have the correct method of adding an icon to a
window?  I have found several code examples on the web
but they all result in an error.  Thanks.


I found this and it works in Linux but only with black
and white xbm images (I would prefer color):

 root.wm_iconbitmap('@myicon.xbm')


iconphoto is the newer API for color icons. I am a bit surprised that it 
is not wrapped in Tkinter, which is odd. You can still call it via eval:


import Tkinter
from Tkinter import Tk
root = Tk()
img = Tkinter.Image("photo", file="appicon.gif")
root.call('wm','iconphoto',root._w,img)


If you Tk is recent enough (8.6, you can find out by doing 
root.eval('info patchlevel')), you can use .png files in addition to 
.gif. If you need to read other image files, look into PIL and ImageTk.


Christian

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


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 18:08:15 +, Grant Edwards wrote:

> On 2016-03-05, Wildman  wrote:
> 
>> Anybody have the correct method of adding an icon to a
>> window?  I have found several code examples on the web
>> but they all result in an error.  Thanks.
> 
> You'll have to be a lot more specific about what you mean by "add an
> icon to a window".  Do you just want to display an .ico file within a
> window?

Sorry.  I am talking about the titlebar or system icon.

-- 
 GNU/Linux user #557453
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 18:38:57 +, Mark Lawrence wrote:

> On 05/03/2016 16:47, Wildman via Python-list wrote:
>> Anybody have the correct method of adding an icon to a
>> window?  I have found several code examples on the web
>> but they all result in an error.  Thanks.
>>
> 
> Would you please be kind enough to read this 
> http://www.catb.org/esr/faqs/smart-questions.html.  Then tell us exactly 
> what you are trying to achieve, how you are trying to achieve it and the 
> error that you get, including the complete traceback if there is one.
> 
> TIA.

Thank you, I will do that.  I am new to Python and this group
but ignorance is no excuse.  In the future I will strive to
do better.

-- 
 GNU/Linux user #557453
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Serhiy Storchaka

On 05.03.16 18:47, Wildman via Python-list wrote:

Anybody have the correct method of adding an icon to a
window?  I have found several code examples on the web
but they all result in an error.  Thanks.


On Windows:

root.wm_iconbitmap(default='myapp.ico')

.ico-file can contain several icons of different size.

Otherwise if TkVersion >= 8.5:

root.wm_iconphoto(True, PhotoImage(file='myapp16.gif'),
PhotoImage(file='myapp32.gif'), ...)

You can specify several icons of different size.

If TkVersion >= 8.5 you can use .png-files.


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


Re: Application console for Tkinter program?

2016-03-05 Thread Terry Reedy

On 3/5/2016 6:45 AM, Christian Gollwitzer wrote:

Am 05.03.16 um 11:15 schrieb Terry Reedy:

On 3/5/2016 2:52 AM, Christian Gollwitzer wrote:

is there an easy way to add an application console to a Tkinter program?


Right now, you should turn the question around.


so this means no, right?


Right.


Is there an easy way to
run a tkinter program within an interactive console?  Answer: yes, two
ways, after removing the runshell stuff and mainloop call*.

1. Call your program mytk.py.  In your system console, run 'python -i
myth.py'.  When the code ends, control passes to the console running
python.  Statements like 'print(nvar.get())' will be executed in the
main namespace of the still running program.


well yes, this does work, but I should have explained why I want it the
other way round. We have an in-house tool which is used to manipulate
images. During production use, at some point you think "and now if I
could just save the image that I see on screen into a PNG file". You
know exactly that MyViewer.image is the thing that contains what you
need, if only you had a way to tell it
'MyViewer.image.save("somewhere.png")'. At this point, you haven't
started the program from an interactive python. Always running the tool
from ipython or idle means there are useless windows hanging around, but
if you close them, your pogram goe away. To make it even more
complicated, the deployed version of the tool uses pyinstaller to be
safe from environment changes.


Since idlelib.PyShell is the idle startup module as well Shell window 
module, importing it imports practically all of idlelib.  Not what you 
want.  Calling PyShell.main calls tk.Tk and tk.mainloop, also not what 
you want.



Of course, I could pack some text widget somewhere and fiddle a few
bindings to make it do this with eval(), but a good REPL has history,
autocompletion, syntax highlighting you get it. I had simply hoped,
since idle is written in Tkinter, that it could be reused for that purpose.


(For statements, you would use exec() rather than eval().)

Not now. A console is a REPL + text display to read from and print to. 
The actual IDLE REPL is PyShell.ModifiedInterpreter, which subclasses 
stdlib code.InteractiveInterpreter.  Most of the additions are for 
interacting with the subprocess that runs user code.  You should start 
instead with the base class.


The Shell text display is a subclass of a subclass of a class that 
contains a subclass of Toplevel with the complete IDLE Menu and a Text 
widget wrapper.  Again, this is too much baggage for an application console.


The idlelib ColorDelegator syntax highlighter can be reused with a Text 
instance.  See turtledemo.__main__ for an example.  I don't know if (or 
how) IDLE's autocompletion modules could be reused in their current 
state.  I believe Shell's history 'list' consists of the statements in 
the Text instance prefixed by the '>>> ' prompt.


A simple app console might have separate text boxes for input and output.


For pure Tcl/Tk, there is tkcon which can do exactly this and I use it
in similar tools writtin in Tcl/Tk. I can run it via Tk.eval(), but I
couldn't find a way to call back into Python coming from the Tkinter
interpreter, and obviously autocompletion and syntax highlighting do not
work well.


For instance, can you embed IDLE into a program such that when a button
is pressed, it pops up a REPL window where the running program can be
examined?


If the REPL window is defined in an imported module, the problem is
linking the main namespace of the tkinter program with the REPL loop in
such a way that commands entered into the REPL are executed in the main
module, not in the REPL module.


I'm happy to pass the main module as an argument to REPLInit().


2) If you click the Shell button twice, it locks up the program, because
main() obviously starts it's own mainloop


IDLE executes user code in a separate process, linked by sockets, so
that execution of IDLE GUI code and user code do not interfere with each
other.


Ahhh - OK this makes sense in the general case, but not for a console
where you *want* your REPL to perform surgery on the main program.


I would like to refactor IDLE so that the Shell window
...
It might be possible to adapt such a component as an embedded console.
An imported frame should not interfere with the main-module code or code
in other modules.  The main problems are a) namespace linkage (mentioned
before),


Perhaps I should have said 'issues that require attention' rather than 
'problems' ;-).  As you note, b) and c) are conceptually easy, though 
the execution in IDLE is complicated by having to communicate between 
two processes.  The execution in a within-process console would be much 
easier.



b) the need for sys.stdin/out/err to not be None,


tkcon solves this be redirecting stdin/stdout/stderr to functions which
write to the console window.


IDLE sets sys.stdin, etc, in the user process to custom instances with 
read/write meth

Re: Adding Icon To Tkinter Window

2016-03-05 Thread Terry Reedy

On 3/5/2016 11:47 AM, Wildman via Python-list wrote:

Anybody have the correct method of adding an icon to a
window?  I have found several code examples on the web
but they all result in an error.  Thanks.


No single simple statement work for all situations.  You should have 
specified OS, Python version, and tcl/tk version.  (IDLE's Help -> About 
IDLE displays full tk version).


Here is the current code from idlelib.PyShell, written by Serhiy 
Storchaka, our current tkinter maintainer.


# set application icon
icondir = os.path.join(os.path.dirname(__file__), 'Icons')
if system() == 'Windows':
iconfile = os.path.join(icondir, 'idle.ico')
root.wm_iconbitmap(default=iconfile)
elif TkVersion >= 8.5:
ext = '.png' if TkVersion >= 8.6 else '.gif'
iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
 for size in (16, 32, 48)]
icons = [PhotoImage(file=iconfile) for iconfile in iconfiles]
root.wm_iconphoto(True, *icons)

Non-windows pre-8.5 systems remain stuck with the tk icon.

I just tried changing the 'if' line to 'if False:' on my 3.5.1 (8.6.4) 
windows install and the 2nd, wm_iconphoto block worked here also.  It 
may be that it did not work on windows with 8.5 and before.


--
Terry Jan Reedy

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


password and username code

2016-03-05 Thread Ömer sarı
hi , all , l m fresh user and l m trying to learn python by doing practice but 
l got stuck in that , l need help , l m a beginner and  l learn some basic 
things so far so, plz take in consideration that before command .

here is my code trial:
#login by using username and password

loop=1

paword=['1234','5678']
pawordch=["1","2","3","4","5","6","7","8","9","0","/","(",")","*","%","&","!","a","b","c","d","e","f","g","h","k","l","m","n","o","p","r","s","t","y","v","y","z","x"]
name=['murat','can','omer','owrasa']

while loop==1 :
print "welcome my website,plz if you have an account , just login , 
otherwise , register plz"
username=raw_input("username:")
password=raw_input("password:")
if username in name and password in paword:
print "login is successful, and continue page 2"
else :
print" please register"
login_username=raw_input ("username:")
login_password=raw_input("password:")
for login_password in pawordch:
if login_password in pawordch :
name.append(login_username)
paword.append(login_password)
print "relogin ,plz"
print name ,"",paword
login_username=raw_input ("username:")
login_password=raw_input("password:")
if login_username in name and login_password in paword:
print "login successful , proceed to page 2"
break

else:
print "login is unseccesful and please make sure your 
username and password is correct"


.l would like to do samething when we login a website. l want program if 
username is not registered , register first , then store it , and l want 
program ask for some specific characters , like 1,2,3../,%. 

thanks for any clearification in advance 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: password and username code

2016-03-05 Thread Ben Finney
Ömer sarı  writes:

> hi , all , l m fresh user and l m trying to learn python by doing
> practice but l got stuck in that , l need help , l m a beginner and  l
> learn some basic things so far so, plz take in consideration that
> before command .

Welcome! You have chosen a good language for learning.

We have a forum explicitly dedicated to collaboratively learning Python
https://mail.python.org/mailman/listinfo/tutor>, you may want to go
there and participate.

Please note that communication is important when programming: please
take care to write English. Using “l m”, or “plz”, leads to a needlessly
difficult-to-read message. Thanks!

-- 
 \ “For a sentimentalist is simply one who desires to have the |
  `\luxury of an emotion without paying for it.” —Oscar Wilde, _De |
_o__) Profundis_, 1897 |
Ben Finney

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


Re: Can I find the class of a method in a decorator.

2016-03-05 Thread Ian Kelly
On Sat, Mar 5, 2016 at 9:21 AM, Antoon Pardon
 wrote:
> Op 05-03-16 om 16:18 schreef Chris Angelico:
>> On Sun, Mar 6, 2016 at 2:05 AM, Antoon Pardon
>>  wrote:
>>> Using python 3.4/3.5
>>>
>>> Suppose I have the following class:
>>>
>>> class Tryout:
>>>
>>> @extern
>>> def method(self, ...)
>>>
>>> Now how can I have access to the Tryout class in
>>> the extern function when it is called with method
>>> as argument
>>>
>>> def extern(f):
>>> the_class = 
>>>
>>> f.__class doesn't work, if I write the following
>>>
>>> def extern(f)
>>> print(f.__class__)
>>>
>>> the result is: , so that doesn't work.
>>> Looking around I didn't find an other obvious candidate
>>> to try. Anybody an idea?
>>
>> At the time when the function decorator is run, there isn't any class.
>> You could just as effectively create your function outside the class
>> and then inject it (Tryout.method = method).
>>
>> What is it you're trying to do? Would it be a problem to have a class
>> decorator instead/as well?
>>
>> ChrisA
>>
>
> The idea is that some of these methods will be externally available
> and others are not. So that I get an external string and can do
> something of the following:
>
> tryout = Tryout()
>
> st = read_next_cmd()
>
> if st in tryout.allowed:
> getattr(tryout, st)()
> else:
> raise ValueError("%s: unallowed cmd string" % st)
>
> And the way I wanted to populate Tryout.allowed as a class attribute
> would have been with the decorator extern, which would just have put
> the name of the method in the Tryout.allowed set and then return the function.

If you only needed the function decorator to access the class when the
method is called, then you could have the function decorator return a
custom descriptor. It sounds like you want this to happen before the
method is called, though.

You could have the function decorator simply set an attribute on the
function and return it. Then use a class decorator or a metaclass to
scan all the class's methods when it's constructed in order to
populate the allowed attribute.

Alternatively you could have the function decorator add the allowed
attribute as a boolean on the method rather than on the class and just
check getattr(type(tryout), st).allowed (with the appropriate
try-except).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I find the class of a method in a decorator.

2016-03-05 Thread Steven D'Aprano
On Sun, 6 Mar 2016 03:21 am, Antoon Pardon wrote:

> The idea is that some of these methods will be externally available
> and others are not. So that I get an external string and can do
> something of the following:
> 
> tryout = Tryout()
> 
> st = read_next_cmd()
> 
> if st in tryout.allowed:
> getattr(tryout, st)()
> else:
> raise ValueError("%s: unallowed cmd string" % st)
> 
> And the way I wanted to populate Tryout.allowed as a class attribute

The simplest way to do this is to forget about the decorator, since it's the
wrong tool for the job. The decorator doesn't have access to the class
itself, unless you pass it as an argument to the decorator. But you can't
do that *inside* the class, since it doesn't exist yet.

Instead, just keep a separate set of the names of methods. Do the simplest
thing which could possibly work, that is, maintain the set manually:

(All code following is untested.)


class Tryout:
allowed = set(['spam', 'ham', 'cheese'])

def spam(self): ...
def ham(self): ...
def eggs(self): ...
def cheese(self): ...



That suggests a way to avoid having to manually add the method name to the
set: have a decorator that adds it to a known set.


def external(aset):
def decorator(func):
aset.add(func.__name__)
return func
return decorator


class Tryout:
allowed = set()

@external(allowed)
def spam(self): ...

@external(allowed)
def ham(self): ...

def eggs(self): ...

@external(allowed)
def cheese(self): ...




Which leads us to our next improvement:

class Tryout:
allowed = set()
allow = functools.partial(external, allowed)

@allow
def spam(self): ...

@allow
def ham(self): ...

def eggs(self): ...

@allow
def cheese(self): ...

del allow




But there's another approach. A decorator cannot easily know anything about
the class that the method will belong to, but it can tag the method itself:


def allow(func):
func.allowed = True
return func


class Tryout:

@allow
def spam(self): ...

@allow
def ham(self): ...

def eggs(self): ...

@allow
def cheese(self): ...



tryout = Tryout()
st = read_next_cmd()
method = getattr(tryout, st)
if method.allowed:
method()
else:
raise ValueError("%s: unallowed cmd string" % st)


Obviously you don't write that out in full each time, you factor it into a
method or function.




-- 
Steven

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


Re: [Still off-topic] Physics

2016-03-05 Thread Steven D'Aprano
On Fri, 4 Mar 2016 09:19 pm, Oscar Benjamin wrote:

>> As far as the reaction of matter and anti-matter, we've known for about a
>> century that mass and energy are related and freely convertible from one
>> to the other. That's the famous equation by Einstein: E = m*c**2. Even
>> tiny amounts of energy (say, the light and heat released from a burning
>> match) involve a correspondingly tiny reduction in mass.
> 
> This is also incorrect and suffers from the same misinterpretation as
> above. Mass and energy are not interchangeable in the sense that you
> can exchange one for the other with e=mc^2 giving the exchange rate.

Hmmm. Well, it's actually a bit more complicated than that. It depends by
what you mean by "converting" mass to energy. We can give at least one
sense in which it is true that mass is converted to energy, and likewise at
least one in which is it not true.

For example, we might say that even if mass-energy equivalence means that
mass and energy are in fact the same sort of thing, we can nevertheless
convert from one to another in the same way that one can convert from
kinetic energy to potential energy, or heat energy to rotational energy.

The Stanford Encyclopedia of Philosophy has a good discussion of the various
interpretations of mass-energy equivalence:

http://plato.stanford.edu/entries/equivME/


And of course, regardless of whether or not mass "really is" converted to
energy or not, using the language of conversion is the standard way to talk
about it:

https://www.physicsforums.com/threads/energy-mass-conversion.177827/

Unfortunately, mass is one of those concepts that seems easy to define, but
actually is anything but!

http://www.physics-online.ru/MessageFiles/6642/EJP-Roche-05.pdf


> Rather mass and energy are *the same thing*. Although they are
> different concepts defined in different ways and having different
> dimensions and units they are inseparable: e=mc^2 gives us the
> proportion in which the two appear together.

So apart from being different concepts defined in different ways with
different dimensions and different units, they're exactly the same?

Right-o.


Wikipedia says:

"... mass–energy equivalence is a concept formulated by Albert Einstein that
explains the relationship between mass and energy. It states every mass has
an energy equivalent and vice versa ..."

https://en.wikipedia.org/wiki/Mass%E2%80%93energy_equivalence

but beware because the Wikipedia article "appears to contradict itself".

Mass-energy equivalence is a simple formula, an important formula, and well
understood in practice. But what it actually "means" in theory is anyone's
guess. And so, on the principle that an analogy that is utterly wrong in a
technical sense but understandable is better than a complicated and complex
explanation that is utterly incomprehensible, I'm going to stick to talking
about mass/energy conversions :-)



-- 
Steven

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


Re: Adding Icon To Tkinter Window - Followup

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 19:36:19 +0100, Christian Gollwitzer wrote:

> Am 05.03.16 um 19:10 schrieb Wildman:
>> On Sat, 05 Mar 2016 10:47:09 -0600, Wildman wrote:
>>
>>> Anybody have the correct method of adding an icon to a
>>> window?  I have found several code examples on the web
>>> but they all result in an error.  Thanks.
>>
>> I found this and it works in Linux but only with black
>> and white xbm images (I would prefer color):
>>
>>  root.wm_iconbitmap('@myicon.xbm')
> 
> iconphoto is the newer API for color icons. I am a bit surprised that it 
> is not wrapped in Tkinter, which is odd. You can still call it via eval:
> 
> import Tkinter
> from Tkinter import Tk
> root = Tk()
> img = Tkinter.Image("photo", file="appicon.gif")
> root.call('wm','iconphoto',root._w,img)

The above worked perfectly.  Thank you very much.

> If you Tk is recent enough (8.6, you can find out by doing 
> root.eval('info patchlevel')), you can use .png files in addition to 
> .gif. If you need to read other image files, look into PIL and ImageTk.
> 
>   Christian

According to "root.eval('info patchlevel')" I have version 8.6.2.
PNG worked.  That is good because PNG is a common file type for
Linux icons.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 21:55:40 +0200, Serhiy Storchaka wrote:

> On 05.03.16 18:47, Wildman via Python-list wrote:
>> Anybody have the correct method of adding an icon to a
>> window?  I have found several code examples on the web
>> but they all result in an error.  Thanks.
> 
> On Windows:
> 
>  root.wm_iconbitmap(default='myapp.ico')
> 
> .ico-file can contain several icons of different size.
> 
> Otherwise if TkVersion >= 8.5:
> 
>  root.wm_iconphoto(True, PhotoImage(file='myapp16.gif'),
>  PhotoImage(file='myapp32.gif'), ...)
> 
> You can specify several icons of different size.
> 
> If TkVersion >= 8.5 you can use .png-files.

Thanks.  I will file away the snippets for later use.  The
code provided by Mr. Gollwitzer is working for me on Linux.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
On Sat, 05 Mar 2016 16:38:08 -0500, Terry Reedy wrote:

> On 3/5/2016 11:47 AM, Wildman via Python-list wrote:
>> Anybody have the correct method of adding an icon to a
>> window?  I have found several code examples on the web
>> but they all result in an error.  Thanks.
> 
> No single simple statement work for all situations.  You should have 
> specified OS, Python version, and tcl/tk version.  (IDLE's Help -> About 
> IDLE displays full tk version).
> 
> Here is the current code from idlelib.PyShell, written by Serhiy 
> Storchaka, our current tkinter maintainer.
> 
>  # set application icon
>  icondir = os.path.join(os.path.dirname(__file__), 'Icons')
>  if system() == 'Windows':
>  iconfile = os.path.join(icondir, 'idle.ico')
>  root.wm_iconbitmap(default=iconfile)
>  elif TkVersion >= 8.5:
>  ext = '.png' if TkVersion >= 8.6 else '.gif'
>  iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext))
>   for size in (16, 32, 48)]
>  icons = [PhotoImage(file=iconfile) for iconfile in iconfiles]
>  root.wm_iconphoto(True, *icons)
> 
> Non-windows pre-8.5 systems remain stuck with the tk icon.
> 
> I just tried changing the 'if' line to 'if False:' on my 3.5.1 (8.6.4) 
> windows install and the 2nd, wm_iconphoto block worked here also.  It 
> may be that it did not work on windows with 8.5 and before.

I appreciate your reply.  Your code looks interesting but it
is over my head right now.  I will save it for further study
and experimentation.  Right now my problem was fixed by using
the code posted by Mr. Gollwitzer.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Adding Icon To Tkinter Window

2016-03-05 Thread Wildman via Python-list
I apologize to the group for my lack of information in
my original post.  I will do better in the future.  I
very much want to remain in good standing in this group
because of all the knowledgeable people here.

Thanks again to everyone that replied and helped me
solve my problem.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list