Angelina Joli Paris Hilton MARISA MILLER

2007-04-24 Thread M M
Angelina  Joli Paris HiltonMARISA   MILLER 

www.alphasearch.gr -- 
http://mail.python.org/mailman/listinfo/python-list

Angelina Joli Paris Hilton MARISA MILLER

2007-04-24 Thread M M
Angelina  Joli  Paris Hilton   MARISA   MILLER 

www.alphasearch.gr -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Let's talk about debuggers!

2017-10-25 Thread m
W dniu 25.10.2017 o 15:53, Ned Batchelder pisze:
> On 10/25/17 9:07 AM, Thomas Jollans wrote:
>> Hi,
>>
>> I just wanted to know what tools everyone used for debugging Python
>> applications - scripts / backend / desktop apps / notebooks / whatever.
>> Apart from the usual dance with log files and strategically inserted
>> print() calls, that is.
>>
>> Of course we all know and mildly dislike pdb.
>>
>> Personally, in practice, I'm most likely to need a debugger when
>> prototyping a function in a Jupyter notebook. There, ipdb, summoned with
>> the %%debug magic incantation, does the trick.
>>
>> Sometimes, though, I miss having a visual debugger. You know, the kind
>> that Visual Basic has had for decades. There's one in Chrome dev tools
>> if you ever have the misfortune of writing JavaScript.
>>
>> What options are there for Python (that work)? What text editors (and
>> IDEs) have a decent integrated debugger or debugging plugin? (Is there
>> anything for Sublime?) Does anyone use them? (How do YOU debug?)
>>
>> I vaguely remember WinPDB, but that hasn't seen a release in more than
>> seven years...
>>
>>
> 
> pudb is a visual terminal debugger: https://pypi.python.org/pypi/pudb
> 
> It uses the same commands as pdb, so it's easy to get started, but it 
> gives you a variables pane, with customizable presentation, and so on.
> 
> One of my favorite features: you can add a set_trace line in your 
> program, and then if during the debugging session you realize you don't 
> want to stop there every time, you can disable that breakpoint even 
> though it's an explicit line of code telling the debugger to stop.

+1

It's excellent piece of software. I started using it when debugging
remote/server things, and ended with using eveywhere.

It has two drawbacks: it doesn't remember your commandline, watches and
sizes of panes, and has ugly default colour scheme.

Few years ago, I used Eclipse+PyDev, but I was tired with recurring
strange problems with Eclipse, which eg hanged until I reinstalled
eclipse or removed workspace metadata.

r. m.

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


Re: Spam levels.

2018-05-21 Thread m
W dniu 10.02.2018 o 15:57, C W Rose pisze:
> No other groups (in the limited set which I read) have the problem,
> and I don't understand why the spammers neither spam a range of
> groups, nor change their adddresses more frequently.  It may be
> that destroying comp.lang.python is their actual objective.
> 
> Either way, a depressing state of affairs.

The sad thing is, that your post is unseen, because of spam :S

I also almost stopped reading c.l.python, because of enormous spam
levels. Do I have any option to read it without spam, other than launch
my own filtering NNTP server and do whack the mole game for myself?

Maybe join forces and establish such server for public use?

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


Re: "Data blocks" syntax specification draft

2018-05-21 Thread m
W dniu 21.05.2018 o 06:00, Mikhail V pisze:
>> As Ian says, reStructuredText is the only supported format [1] for
>> PEPs, so you may as well just start using it straight away. GitHub
>> automatically renders it if you use a ".rst" extension on your file,
>> so the rendered form would be visible on the web.
> Ok. How is about images? this proposal will require a lot of images
> - otherwise people who read it are forced to copy-paste snippets
> into their code editors to understand how it may look in reality.
> 

I would say, that if proposition of your syntax requires images, then
it's bad syntax.

And re PDF - i opened that pdf with one click - hopefully I have
configured my thunderbird to that. And what do I see? Completely
unreadable code, because you used bizzare, non monospaced,  font to code
examples.

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


Re: kivy [quick report]

2018-10-08 Thread m
W dniu 05.10.2018 o 18:43, Stefan Ram pisze:
>   BTW: For Android, there is a "Bulldozer" (or some such) that
>   can create an APK. I wonder what the best way to package one's
>   kivy program to distribute it to Windows users?

I use wine + pyinstaller.

regards

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


Re: Python versus Perl ?

2005-02-08 Thread m
Courageous wrote:

If Python is better than Perl, I'm curious how really significant
those advantages are ?
speedwise, i think perl is faster than python and python performed the 
slowest as shown in http://www.flat222.org/mac/bench/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-08 Thread m
Fredrik Lundh wrote:
if you use Python mostly to write empty loops, your programming license
should be revoked.  the benchmark author seems to have realized that, as
can be seen from the "it's dead" paragraph at the top of the page, which
makes me wonder why you posted this link...
 
i was trying to decide whether i needed perl or python for some work 
that i had to get done and was seeing which was faster. and came across 
this link which i tht was pertinent. is python as fast as perl for the 
nonempty loops that the author wrote?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-08 Thread m
Irmen de Jong wrote:
m wrote:

Why do you care?
Have you read http://www.python.org/moin/PythonSpeed ?
--Irmen
i had not read it. thanks for pointing it out!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-08 Thread m

You really will have to convince people here that execution speed is a
real issue for your programming task (in order to continue this  
discussion).  Otherwise the debate will go south real quick.

Keep well
Caleb
On Tue, 08 Feb 2005 12:17:05 -0600, m <[EMAIL PROTECTED]> wrote:
Courageous wrote:

If Python is better than Perl, I'm curious how really significant
those advantages are ?

speedwise, i think perl is faster than python and python performed 
the  slowest as shown in http://www.flat222.org/mac/bench/

i have nothing else to add. thanks caleb!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-18 Thread m
m wrote:
gives just one hi for me.
"
Content-type: text/html
hi
"
I get this
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-18 Thread m
Rory Campbell-Lange wrote:
#!/usr/bin/python
import cgi
print "Content-type: text/html\n\n"
print "hi"
Gives me the following in my browser:
'''
hi
Content-type: text/html
hi
'''
Why are there two 'hi's?
Thanks,
Rory
gives just one hi for me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: We will be moving to GitHub

2016-01-04 Thread m
W dniu 03.01.2016 o 01:33, Marko Rauhamaa pisze:
> Teamware didn't have to pick any of them since Teamware's commits were
> done per individual files. The repository didn't have a commit history.
> 
> Thus, Teamware was equivalent to Hg/Git with each file treated as an
> independent repository.
> 

It sounds like CVS.

How can you be sure that your code is consistent if each of your file
has it's own, independent history? Use tags like in CVS?

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



Re: GitHub's “pull request” is proprietary lock-in

2016-01-04 Thread m
W dniu 03.01.2016 o 05:43, Ben Finney pisze:
> That and other vendor-locked workflow aspects of GitHub makes it a poor
> choice for communities that want to retain the option of control over
> their processes and data.

I'm also afraid that Github will make to git the same thing as Google
did to Jabber/XMPP.

Decade ago, I had plenty of friends on my jabber contacts list. Next,
Google made it's talk compatible with jabber, then my friends slowly
migrated to gtalk, because if they used gmail anyway, then why not use
it also for jabber?

And then Google turned off XMPP support and suddenly I lost ability to
contact with 80% of my friends without having stupid hangouts running,
or without falling back to email (which is not so bad BTW).

The same can be with Github and git. PPL will forget how to use git
without github. When Github will make git-incompatible changes, vast
majority will need/want to follow the changes and eg. will use Gitlabs
propertiary binary.

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


Re: GitHub's “pull request” is proprietary lock-in

2016-01-04 Thread m
W dniu 04.01.2016 o 18:41, Michael Torrie pisze:
>> Decade ago, I had plenty of friends on my jabber contacts list. Next,
>> > Google made it's talk compatible with jabber, then my friends slowly
>> > migrated to gtalk, because if they used gmail anyway, then why not use
>> > it also for jabber?
>> > 
>> > And then Google turned off XMPP support and suddenly I lost ability to
>> > contact with 80% of my friends without having stupid hangouts running,
>> > or without falling back to email (which is not so bad BTW).
> I use gtalk with Pidgin every day using XMPP.  So Google still supports
> XMPP.  However what they stopped doing was allowing federated XMPP,
> which pretty much breaks XMPP, at least the spirit of it.  So the only
> way to chat with gtalk users is to use your gtalk account.  

Exactly. My friends slowly migrated to using gtalk instead of jabber
client, because if they have open gmail anyways, then why should they
bother with installing additional software. 80% never came back to
jabber client. They don't need to, they still have communication between
them and I'm minority which uses strange not supported technology :).

> But you
> certainly don't need hangouts.  XMPP works fine between your client and
> the Google server.

Oh, and it's definitively what I want - talk with google server ;).

> 
> I agree that Google really pulled a bad one with gtalk though.  Dropping
> federated XMPP support was definitely not in keeping with their original
> "do no evil" mantra.
> 
>> > The same can be with Github and git. PPL will forget how to use git
>> > without github. When Github will make git-incompatible changes, vast
>> > majority will need/want to follow the changes and eg. will use Gitlabs
>> > propertiary binary.
> Yup you are correct.  However for the foreseeable future, you can still
> do a git clone from github, and you can still use your local repository
> normally.  

And I can do nothing with it, because nobody will want to cooperate with
me - they will use github instead of git.

Sad thing is that it's rather inevitable and not moving python repo to
github or not won't stop the process. However - wise would be to have
github-like software on own servers.

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


Re: Python Worst Practices

2015-02-26 Thread m

W dniu 25.02.2015 21:45, Mark Lawrence pisze:

http://www.slideshare.net/pydanny/python-worst-practices

Any that should be added to this list?  Any that be removed as not that bad?




I disagree with slide 16. If I wanted to use long variable names, I 
would still code in Java.


regards

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


[OT]Re: what is wrong with d.clear()?

2015-03-05 Thread m

W dniu 23.12.2014 o 11:25, Steve Hayes pisze:

>[1] Or worse, one of those shitty messages that include a plain text part
>that says "Your mail program cannot read this email. Please upgrade to a
>better mail program."

I usually reply to those saying "So why did you send it to me?"

I suspect that in most cases the senders do not know that that is what their
mail program is sending, and do it to let them know that their mesdsage could
not be read.


I suspect that in most cases sender don't understand what do you mean 
saying "So why did you send it to me?".


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


Re: bottle app "crashes"

2015-07-06 Thread m
W dniu 06.07.2015 o 21:28, mm0fmf pisze:
> On 05/07/2015 17:45, Martin S wrote:
>> > Hi all,
>> >
>> > Last summer I fumbled together a small appplication that calculates both 
>> > LASK
>> > and Elo ratings for chess. I managed to "webify" it using Bottle. This 
>> > works
>> > nicely on my laptop for testing.
>> >
> [snip]
> 
>> >
>> > Do anyone have a pointer to an idiot proof instruction on how to deploy a
>> > simple bottle application to a live server.
>> >
>> > /Martin S
>> >
> I use bottle as it comes to provide 2 apps that face straight onto the 
> web. I have to say that I have only done half the job because I never 
> got as far as daemonising them. I simply run them from a "screen" 
> session. This is fine as they run on my own teeny-tiny Linux VM (256MB 
> ram/5GB disk with 1 Xeon core).
> 
> I simply log in and type "screen python3 myapp.py" and remember to exit 
> with ctrl-A D. 

I would suggest using supervisor.

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


Re: Split on multiple delimiters, and also treat consecutive delimiters as a single delimiter?

2015-07-28 Thread m
W dniu 28.07.2015 o 15:55, Victor Hooi pisze:
> I know the regex library also has a split, unfortunately, that does not 
> collapse consecutive whitespace:
> 
> In [19]: re.split(' |', f)

Try ' *\|'

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


Re: Packaging and deployment of standalone Python applications?

2015-09-17 Thread m
W dniu 14.09.2015 o 08:58, Kristian Rink pisze:
[...]

> 
> Any pointers, ideas, inspirations on that greatly appreciated - even
> in total different ways if what I am about to do is completely off
> anyone would do it in a Python environment. ;)

Look at https://github.com/jordansissel/fpm/wiki - it's really nice
tool, which converts python package into .deb, .rpm - so assuming that
"everyone has some (2.x/3.x) python" is true, you can just ship .deb or
.rpm files.

reg

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


Re: Einstein's Riddle

2015-09-19 Thread m
W dniu 20.09.2015 o 05:27, Michael Torrie pisze:
> On 09/18/2015 03:51 AM, Nick Sarbicki wrote:
>> > On Fri, Sep 18, 2015 at 10:33 AM, Steven D'Aprano 
>>> >> Time is relative. Perhaps the poster has been travelling at close to the
>>> >> speed of light, and for him it is only a few minutes after the original
>>> >> post was sent.
>> > 
>> > I prefer to think that it just took him this long to do it.
> Probably what happened is some computer somewhere was finally rebooted
> after 15 years of uptime, and this messages finally was processed after
> years stuck in the queue.

It's posted from @gmail account, and Gmail started near 2004

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


Re: Strong typing implementation for Python

2015-10-13 Thread m
W dniu 13.10.2015 o 03:35, Michael Torrie pisze:
> On 10/12/2015 06:07 PM, Steven D'Aprano wrote:
>> > Where is the "vast amounts of noise" added to the code?
> Well in Java code for one.  No wonder they require auto-completion.
> Java class-based namespaces must be a nightmare to work with. 

IMHO mainly because their naming convention. They just love typing long
names. If they used named like in python, that "vast amount of noise
added to code" would be just "a bit noise added to code"

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


Monitor and compare two log files in real time

2008-08-06 Thread m
I have a script I would like to write but I am not sure of where to
start / approach. Perhaps someone could help direct me in the right
direction. Any advice is appreciated.

I would like to write a python script that monitors two log files.
If a certain string, lets say string1 shows up in logfile-A, I want to
check if that same string shows up in log file-B within 8 minutes. If
it does not show up within 8 minutes, send an email ( using sendmail
or postfix).

Do you have any suggestions?
--
http://mail.python.org/mailman/listinfo/python-list


Very odd output from subprocess

2010-06-30 Thread m
I have this function:


def GetMakeOutput(make, rules, out=None):
p = subprocess.Popen('%s %s' % (make,rules),
 shell=True,
 bufsize=1024,
 stderr=subprocess.PIPE,
 stdout=subprocess.PIPE,
 close_fds=False)
