How to group list of list with condition in Python

2014-11-19 Thread Gundala Viswanath
I have the following list of lists that contains 6 entries:

lol = [['a', 3, 1.01], ['x',5, 1.00],['k',7, 2.02],['p',8, 3.00],
['b', 10, 1.09],
   ['f', 12, 2.03]]

each list in lol contain 3 elements:

['a', 3, 1.01]
  e1  e2   e3

The list above is already sorted according to the e2 (i.e, 2nd element)

I'd like to 'cluster' the above list following roughly these steps:

1. Pick the lowest entry (wrt. e2) in lol as the key of first cluster
2. Assign that as first member of the cluster (dictionary of list)
3. Calculate the difference current e3 in next list with first member
of existing clusters.
3. If the difference is less than threshold, assign that list as the
member of the corresponding cluster Else, create new cluster with
current list as new key.
3. Repeat the rest until finish

The final result will look like this, with threshold <= 0.1.

dol = {'a':['a','x','b'], 'k':['k','f'], 'p':['p']}

I'm stuck with this step what's the right way to do it:

__BEGIN__
import json
from collections import defaultdict

thres = 0.1
tmp_e3 = 0
tmp_e1 = "-"

lol = [['a', 3, 1.01], ['x',5, 1.00],['k',7, 2.02],
   ['p',8, 3.00], ['b', 10, 1.09], ['f', 12, 2.03]]

dol = defaultdict(list)
for thelist in lol:
e1, e2, e3 = thelist

if tmp_e1 == "-":
tmp_e1 = e1
else:
diff = abs(tmp_e3 - e3)
if diff > thres:
tmp_e1 = e1

dol[tmp_e1].append(e1)
tmp_e1 = e1
tmp_e3 = e3

print json.dumps(dol, indent=4)
__END__

Best,
G.v.
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: eGenix mxODBC Connect 2.1.1 - Python Database Interface

2014-11-19 Thread eGenix Team: M.-A. Lemburg

ANNOUNCING
  eGenix.com mxODBC Connect

  Python Database Interface

Version 2.1.1


 mxODBC Connect is our commercially supported client-server product for
   connecting Python applications to relational databases
 in a truly platform independent way.


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mxODBC-Connect-2.1.1-GA.html


INTRODUCTION

The mxODBC Connect Database Interface for Python allows users to
easily connect Python applications to all major databases on the
market today in a highly portable, convenient and secure way.

Python Database Connectivity the Easy Way
-

Unlike our mxODBC Python extension, mxODBC Connect is designed as
client-server application, so you no longer need to find production
quality ODBC drivers for all the platforms you target with your Python
application.

Instead you use an easy to install royalty-free Python client library
which connects directly to the mxODBC Connect database server over the
network.

This makes mxODBC Connect a great basis for writing cross-platform
multi-tier database applications and utilities in Python, especially
if you run applications that need to communicate with databases such
as MS SQL Server and MS Access, Oracle Database, IBM DB2 and Informix,
Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many
more, that run on Windows or Linux machines.

Ideal for Database Driven Client Applications
-

By removing the need to install and configure ODBC drivers on the
client side and dealing with complicated network setups for each set
of drivers, mxODBC Connect greatly simplifies deployment of database
driven client applications, while at the same time making the network
communication between client and database server more efficient and
more secure.

For more information, please have a look at the mxODBC Connect product
page, in particular, the full list of available features.

For more information, please see the product page:

http://www.egenix.com/products/python/mxODBCConnect/


NEWS

mxODBC Connect 2.1.0 is a patch level release of our successful mxODBC
Connect product. We have put great emphasis on enhancing the TLS/SSL
setup of the mxODBC Connect product, addressing recent attacks on
SSLv3 and improving the security defaults.

Security Enhancements
-

 * Updated included eGenix pyOpenSSL to 0.13.6, which includes OpenSSL
   1.0.1j and enables the TLS_FALLBACK_SCSV protection against
   protocol downgrade attacks.

 * OpenSSL cipher string list updated to use the best available
   ciphers in OpenSSL 1.0.1j per default and support perfect forward
   security.

 * OpenSSL context options setup to disallow weak protocol features.

 * Disabled SSLv3 for the mxODBC Connect Client in response to the
   recent POODLE attack on SSLv3.

   mxODBC Connect Client 2.1.1 will not be able to communicate with
   mxODBC Connect Server 2.1.0 and earlier when using SSL mode. The
   error message looks like this: [Error] [('SSL routines',
   'SSL23_GET_SERVER_HELLO', 'unsupported protocol')] (using
   pyOpenSSL) or [SSLError] [Errno 1] _ssl.c:493: error:1408F10B:SSL
   routines:SSL3_GET_RECORD:wrong version number (using the ssl
   module).

 * Enabled TLS v1, v1.1 and v1.2 for the mxODBC Connect Server in SSL
   mode and have it use the best possible protocol when talking to a
   client.

   The server will still support SSLv3 for backwards compatibility
   reasons, since older mxODBC Connect Clients only support
   SSLv3. This will be changed in the next major/minor mxODBC Connect
   Server release.

 * Fixed a linker setting on Linux to have the mxODBC Connect Server
   use the embedded OpenSSL libraries instead of the system ones.

 * Improved the protocol handlers for SSL connection setups using
   mixed plain text/TLS connections to renew the session id after
   having established the TLS session.

mxODBC Connect Enhancements
---

 * Fixed a problem where connection/cursor.messages could not be
   accessed from the client side.

 * mxODBC Connect Client is now also available as web installer,
   greatly simplifying the installation of the client. It is now
   possible to install the client using a single pip command:

   pip install egenix-mx-base egenix-mxodbc-connect-client egenix-pyopenssl

 * Upgraded eGenix PyRun used for mxODBC Connect Server on Linux to
   2.0.1.

 * Upgraded the Python version used for mxODBC Connect Server on
   Windows to 2.7.8.

Asynchronous Processing
---

 * Fixed a problem which prevented the mxOD

tkinter mainloop

2014-11-19 Thread ast

Hello

mainloop() is a window method which starts the event manager 
which tracks for events (mouse, keyboard ...) to be send to the 
window.


But if I forget the root.mainloop() in my program, it works well 
anyway, I cant see any failure. Why ?


Second question, is it possible to cancel a mainloop() ?

I neeed this feature because I have a main window "root = Tk()"
which opens a Toplevel secondary window "top = Toplevel()"
and I would like root window to be frozen while the user fills
the top window. 


thx


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


Re: How to group list of list with condition in Python

2014-11-19 Thread Peter Otten
Gundala Viswanath wrote:

> I have the following list of lists that contains 6 entries:
> 
> lol = [['a', 3, 1.01], ['x',5, 1.00],['k',7, 2.02],['p',8, 3.00],
> ['b', 10, 1.09],
>['f', 12, 2.03]]
> 
> each list in lol contain 3 elements:
> 
> ['a', 3, 1.01]
>   e1  e2   e3
> 
> The list above is already sorted according to the e2 (i.e, 2nd element)
> 
> I'd like to 'cluster' the above list following roughly these steps:
> 
> 1. Pick the lowest entry (wrt. e2) in lol as the key of first cluster
> 2. Assign that as first member of the cluster (dictionary of list)
> 3. Calculate the difference current e3 in next list with first member
> of existing clusters.
> 3. If the difference is less than threshold, assign that list as the
> member of the corresponding cluster Else, create new cluster with
> current list as new key.
> 3. Repeat the rest until finish
> 
> The final result will look like this, with threshold <= 0.1.
> 
> dol = {'a':['a','x','b'], 'k':['k','f'], 'p':['p']}
> 
> I'm stuck with this step what's the right way to do it:
> 
> __BEGIN__
> import json
> from collections import defaultdict
> 
> thres = 0.1
> tmp_e3 = 0
> tmp_e1 = "-"
> 
> lol = [['a', 3, 1.01], ['x',5, 1.00],['k',7, 2.02],
>['p',8, 3.00], ['b', 10, 1.09], ['f', 12, 2.03]]
> 
> dol = defaultdict(list)
> for thelist in lol:
> e1, e2, e3 = thelist
> 
> if tmp_e1 == "-":
> tmp_e1 = e1
> else:
> diff = abs(tmp_e3 - e3)
> if diff > thres:
> tmp_e1 = e1
> 
> dol[tmp_e1].append(e1)
> tmp_e1 = e1
> tmp_e3 = e3
> 
> print json.dumps(dol, indent=4)
> __END__

I won't provide the complete solution for a homework question, but here's 
the idea that let me to working code:

Introduce a helper list (let's call it `pairs`) where you put (e1, e3) 
tuples (called `inner_e1`, `inner_e3` below).

Inside the loop over `lol` loop over `pairs` -- and if you find an item 
where the inner_e3 is close enough to e3 you stop and use the inner_e1 as 
the key: 

dol[inner_e1].append(e1)

If there is no inner_e3 close enough you add another item to pairs and a new 
key to dol:

pairs.append((e1, e3))
dol[e1] = [e1]

Hints: `for ... else` with a `break` thrown in fits the above description 
for the inner loop nicely.

Note that this 2-loop approach is not very efficient if the number of 
clusters is large -- but first make it work, then -- maybe -- make it fast.

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


Re: tkinter mainloop

2014-11-19 Thread Terry Reedy

On 11/19/2014 3:46 AM, ast wrote:

Hello

mainloop() is a window method which starts the event manager which
tracks for events (mouse, keyboard ...) to be send to the window.

But if I forget the root.mainloop() in my program, it works well anyway,
I cant see any failure. Why ?

Second question, is it possible to cancel a mainloop() ?


The one loop should been handling all events for all windows.


I neeed this feature because I have a main window "root = Tk()"
which opens a Toplevel secondary window "top = Toplevel()"
and I would like root window to be frozen while the user fills
the top window.


There are methods for freezing a widget.  Something like root.withdraw. 
 But there is more than one for doing slightly different things.


--
Terry Jan Reedy

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


Re: How modules work in Python

2014-11-19 Thread Steven D'Aprano
Larry Hudson wrote:

> Your example may look the same (it uses the same dot syntax), but here it
> is to resolve a namespace -- a module is not an object.  So yes, this is
> still a function and not a method.  But we're getting rather pedantic
> here.


But not pedantic enough. Modules are, in fact, objects. All values in Python
are objects, including classes themselves! But modules are merely instances
of ModuleType:


py> import types
py> isinstance(types, types.ModuleType)
True
py> print(types)




The *simple* answer is that when you define a function inside the body of a
class, Python "magically" turns it into a method. But the *pedantic* answer
has to do with the descriptor protocol, and that is quite pedantic indeed.

A *simplified* description of the pedantic answer:

When you look up an attribute, say obj.attr, Python checks 
whether the attribute has a __get__ method. If it does, 
rather than return that object itself, Python returns the 
result of calling __get__. Functions have a __get__ method,
and so they are descriptors.  The __get__ method of functions
returns a method object.


Here's an example. Let's define a class with a function inside it, and an
instance:

py> class X(object):
... def method(self):
... return "spam"
... 
py> instance = X()


If we look inside the class __dict__, we can see the original function:

py> X.__dict__['method']



If we look at that function, we see it has a __get__ method:

py> f = X.__dict__['method']
py> f.__get__



Calling that __get__ method returns a method object:

py> f.__get__(instance, X)
>


which is what a normal attribute lookup does:

py> instance.method
>


Now, the twist: when you store an object in the *instance* __dict__, the
descriptor protocol doesn't get invoked. So when you have a function in a
module, it is stored in the instance dictionary and looking up module.func
does not call __get__ and does not return a method, it just returns the
function.

The same thing applies to non-modules too. If you define a function inside
the body of a class, it is stored in the class __dict__, but if you store
it in the instance __dict__, it never gets converted to a method.


You can read up on descriptors here:

https://docs.python.org/3/howto/descriptor.html



-- 
Steven

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


Re: Trouble getting full response content from PATCH request

2014-11-19 Thread John Gordon
In  Cameron Simpson 
 writes:

> >The API uses the HTTP PATCH operation to set user passwords, and in
> >case of unacceptable passwords, the response is supposed to be an HTML
> >document containing a diagnostic message in the  tag.
> >
> >When I submit my test data via a functional testing tool (SoapUI), it
> >behaves as expected.
> >
> >However, when I submit test data from Python code, the response content
> >consists only of the diagnostic message, with no enclosing  or 
> >tags.
> [...]

> You need a "SOAPAction: " HTTP header with SOAP requests. It may be that 
> simple.

The API does provide some SOAP calls, but the specific call I'm using is
REST.  Is there a corresponding header I should use?

Thanks.

-- 
John Gordon Imagine what it must be like for a real medical doctor to
[email protected] 'House', or a real serial killer to watch 'Dexter'.

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


Re: How modules work in Python

2014-11-19 Thread sohcahtoa82
On Tuesday, November 18, 2014 11:44:53 PM UTC-8, Larry Hudson wrote:
> On 11/18/2014 12:59 PM, [email protected] wrote:
> > On Tuesday, November 18, 2014 12:14:15 AM UTC-8, Larry Hudson wrote:
> >> First, I'll repeat everybody else:  DON'T TOP POST!!!
> >>
> >> On 11/16/2014 04:41 PM, Abdul Abdul wrote:
> >>> Dave,
> >>>
> >>> Thanks for your nice explanation. For your answer on one of my questions:
> >>>
> >>> *Modules don't have methods. open is an ordinary function in the module.*
> >>>
> >>> Isn't "method" and "function" used interchangeably? In other words, 
> >>> aren't they the same thing?
> >>> Or, Python has some naming conventions here?
> >>>
> >>
> >> You've already received answers to this, but a short example might clarify 
> >> the difference:
> >>
> >> #---  Code  
> >> #   Define a function
> >> def func1():
> >>   print('This is function func1()')
> >>
> >> #   Define a class with a method
> >> class Examp:
> >>   def func2(self):
> >>   print('This is method func2()')
> >>
> >> #   Try them out
> >> obj = Examp()  #  Create an object (an instance of class Examp)
> >> func1()#  Call the function
> >> obj.func2()#  Call the method through the object
> >> func2()#  Try to call the method directly -- Error!
> >> #---  /Code  
> >>
> >> This code results in the following:
> >>
> >> This is function func1()
> >> This is method func2()
> >> Traceback (most recent call last):
> >> File "fun-meth.py", line 14, in 
> >>   func2()
> >> NameError: name 'func2' is not defined
> >>
> >>-=- Larry -=-
> >
> > You COULD have something like this though:
> >
> > # --- myModule.py ---
> > def myFunc():
> >  print 'myFunc'
> >
> >
> > # --- main.py ---
> > import myModule
> > myModule.myFunc()
> >
> >
> > In this case, myFunc LOOKS like a method when it is called from main.py, 
> > but it is still a function.
> >
> 
> My purpose was to give a _simple_ example of the difference in the two terms: 
>  that a function 
> is called directly and a method is called through an object.
> 
> Your example may _look_ the same (it uses the same dot syntax), but here it 
> is to resolve a 
> namespace -- a module is not an object.  So yes, this is still a function and 
> not a method.  But 
> we're getting rather pedantic here.
> 
>   -=- Larry -=-

I only started reading this list about a month ago, and from what I've seen, 
being pedantic is pretty much par for the course.
-- 
https://mail.python.org/mailman/listinfo/python-list


Potential pitfalls when going from old-style to new-style classes

2014-11-19 Thread Skip Montanaro
I discussion on the code-quality list got me thinking. Suppose I have
an old-style class in a 2.x app:

class Foo:
  def __init__(self):
blah blah blah

I still use 2.x exclusively, but anytime I run pylint over a bit of
code and it complains that Foo is old-school, I make the obvious
change to inherit from object. While I do this mostly to shut up
pylint so I can focus on more serious messages, I must admit I have
never experienced any problem changing from old-style to new-style
classes. Under what circumstances might this be problematic?

Thx,

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


Re: Potential pitfalls when going from old-style to new-style classes

2014-11-19 Thread Ethan Furman
On 11/19/2014 11:14 AM, Skip Montanaro wrote:
> I discussion on the code-quality list got me thinking. Suppose I have
> an old-style class in a 2.x app:
> 
> class Foo:
>   def __init__(self):
> blah blah blah
> 
> I still use 2.x exclusively, but anytime I run pylint over a bit of
> code and it complains that Foo is old-school, I make the obvious
> change to inherit from object. While I do this mostly to shut up
> pylint so I can focus on more serious messages, I must admit I have
> never experienced any problem changing from old-style to new-style
> classes. Under what circumstances might this be problematic?

One problem is if your class has dunder methods on the instance -- they will be 
ignored.

class Foo(object):
   def __init__(self):
   self.__add__ = lambda : 'whatever'

dunder methods are looked up on the class.

--
~Ethan~



signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Potential pitfalls when going from old-style to new-style classes

2014-11-19 Thread Chris Kaynor
On Wed, Nov 19, 2014 at 11:14 AM, Skip Montanaro 
wrote:

> I discussion on the code-quality list got me thinking. Suppose I have
> an old-style class in a 2.x app:
>
> class Foo:
>   def __init__(self):
> blah blah blah
>
> I still use 2.x exclusively, but anytime I run pylint over a bit of
> code and it complains that Foo is old-school, I make the obvious
> change to inherit from object. While I do this mostly to shut up
> pylint so I can focus on more serious messages, I must admit I have
> never experienced any problem changing from old-style to new-style
> classes. Under what circumstances might this be problematic?
>

Under most common cases, its as trivial as just subclassing object, however
there are some oddities:

   - The main case errors may pop up is with multiple inheritance (MRO was
   changed).
   - If you are accessing or have defined magic methods.
  - For example, overriding __call__ on a specific instance will no
  work with new-style classes, but will work with old-style
classes. Defining
  it on the class (the common case) works the same in both cases.
  - A number of new magic properties were added, __slots__ and __mro__.
  So if those are being defined (they shouldn't - all dunder names are
  reserved by Python) it could change behavior oddly.

It looks like
http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python
has some decent answers to your question.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access Qt components loaded from file?

2014-11-19 Thread Juan Christian
Let's say that I want to call the site in a 5min interval. I'm currently
getting the info this way just for testing and to know that the 'core
engine' is working, and indeed, it's working:

if __name__ == "__main__":
import sys

app = QApplication(sys.argv)
MainWindow = loadui("main.ui")

def output_slot():
MainWindow.txtbox.setText(call_site())

MainWindow.btn.clicked.connect(output_slot)

MainWindow.show()
app.exec_()

How can I proceed if I want the txtbox to automatically do the
'setText(call_site())' in a X defined interval? The final app will have not
only a txtbox, but a complete interface with buttons, avatar image, some
txtboxes, and all that stuff. If I know how to "call the site" in a defined
interval, I can get all the info that I need and set them one by one.

If I'm not mistaken my app is locked in the app.exec_() loop, so I need to
have a trigger configured that will be called in a defined interval, then
inside this trigger I configure the "set_avatar", "set_text",
"set_btn_link", etc, is that right?

On Tue Nov 18 2014 at 9:37:21 PM Chris Angelico  wrote:

> On Wed, Nov 19, 2014 at 5:15 AM, Juan Christian
>  wrote:
> >
> > Thanks, it's working. What would be a "professional" approach if I want
> to
> > constantly call a URL to get it's content and access this data within the
> > GUI?
> >
>
> "Constantly" doesn't make much sense when you're talking about network
> operations. There are two basic approaches: either you re-fetch
> periodically and update the GUI (in which case you have to decide how
> frequently), or you re-fetch on some trigger (when it's changed, or
> when the user's about to need it, or something). Either way, you have
> to balance network traffic versus promptness of update, and it's
> nearly impossible to pick perfectly. But if you don't mind it being a
> little clunky, you should be able to pick something fairly simple and
> deploy it, and then maybe refine it a bit afterward.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to access Qt components loaded from file?

2014-11-19 Thread Rob Gaddi
On Wed, 19 Nov 2014 20:47:31 +
Juan Christian  wrote:

> Let's say that I want to call the site in a 5min interval. I'm currently
> getting the info this way just for testing and to know that the 'core
> engine' is working, and indeed, it's working:
> 
> if __name__ == "__main__":
> import sys
> 
> app = QApplication(sys.argv)
> MainWindow = loadui("main.ui")
> 
> def output_slot():
> MainWindow.txtbox.setText(call_site())
> 
> MainWindow.btn.clicked.connect(output_slot)
> 
> MainWindow.show()
> app.exec_()
> 
> How can I proceed if I want the txtbox to automatically do the
> 'setText(call_site())' in a X defined interval? The final app will have not
> only a txtbox, but a complete interface with buttons, avatar image, some
> txtboxes, and all that stuff. If I know how to "call the site" in a defined
> interval, I can get all the info that I need and set them one by one.
> 
> If I'm not mistaken my app is locked in the app.exec_() loop, so I need to
> have a trigger configured that will be called in a defined interval, then
> inside this trigger I configure the "set_avatar", "set_text",
> "set_btn_link", etc, is that right?
> 
> On Tue Nov 18 2014 at 9:37:21 PM Chris Angelico  wrote:
> 
> > On Wed, Nov 19, 2014 at 5:15 AM, Juan Christian
> >  wrote:
> > >
> > > Thanks, it's working. What would be a "professional" approach if I want
> > to
> > > constantly call a URL to get it's content and access this data within the
> > > GUI?
> > >
> >
> > "Constantly" doesn't make much sense when you're talking about network
> > operations. There are two basic approaches: either you re-fetch
> > periodically and update the GUI (in which case you have to decide how
> > frequently), or you re-fetch on some trigger (when it's changed, or
> > when the user's about to need it, or something). Either way, you have
> > to balance network traffic versus promptness of update, and it's
> > nearly impossible to pick perfectly. But if you don't mind it being a
> > little clunky, you should be able to pick something fairly simple and
> > deploy it, and then maybe refine it a bit afterward.
> >
> > ChrisA
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >
> 
You'd use a QTimer to do that.  Once you .start(5*60*1000) the
timer, it'll fire a timeout signal every 5 minutes.  You connect that
timeout to the slots you want to execute if you don't care about order,
or to a single slot function that runs the things that you want to do in
some defined order.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Working with HTML5 documents

2014-11-19 Thread Denis McMahon
So what I'm looking for is a method to create an html5 document using "dom 
manipulation", ie:

doc = new htmldocument(doctype="HTML")
html = new html5element("html")
doc.appendChild(html)
head = new html5element("body")
html.appendChild(head)
body = new html5element("body")
html.appendChild(body)
title = new html5element("title")
txt = new textnode("This Is The Title")
title.appendChild(txt)
head.appendChild(title)
para = new html5element("p")
txt = new textnode("This is some text.")
para.appendChild(txt)
body.appendChild(para)

print(doc.serialise())

generates:

This Is The TitleThis is some text.

I'm finding various mechanisms to generate the structure from an existing 
piece of html (eg html5lib, beautifulsoup etc) but I can't seem to find 
any mechanism to generate, manipulate and produce html5 documents using 
this dom manipulation approach. Where should I be looking?

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error when trying to open an image

2014-11-19 Thread Denis McMahon
On Mon, 17 Nov 2014 02:03:01 +0100, Abdul Abdul wrote:

> Thanks for your kind reply. Yes, it seemed it worked with an older
> version than 3.x
> 
> I got the following output:
> 
> Process finished with exit code 0
> 
> So, what is the purpose of open() here?

*STOP TOP-POSTING! IT@S GETTING ANNOYING NOW!*

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Working with HTML5 documents

2014-11-19 Thread Novocastrian_Nomad
On Wednesday, November 19, 2014 2:08:27 PM UTC-7, Denis McMahon wrote:
> So what I'm looking for is a method to create an html5 document using "dom 
> manipulation", ie:
> 
> doc = new htmldocument(doctype="HTML")
> html = new html5element("html")
> doc.appendChild(html)
> head = new html5element("body")
> html.appendChild(head)
> body = new html5element("body")
> html.appendChild(body)
> title = new html5element("title")
> txt = new textnode("This Is The Title")
> title.appendChild(txt)
> head.appendChild(title)
> para = new html5element("p")
> txt = new textnode("This is some text.")
> para.appendChild(txt)
> body.appendChild(para)
> 
> print(doc.serialise())
> 
> generates:
> 
> This Is The Title head>This is some text.
> 
> I'm finding various mechanisms to generate the structure from an existing 
> piece of html (eg html5lib, beautifulsoup etc) but I can't seem to find 
> any mechanism to generate, manipulate and produce html5 documents using 
> this dom manipulation approach. Where should I be looking?
> 
> -- 
> Denis McMahon,

Use a search engine (Google, DuckDuckGo etc) and search for 'python write html'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How modules work in Python

2014-11-19 Thread Chris Angelico
On Thu, Nov 20, 2014 at 6:00 AM,   wrote:
> I only started reading this list about a month ago, and from what I've seen, 
> being pedantic is pretty much par for the course.

Usually in a good way. :)

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


about suds and soap and parameters.

2014-11-19 Thread JustSomeGuy
I'm trying to call a soap method with suds.
The parameter however is not straight forward.


queryContent (
xs:string mpiId, 
tmPidAndIssuer[] idsAndIssuers, 
tmPersonName name, 
xs:string patientAge, 
tmAccessionNumberAndIssuer accNumAndIssuer, 
xs:string studyUID,
xs:string studyID, 
tmDateRange studyDateRange, 
xs:string studyDescription, 
xs:string[] modalities, 
xs:string stmo, 
xs:string folderName, 
xs:string folderDescription, 
tmDateRange folderDateRange, 
xs:string[] labels
)

What are these xs: ?
there seems to be other other types defined here that I'm not sure what they 
are.

  

-- 

--
If you believe you have received this electronic transmission in error, 
please notify the original sender of this email and destroy all copies of 
this communication.
-- 
https://mail.python.org/mailman/listinfo/python-list


Is StopIteration a singleton?

2014-11-19 Thread Chris Angelico
While poking about the cpython source tree with reference to PEP 479,
I came across this:

https://docs.python.org/3.5/library/marshal.html

"""singletons None, Ellipsis and StopIteration can also be marshalled
and unmarshalled."""

StopIteration is a type. I suppose it's still kinda true that there's
only one StopIteration class (otherwise exception handling would get
very messy), but it seems unusual that this one particular exception
class should be special-cased. (And yes, the code does correspond -
marshal.c:293 handles StopIteration with its own byte code.)

Why is StopIteration marshallable but no other exception is? Or, if
they are marshallable, why does this one get special handling?

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


Re: tkinter mainloop

2014-11-19 Thread Rick Johnson
On Wednesday, November 19, 2014 5:23:38 AM UTC-6, Terry Reedy wrote:
> On 11/19/2014 3:46 AM, ast wrote:
> > mainloop() is a window method which starts the event
> > manager which tracks for events (mouse, keyboard ...) to
> > be send to the window. But if I forget the
> > root.mainloop() in my program, it works well anyway, I
> > cant see any failure. Why ?

You don't need to call "mainloop()" when building Tkinter
widgets on the command-line, but for *real* scripts i believe
you'll need to. For instance, if you run the following code
you will see a window with a label inside:

## START CODE ##
import Tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Hello Blackness')
label.pack()
root.mainloop()
## END CODE ##

However, if you comment out the "root.mainloop()" line you
will see nothing. Post an example that shows how you build
Tkinter GUIs without calling "mainloop".

> > Second question, is it possible to cancel a mainloop() ?

I don't think you meant to say "cancel", did you really mean
"pause"?

> > I neeed this feature because I have a main window "root
> > = Tk()" which opens a Toplevel secondary window "top =
> > Toplevel()" and I would like root window to be frozen
> > while the user fills the top window.

Sounds like you're trying to create a modal dialog, yes?

Tkinter has a few methods for handling such cases. One is
called "wait_window" and another is called "quit", with
"wait_window" being preferred over "quit" for most tasks.
There are also methods for setting the input "focus" and
"grab". A good example for you to look at is the
tkSimpleDialog.Dialog class. But remember, why re-invent the
wheel if you don't need to. The tkSimpleDialog.Dialog class
is a wrapper around a modal dialog behavior. And it is very
simple (imagine that!) to use.


## START CODE ##
import Tkinter as tk
from tkSimpleDialog import Dialog
from tkMessageBox import showerror
from Tkconstants import LEFT, YES, END

class MyDialog(Dialog):
def body(self, body):
tk.Label(body, text='Enter a value').pack(side=LEFT)
self.entry = tk.Entry(body)
self.entry.pack(side=LEFT, expand=YES)

def validate(self):
if self.entry.get() != '':
return True
showerror('', 'Must enter a value first, or cancel!')
return False

def apply(self):
self.result = self.entry.get()

if __name__ == '__main__':
root = tk.Tk()
root.update_idletasks() # Don't do this normally
d = MyDialog(root)
print 'User Entered: {0!r}'.format(d.result)
root.mainloop()
## END CODE ##

However, i must admit the API is both poorly written, uses
poor naming conventions for the hooks, and also trys to be
too implicit by auto-showing the dialog. I rewrote the entire 
class many years ago and have not missed it one bit. 

> There are methods for freezing a widget.  Something like
> root.withdraw. But there is more than one for doing
> slightly different things - Terry Jan Reedy

Actually that's not true Terry. The "Toplevel" method named
"withdraw" will cause a window to be hidden from view. And
if the OP tries to use withdraw on the root window, the root
and *ALL* child window(s) will be withdrawn, leaving no visible
windows at all -- at least in the example he gave anyhow.

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


Re: How to access Qt components loaded from file?

2014-11-19 Thread Juan Christian
Thanks, it's working using QTimer. The thing is that whenever the program
is going to do something, in my case, draw a new QGroupBox with some
components inside and put it in the Form (I'm using VBoxLayout in the main
form) the program freezes, and I'm using very simple components just for
testing.This shouldn't be normal, right?

Am I doing something wrong?

On Wed Nov 19 2014 at 7:00:43 PM Rob Gaddi
 wrote:

> On Wed, 19 Nov 2014 20:47:31 +
> Juan Christian  wrote:
>
> > Let's say that I want to call the site in a 5min interval. I'm currently
> > getting the info this way just for testing and to know that the 'core
> > engine' is working, and indeed, it's working:
> >
> > if __name__ == "__main__":
> > import sys
> >
> > app = QApplication(sys.argv)
> > MainWindow = loadui("main.ui")
> >
> > def output_slot():
> > MainWindow.txtbox.setText(call_site())
> >
> > MainWindow.btn.clicked.connect(output_slot)
> >
> > MainWindow.show()
> > app.exec_()
> >
> > How can I proceed if I want the txtbox to automatically do the
> > 'setText(call_site())' in a X defined interval? The final app will have
> not
> > only a txtbox, but a complete interface with buttons, avatar image, some
> > txtboxes, and all that stuff. If I know how to "call the site" in a
> defined
> > interval, I can get all the info that I need and set them one by one.
> >
> > If I'm not mistaken my app is locked in the app.exec_() loop, so I need
> to
> > have a trigger configured that will be called in a defined interval, then
> > inside this trigger I configure the "set_avatar", "set_text",
> > "set_btn_link", etc, is that right?
> >
> > On Tue Nov 18 2014 at 9:37:21 PM Chris Angelico 
> wrote:
> >
> > > On Wed, Nov 19, 2014 at 5:15 AM, Juan Christian
> > >  wrote:
> > > >
> > > > Thanks, it's working. What would be a "professional" approach if I
> want
> > > to
> > > > constantly call a URL to get it's content and access this data
> within the
> > > > GUI?
> > > >
> > >
> > > "Constantly" doesn't make much sense when you're talking about network
> > > operations. There are two basic approaches: either you re-fetch
> > > periodically and update the GUI (in which case you have to decide how
> > > frequently), or you re-fetch on some trigger (when it's changed, or
> > > when the user's about to need it, or something). Either way, you have
> > > to balance network traffic versus promptness of update, and it's
> > > nearly impossible to pick perfectly. But if you don't mind it being a
> > > little clunky, you should be able to pick something fairly simple and
> > > deploy it, and then maybe refine it a bit afterward.
> > >
> > > ChrisA
> > > --
> > > https://mail.python.org/mailman/listinfo/python-list
> > >
> >
> You'd use a QTimer to do that.  Once you .start(5*60*1000) the
> timer, it'll fire a timeout signal every 5 minutes.  You connect that
> timeout to the slots you want to execute if you don't care about order,
> or to a single slot function that runs the things that you want to do in
> some defined order.
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What does this line of code mean?

2014-11-19 Thread Rick Johnson
On Sunday, November 16, 2014 3:45:58 PM UTC-6, Abdul Abdul wrote:
> I just came across the following line of code:
> 
> outputfile = os.path.splitext(infile)[0] + ".jpg"
> 
> Can you kindly explain to me what those parts mean?

What that line of code "means" is:

  The author is far too dependent on authority (Python) and
  either lacks the *motivation* to improve the situation, or
  lacks the *skill* to improve the situation -- or both!

It is my strong opinion that path munging like the type
displayed here should be avoided when all possible. The
author is doing more work than he needs to do and he's doing
the work in an overly cryptic manner. Sure, any Python coder
worth his SALT can grok the code, but Python code like this
should never be celebrated, it should be excommunicated!

Instead of calling a function that splits a file-path, *THEN*
indexing the return value of the split to fetch a subsection
(YUCK!), *THEN* concatenating the fetched subsection with a
new extension (PUKE!)... he should have called one simple
*SELF-EXPLANATORY* method:

os.path.substitute_extension(inPath, ".jpg")

But of course that method does not exists in *YOUR* Python!
No, you're forced to drink the cheap, "powdery tasting",
bitterly-under-sugared kool-aide that the os.path module has
demanded of you.

"Oh Yeah!"

Urm, 

Oh *NO THANKS*!

To further aid in memory recall, the os.path module should
have many "get_*" and "substitute_*" methods, however, it
should have *ONLY* one "split" method which breaks a path
into *ALL* of it's atomic parts:

drive, folder, filename, extension = os.path.split(path)

Of course the author also failed to use intuitive "self
documenting" names. "infile" suggest a file *object*, when
"inPath" and "outPath" are better suited to suggesting file
paths as *strings*.




  
  

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


Most gratuitous comments

2014-11-19 Thread Steven D'Aprano
And the award for the most gratuitous comments before an import goes to 
one of my (former) workmates, who wrote this piece of code:

# Used for base64-decoding.
import base64
# Used for ungzipping.
import gzip



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


Re: Most gratuitous comments

2014-11-19 Thread Chris Angelico
On Thu, Nov 20, 2014 at 3:58 PM, Steven D'Aprano  wrote:
> And the award for the most gratuitous comments before an import goes to
> one of my (former) workmates, who wrote this piece of code:
>
> # Used for base64-decoding.
> import base64
> # Used for ungzipping.
> import gzip

Well hey. Good to know he's using the tools for their intended purposes!

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


Re: Is StopIteration a singleton?

2014-11-19 Thread Steven D'Aprano
On Thu, 20 Nov 2014 12:52:25 +1100, Chris Angelico wrote:

> While poking about the cpython source tree with reference to PEP 479, I
> came across this:
> 
> https://docs.python.org/3.5/library/marshal.html
> 
> """singletons None, Ellipsis and StopIteration can also be marshalled
> and unmarshalled."""
> 
> StopIteration is a type. I suppose it's still kinda true that there's
> only one StopIteration class (otherwise exception handling would get
> very messy), but it seems unusual that this one particular exception
> class should be special-cased. (And yes, the code does correspond -
> marshal.c:293 handles StopIteration with its own byte code.)

StopIteration is not a singleton class.

py> e1 = StopIteration()
py> e2 = StopIteration()
py> e1 is e2
False

It it were, you couldn't support "return value" from generators, since 
the return value gets turned into the argument for StopIteration.

Nor is it a singleton itself: StopIteration (the class) is an instance of 
type, and there are *many* instances of type:


py> all(isinstance(T, type) for T in [int, float, str, bool, 
... Exception, StopIteration, dict, type])
True


I cannot imagine what they mean by calling StopIteration a singleton.



> Why is StopIteration marshallable but no other exception is? Or, if they
> are marshallable, why does this one get special handling?

No idea. But you can marshal StopIteration itself, but not StopIteration 
instances:

py> marshal.dumps(StopIteration)
'S'
py> marshal.dumps(StopIteration())
Traceback (most recent call last):
  File "", line 1, in 
ValueError: unmarshallable object



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


Re: Is StopIteration a singleton?

2014-11-19 Thread Chris Angelico
On Thu, Nov 20, 2014 at 4:09 PM, Steven D'Aprano  wrote:
> StopIteration is not a singleton class.
>
> py> e1 = StopIteration()
> py> e2 = StopIteration()
> py> e1 is e2
> False
>
> It it were, you couldn't support "return value" from generators, since
> the return value gets turned into the argument for StopIteration.

Clearly so. Also, the special case is for StopIteration, not for its
type (just as there is for None, and not NoneType).

> Nor is it a singleton itself: StopIteration (the class) is an instance of
> type, and there are *many* instances of type:
>
>
> py> all(isinstance(T, type) for T in [int, float, str, bool,
> ... Exception, StopIteration, dict, type])
> True

Indeed; however, there is a fixed pointer PyExc_StopIteration at the C
level, so in a sense, there can be only one StopIteration. Even if you
shadow the name with a subclass, C code will still raise and look for
the original.

> I cannot imagine what they mean by calling StopIteration a singleton.

Okay, so I'm not the only one finds this strange!

>> Why is StopIteration marshallable but no other exception is? Or, if they
>> are marshallable, why does this one get special handling?
>
> No idea. But you can marshal StopIteration itself, but not StopIteration
> instances:
>
> py> marshal.dumps(StopIteration)
> 'S'
> py> marshal.dumps(StopIteration())
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: unmarshallable object

Under what circumstances would you marshal an exception type? I don't
use the module at all, I only happened upon it (its docs, to be
precise) by grepping across files.

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


Beginner

2014-11-19 Thread Karthik Reddy
Hi all 

I am python beginner I am trying the below code and getting incorrect syntax in 
python (3.3.2)

number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print ("Congratulations, you guessed it.")
running = False # this causes the while loop to stop
elif guess < number:
print ("No, it is a little higher than that.")
else:
print ("No, it is a little lower than that.")
else:
print ("The while loop is over.")
# Do anything else you want to do here
print ("Done")

Please help me with this 

Thank you in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Beginner

2014-11-19 Thread Steven D'Aprano
On Wed, 19 Nov 2014 22:40:09 -0800, Karthik Reddy wrote:

> Hi all
> 
> I am python beginner I am trying the below code and getting incorrect
> syntax in python (3.3.2)

You need to indent the while and if blocks.

Instead of writing:

while running:
code


you need to write:

while running:
code


See the indent? You should use either 1 tab or 4 spaces, but not both.


Another problem with your code, although it is not a syntax error, is 
that you have:

guess = int(raw_input('Enter an integer : '))


That is from Python 2. In Python 3, use:

guess = int(input('Enter an integer : '))

(don't forget to indent it correctly).

There may be other problems, please fix these first and if you have any 
other problems copy and paste the FULL error, everything from the line 
starting

Traceback 

to the end of the error message.


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


Re: about suds and soap and parameters.

2014-11-19 Thread dieter
JustSomeGuy  writes:

> I'm trying to call a soap method with suds.
> The parameter however is not straight forward.
>
>
> queryContent (
> xs:string mpiId, 
> tmPidAndIssuer[] idsAndIssuers, 
> tmPersonName name, 
> xs:string patientAge, 
> tmAccessionNumberAndIssuer accNumAndIssuer, 
> xs:string studyUID,
> xs:string studyID, 
> tmDateRange studyDateRange, 
> xs:string studyDescription, 
> xs:string[] modalities, 
> xs:string stmo, 
> xs:string folderName, 
> xs:string folderDescription, 
> tmDateRange folderDateRange, 
> xs:string[] labels
> )
>
> What are these xs: ?

Likely, "xs" stands for "Xml-Schema" and then would refer to
the XML-Schema standard datatypes.

In general, "suds" shows you type information in the
form "[:]". It uses the information
from the WSDL description. The prefix itself is without semantic
meaning; it is just a shorthand for an "uri" which ideally
points to some relevant definitions. The WSDL will have
information for this "prefix -> uri" mapping. You will
need to look there, in order to determine precisely, what
the prefix means.

If "" is missing, then the type is locally
defined. You should find its definition in the WSDL (or
included resources).

> there seems to be other other types defined here that I'm not sure what they 
> are.

Look at the WSDL defintions.

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


Re: about suds and soap and parameters.

2014-11-19 Thread Marko Rauhamaa
dieter :

> The [namespace] prefix itself is without semantic meaning; it is just
> a shorthand for an "uri" which ideally points to some relevant
> definitions. The WSDL will have information for this "prefix -> uri"
> mapping. You will need to look there, in order to determine precisely,
> what the prefix means.

FWIW, even the URI is without inherent meaning. It's just a
funny-looking identifier for a namespace.


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