ret = []
line = p.stdout.readline()
while len(line):
if line[:5] not in ['make[','make:']:
if out:
out.write(line)
out.flush()
else:
ret.append(line)
line = p.stdout.readline()
return string.join(map(string.strip,ret),'\n')

Very simple ... it cleans any line that is output from make itself.

Now, I have used it for quite awhile with no problem.  But, I noticed
today that it wasn't doing its job on my 64 bit machine.

If I add the line:
 for l in line: print ord(l),'\t',l
after the first readline, I get the following:


27  
91  [
48  0
48  0
109 m
27  
91  [
51  3
55  7
109 m

before the codes begin for the string as it appears if I just print
it.  So, what is this sequence?  They seem like some sort of escape
codes, I've never seen this before at all.

Can anyone enlighten me as to what is going on?

And, can I safely strip sets of 5 characters from the front as long as
they start with Escape (27)?

Thanks,

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


Re: Very odd output from subprocess

2010-07-05 Thread m
On Jul 1, 12:42 am, Nobody  wrote:
> On Wed, 30 Jun 2010 21:12:12 -0700, m wrote:
> > If I add the line:
> >      for l in line: print ord(l),'\t',l
> > after the first readline, I get the following:
>
> > 27          
> > 91         [
> > 48         0
> > 48         0
> > 109        m
> > 27          
> > 91         [
> > 51         3
> > 55         7
> > 109        m
>
> > before the codes begin for the string as it appears if I just print
> > it.  So, what is this sequence?  They seem like some sort of escape
> > codes, I've never seen this before at all.
>
> [00m is the ANSI code to reset attributes to their default state.
> [37m is the ANSI code to set the foreground color to white.
>
> > Can anyone enlighten me as to what is going on?
>
> > And, can I safely strip sets of 5 characters from the front as long as
> > they start with Escape (27)?
>
> No, escape sequences can be of arbitrary length.
>

It turned out that make was aliased to colourmake, and the escape
codes were being
put in there for beautifying the console output.  Sorry to bother
everyone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Defining features in a list

2012-09-07 Thread M Whitman
Good Morning,

I have been recently trying to define all of the features in a list but have 
been running into errors.  I would like to define the features similar to the 
following print statement.  Any advice would be appreciated.  I'm trying to 
transition my output from a text file to excel and if I can loop through my 
lists and define them that transition will be cleaner.

Many Thanks,

-Matt

#Author: MGW
#2012 
import os, datetime, sys, arcpy, xlrd
from arcpy import env
submission = "Rev.mdb"
env.workspace = "C:/temp/"+submission+"/Water"

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
print fc+"="+str(arcpy.GetCount_management(fc).getOutput(0))

print "Complete"
raw_input("Press ENTER to close this window") 

Output Generated
WATER_Net_Junctions=312
WS_Hyd=484
WS_Mains=2752
WS_Node=4722
WS_Vlvs=1078
WS_WatLats=3661
WS_WatMtrs=3662
WTRPLANTS_points=0
WTRPUMPSTA_points=0
WTRTANKS=0
WTR_ARV=10
WTR_MISC=0
Complete
Press ENTER to close this window

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
fc=str(arcpy.GetCount_management(fc).getOutput(0))
#TEST
print WS_Hyd
   

print "Complete"
raw_input("Press ENTER to close this window") 

Output Generated
Traceback (most recent call last):
  File "C:\Documents and Settings\mattheww\Desktop\Copy of QAQCexce_2.py", line 
14, in 
print WS_Hyd
NameError: name 'WS_Hyd' is not defined
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Defining features in a list

2012-09-07 Thread M Whitman
Dave- By features I was refering to items in the list.  For background the 
arcpy module is used for geoprocessing of geographic information.  I'm using my 
script to get totals for features in a dataset that I receive on a regular 
basis- for example total number of hydrants, total number of hydrants with null 
or missing attributes, and total number of hydrants with outlining attributes.

I am experienced particularly with the arcpy module and I am trying deligently 
to become more experienced with Python in general.  My goal is to fetch values 
by name and then print output by name. print WS_Hyd and then see "484".   I 
have some experience with class definition but a dictionary might be the way to 
go.  I was understanding the response of the Arcpy module but hadn't understood 
why the list wasn't being defined in my previous loop statement.  I appreciate 
the response.  I will look into dict if you have a class definition suggestion 
I will run with that.  Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing Classes from child folders.

2013-01-17 Thread Tobias M.
On an import python looks for the module in the directories specified in 
sys.path.

The documentation on sys.path says:

"As initialized upon program startup, the first item of this list is the 
directory containing the script that was used to invoke the Python 
interpreter." [1]


So it`s important that the script you execute by passing it to the 
python interpreter is in your root folder ("ProjectX").

If this script is Controller.py, you might want to check the path there by:

import sys
print(sys.path)

There should be an entry with a empty string ("") standing for the 
current directory.


Note: This is just what I suggest according to my knowledge (I'm also a 
newbie in python).


References:
[1] http://docs.python.org/3.3/library/sys.html#sys.path

On 17.01.2013 08:37, [email protected] wrote:

Trying to do some OO Python with files in different directories.
I have a blank __init__.py in each directory.
It is my assumption that having an __init__.py marks the directory as a module.
I am trying to run Controller.py from the command line.

I would assume this has already been solved but could not find in forum
I am somewhat new to Python. Using Python3 under Ubuntu.
...
So I have a project structure as follows:
...
ProjectX (root folder)
__init__.py
Controller.py
+ service (folder under ProjectX)
   __init__.py
   SystemSetup.py (has a class SystemSetup)
+ model (folder under ProjectX)
   __init__.py
   Directory.py (has a class Directory)

In Controller.py if I want to use SystemSetup class, I do:
from service.SystemSetup import SystemSetup
...
and in Controller Class I have:
def main():
 systemSetup = SystemSetup()

I get error:
   File "Controller.py", line 4, in 
   from service.SystemSetup import SystemSetup
ImportError: cannot import name SystemSetup

What am I doing wrong? I am running from the command line.
Do I need to set the project in PYTHONPATH first?

But if SystemSetup and Directory are in same directory as Controller I have no 
problems.

Your help would be highly appreciated.
...
Btw I also tried:
import sys, os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 
os.path.pardir)))
from service.SystemSetup import SystemSetup
...
No luck.

Thank you again.

Monosij


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


Else statement executing when it shouldnt

2013-01-20 Thread eli m
an else statement is running when it shouldnt be. It is on the last line. 
Whenever i am in the math or game function, when i type in main, it goes back 
to the start of the program, but it also says not a valid function. I am 
stumped!
Here is my code:
#Cmd 
#Created By Eli M.
#import modules
import random
import math
gtn = 0
print ("Type in help for a list of cmd functions")
#initiate main loop
cmd = 0
while cmd == 0:
#ask for input on function
function = raw_input("Type in a function:")
#start math loop
if function == "math":
run = 0
while run == 0:
#ask for math operation
type = raw_input("What math operation do you want to use?")
if type == "multiplication":
x = raw_input("Type in your first number:")
y = raw_input("Multiply your first number by:")
try:
ans = int(x) * int(y)
print (ans)
try:
ans = float(x) * float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#division math function
if type == "division":
x = raw_input("Type in your first number:")
y = raw_input("Divide your first number by:")
try:
ans = float(x) / float(y)
print (ans)
except ZeroDivisionError, err:
print ("Can't divide by zero")
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#subtraction math function
if type == "subtraction":
x = raw_input("Type in your first number:")
y = raw_input("Subtract your first number by:")
try:
ans = float(x) - float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
#addition math function
if type == "addition":
x = raw_input("Type in your first number:")
y = raw_input("Add your first number by:")
try:
ans = float(x) + float(y)
print (ans)
except ValueError, err:
try:
ans = int(x) + int(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#square root math function
if type == "square root":
x = raw_input("Type in your number:")
try:
y = float(x)
z = math.sqrt(y)
print (z)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")

#to the power of... math function
if type == "power":
x = raw_input("Type in your number:")
y = raw_input("Multiply your first number by the power of:")
try:
ans = float(x) ** float(y)
print (ans)
except OverflowError, err:
print ("Number too large")
except ValueError, err:
print ("Not a valid number")
#break the math loop
if type == "main":
run = 1
#absolute value math function
if type == "absolute value":
try:
x = float(raw_input("Type in your number:"))
y = math.fabs(x)
print (y)
except ValueError, err:
print ("Not a valid number")
if function == "random number":
try:
x = int(raw_input("Minimum number:"))
y = int(raw_input("Maximum number:"))
num = random.randint(x, y)
print (num)
except ValueError, err:
print ("Not a valid number")
if function == "games":
games = 0

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> You have to break while loop not to execute else branch
> 
> 
> Rene
> 
> 
> 
Can you explain in more detail please.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m

> 
> 
> 
> Your else is lined up with while, not with if.
> 
> 
> 
>   -m
> 
> 
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> 
> 
> 
> When a friend succeeds, I die a little.  Gore Vidal
Its lined up. It got messed up when i copied the code into the post.

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:40:47 PM UTC-8, eli m wrote:
hint: Use the comments in the code to find out where my error is.
> 
> Here is my code:
> 
> #Cmd 
> 
> #Created By Eli M.
> 
> #import modules
> 
> import random
> 
> import math
> 
> gtn = 0
> 
> print ("Type in help for a list of cmd functions")
> 
> #initiate main loop
> 
> cmd = 0
> 
> while cmd == 0:
> 
> #ask for input on function
> 
> function = raw_input("Type in a function:")
> 
> #start math loop
> 
> if function == "math":
> 
> run = 0
> 
> while run == 0:
> 
> #ask for math operation
> 
> type = raw_input("What math operation do you want to use?")
> 
> if type == "multiplication":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Multiply your first number by:")
> 
> try:
> 
> ans = int(x) * int(y)
> 
> print (ans)
> 
> try:
> 
> ans = float(x) * float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #division math function
> 
> if type == "division":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Divide your first number by:")
> 
> try:
> 
> ans = float(x) / float(y)
> 
> print (ans)
> 
> except ZeroDivisionError, err:
> 
> print ("Can't divide by zero")
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #subtraction math function
> 
> if type == "subtraction":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Subtract your first number by:")
> 
> try:
> 
> ans = float(x) - float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> #addition math function
> 
> if type == "addition":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Add your first number by:")
> 
> try:
> 
> ans = float(x) + float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> try:
> 
> ans = int(x) + int(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #square root math function
> 
> if type == "square root":
> 
> x = raw_input("Type in your number:")
> 
> try:
> 
> y = float(x)
> 
> z = math.sqrt(y)
> 
> print (z)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> 
> 
> #to the power of... math function
> 
> if type == "power":
> 
> x = raw_input("Type in your number:")
> 
> y = raw_input("Multiply your first number by the power 
> of:")
> 
> try:
> 
> ans = float(x) ** float(y)
> 
> print (ans)
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> except ValueError, err:
> 
&

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:52:12 PM UTC-8, Chris Angelico wrote:
> On Mon, Jan 21, 2013 at 3:40 PM, eli m  wrote:
> 
> > an else statement is running when it shouldnt be. It is on the last line. 
> > Whenever i am in the math or game function, when i type in main, it goes 
> > back to the start of the program, but it also says not a valid function. I 
> > am stumped!
> 
> 
> 
> Check your indentation levels. I see a few things here that look odd:
> 
> 
> 
> > if function == "help":
> 
> > while helpfunc == 0:
> 
> > if helpmain == "main":
> 
> > else:
> 
> 
> 
> What is the else meant to bind to? The innermost if? The 'if function
> 
> == "help"'? It's currently binding to the while.
> 
> 
> 
> Recommendation: Break this up! Your main loop is huge! It's way too
> 
> easy to get lost in it. And while you're at it, consider unifying some
> 
> of the similar blocks of code. The solution to both issues is simple:
> 
> Use functions. Have you been taught about them yet?
> 
> 
> 
> Also, side tip: Be honest about homework. I'm fairly sure that's what
> 
> this is. :)
> 
> 
> 
> ChrisA

Its not homework. It is a personal project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-21 Thread eli m
On Sunday, January 20, 2013 9:56:59 PM UTC-8, alex23 wrote:
> On Jan 21, 2:40 pm, eli m  wrote:
> 
> > an else statement is running when it shouldnt be. It is
> 
> > on the last line. Whenever i am in the math or game
> 
> > function, when i type in main, it goes back to the start
> 
> > of the program, but it also says not a valid function.
> 
> > I am stumped!
> 
> 
> 
> Here is your code with the irrelevancy stripped away:
> 
> 
> 
> function = raw_input("Type in a function:")
> 
> #start math loop
> 
> if function == "math":
> 
> #math code
> 
> if function == "random number":
> 
> #random code
> 
> if function == "games":
> 
> #games code
> 
> if function == "help":
> 
> #help code
> 
> else:
> 
> print ("Not a valid function")
> 
> 
> 
> Say you enter 'math'. It passes the first condition, so runs the math
> 
> code.
> 
> It then fails on the next 3 conditions, the last of which has an else,
> 
> so if you type _anything_ other than 'help', you'll see "Not a valid
> 
> function".
> 
> 
> 
> Easy answer, use `elif` ("else if") instead of else for the subsequent
> 
> tests:
> 
> 
> 
> if function == "math":
> 
> #math code
> 
> elif function == "random number":
> 
> #random code
> 
> elif function == "games":
> 
> #games code
> 
> elif function == "help":
> 
> #help code
> 
> else:
> 
> print ("Not a valid function")
> 
> 
> 
> Better answer: read up on real functions, and look into dictionary
> 
> dispatch:
> 
> 
> 
> def f_math():
> 
>#math code
> 
> 
> 
> def f_random_number():
> 
>#random code
> 
> 
> 
> 
> 
> 
> 
> function_dispatcher = {
> 
> 'math': f_math,
> 
> 'random number': f_random_number,
> 
> 
> 
> }
> 
> 
> 
>while cmd == 0:
> 
>function_name = raw_input("Type in a function:")
> 
>if function_name in function_dispatcher:
> 
>function_dispatcher[function_name]()
> 
>else:
> 
>print("Not a valid function")
> 
> 
> 
> To have your functions break out of the loop, use a `global` variable
> 
> or pass a context object into each function to allow them to set
> 
> `cmd`.

Thank you, that solved my problem. Sorry for my posts, i am a noob and this is 
my first time posting on here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing class from another file

2013-01-23 Thread Tobias M.

Hi,

Kevin Holleran wrote:


Traceback (most recent call last):

  File "testing.py", line 1, in 

from Sub_Dir.My_Class import *

ImportError: No module named Sub_Dir.My_Class



Make sure, the script you execute by passing it to the python
interpreter is in the parent directory of Sub_Dir.
Additionaly put an empty file called __init__.py (double underscores!)
in Sub_Dir if you don't already have.  This is necessary to use Sub_Dir
as a package and import modules from it.

For more details see:
http://docs.python.org/3.3/tutorial/modules.html#packages


I have played around a bit with the calls (removing the My_Class in
the q_api assignment to instantiate the object, etc).


When using "from...import" on the module that contains the class, you
can use the class without the package identifier:
q_api = My_Class_Connector(string1,string2)

For your information: I think beginner questions like this one should be
asked on the tutor list:
http://mail.python.org/mailman/listinfo/tutor

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Hi,

do a "print sp" after the split and you might see that the strings don't 
look as you expected. There might be leading or trailing whitespaces in 
the splitted strings and in sp[10] there probably is a line break "\n" 
at the end.

To remove those unwanted characters you could use the strip() function.

So your code could be:

if sp[9].strip() == sp[10].strip():
print "Same class"
else:
print "Different class"

At least this works for me when I tried it...

Am 24.01.2013 11:37, schrieb inshu chauhan:
Here I have a code which basically reads a csv file, tries to compare 
the last 2 items in each line of the file.


f = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
for l in f:
sp = l.split(",")
if len(sp) != 11:
print >> of, l,

else:
#print sp[9], sp[10]
if sp[9] == sp[10]:
print " Same class"
else :
print "Different class"

f.close()

For me I think the programme is logically correct, but its giving me 
results which are strange.
It is  Printing " Different Class"  even when sp[9] is equal to sp[10] 
and "Same class" when sp[9] is not equal to sp[10]. and sp[9] and 
sp[10] are simple integers like 3, 3, 4 ,4.


I have a little understanding why the programme is behaving like this ?




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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Chris Angelico wrote:



The other thing you may want to consider, if the values are supposed
to be integers, is to convert them to Python integers before
comparing. Currently, you're working with strings. Replace this:

if sp[9] == sp[10]:

with this:

if int(sp[9]) == int(sp[10]):
I thought of this too and I wonder if there are any major differences 
regarding performance compared to using the strip() method when parsing 
large files.


In addition I guess one should catch the ValueError that might be raised 
by the cast if there is something else than a number in the file.

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Chris Angelico wrote:

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)
Well, when I said you should catch the ValueError I didn't imply you 
should ignore the error and supress any error messages. Of course this 
depents on the use case. Maybe you want to raise another exception with 
a more user friendly error message or you might want to skip the line 
and just print a warning. :)


What I'm trying to say: When I give a script/program to a user who is 
not a python programmer I don't want him to see an error message like 
"ValueError: invalid literal for int() with base 10: 'abc'" as this 
would help him in no way.

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Am 24.01.2013 13:02, schrieb Chris Angelico:

On Thu, Jan 24, 2013 at 10:58 PM, Tobias M.  wrote:

Chris Angelico wrote:

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)

Well, when I said you should catch the ValueError I didn't imply you should
ignore the error and supress any error messages. Of course this depents on
the use case. Maybe you want to raise another exception with a more user
friendly error message or you might want to skip the line and just print a
warning. :)

What I'm trying to say: When I give a script/program to a user who is not a
python programmer I don't want him to see an error message like "ValueError:
invalid literal for int() with base 10: 'abc'" as this would help him in no
way.

Sure. Definitely. But for a proglet where the programmer IS the user
(which I think is one of Python's best use-cases), that exception
landing on the console is better than having to think ahead of time
about what might go wrong.

ChrisA

Okay, I absolutely agree with that :)

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


Re: python: HTTP connections through a proxy server requiring authentication

2013-01-28 Thread Saju M
Hi ,
Thanks barry,

I solved that issue.
I reconfigured squid3 with ncsa_auth, now its working same python code.
Earlier I used digest_pw_auth.

Actually I am trying to fix an issue related to python boto API.

Please check this post
https://groups.google.com/forum/#!topic/boto-users/1qk6d7v2HpQ


Regards
Saju Madhavan
+91 09535134654


On Tue, Jan 29, 2013 at 5:01 AM, Barry Scott  wrote:

> The shipped python library code does not work.
>
> See http://bugs.python.org/issue7291 for patches.
>
> Barry
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Http post and http get

2012-02-06 Thread n3d!m
Cookies work because I am able to login on website and GET other pages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: log and figure out what bits are slow and optimize them.

2012-02-10 Thread Saju M
Hi,

Yes i saw profile module,
I think i have to do function call via

cProfile.run('foo()')

I know, we can debug this way.

But i need a fixed logging system ..



On Fri, Feb 10, 2012 at 6:08 PM, Arnaud Delobelle  wrote:

> On 10 February 2012 12:30, sajuptpm  wrote:
> > Hi,
> >
> > I want to log time taken to complete database requests inside a method/
> > function using decorator .  is it possible 
> > I think, i have to inject log code inside the method/fuctions or
> > modify it.
> > I wrote a decorator to log taken by a method/function to complete it
> > execution and its working well.
> >
> > My requirement : log everything and figure out what bits are slow and
> > optimize them.
> >
> > What are your suggestions ??
>
> Are you familiar with this?
>
> http://docs.python.org/library/profile.html
>
> --
> Arnaud
>



-- 
Regards
Saju Madhavan
+91 09535134654

Anyone who has never made a mistake has never tried anything new -- Albert
Einstein
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: log and figure out what bits are slow and optimize them.

2012-02-10 Thread Saju M
On Fri, Feb 10, 2012 at 6:12 PM, Saju M  wrote:

> Hi,
>
> Yes i saw profile module,
> I think i have to do function call via
>
> cProfile.run('foo()')
>
> I know, we can debug this way.
>
> But i need a fixed logging system ..
>
>
>
> On Fri, Feb 10, 2012 at 6:08 PM, Arnaud Delobelle wrote:
>
>> On 10 February 2012 12:30, sajuptpm  wrote:
>> > Hi,
>> >
>> > I want to log time taken to complete database requests inside a method/
>> > function using decorator .  is it possible 
>> > I think, i have to inject log code inside the method/fuctions or
>> > modify it.
>> > I wrote a decorator to log taken by a method/function to complete it
>> > execution and its working well.
>> >
>> > My requirement : log everything and figure out what bits are slow and
>> > optimize them.
>> >
>> > What are your suggestions ??
>>
>> Are you familiar with this?
>>
>> http://docs.python.org/library/profile.html
>>
>


  I need a fixed logging system and want to use it in production.
  I think, we can't permanently include profile's debugging code in
source code,
 will cause any performance issue ??




> --
>> Arnaud
>>
>
>
>
> --
> Regards
> Saju Madhavan
> +91 09535134654
>
> Anyone who has never made a mistake has never tried anything new -- Albert
> Einstein
>



-- 
Regards
Saju Madhavan
+91 09535134654

Anyone who has never made a mistake has never tried anything new -- Albert
Einstein
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: log and figure out what bits are slow and optimize them.

2012-02-10 Thread Saju M
Yes i saw profile module,
I think, i have to do function call via
cProfile.run('foo()')
I know, we can debug this way.
But, I need a fixed logging system and want to use it in production.
  I think, we can't permanently include profile's debugging code in
source code,
 will cause any performance issue ??


On Fri, Feb 10, 2012 at 6:18 PM, Saju M  wrote:

>
>
> On Fri, Feb 10, 2012 at 6:12 PM, Saju M  wrote:
>
>> Hi,
>>
>> Yes i saw profile module,
>> I think i have to do function call via
>>
>> cProfile.run('foo()')
>>
>> I know, we can debug this way.
>>
>> But i need a fixed logging system ..
>>
>>
>>
>> On Fri, Feb 10, 2012 at 6:08 PM, Arnaud Delobelle wrote:
>>
>>> On 10 February 2012 12:30, sajuptpm  wrote:
>>> > Hi,
>>> >
>>> > I want to log time taken to complete database requests inside a method/
>>> > function using decorator .  is it possible 
>>> > I think, i have to inject log code inside the method/fuctions or
>>> > modify it.
>>> > I wrote a decorator to log taken by a method/function to complete it
>>> > execution and its working well.
>>> >
>>> > My requirement : log everything and figure out what bits are slow and
>>> > optimize them.
>>> >
>>> > What are your suggestions ??
>>>
>>> Are you familiar with this?
>>>
>>> http://docs.python.org/library/profile.html
>>>
>>
>
>
>   I need a fixed logging system and want to use it in production.
>   I think, we can't permanently include profile's debugging code in
> source code,
>  will cause any performance issue ??
>
>
>
>
>>  --
>>> Arnaud
>>>
>>
>>
>>
>> --
>> Regards
>> Saju Madhavan
>> +91 09535134654
>>
>> Anyone who has never made a mistake has never tried anything new --
>> Albert Einstein
>>
>
>
>
> --
> Regards
> Saju Madhavan
> +91 09535134654
>
> Anyone who has never made a mistake has never tried anything new -- Albert
> Einstein
>



-- 
Regards
Saju Madhavan
+91 09535134654

Anyone who has never made a mistake has never tried anything new -- Albert
Einstein
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate Windows exe on Linux

2012-02-22 Thread Waldek M.
On Wed, 22 Feb 2012 04:12:29 -0800 (PST), Plumo wrote:
> I have a python script using only the standard libraries.
> Currently I use a Windows VM to generate exe's, which is cumbersome.

And what exactly *is* this exe about?

> Has anyone had success generating exe's from within Linux?

That doesn't seem to have anything to do with Python,
but you might want to google for cross-compiling.

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


Re: generate Windows exe on Linux

2012-02-23 Thread Waldek M.
On Wed, 22 Feb 2012 18:42:11 +0100, Jérôme wrote:
>>> Has anyone had success generating exe's from within Linux?
>> 
>> That doesn't seem to have anything to do with Python,
>> but you might want to google for cross-compiling.
> 
> I think his question is totally python related. 
> 
> As I understand it, Richard creates executables from python scripts using a
> tool, such as py2exe [1], that requires windows. He would like to have an
> equivalent tool that runs on linux, to avoid going through the trouble of
> having to run a windows installation.

Ah, that's the part I was missing :-)
Thanks.

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


Re: New learner of Python--any suggestion on studying it?

2012-03-19 Thread Wim M
Hi,
this might be of interest to you:
http://www.udacity.com/overview/Course/cs101

All the best Wimm

On 2012-03-19, yan xianming  wrote:
> Hello all,
>
> I'm a new learning of Python.
>
>
>
> Can someone give me some suggestion about it?
>
> thanks
> xianming


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


Re: python 3 constant

2011-06-22 Thread Waldek M.
Dnia Wed, 22 Jun 2011 22:17:49 +0100, Noah Hall napisał(a):

> On Wed, Jun 22, 2011 at 7:54 PM, sidRo  wrote:
>> How to declare a constant in python 3?
> 
> There aren't true constants in Python, but instead we use a standard
> defined by PEP 8, which states constants are in all caps, for example,
> PI = 3.14, as opposed to pi = 3.14 which could change (according to
> PEP 8, that is)

That said, there are some workarounds for that:
http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991

Still, I'd reallly like to have constants as a built-in...

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


Re: python 3 constant

2011-06-23 Thread Waldek M.
Dnia Thu, 23 Jun 2011 17:22:37 +1000, Ben Finney napisał(a):
> If you mean creating a binding which can't be re-bound: −1.

Perhaps. Or perhaps that could be done in some other fashion;
I admit that I usually stick to more strict languages
and while Python's flexibility is great... I'm really missing
constants.

> The ability to re-bind any attribute, even ones which the author thought
> should be constant, makes writing unit tests much easier. I don't see
> that putative benefits of constant bindings would be anywhere near as
> valuable.

Primo, isn't it usually the author that does the unit testing?
Anyway, correct me if I'm wrong but I always thought that unit tests
should prove the correctness and quality of the code under test,
and not the other way around, which would be sacrifising
code security to make testing easier.

Secundo, one can say that re-binding gives the freedom to change
what one likes; I'd say that I'd also like the freedom to decide what
is mutable and what is not.

Of course, it is just my personal opinion. It might be not pythonic,
I may be wrong, yet - concept of constants is not something new and
if other languages, like C/C++/Java/Perl/ (bash even) have them, 
I can't see the reason not to have them in Python.

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


Re: python 3 constant

2011-06-23 Thread Waldek M.
Dnia Fri, 24 Jun 2011 01:29:38 +1000, Chris Angelico napisał(a):
> You can have them in Python. Just run your code through cpp (the C
> preprocessor) first. Voila!
> 
> It's handy for other things too. Don't like Python's lack of "then"
> and "end if"?
[...]
Yup, got the sarcasm, that's for sure.
But your point was...?

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


Re: python 3 constant

2011-06-25 Thread Waldek M.
Dnia Thu, 23 Jun 2011 23:04:37 +1000, Ben Finney napisał(a):
>>> The ability to re-bind any attribute, even ones which the author
>>> thought should be constant, makes writing unit tests much easier. I
>>> don't see that putative benefits of constant bindings would be
>>> anywhere near as valuable.
>>
>> Primo, isn't it usually the author that does the unit testing?
> 
> I don't see how that's relevant. I'm referring to run-time re-binding of
> attributes, without the need for changing the code.

I meant simply that the author knows his/hers software and takes into
consideration while unit testing the fact that some things is constant.
I still can't see how checking if 2 == 2 (in the morning, in the afternoon
and in the night, and even tomorrow) helps making the software
significantly better.

>> Anyway, correct me if I'm wrong but I always thought that unit tests
>> should prove the correctness and quality of the code under test,
> 
> Right. Which often involves special set up of the environment in which
> that code runs, in order to conduct a proper test.
> 
> If the test I need to perform involves demonstrating what the code under
> test will do with different values for a name you consider constant,
> then I have Python's ability to re-bind that name at run-time.

In languages that allow constants, you can still make dirty hacks, like
casting to pointers, const_cast<>'ing and so on.
It is technically possible to override the constants one way or another;
yet I (and many people) find it useful that the language itself helps me
preventing myself from eg. distraction or being overwhelmed by the size of
a project.

Or, when a project is being developed by several people, helps
avoiding problems caused by 'hey, I thought binding 5 to this great 
name DOZEN was a realy great idea' attitude.

>> Secundo, one can say that re-binding gives the freedom to change what
>> one likes; I'd say that I'd also like the freedom to decide what is
>> mutable and what is not.
> 
> And I, as the user of your code, say that you don't get to dictate how I
> use it. I will take the authors's recommendations under advisement, but
> I reject any authority to restrict what I can do with it.
> 
> Unit tests are just an obvious example. The real lesson here is that the
> reciient of the code you write can, and probably will, use it in ways
> you never expected. It's not for you to decide which of those uses are
> permitted.

He can take my code and rework it if he/she likes. If that's what he wants,
that's fine with me. If he doesn't want to do that, I'm pretty sure he'll
find another ways to hack the logic I put into my code.
But he's one for a thousand; the rest would be rather grateful to me that
I let them know some things are constants. And currently, in Python,
I cannot do that.

>> Of course, it is just my personal opinion. It might be not pythonic,
> 
> Right. One useful phrase to remember from the founder of the Python
> language is that “We're all consenting adults here”.

I agree with that statement, sure. Only... I've never seen an adult who
doesn't make mistakes and who shouldn't be given any instructions.

> Indicate through the API and its documentation how you recommend I use
> your code; but treat me as an adult capable of making my own decisions
> about what risks I accept. Understand that I will be using the code you
> wrote in the way I see fit.

Yup. That's what I'd like to do: be able to indicate in the API that some
things should be *better* left unchanged. That A_DOZEN_IN_INTEGER IMO
should really stay 12, not 1 or -23.34. 

Documentation is a great thing, but tends to go out of date pretty soon..
much sooner than the code itself. Not mentioning those who just don't read
them carefully enough (I guess you'd call them non-adults, right? ;-) ).

So let me warn with language syntax that it's probably not a good idea
to change 'this' and 'that'. Do they still want to change it? It's their
responsibility, I'd let them hack themselves silly...

To summarize: I do miss constants in Python and I think Python could really
benefit from them. I haven't seen so far any convincing argument to not
have them. That said, I'm not that kind of person who says "hey, you Python
people, give me my constants or I won't use it". No, I like the language, 
I will still learn it and use it...  and I'll still miss the constants ;-)

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


Re: python 3 constant

2011-06-25 Thread Waldek M.
Dnia Thu, 23 Jun 2011 20:04:43 -0700 (PDT), alex23 napisał(a):
>> But your point was...?
> 
> That it's easier for you to find ways to achieve what you want than it
> is require Python to change to accommodate your need.

And when exactly did I write that I require anyone to change anything?
I'd like that, sure. IMHO it'd be useful. But I don't *require*.

Can you see the slight difference? :-)

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


Re: python 3 constant

2011-06-25 Thread Waldek M.
Dnia Fri, 24 Jun 2011 08:00:06 +1000, Chris Angelico napisał(a):
>> Yup, got the sarcasm, that's for sure.
>> But your point was...?
> 
> That if you want something, there's usually a way to get it.
> Sometimes, giving someone what they want - or showing them how to get
> it - makes it obvious to them whether or not they really want it.
> 
> Chris Angelico

Usually, it does. But presenting me with a fake and
obviously-not-logical-and-useful version of constants didn't really
say anything about why is having constants such a bad idea :-)
Just like presenting me with a rotten apple doesn't prove
anything general about that fruit.

I'm not into endless/pointless advocacy; I'm really curious.

And - as I've answered to someone else - I dont't *require* anyone
to change anything in the language. I just miss the feature and can't
really think of a sensible reason why it so wrong.

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


Re: python 3 constant

2011-06-25 Thread Waldek M.
Dnia Sat, 25 Jun 2011 20:59:17 +1000, Chris Angelico napisał(a):
> In all seriousness, sometimes adding features to one language is best
> done by dropping to another. This is probably not as useful in
> interpreted languages like Python, but I have on multiple occasions
> run code through the C preprocessor as part of my compilation process,
> as per my example.

A little off-topic but I see your point :-) Tried it once or twice - when
generating some C++ and .sip files code from a template, then generating
SIP wrappers, then generating .pyd libraries, then using in Python...  

Yeah, might be useful, even if sometimes complexity of the process
is a bit overwhelming to me :-)

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


Re: ANN: pyparsing 1.5.6 released!

2011-07-01 Thread Waldek M.
Dnia Thu, 30 Jun 2011 23:09:18 -0700 (PDT), Paul McGuire napisał(a):
> After about 10 months, there is a new release of pyparsing, version
> 1.5.6.  This release contains some small enhancements, some bugfixes,
> and some new examples.

Thanks! That is great news.

I'm not using pyparsing right now, but I used to and surely
will. I just wish it was included in the standard Python distribution
some day...

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


Re: Testing if a global is defined in a module

2011-07-05 Thread Waldek M.
Dnia Tue, 5 Jul 2011 14:11:56 + (UTC), Grant Edwards napisał(a):
> Because those specially-formatted comments are wrong.

... because?
Not in sarcasm mode; just curious why you don't like them.

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


Re: Testing if a global is defined in a module

2011-07-05 Thread Waldek M.
Dnia Wed, 06 Jul 2011 03:36:24 +1000, Steven D'Aprano napisał(a):
> Because unless you are extremely disciplined, code and the comments
> describing them get out of sync. [...]
True, but that gets far worse with external docs.
Do you have in mind any better replacement?

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread Waldek M.
Dnia Wed, 6 Jul 2011 08:10:27 -0700 (PDT), rantingrick napisał(a):
>> In the Unix/Linux world, there is a graphical application called xkill which
>> has no menus and no windows, all it has is a mouse cursor! No, it does not
>> run in the background: it is a foreground app.
> 
> Wow nice corner case. Can you come up with at least five of them
> though? You and I both know that the vast majority of GUI's require
> visible windows.

- 90% of MS DOS games; should I list them here? ;-)
- M$ Windows taskbar-only applications
- Linux apps using framebuffer but not X

One could argue that the second and the third case are - in one
way or another - using windows. But not the first case, and I don't think
you'd call them GUI-less.

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


Re: How to get or set the text of a textfield?

2011-07-10 Thread Waldek M.
Dnia Sun, 10 Jul 2011 21:14:10 -0500, Anthony Papillion napisał(a):
> 
> So I've built a UI with Glade and have loaded it using the standard
> Python code. In my UI, I have a textfield called txtUsername. How do I
> get and set the text in this field from my Python code?

http://developer.gnome.org/pygtk/stable/
http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/

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


Re: Python ++ Operator?

2011-07-16 Thread Waldek M.
Dnia Fri, 15 Jul 2011 23:09:02 +0200, Stefan Behnel napisał(a):
[...]
>> array[count++]=value;
>>
>> or the more direct pointer management:
>> *ptr++=value;
> 
> More direct, sure. But readable? Well, only when you know what this 
> specific pattern does. If you have to think about it, it may end up hurting 
> your eyes before you figure it out.

Oh, come on. I don't say the post- and pre-incrementing is 
good or bad, but please don't exagerate. 

Almost any other construction is unreadable to people, who
don't know this construction, eg. a==1, a+=1
may be completely senseless to mathematicians.

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


Re: Python threading/multiprocessing issue.

2011-07-16 Thread Waldek M.
Dnia Fri, 15 Jul 2011 22:15:15 -0700, Dennis Lee Bieber napisał(a):
>   And (so far as I understand it) each process can claim its own CPU
> core, whereas threads share the active core.

I do not think so. AFAIK, threads may be distributed over differrent
CPUs (just like in any other programming language), only because of GIL, 
you might not notice any performance improvement with that.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Waldek M.
>> I'm still looking for the perfect programming font. Suggestions
>> welcomed.
> 
> When you find it Dotan, let me know, I've been looking since the later 
> '70's.

For me, it's Terminus* (from sourceforge).

Br.
Waldek
[*] As long as you don't need anything but iso8859-1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AUTO: Craig Churchill is out of the office (returning 27/07/2011)

2011-07-18 Thread Waldek M.
> I am out of the office until 27/07/2011.
> 
> I will respond to your message when I return.
> If you require assitance in relation to the SPEAR Integration project
> please contact Terry Mandalios.

Why, thank you Craig. I will definitely contact Terry ;-)

Br.
Waldek
PS. Sorry, couldn't stop myself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: os.path needs immediate attention!

2011-07-29 Thread Waldek M.
Dnia Fri, 29 Jul 2011 14:41:22 -0500, harrismh777 napisał(a):
> The backslash sep is an asinine CPM/80 | DOS disk based carry-over which 
> does not fit well with the modern forward direction. The disk based file 
> system carry-over is bad enough; but, propagating multiple ways of doing 
> simple things like specifying file-system paths is not helpful in any 
> context.

Please, do tell it to Microsoft. And once you've convinced them,
and they've implemented it, do report :-)

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


Re: Help parsing a text file

2011-08-30 Thread Waldek M.
On Mon, 29 Aug 2011 23:05:23 +0200, Thomas Jollans wrote:
> A name that is often thrown around on this list for this kind of
> question is pyparsing. Now, I don't know anything about it myself, but
> it may be worth looking into.

Definitely. I did use it and even though it's not perfect - it's very
useful indeed. Due to it's nature it is not a demon of speed when parsing
complex and big structures, so you might want to keep it in mind.
But I whole-heartedly recommend it.

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


Re: mystery string code - help!

2011-04-20 Thread Dan M
> As a newbie Pythoner, I understand [] -1] but would some tell me how
> '::' does its magic?
> 
> Uncle Ben

The -1 is the "stride" or "step" argument. It's described at 
http://docs.python.org/release/2.3.5/whatsnew/section-slices.html

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


PyQt: viewport vs window - how do you translate co-ordinates?

2017-09-23 Thread Veek M
pg 329, Rapid GUI Programming

http://storage4.static.itmages.com/i/17/0923/h_1506165624_2588733_59fdfcd4cc.png

In PyQt terminology the physical coordinate system is called the “viewport”,
and confusingly, the logical coordinate system is called the “window”.

In Figure 11.4, we have a physical widget size of 800 × 600. By calling setWin-
dow(-60, -60, 120, 120) we can create a “window” with a top-left coordinate of
(-60, -60), a width of 120, a height of 120, and centered at point (0, 0). The
window’s coordinate system is a logical coordinate system that QPainter auto-
matically maps to the underlying physical device. After the setWindow() call,
all our painting takes place using the logical (window) coordinate system.
In this case, the widget is rectangular, but our window has the same width and
height. This means that the items we paint will be stretched out horizontally,
since coordinates in the y-axis will be scaled by QPainter in the ratio 120:600
(1:5), whereas those in the x-axis will be scaled in the ratio 120:800 (1:6 2
3
).



1. The physical (coordinate system) widget size is 800x600 = Viewport
2. Logical Coordinates = Window

When he does setWindow(-60, -60, 120, 120) he's moving along a diagonal from 
top-left to bottom-right. From that point he's then drawing a 120x120 rectangle.

A. So how does he get a (150,200) point and a -37.5 point??? 
B. Also, how is it stretched horizontally? If i use the inner 120x120 as a 
frame of reference and draw a circle - it'll still be a circle??? Just draw a 
square on a blackboard.. and then draw a circle in it..

I didn't understand any of that - could someone expand on that para?

C. Why does QPainter have to scale in a different ratio??
QPainter understands two coordinate systems - physical and logical and by 
default the two systems match each other.

Is there a reading resource that explains the Viewport and translations? I am 
not a CS student so I did not study computer graphics.


(sorry for using google groups but my knode is broken and pan is horrible on 
olvwm - my plan is to write myself a News client in PyQt :))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQt: viewport vs window - how do you translate co-ordinates?

2017-09-24 Thread Veek M
On Saturday, September 23, 2017 at 8:44:25 PM UTC+5:30, Michael Torrie wrote:
> On 09/23/2017 05:38 AM, Veek M wrote:
> > I didn't understand any of that - could someone expand on that para?
> > Is there a reading resource that explains the Viewport and translations? I 
> > am not a CS student so I did not study computer graphics.
> 
> I'm sure there are lots of things that might help. This is primarily
> about OpenGL but the principles may apply:
> https://www.cs.mtsu.edu/~jhankins/files/4250/notes/WinToView/WinToViewMap.html
> 
> Alternatively, you can think it through.  Imagine you're laying out a
> fence around your house. You could use global coordinates for
> everything, or you could just call the exact center of your yard 0,0 and
> measure everything from there, in whatever units you wish. That's the
> idea here. Rather than referring to pixels by their screen coordinates
> (which can change if it moves around the screen), you refer to them by
> an arbitrary coordinate system with it's own scaling relative to the
> screen region.  You could have a screen region that is 100 px by 100 px,
> and the you designate that the upper left corner of that region is
> -500,500 and the lower right corner is 500,-500. Or it could be
> something like -500,200 to 500,-200, which would make things stretched
> out in the x axis compared to the y axis.
> 
> > (sorry for using google groups but my knode is broken and pan is horrible 
> > on olvwm - my plan is to write myself a News client in PyQt :))
> 
> I don't think you need to know that much about graphics coordinate
> systems to get started with Qt. Most GUI layout stuff does not depend on
> pixels or coordinates.

I took a look at the: OpenGL SuperBible - 7e - it's heavy on doing, and not 
much theory; they have a section on Views. Also, read that link. The link has 
some mistakes I suspect..

Let's say we have a teacup-photograph and a table in a 3d-room. The photo has a 
local space - called Model Space or Object Space. The edges of the photo will 
form a coordinate system and using that i could make the teacup handle red.

If i take that photo and place it on top of that table - i get a World Space 
that contains both objects and the walls of the room form a coordinate system. 
(this is where that link is wrong)

Now let's say I want to display the room on a computer screen.

The entire computer screen forms a Screen coordinate system and will include 
the Dolphin file browser, maybe firefox, the kde toolbar)

However, I can't directly take a 3d room and stick it in my 2d screen so, I 
have to capture part of the room from a PERSPECTIVE - this is 2d because the 
camera film is 2d - so, this is a View Space/Clipping Window (link/url).

Now the View Space data that I captured has to be placed on the screen BUT not 
everywhere - this is the Interface Window (link/url).

However I may want to caption the room-image-displayed-on-screen so the 
Interface Window is further shrunk into a Viewport which represents 
pixels/points on the device/paper.

Transformation is a matrix associated with a space that will give you the 
desired pixels in the Viewport.

View Space is how this World Space looks when viewed
---

So how does the above fit into PyQt/book-description.

We have a Widget that is drawn in pixels/picas/whatever that has a 
physical-coordinate system associated with it (800x600 and will prolly fill the 
entire computer-screen). 

We have a window which is at (-60, -60) + 120 length&breadth - so you have a 
small rectangle in which to draw - equivalent to the ViewSpace however since 
this is 2d, it can also be equivalent to the Model/Object Space - with some 
random center (0,0) could be the teacup-handle.

The aspect ratio for widget is 1.
aspect ratio for window is 1

If the aspect ratios were the same there would be no problem - however since 
the aspect ratios are different, x-axis scaling is 120:800 and y-axis is 
120:600. We need to bear this in mind when we draw in our little window because 
what looks proportional/linear will be deformed when placed on screen/viewport.

So if we badly want a square window, we can create a square Screen/Viewport and 
loose some drawing area as a result of the viewport being squared from a 
rectangle.
--

Phew! anyway this is just my longwinded way but I think I got it. Thanks :)





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


PyQt: Parenting a Widget

2017-09-25 Thread Veek M
Summary: Could someone explain widget and dialog parenting - the text book is 
not making sense.
##
I'm trying to understand widget parenting, from the book: Rapid GUI 
Programming, pg 118, and thereabouts - he says:

A. All PyQt classes that derive from QObjectand this includes all the widgets,
since QWidget is a QObject subclasscan have a “parent”.

B. PyQt automatically repar-
ents the widgets that are laid out. So although we did not give our widgets a
parent of self (the Form instance),when we call setLayout() the layout manager
gives ownership of the widgets and of itself to the form,and takes ownership of
any nested layouts itself. This means that none of the widgets that are laid out
is a top-level window, and all of them have parents, which is what we want. So
when the form is deleted, all its child widgets and layouts will be deleted with
-
1. In A, does he mean, you are ALLOWED to set a parent on a widget ONLY because 
its Base Class is QObject? 

With DockWidgets, you have to explicitly parent them - why?

2. If I create two widgets and wdget.show() them, and app.exec_() - which one 
becomes the main-window and which one is the memory leak? I have not used a 
layout manager so, one widget with no parent auto-becomes the main-window (as 
per B), which would result in a leak with the other?

#!/usr/bin/python

import sys, os, re


from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)

lbl = QLabel('Hello World')
lbl.setWindowFlags(Qt.SplashScreen)
lbl.show()
txtBrw = QTextBrowser()
txtBrw.show()

QTimer.singleShot(3000, app.quit)
app.exec_()

3. QObject --> QWidget --> QDialog --> Form --> Form_Layout_Manager --> 
Nested_Layout_Manager

B, says that the layout manager parents the widgets under it and makes 'Form' 
the parent. If the Form Layout Manager is taking charge of the Nested Layout 
Manager, who is the parent of the widgets under the Nested Layout Mangaer? 

4. In the Chapter on 'Dialogs', I am trying to create a QMainWindow Style 
application with one label as the central widget and one button to invoke a 
dialog. It doesn't work and I get:

QWidget::setLayout: Attempting to set QLayout "" on Parent "", which already 
has a layout

I tried this link and it made no sense:
https://stackoverflow.com/questions/25450598/qlayout-attempting-to-add-qlayout-to-qwidget-which-already-has-a-layout

How does parenting work in PyQt? What is autoparented, what needs to be 
explicitly parented and who is scrwing whom? Additionally, why is my button, 
hiding?


#!/usr/bin/python

import sys, os, re


from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)

class Dialog(QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)

self.lbl = QLabel('Width: ')
self.spn = QSpinBox()
self.spn.setRange(0, 100)
self.lbl.setBuddy(self.spn)

self.chk = QCheckBox('&Beveled Edges')

self.lbl_styl = QLabel('Style')
self.lst = QComboBox()
self.lst.addItems(['dashed', 'dotted', 'star'])
self.lbl_styl.setBuddy(self.lst)

self.ok_btn = QPushButton('&Ok')
self.cncl_btn = QPushButton('&Cancel')

self.layout([(self.lbl, 0, 0), (self.spn, 0, 1), (self.chk, 0, 2), 
 (self.lbl_styl, 1, 0), (self.lst, 1, 1), 
 (self.ok_btn, 2, 0), (self.cncl_btn, 2, 1)])

def layout(self, wgts = []):
self.lyt = QGridLayout()
for wgt, row, col in wgts:
self.lyt.addWidget(wgt, row, col)

self.setLayout(self.lyt)


class Parent(QMainWindow):
def __init__(self, parent = None):
super(Parent, self).__init__(parent)

lbl = QLabel('HELLO WORLD')
btn = QPushButton('&Start Dialog')
lbl.setBuddy(btn)

lyt = QHBoxLayout()
lyt.addWidget(lbl)
lyt.addWidget(btn)

self.setLayout(lyt)
self.connect(btn, SIGNAL('clicked()'), self.popup_dialog)

def popup_dialog(self):
x = Dialog(self)
if x.exec_():
print(x.spn.value())

p = Parent()
p.show()

app.exec_()


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


Re: PyQt: Parenting a Widget

2017-09-25 Thread Veek M
On Tuesday, September 26, 2017 at 11:18:54 AM UTC+5:30, Veek M wrote:
> Summary: Could someone explain widget and dialog parenting - the text book is 
> not making sense.
> ##
> I'm trying to understand widget parenting, from the book: Rapid GUI 
> Programming, pg 118, and thereabouts - he says:
> 
> A. All PyQt classes that derive from QObjectand this includes all the widgets,
> since QWidget is a QObject subclasscan have a “parent”.
> 
> B. PyQt automatically repar-
> ents the widgets that are laid out. So although we did not give our widgets a
> parent of self (the Form instance),when we call setLayout() the layout manager
> gives ownership of the widgets and of itself to the form,and takes ownership 
> of
> any nested layouts itself. This means that none of the widgets that are laid 
> out
> is a top-level window, and all of them have parents, which is what we want. So
> when the form is deleted, all its child widgets and layouts will be deleted 
> with
> -
> 1. In A, does he mean, you are ALLOWED to set a parent on a widget ONLY 
> because its Base Class is QObject? 
> 
> With DockWidgets, you have to explicitly parent them - why?
> 
> 2. If I create two widgets and wdget.show() them, and app.exec_() - which one 
> becomes the main-window and which one is the memory leak? I have not used a 
> layout manager so, one widget with no parent auto-becomes the main-window (as 
> per B), which would result in a leak with the other?
> 
> #!/usr/bin/python
> 
> import sys, os, re
> 
> 
> from PyQt4.QtCore import *
> from PyQt4.QtGui import *
> 
> app = QApplication(sys.argv)
> 
> lbl = QLabel('Hello World')
> lbl.setWindowFlags(Qt.SplashScreen)
> lbl.show()
> txtBrw = QTextBrowser()
> txtBrw.show()
> 
> QTimer.singleShot(3000, app.quit)
> app.exec_()
> 
> 3. QObject --> QWidget --> QDialog --> Form --> Form_Layout_Manager --> 
> Nested_Layout_Manager
> 
> B, says that the layout manager parents the widgets under it and makes 'Form' 
> the parent. If the Form Layout Manager is taking charge of the Nested Layout 
> Manager, who is the parent of the widgets under the Nested Layout Mangaer? 
> 
> 4. In the Chapter on 'Dialogs', I am trying to create a QMainWindow Style 
> application with one label as the central widget and one button to invoke a 
> dialog. It doesn't work and I get:
> 
> QWidget::setLayout: Attempting to set QLayout "" on Parent "", which already 
> has a layout
> 
> I tried this link and it made no sense:
> https://stackoverflow.com/questions/25450598/qlayout-attempting-to-add-qlayout-to-qwidget-which-already-has-a-layout
> 
> How does parenting work in PyQt? What is autoparented, what needs to be 
> explicitly parented and who is scrwing whom? Additionally, why is my button, 
> hiding?
> 
> 
> #!/usr/bin/python
> 
> import sys, os, re
> 
> 
> from PyQt4.QtCore import *
> from PyQt4.QtGui import *
> 
> app = QApplication(sys.argv)
> 
> class Dialog(QDialog):
> def __init__(self, parent = None):
> super(Dialog, self).__init__(parent)
> 
> self.lbl = QLabel('Width: ')
> self.spn = QSpinBox()
> self.spn.setRange(0, 100)
> self.lbl.setBuddy(self.spn)
> 
> self.chk = QCheckBox('&Beveled Edges')
> 
> self.lbl_styl = QLabel('Style')
> self.lst = QComboBox()
> self.lst.addItems(['dashed', 'dotted', 'star'])
> self.lbl_styl.setBuddy(self.lst)
> 
> self.ok_btn = QPushButton('&Ok')
> self.cncl_btn = QPushButton('&Cancel')
> 
> self.layout([(self.lbl, 0, 0), (self.spn, 0, 1), (self.chk, 0, 2), 
>  (self.lbl_styl, 1, 0), (self.lst, 1, 1), 
>  (self.ok_btn, 2, 0), (self.cncl_btn, 2, 1)])
> 
> def layout(self, wgts = []):
> self.lyt = QGridLayout()
> for wgt, row, col in wgts:
> self.lyt.addWidget(wgt, row, col)
> 
> self.setLayout(self.lyt)
> 
> 
> class Parent(QMainWindow):
> def __init__(self, parent = None):
> super(Parent, self).__init__(parent)
> 
> lbl = QLabel('HELLO WORLD')
> btn = QPushButton('&Start Dialog')
> lbl.setBuddy(btn)
> 
> lyt = QHBoxLayout()
> lyt.addWidget(lbl)
> lyt.addWidget(btn)
> 
> self.setLayout(lyt)
> self.connect(btn, SIGNAL('clicked()'

Re: PyQt: Parenting a Widget

2017-09-26 Thread Veek M
On Tuesday, September 26, 2017 at 2:23:22 PM UTC+5:30, Thomas Jollans wrote:
> On 2017-09-26 08:16, Veek M wrote:
> > On Tuesday, September 26, 2017 at 11:18:54 AM UTC+5:30, Veek M wrote:
> >> Summary: Could someone explain widget and dialog parenting - the text book 
> >> is not making sense.
> >> ##
> >> I'm trying to understand widget parenting, from the book: Rapid GUI 
> >> Programming, pg 118, and thereabouts - he says:
> >>
> >> A. All PyQt classes that derive from QObjectand this includes all the 
> >> widgets,
> >> since QWidget is a QObject subclasscan have a “parent”.
> >>
> >> B. PyQt automatically repar-
> >> ents the widgets that are laid out. So although we did not give our 
> >> widgets a
> >> parent of self (the Form instance),when we call setLayout() the layout 
> >> manager
> >> gives ownership of the widgets and of itself to the form,and takes 
> >> ownership of
> >> any nested layouts itself. This means that none of the widgets that are 
> >> laid out
> >> is a top-level window, and all of them have parents, which is what we 
> >> want. So
> >> when the form is deleted, all its child widgets and layouts will be 
> >> deleted with
> >> -
> >> 1. In A, does he mean, you are ALLOWED to set a parent on a widget ONLY 
> >> because its Base Class is QObject? 
> >>
> >> With DockWidgets, you have to explicitly parent them - why?
> >>
> >> 2. If I create two widgets and wdget.show() them, and app.exec_() - which 
> >> one becomes the main-window and which one is the memory leak? I have not 
> >> used a layout manager so, one widget with no parent auto-becomes the 
> >> main-window (as per B), which would result in a leak with the other?
> >>
> >> #!/usr/bin/python
> >>
> >> import sys, os, re
> >>
> >>
> >> from PyQt4.QtCore import *
> >> from PyQt4.QtGui import *
> >>
> >> app = QApplication(sys.argv)
> >>
> >> lbl = QLabel('Hello World')
> >> lbl.setWindowFlags(Qt.SplashScreen)
> >> lbl.show()
> >> txtBrw = QTextBrowser()
> >> txtBrw.show()
> >>
> >> QTimer.singleShot(3000, app.quit)
> >> app.exec_()
> >>
> >> 3. QObject --> QWidget --> QDialog --> Form --> Form_Layout_Manager --> 
> >> Nested_Layout_Manager
> >>
> >> B, says that the layout manager parents the widgets under it and makes 
> >> 'Form' the parent. If the Form Layout Manager is taking charge of the 
> >> Nested Layout Manager, who is the parent of the widgets under the Nested 
> >> Layout Mangaer? 
> >>
> >> 4. In the Chapter on 'Dialogs', I am trying to create a QMainWindow Style 
> >> application with one label as the central widget and one button to invoke 
> >> a dialog. It doesn't work and I get:
> >>
> >> QWidget::setLayout: Attempting to set QLayout "" on Parent "", which 
> >> already has a layout
> >>
> >> I tried this link and it made no sense:
> >> https://stackoverflow.com/questions/25450598/qlayout-attempting-to-add-qlayout-to-qwidget-which-already-has-a-layout
> >>
> >> How does parenting work in PyQt? What is autoparented, what needs to be 
> >> explicitly parented and who is scrwing whom? Additionally, why is my 
> >> button, hiding?
> >>
> >>
> >> #!/usr/bin/python
> >>
> >> import sys, os, re
> >>
> >>
> >> from PyQt4.QtCore import *
> >> from PyQt4.QtGui import *
> >>
> >> app = QApplication(sys.argv)
> >>
> >> class Dialog(QDialog):
> >> def __init__(self, parent = None):
> >> super(Dialog, self).__init__(parent)
> >> 
> >> self.lbl = QLabel('Width: ')
> >> self.spn = QSpinBox()
> >> self.spn.setRange(0, 100)
> >> self.lbl.setBuddy(self.spn)
> >> 
> >> self.chk = QCheckBox('&Beveled Edges')
> >>
> >> self.lbl_styl = QLabel('Style')
> >> self.lst = QComboBox()
> >> self.lst.addItems(['dashed', 'dotted', 'star'])
> >> self.lbl_styl.setBuddy(self.lst)
> >> 
> >> self.ok_btn = QPushButton('

Re: .0 in name

2022-05-28 Thread Ralf M.

Am 13.05.2022 um 23:23 schrieb Paul Bryan:

On Sat, 2022-05-14 at 00:47 +0800, bryangan41 wrote:


May I know (1) why can the name start with a number?


The name of an attribute must be an identifier. An identifier cannot
begin with a decimal number.


I'm not sure about the first statement. Feeding

[print("locals:", locals()) or c for c in "ab"]

to the REPL, the result is

locals: {'.0': , 'c': 'a'}
locals: {'.0': , 'c': 'b'}
['a', 'b']

i.e. there is a variable of name .0 in the local namespace within the 
list comprehension, and .0 is definitely not an identifier.


I came across this while investigating another problem with list 
comprehensions, and I think the original post was about list comprehensions.


There also can be non-identifier names in the global namespace and as 
attributes, e.g. using the REPL again:


globals()["42"] = "The Answer"
globals()

outputs (see last entry)

{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': , '__spec__': 
None, '__annotations__': {}, '__builtins__': (built-in)>, '42': 'The Answer'}


and

class Cls:
def __init__(self, lst):
for i, e in enumerate(lst):
self.__dict__[str(i)] = e

obj = Cls([31, 42, 53])
getattr(obj, "1")

works and outputs

42


(2) where in the doc is it?!


https://docs.python.org/3/reference/lexical_analysis.html#identifiers


That refers to identifiers, i.e. names that are recognised as such by 
the lexer, i.e. that can be written directly in Python source code.


As shown above, names that are not identifiers can be used in several 
namespaces and as attributes. It's just a bit harder to use 
non-identifier names than identifiers.

Whether it's a good idea to use them at all is a different question.

I think the OP wondered about the .0 in the local namespace within list 
comprehensions. Unfortunately I cannot say much about that.



Paul


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


How to replace an instance method?

2022-09-16 Thread Ralf M.
I would like to replace a method of an instance, but don't know how to 
do it properly.


My first naive idea was

inst = SomeClass()
def new_method(self, param):
# do something
return whatever
inst.method = new_method

however that doesn't work: self isn't passed as first parameter to
the new inst.method, instead inst.method behaves like a static method.

I had a closer look at the decorators classmethod and staticmethod.
Unfortunetely I couldn't find a decorator / function "instancemethod"
that turns a normal function into an instancemethod.

The classmethod documentation contains a reference to the standard
type hierarchie, and there is an explanation that an instancemethod
is sort of a dynamically created wrapper around a function, which
is accessable as __func__.
So I modified the last line of the example above to

inst.method.__func__ = new_method

but got told that __func__ is read only.

I found some information about methods in the Descriptor HowTo Guide,
but it's about how it works internally and doesn't tell how to solve
my problem (at least it doesn't tell me).

Now I'm running out of ideas what to try next or what sections of the
documentation to read next.

Any ideas / pointers?

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


Re: How to replace an instance method?

2022-09-17 Thread Ralf M.

Am 16.09.2022 um 23:34 schrieb Eryk Sun:

On 9/16/22, Ralf M.  wrote:

I would like to replace a method of an instance, but don't know how to
do it properly.


A function is a descriptor that binds to any object as a method. For example:

 >>> f = lambda self, x: self + x
 >>> o = 42
 >>> m = f.__get__(o)
 >>> type(m)
 
     >>> m.__self__ is o
 True
 >>> m(10)
 52


Thank you and Chris A. for the two suggestions how to replace a method.

I tried both
  inst.method = functools.partial(new_method, inst)
and
  inst.method = new_method.__get__(inst)
and both work in my toy example.
I will try it on the real code next week.

Even though the functools.partial solution is easier to understand (at
least for me), I will probably use the __get__ solution as it avoids
the import of an extra library.

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


Re: How to replace an instance method?

2022-09-17 Thread Ralf M.

Am 17.09.2022 um 00:35 schrieb Dan Stromberg:



On Fri, Sep 16, 2022 at 2:06 PM Ralf M. <mailto:[email protected]>> wrote:


I would like to replace a method of an instance, but don't know how to
do it properly.


You appear to have a good answer, but...  are you sure this is a good idea?


It's definitely a dirty hack.

It'll probably be confusing to future maintainers of this code, and I 
doubt static analyzers will like it either.


I agree that I will have to add sufficient comments for the future
maintainer, should there ever be one (and even for me to still
understand it next year). I don't use static analyzers.

I'm not the biggest fan of inheritance you'll ever meet, but maybe this 
is a good place for it?


Using a derived version of the class in question to overwrite the
method was my first idea, however I don't instantiate the class in
question myself, it is instantiated during the initialisation of
another class, so I would at least have to derive a modified version of
that as well. And that code is rather complex, with metaclasses and
custom decorators, and I feel uncomfortable messing with that, while
the method I intend to change is quite simple and straightforward.

In case anybody is interested what I'm trying to achieve:

It's simple in pandas to read an excel file into a dataframe, but only
the cell value is read. Sometimes I need more / other information, e.g.
some formatting or the hyperlink in a cell. Reopening the file with
openpyxl and getting the info is possible, but cumbersome.
Looking into the pandas code for reading excel files (which uses
openpyxl internally) I noticed a method (of an internal pandas class)
that extracts the value from an openpyxl cell. This method is rather
simple and seems the ideal spot to change to get what I want.

My idea is to instantiate pandas.ExcelFile (official pandas API), get
the reader instance (an attribute of the ExcelFile object) and modify
the method of the reader instance.

The fact that the method I change and the ExcelFile attribute containing
the reader are both private (start with _) doesn't make it any better,
but I'm desperate enough to be willing to adapt my code to every major
pandas release, if necessary.

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


Fwd: About the Python

2023-01-02 Thread Ramya M
-- Forwarded message -
From: Ramya M 
Date: Mon, Jan 2, 2023, 9:58 AM
Subject: About the Python
To: 


This is from JNN College of Engineering, Shimoga. we are facing some
problems while using python. Please can you resolve this issue.

We are using python 3.11.1 (64 bit) for windows 10. but while installing
the "numpy and matplotlib" packages we are getting errors. In some cases
after installation of the above said packages we are getting errors while
working.

So, Please can you people resolve this issue as the python labs are going
on and students are facing some difficulties.

Thanking you


Regards
Ramya M
Instructor, ECE Dept.
JNNCE, Shimoga
-- 
https://mail.python.org/mailman/listinfo/python-list


Incomplete sys.path with embeddable python (Windows)!?

2023-04-21 Thread Ralf M.

Hello,

when I run a script with a "normally" installed python, the directory 
the script resides in is automatically added as first element to 
sys.path, so that "import my_local_module" finds my_local_module.py in 
the directory of the script.


However, when I run the same script with embeddable python ("Windows 
embeddable package (64-bit)", download link
https://www.python.org/ftp/python/3.11.3/python-3.11.3-embed-amd64.zip) 
the script directory is *not* prepended to the path, thus "import 
my_local_module" gives an ImportError.


I couldn't find an option to get the "normal" behaviour. Any ideas how 
to do that?


What I tried so far:

* The start-up value for sys.path seems to be defined in python311._pth. 
It looks that I can add further static paths to it, but I don't know how 
to make it add the script path (which can be different for different 
scripts).


* Uncommenting "import site" in python311._pth doesn't help.

* It seems that I could import something else in python311._pth, but I 
don't know how something imported from there could find out the path of 
the script that is about to be started.


* I read the (rather short) documentation of the embeddable package and 
of the site module several times but couldn't recognize a hint as to how 
to solve the issue.


* I can add the following lines to every script:
import sys
script_path = __file__.rsplit("\\", 1)[0]
if script_path not in sys.path:
sys.path[0:0] = [script_path]
import my_local_modul
That works, but it's ugly, executing code between imports is frowned 
upon, and it needs to be added to every script.


Does anybody have a better idea?
Any help is appreciated.

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


Re: Incomplete sys.path with embeddable python (Windows)!?

2023-04-22 Thread Ralf M.

Am 21.04.2023 um 17:31 schrieb Mats Wichmann:

On 4/20/23 15:47, Ralf M. wrote:

Hello,

when I run a script with a "normally" installed python, the directory 
the script resides in is automatically added as first element to 
sys.path, so that "import my_local_module" finds my_local_module.py in 
the directory of the script.


However, when I run the same script with embeddable python ("Windows 
embeddable package (64-bit)", download link

https://www.python.org/ftp/python/3.11.3/python-3.11.3-embed-amd64.zip) the script 
directory is *not* prepended to the path, thus "import my_local_module" gives 
an ImportError.


This is intended behavior - the question comes up from time to time. The 
embeddable distribution is intended to be part of an application, not a 
general-purpose Python you can call for just anything.


There are a bunch of details here, for example:

https://github.com/python/cpython/issues/79022

Thank you for the pointer to the issue. I'll try to remove the ._pth 
completely (and see whether that breaks anything) and may have a look at 
the nuget.org package.


I can see that for many cases the behaviour is appropriate, but I had 
hoped that there is a configuration option for the cases where it is not.


About my use case:
There is a complex application package, consisting of some commercial 
and some freeware software, tied together with scripts in at least four 
different scripting languages. Now I intend to add further functionality 
in a fifth language, Python. The idea is to make the embeddedable 
package part of the application package and have scripts for the new 
functions. Several independent functions are to be added, each 
consisting of a script plus some local modules, and all of them should 
use the same python embedded into the application package.

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


Re: Incomplete sys.path with embeddable python (Windows)!?

2023-04-22 Thread Ralf M.

Am 22.04.2023 um 03:27 schrieb Greg Ewing via Python-list:

How are you invoking your script? Presumably you have some code
in your embedding application that takes a script path and runs
it. Instead of putting the code to update sys.path into every
script, the embedding application could do it before running
the script.


In principle a good idea, but I don't know how to do that:
The script is currently invoked by a .cmd file, but that may change to a 
shortcut (.lnk). This is what the embeddable package documentation calls 
"Python Application - simple approach".

To update sys.path on start up I would need to do something like
  C:\path\to\python.exe --add-path C:\s-path C:\s-path\script.py
but I couldn't find an option like --add-path.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Incomplete sys.path with embeddable python (Windows)!?

2023-04-22 Thread Ralf M.

Am 21.04.2023 um 18:07 schrieb Thomas Passin:

On 4/20/2023 5:47 PM, Ralf M. wrote:

Hello,

when I run a script with a "normally" installed python, the directory 
the script resides in is automatically added as first element to 
sys.path, so that "import my_local_module" finds my_local_module.py in 
the directory of the script.


However, when I run the same script with embeddable python ("Windows 
embeddable package (64-bit)", download link

https://www.python.org/ftp/python/3.11.3/python-3.11.3-embed-amd64.zip) the script 
directory is *not* prepended to the path, thus "import my_local_module" gives 
an ImportError.

I couldn't find an option to get the "normal" behaviour. Any ideas how 
to do that?


What I tried so far:
[...]
* I can add the following lines to every script:
 import sys
 script_path = __file__.rsplit("\\", 1)[0]
 if script_path not in sys.path:
 sys.path[0:0] = [script_path]
 import my_local_modul
[...] 


Thank your for your hints.

I haven't worked with embeddable python, but here are some possibilities 
that came to mind, depending on how your system works -


1. If your script is started from the command line, sys.argv[0] gives 
the path to the script; 
I didn't think of sys.argv[0] to get at the path; this might be quite 
useful, I'll try it out next week.


You could use os.path.dirname() to get its 
directory.  This will end up the same place as your code fragment, but 
looks nicer and handles different path separators (e.g., Linux vs Windows);
Yes, but it requires another import and the embedded package is only 
available for windows anyway, I think. I'll consider the idea, though.


2. You could write a little module that figures out the script's path 
and import that first in all your scripts.


3. If you know all the directories that your scripts will be in, you 
could add them all to a xx.pth file (do a search to make sure where to 
put .pth files for an embeddable case).
I thought about that, but for that to work all local modules across all 
script locations must have unique names, otherwise import might get hold 
of a module from the wrong directory. Certainly doable for a few 
scripts, but might become a source of hard to track errors when the 
number of scripts increases and later maintainers are not aware of the 
naming restriction.



[...}


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


Re: "py.ini" question

2021-04-25 Thread Ralf M.

Am 25.04.2021 um 16:30 schrieb Mats Wichmann:


On 4/24/21 2:57 PM, Chris Angelico wrote:
On Sun, Apr 25, 2021 at 5:57 AM Gisle Vanem  
wrote:


With 'py -3.6' or 'py 3.8' I get the expected.
But with 'py -3':
    Python 3.8.9 (default, Apr 13 2021, 15:54:59)  [GCC 10.2.0 64 bit 
(AMD64)] on win32


I believe that's because you're asking for "the latest in the 3.x 
series".


unless differently described by the ini file, which is what the OP is 
trying to do.


I just added a 3.10 alpha to my Windows setup (I don't do my programming 
there, so there hadn't been any need), and set up an ini file to leave 
3.9 as the default and all works as expected - py -0, py, py -3, py 
-3.10 all given me the one I would expect to get based on that setup (-0 
shows 3.9-64 starred, despite 3.10-64 being "the latest).


Personally stumped why it's not working for Gisle.


I think the problem / misunderstanding is that Gisle put in py.ini only
 [defaults]
 python=3.6

and expected this to make py -3 start 3.6. However py -3 looks for a key 
named 'python3' and, not finding it, uses default behaviour (ignoring 
the 'python' key), i.e. starts the most modern stable 3.x.


The py.ini documentation is a bit hard to find in the help file and hard 
to understand as the interesting part talks about environment variables 
and shebang line commands, not py.ini settings and py.exe parameters. 
However, the behaviour is the same in both cases and the relevant 
example is:


"If PY_PYTHON=3.1-32, the command python will use the 32-bit 
implementation of 3.1 whereas the command python3 will use the latest 
installed Python (PY_PYTHON was not considered at all as a major version 
was specified.)"


I tried the (rather insane) py.ini
 [defaults]
 python=3.7
 python2=3.8
 python4=2.7
and it works as documented (py -3 shows default behaviour as there is no 
'python3' in py.ini):


C:\>py
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 
64 bit(AMD64)] on win32

C:\>py -2
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 
bit (AMD64)] on win32

C:\>py -3
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 
bit (AMD64)] on win32

C:\>py -4
Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:19:08) [MSC v.1500 32 
bit (Intel)] on win32





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


Pandas: How does df.apply(lambda work to create a result

2021-05-26 Thread Veek M
t = pd.DataFrame([[4,9],]*3, columns=['a', 'b'])
   a  b
0  4  9
1  4  9
2  4  9

t.apply(lambda x: [x]) gives
a[[1, 2, 2]]
b[[1, 2, 2]]
How?? When you 't' within console the entire data frame is dumped but how are 
the individual elements passed into .apply()? I can't do lambda x,y: [x,y] 
because only 1 arg is passed so how does [4] generate [[ ]]

Also - this:
 t.apply(lambda x: [x], axis=1)
0[[139835521287488, 139835521287488]]
1[[139835521287488, 139835521287488]]
2[[139835521287488, 139835521287488]]
vey weird - what just happened??

In addition, how do I filter data eg:  t[x] = t[x].apply(lambda x: x*72.72) I'd 
like to remove numeric -1 contained in the column output of t[x]. 'filter' only 
works with labels of indices, i can't do t[ t[x] != -1 ] because that will then 
generate all the rows and I have no idea how that will be translate to 
within a .apply(lambda x... (hence my Q on what's going on internally)

Could someone clarify please.

(could someone also tell me briefly the best way to use NNTP and filter
out the SPAM - 'pan' and 'tin' don't work anymore afaik
[eternal-september]  and I'm using slrn currently - the SLang regex is 
weird within the kill file - couldn't get it to work - wound up killing
everything when I did
Subject: [A-Z][A-Z][A-Z]+
)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Selenium script - stuck - could someone take a look?

2021-05-29 Thread Veek M
On 2021-05-29, Veek M  wrote:

fixed div './/' vs '//'
-- 
https://mail.python.org/mailman/listinfo/python-list


Selenium script - stuck - could someone take a look?

2021-05-29 Thread Veek M


Script: http://paste.debian.net/1199271/

It mostly works but line 78 is supposed to extract 
100 pieces / lot No matter what I
try it's failed and I DON'T KNOW WHY? It's a simple div.classname
match..

Could someone take a look and figure it out - I'm stuck.




import re, sys, time

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

url = 'https://www.aliexpress.com'

caps = DesiredCapabilities().FIREFOX; caps["pageLoadStrategy"] = 'eager' 
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)

fh = open('/tmp/log.html', 'w')
fh.write(' parts\n\n')


def convert(m):
money = m.group()
return str(round(float(money) * 72.4, 3))

import re
def process_fields(txt):
if '$' in txt:
txt = txt.replace('+', '')
txt = txt.replace('$', '')
txt = txt.replace('US', '')
txt = txt.replace('Shipping:', '')
r = re.sub(r'(\s*[0-9]+\.[0-9]+)', convert, txt)
return str(r)

def ali_search(url, txt):
driver.get(url)
assert 'AliExpress' in driver.title

try:
srch_elem = WebDriverWait(driver, 3600, 
ignored_exceptions=ignored_exceptions).until( 
EC.presence_of_element_located((By.XPATH, '//div[@class="search-key-box"]')))
print('search')
x = driver.find_element_by_id('search-key')
if 'input' in x.tag_name:
print 'success'
finally:
for c in list(txt):
time.sleep(1)
x.send_keys(c)
x.send_keys(Keys.RETURN)

try:
element = WebDriverWait(driver, 3600, 
ignored_exceptions=ignored_exceptions).until( 
EC.presence_of_element_located((By.XPATH, '//div[@class="product-container"]')))
finally:
print('product-container')
x = driver.find_element_by_xpath('//body')
x.send_keys(Keys.HOME)

for i in range(1,10):
print('send END')
time.sleep(1)
x.send_keys(Keys.PAGE_DOWN)
time.sleep(1)
#driver.execute_script("window.scrollTo(0, 
document.body.scrollHeight);")


   # EC.presence_of_element_located((By.XPATH, '//div[contains(@class, " 
product-list")]')))
divs = element.find_elements_by_xpath('//li[@class="list-item 
packaging_sale"]')
for c, div in enumerate(divs):
fh.write('')
for param in ['price-current', 'item-price-row packaging-sale', 
'shipping-value', 'store-name']:
try:
if 'store' in param:
fh.write('' + 
div.find_elements_by_class_name(param)[0].text + '')
elif 'sale' in param:
print param
lot = div.find_elements_by_class_name(param)
fh.write('' + str(lot) + '')
else:
fh.write('' + 
process_fields(div.find_elements_by_class_name(param).text) + '')
except Exception as e:
fh.write('' + str(e) + '')
fh.write('\n')
fh.write('\n')
fh.close()


def part_lookup():
global driver
with webdriver.Firefox(executable_path=r'/mnt/sdb1/root/geckodriver', 
firefox_binary='/mnt/sdb1/firefox/firefox-bin', capabilities=caps) as driver:
if len(sys.argv) == 2:
ali_search(url, sys.argv[1])
time.sleep(3600)

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


Re: Selenium script - stuck - could someone take a look?

2021-05-29 Thread Veek M
On 2021-05-29, Dennis Lee Bieber  wrote:
> On Sat, 29 May 2021 09:40:35 - (UTC), Veek M  declaimed
> the following:
>

ah, yeah - man that took me a while to do (save to local file and use
file:///). It's working now, basically xpath mistake because I've
forgotten stuff.. but the script is almost complete and cleaned up..
Basically forgot that div.xpath('// doesn't use div as the root window -
thing starts the lookup from the very beginning. You got to .//

My "Next Page" is creating problems - asked here as well:
https://www.reddit.com/r/selenium/comments/nnrxuu/
what_is_overlay_backdrop_how_does_it_block_a/

def page_next():
tmp = driver.find_element_by_xpath('//button[contains(@class, 
" next-next")]')
tmp = driver.find_element_by_xpath('.//div[@class=
"next-overlay-backdrop")]')
#e = WebDriverWait(driver, 200).until(EC.element_to_be_clickable(
#(By.XPATH, "//button[contains(@class, ' next-next']"))).click()
#e.click()

if tmp: tmp.click()
else: raise SystemExit('no next')

 This is the error I get
 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: 
Element  is not clickable at 
point (699,649) because another element  
obscures it

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


Tree library that allows conditions on nodes and will return the node

2021-06-14 Thread Veek M
LibreOffice has a huge class tree and I need to familiarize myself with
it - trouble is, it won't fit on A4 because it has a flat hierarchy with
loads of leaf nodes.

I wanted to shove all the leaf nodes > x into a subgraph and style that
differently using Graphviz.

I tried treelib but while i can build and print a tree, AND figure out
the size for each level of the Tree, it won't give me the parent node
for a particular size.. So I know that level 3 has 7 children too much
but which is the jackass parentID responsible - no idea.

Graphviz has nice plotting and subgraphs and such but same problem - I
checked pydot which is a clone of Graphviz and I'm not sure what exactly
it does different from Graphviz..

Anyway I don't want to spend another two days checking out Plotly or
Pygraphviz.. can someone point me in the right direction?
-- 
https://mail.python.org/mailman/listinfo/python-list


Extend unicodedata with a name/pattern/regex search for character entity references?

2016-09-03 Thread Veek. M
https://mail.python.org/pipermail//python-ideas/2014-October/029630.htm

Wanted to know if the above link idea, had been implemented and if 
there's a module that accepts a pattern like 'cap' and give you all the 
instances of unicode 'CAP' characters.
 ⋂ \bigcap
 ⊓ \sqcap
 ∩ \cap
 ♑ \capricornus
 ⪸ \succapprox
 ⪷ \precapprox

(above's from tex)

I found two useful modules in this regard: unicode_tex, unicodedata
but unicodedata is a builtin which does not do globs, regexs - so it's 
kind of limiting in nature.

Would be nice if you could search html/xml character entity references 
as well.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Extend unicodedata with a name/pattern/regex search for character entity references?

2016-09-03 Thread Veek. M
Thomas 'PointedEars' Lahn wrote:

> Veek. M wrote:
> 
>> https://mail.python.org/pipermail//python-ideas/2014-October/029630.htm
>> 
>> Wanted to know if the above link idea,
> 
> … which is 404-compliant; the Internet Archive does not have it either
> …
> 
>> had been implemented
> 
> Probably not.
> 
>> and if there's a module that accepts a pattern like 'cap' and give
>> you all the instances of unicode 'CAP' characters.
> 
> I do not know any.
> 
>>  ⋂ \bigcap
>>  ⊓ \sqcap
>>  ∩ \cap
>>  ♑ \capricornus
>>  ⪸ \succapprox
>>  ⪷ \precapprox
>> 
>> (above's from tex)
>> 
>> I found two useful modules in this regard: unicode_tex, unicodedata
>> but unicodedata is a builtin which does not do globs, regexs - so
>> it's kind of limiting in nature.
> 
> Quick hack:
> 
> #
> from unicode_tex import unicode_to_tex_map
> 
> for key, value \
> in filter(lambda item: "cap" in item[1], unicode_to_tex_map.items()):
> print(key, value)
> #
> 
> (Optimizations are welcome.)
> 
> It is easy to come up with methods that take a globbing or a regular
> expression (globbing expressions can be turned into regular
> expressions easily) and returns, perhaps as a dictionary or list of
> tuples, only the matching entries.
> 
> Other than that I think you will have to turn the Unicode Character
> Database (which is available via HTTP as one huge text file; see the
> Python Tutorial on “Internet Access” for how to get it dynamically)
> into whatever form suits you for querying it.
>  
>> Would be nice if you could search html/xml character entity
>> references as well.
> 
> For what purpose?
> 
> Your posting is lacking a real name in the “From” header field.
> 

Ouch! Sorry for the bad link Thomas. The link is titled '[Python-ideas] 
Extend unicodedata with a name search' and I suspect this updated link 
data (http://code.activestate.com/lists/python-ideas/29504/) may work - 
if it doesn't you could google the title.

I don't want to dump/replicate the existing Unicode data in module 
'unicodedata'.

Regarding purpose, well I need this for hexchat. I IRC a lot and often, 
I want to ask a question involving math symbols. I've written some 
python (included at the bottom) that translates:
 \help filter_word #into a list of symbols and names 
(serves as a memory jog). It also translates stuff like:
 A \cap B \epsilon C to A ∩ B ε C.
but all this works with a subset of tex - it can't do complicated 
formula. I wanted to extend it further.. I don't think I shall be able 
to subscript integrals easily but I could make better use of the 
available unicode, which means making it more accessible (hence the 
pattern matching feature) - html/xml entities provide a new way of 
remembering stuff.

---
Regarding the name (From field), my name *is* Veek.M though I tend to 
shorten it to Vek.M on Google (i think Veek was taken or some such 
thing). Just to be clear, my parents call me something closely related 
to Veek that is NOT Beek or Peek or Squeak or Sneak and my official name 
is something really weird. Identity theft being what it is, I probably 
am lying anyhow about all this, but it sounds funny so :p

import hexchat
import re, unicode_tex, unicodedata

__module_name__ = 'Unicode'
__module_version__ = '0.1'
__module_description__ = 'Substitute \whatever with Unicode char in 
cmdline input'

#re_repl = unicodedata.lookup('N-ARY UNION')

def debug(*args):
hexchat.prnt('#{}#'.format(*args))

def print_help(*args):
hexchat.prnt('{}'.format(*args))

def send_message(word, word_eol, userdata):
if not(word[0] == "65293"):
return

msg = hexchat.get_info('inputbox')
if msg is None:
return

x = re.match(r'(^\\help)\s+(\w+)', msg)
if x:
filter = x.groups()[1]
for key, value in unicode_tex.tex_to_unicode_map.items():
if filter in key:
print_help(value + ' ' + key)
hexchat.command("settext %s" % '')
return

tex_matches = re.findall(r'(\\\w+)', msg)
for tex_word in tex_matches:
repl = unicode_tex.tex_to_unicode_map.get(tex_word)

if repl is None:
repl = 'err'

msg = re.sub(re.escape(tex_word), repl, msg)

hexchat.command("settext %s" % msg)

hexchat.hook_print('Key Press', send_message)


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


Re: Extend unicodedata with a name/pattern/regex search for character entity references?

2016-09-04 Thread Veek. M
Steve D'Aprano wrote:

> On Sun, 4 Sep 2016 06:53 pm, Thomas 'PointedEars' Lahn wrote:
> 
>>> Regarding the name (From field), my name *is* Veek.M […]
>> 
>> Liar.  *plonk*
> 
> You have crossed a line now Thomas.
> 
> That is absolutely uncalled for. You have absolutely no legitimate
> reason to believe that Veek is not his or her real name.
> 
> You owe Veek an apology, and a promise to the entire community that
> you will not act in such a bigoted, racist manner again.
> 
> 
> 

ah umm.. I'm not overly offended - it was more of a startle. I've gotten 
used to USENET, somewhat - nature of the beast. 

Here's a link: 
https://www.eff.org/deeplinks/2010/01/primer-information-theory-and-privacy

Apparently 33 bits of information are enough to identify you. I don't 
bother about the NSA, but plenty of shady scummy types around, so I tend 
to spread misinformation which *would* make me a big time liar. It's not 
a besetting sin.

Here's a link to my Youtube thingy: 
https://www.youtube.com/channel/UCj93gHgUt69R8oGE5hRXd9g

Really, if someone's feeling racist, hire someone of your own kind 
(whatever that is) to kick you and make you study - that way, you are 
more in control of your destiny. There's plenty of energy the sun kick 
out that just goes to waste. (Not the easiest thing to do - finding 
someone reliable enough to zap the toes, anyway..) It's rather 
unreasonable for humans to expect the Universe to spin around them 
indefinitely..

If there are trolls here, then:
https://www.psychologytoday.com/blog/your-online-secrets/201409/internet-trolls-are-narcissists-psychopaths-and-sadists
(scientific study of some sort)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Extend unicodedata with a name/pattern/regex search for character entity references?

2016-09-05 Thread Veek. M
Thomas 'PointedEars' Lahn wrote:

> Gregory Ewing wrote:
> 
>> Larry Hudson wrote:
>>> If you continue to read this forum, you will quickly learn to ignore
>>> "Pointy-Ears".  He rarely has anything worth while to post, and his
>>> unique fetish about Real Names shows him to be a hypocrite as well.
>> 
>> To be fair, it's likely that Thomas Lahn is his real
>> name,
> 
> Of course it is my real name.
> 
>> and he's never claimed that one shouldn't also
>> include a nickname in one's posted identifier.
> 
> In fact, I have recommended doing that several times to people who
> only used their nickname in the “From” header field value.
> 
>> So Veek should be able to appease P.E. by calling
>> himself 'Veek "David Smith" M'.
> 
> That would not help.  “Veek” might be (the transcription of) a given
> name or
> a family name, but “Veek M” is not a real name.  [Real name filter
> rules need to be adapted, though, because “O” is the transcription of
> an East Asian family name.]
> 
>> The quotes clearly mark the middle part as an invented addition, so
>> he's not lying,
> 
> He is lying and would be.  That is the main issue.  How can I trust a
> person who does not even have the decency and the courage to stand by
> their statements with their real name?
> 
>> and it looks enough like a Western style real name to avoid
>> triggering P.E.'s "fake name" reflex. :-)
> 
> It is not a reflex, but a request for something so basic that no
> request should be necessary: showing the simple politeness of
> introducing yourself properly when meeting strangers – of not lying to
> them about one’s identity – especially if one asks them for help.
> 

Ah! Now that's the root of his troubles, right there. Just in case 
anyone else is confused, I DON'T feel helped, thankful, grateful when 
someone answers my posts/questions. I expect you to have a whale of a 
good time when you post (I've always found it to be rather pleasant and 
fun to post). However I'm shhing on the subject of Thomas more or less 
permanently. This sort of humor works only when you're in a good mood 
and feeling chirpy, but that's not always the case so.. He's more or 
less Steve's baby anyhow (sorry Steve).




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


Pasting code into the cmdline interpreter

2016-09-21 Thread Veek M
I wanted to test this piece of code which is Kate (editor) on the cmd 
line python >>> prompt:

tex_matches = re.findall(r'(\\\w+{.+?})|(\\\w+)', msg)
for tex_word in tex_matches:
repl = unicode_tex.tex_to_unicode_map.get(tex_word)

if repl is None:
  repl = 'err'

msg = re.sub(re.escape(tex_word), repl, msg)


There are a number of difficulties i encountered.
1. I had to turn on  highlighting to catch mixed indent (which is a 
good thing anyways so this was resolved - not sure how tabs got in 
anyhow)
2. Blank lines in my code within the editor are perfectly acceptable for 
readability but they act as a block termination on cmd line. So if i 
paste:
tex_matches = re.findall(r'(\\\w+{.+?})|(\\\w+)', msg)
for tex_word in tex_matches:
repl = unicode_tex.tex_to_unicode_map.get(tex_word)

if repl is None:

I get:
 IndentationError: unexpected indent

How do i deal with this - what's the best way to achieve what I'm trying 
to do.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-21 Thread Veek M
Ben Finney wrote:

> Veek M  writes:
> 
>> 1. I had to turn on  highlighting to catch mixed indent (which
>> is a good thing anyways so this was resolved - not sure how tabs got
>> in anyhow)
> 
> The EditorConfig system is a growing consensus for configuring a code
> base to instruct text editors not to mangle it. See the EditorConfig
> site http://editorconfig.org/> for more information.
> 
> Sadly, it seems Kate does not yet recognise EditorConfig instructions
> https://bugs.kde.org/show_bug.cgi?id=330843>. In the meantime,
> manually configure Kate to only ever insert spaces to indent lines.
> 
>> 2. Blank lines in my code within the editor are perfectly acceptable
>> for readability but they act as a block termination on cmd line.
> 
> Yes. That is a deliberate compromise to make it easy to write code
> interactively at the interactive prompt.
> 
>> I get:
>>  IndentationError: unexpected indent
>>
>> How do i deal with this - what's the best way to achieve what I'm
>> trying to do.
> 
> Since you are writing code into a module file, why not just run the
> module from that file with the non-interactive Python interpreter?
> 
It's part of a hexchat plugin/addon.. like below (basically lots of 
hexchat crud interspersed. 

Anyway, i should hive it off into a separate function, and hide the 
import hexchat - still, bit of a pain.

import hexchat

def send_message(word, word_eol, userdata):
if not(word[0] == "65293"):
return

msg = hexchat.get_info('inputbox')
if msg is None:
return

x = re.match(r'(^\\help)\s+(\w+)', msg)
if x:
filter = x.groups()[1]
for key, value in unicode_tex.tex_to_unicode_map.items():
if filter in key:
print_help(value + ' ' + key)
hexchat.command("settext %s" % '')
return

# findall returns: [(,), (,), ...] or []
tex_matches = re.findall(r'((\\\w+){(.+?)})|(\\\w+)', msg)
if len(tex_matches) == 0: 
  return
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
eryk sun wrote:

> On Thu, Sep 22, 2016 at 5:12 AM, Veek M  wrote:
>> 2. Blank lines in my code within the editor are perfectly acceptable
>> for readability but they act as a block termination on cmd line.
> 
> You can write a simple paste() function. For example:
> 
> import sys
> paste = lambda: exec(sys.stdin.read(), globals())
> 
> >>> paste()
> class Foo:
> """test class"""
> 
> def spam(self):
> '''test method'''
> return 'eggs'
> 
> >>> Foo().spam()
> 'eggs'
> 
> In a Unix terminal and IDLE, stdin.read() is terminated by typing
> Ctrl+D at the start of an empty line. For the Windows console, it's
> Ctrl+Z, Enter. Actually in a Unix terminal the cursor can also be at
> the end of a line, but a bug in Python requires pressing Ctrl+D twice
> in that case.

ah! very clever and many thanks! so, you use .pythonrc.py to 
store/define your cmd-line shortcuts.

It doesn't work in python2.x, because exec is a stmt, so, def paste(
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
Ben Finney wrote:

> Veek M  writes:
> 
>> Ben Finney wrote:
>>
>> > Since you are writing code into a module file, why not just run the
>> > module from that file with the non-interactive Python interpreter?
>> > 
>> It's part of a hexchat plugin/addon..
> 
> Which tells me that it still isn't appropriate to copy-paste the code
> directly into the *interactive* Python interpreter. Instead, it's a
> module that should be imported from file, by Hexchat.
> 
> Unless I misunderstand what you're talking about?
> 
ah nope, you got it.
-- 
https://mail.python.org/mailman/listinfo/python-list


h(re) for help, import re - on NameError

2016-09-22 Thread Veek M
Is there a way to use .pythonrc.py to provide a help function that 
autoloads whatever module name is passed like so:
\>>> h(re)

I tried inheriting site._Helper and overriding __init__ and __call__ but 
that didn't work, also I don't know how to deal/trap/catch the NameError 
(no quotes on h(re)) - is there a way to insert a try/except block 
around the >>> prompt?

I hate having to: import whatever every-time i forget. Actually could I 
ditch the () in h(re) and just do: h re - the joy of that :p
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
eryk sun wrote:

> On Thu, Sep 22, 2016 at 12:40 PM, Gregory Ewing
>  wrote:
>> eryk sun wrote:
>>>
>>> Actually in a Unix terminal the cursor can also be at
>>> the end of a line, but a bug in Python requires pressing Ctrl+D
>>> twice in that case.
>>
>> I wouldn't call that a bug, rather it's a consequence of
>> what Ctrl-D does. It doesn't really mean EOF, it means to
>> send whatever the terminal driver has in its input buffer.
>> If the buffer is empty at the time, the process gets a
>> zero-length read which is taken as EOF. But if the buffer
>> is not empty, it just gets whatever is in the buffer.
>>
>> There's nothing Python can do about that, because it
>> never sees the Ctrl-D -- that's handled entirely by the
>> terminal driver.
> 
> Yes, FileIO.readall continues making read() system calls until it sees
> an empty read. But if we know we're reading from a terminal, we should
> be able to assume that a read either consumes an entire line up to a
> newline character or the entire buffer, no? In other words, if we see
> a read that returns less than the buffer size but doesn't end on a
> newline, then for a terminal, and only a terminal, I think we can
> infer Ctrl+D was typed and handle it as EOF.
 
read() changes it behavior intelligently according to the file type 
(pipe, fifo, etc). By default, from a terminal, it reads up to the first 
newline - canonical mode/cooked mode vs non-canonical mode (vi/less). 
Maybe python interpreter is doing the read in non-canonical mode?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: h(re) for help, import re - on NameError

2016-09-22 Thread Veek M
Chris Angelico wrote:

> On Thu, Sep 22, 2016 at 8:10 PM, Veek M  wrote:
>> Is there a way to use .pythonrc.py to provide a help function that
>> autoloads whatever module name is passed like so:
>> \>>> h(re)
>>
>> I tried inheriting site._Helper and overriding __init__ and __call__
>> but that didn't work, also I don't know how to deal/trap/catch the
>> NameError (no quotes on h(re)) - is there a way to insert a
>> try/except block around the >>> prompt?
>>
>> I hate having to: import whatever every-time i forget. Actually could
>> I ditch the () in h(re) and just do: h re - the joy of that :p
> 
> You could use sys.excepthook to catch the NameError. I don't know of a
> way to catch the SyntaxError and look at the original text, but with
> NameError it's pretty easy:
> 
> def excepthook(t,v,tb):
> if t is NameError:
> n = v.args[0].split("'")[1]
> globals()[n] = __import__(n)
> exec(tb.tb_frame.f_code, tb.tb_frame.f_globals)
> else:
> excepthook.old(t,v,tb)
> 
> import sys
> excepthook.old = sys.excepthook
> sys.excepthook = excepthook
> 
> Paste that into interactive Python and give it a try. Be aware that
> it'll attempt to import *any* dud name, so it'll potentially slow
> stuff down any time you typo. Also, it re-executes the current
> traceback frame, which may or may not be appropriate; it's fine for
> help(re), but not otherwise.
> 
> As an alternative, you could inspect tb.tb_frame.f_code to see if it
> matches "help(x)", and if it does, simply re-execute it with the
> string form of the name:
> 
> exec(tb.tb_frame.f_code, tb.tb_frame.f_globals, {n: n})
> 
> This works because help('re') does the same thing as help(re), so by
> effectively setting re="re", you gain that functionality without
> actually importing into the global namespace.
> 
> Adequately recognizing help(re) without false positives is left as an
> exercise for the reader. :)
> 
> ChrisA

works great :) - okay so you save and replace the default exception 
handler for the interpreter. Then when the procedure is called, check to 
see if type is NameError - if yes, then value contains the error string 
with module name, so you split and extract module name, and import the 
module and map it to a name in the global NS and hey presto (run the old 
code with the modified NS - that's a bit funky)!

Regarding fiddling with the code-object, yep, 
tb.tb_frame.f_code.co_names has a tuple ('h', 're') I suppose that's 
clean because it's your input after all vs splitting on something system 
generated (like an error message) 

works brilliantly - thanks :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print to previous line in console

2016-10-03 Thread Adam M
On Monday, October 3, 2016 at 12:46:41 PM UTC-4, Skip Montanaro wrote:
> On Mon, Oct 3, 2016 at 10:23 AM, udhay prakash pethakamsetty
> > Hi skip,
> >
> > I am unable to even install that curses package
> >
> >
> > C:\>pip install curses
> > Collecting curses
> >   Could not find a version that satisfies the requirement curses (from
> > versions: )
> > No matching distribution found for curses
> >
> >
> > I am using python 2.7.
> 
> You shouldn't have to install it. Unless your Python installation is
> defective in some regard, you should have it. That said, I don't do
> Windows, so perhaps curses isn't available there.
> 
> % python
> Python 2.7.2 (default, Nov 14 2012, 05:07:35)
> [GCC 4.4.6 [TWW]] on linux3
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import curses
> >>> curses.version
> '2.2'
> 
> Oh, and when asking for help, it's best to cc the mailing list, not
> just the person to whom you are responding. You get more timely -- and
> more complete -- help. In this case, I can't state authoritatively if
> curses is available on Windows. You also don't know that I didn't hit
> "send" on my original response then immediately head off to the North
> Woods for a week of hiking.
> 
> Skip

Because on Linux it is part of 2.7.x distribution. On Windows it is not.
You will need to download wheel from that place:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
And install it using PIP.

Regards
Adam

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


PyQT - Signals and Slots?

2016-10-10 Thread Veek M
I'm reading Rapid GUI Programming - Mark Summerfield with Python and QT 
pg 131. Basically the mechanism is an event table which maps a 'signal' 
to a 'function/slot' -correct?

  self.connect(dial, SIGNAL("valueChanged(int)"), spinbox.setValue)

Here, dial.valueChanged -> spinbox.setValue

 s.connect(w, SIGNAL("signalSignature"), functionName)
 s.connect(w, SIGNAL("signalSignature"), instance.methodName)
 s.connect(w, SIGNAL("signalSignature"), instance, 
SLOT("slotSignature"))

Here, w.signalSignature -> functionName
-> instance.methodName
-> instance.slotSignature

If signalSignature is a C++ implemented thingy then we got to pass type 
info as part of the mapping so "signalSignature(int, float, const char 
*). PyQT signals are any type and any number of args..


If the Slot-function is implemented in C++ it's better to use the SLOT() 
mechanism:
 self.connect(dial, SIGNAL("valueChanged(int)"), spinbox, 
SLOT("setValue(int)"))
Here, we are mapping dial.valueChanged(int) --> spinbox.setValue(int)


The part i found tricky was this:

class ZeroSpinBox(QSpinBox):
zeros = 0
def __init__(self, parent=None):
super(ZeroSpinBox, self).__init__(parent)
self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero)

def checkzero(self):
if self.value() == 0:
self.zeros += 1
self.emit(SIGNAL("atzero"), self.zeros)

ZeroSpinBox.valueChanged -> ZeroSpinBox.checkzero? Why is he mapping 
back to himself? Shouldn't it be widget-to-widget?

Then he raises a signal 'atzero' with one arg - the lack of a atzero() 
implies it's a 'short-circuit' signal so self.zeroes is a python data 
type. And in the book he says:

###
Here is how we connect to the signal in the form’s __init__() method:
zerospinbox = ZeroSpinBox()
...
self.connect(zerospinbox, SIGNAL("atzero"), self.announce)
Again, we must not use parentheses because it is a short-circuit signal. 
And
for completeness, here is the slot it connects to in the form:
def announce(self, zeros):
print "ZeroSpinBox has been at zero %d times" % zeros
###

Whaaa...t?? Could someone explain what exactly is his grand design 
besides being awfully circuitous? So he has some other Form thingy.. and 
in that he sets up another mapping from ZeroSpinBox.atzero --> 
ZeroSpinBox.announce  where's announce and atzero defined?





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


Re: PyQT - Signals and Slots?

2016-10-10 Thread Veek M
Mark Summerfield wrote:

> 
> The ZeroSpinBox is a tiny example designed to show how the signal/slot
> mechanism works. It is just a QSpinBox with the addition of
> remembering how many times (all the) ZeroSpinBox(es) have had a 0
> value.
> 
> Nowadays the connections would be made with a new improved syntax:
> 
> self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero) # OLD
> self.valueChanged.connect(self.checkzero) # NEW
> # or
> self.valueChanged[int].connect(self.checkzero) # NEW
> 
> Similarly the emit:
> self.emit(SIGNAL("atzero"), self.zeros) # OLD
> self.atzero.emit(self.zeros) # NEW
> 
> What's happening inside ZeroSpinBox? Whenever its value is set to 0 it
> calls its own checkzero() method, and this in turn emits an atzero
> signal with the number of zeros so far. Why does it do this? Just to
> show the mechanism. It doesn't matter whether you connect a widget to
> itself (unusual but done here), or to another widget (the norm).
> 
> See the book's website https://www.qtrac.eu/pyqtbook.html
> for all the source code including some updated with the new syntax.
> (But the book is old, so even the Python 3.1 examples aren't as
> Pythonic as they would be written in Python 3.4+.)

ah - okay, so i was on the right track - thanks :) cool that you hang 
out here :) 
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >