PIL: check if image is animated

2013-05-06 Thread Sven
Hello,

I am trying to check if an image is animated. I can't rely on the extension
as it may be a gif that's been renamed to .jpg or something else and is
still animated.

I thought that this used to work:

from PIL import Image


def check_animated(img):
try:
img.seek(1)
except (EOFError):
return 0
return 1

img = Image('image.jpg')
print "animated?", check_animated(img)

Regardless if it's animated or not I get this exception:
ValueError: cannot seek to frame 1

I need to return 0 or 1, so excuse not using True or False.

Did the above get deprecated/change in a version at some point? Perhaps
there's something I missed during install (using PIP). Are there any other
ways to accomplish what I am trying to do, with or without PIL?

Python 2.7, linux

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


Re: Unicode humor

2013-05-08 Thread Sven
I saw this this morning and the first thing I thought of was this list...

unlike you I was too lazy to post it :)


On 8 May 2013 14:19, Roy Smith  wrote:

> Apropos to any of the myriad unicode threads that have been going on
> recently:
>
> http://xkcd.com/1209/
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: PIL: check if image is animated

2013-05-09 Thread Sven
Figured out my issue. I did called the check_animated function more than
once and the second call causes the exception unless I seek back to 0


On 6 May 2013 21:57, Sven  wrote:

> Hello,
>
> I am trying to check if an image is animated. I can't rely on the
> extension as it may be a gif that's been renamed to .jpg or something else
> and is still animated.
>
> I thought that this used to work:
>
> from PIL import Image
>
>
> def check_animated(img):
> try:
> img.seek(1)
> except (EOFError):
> return 0
> return 1
>
> img = Image('image.jpg')
> print "animated?", check_animated(img)
>
> Regardless if it's animated or not I get this exception:
> ValueError: cannot seek to frame 1
>
> I need to return 0 or 1, so excuse not using True or False.
>
> Did the above get deprecated/change in a version at some point? Perhaps
> there's something I missed during install (using PIP). Are there any other
> ways to accomplish what I am trying to do, with or without PIL?
>
> Python 2.7, linux
>
> --
> ./Sven
>



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


defining __repr__

2005-09-12 Thread sven
hi list,
i'd like to define __repr__ in a class to return the standardrepr
a la "<__main__.A instance at 0x015B3DA0>"
plus additional information.
how would i have to do that?
how to get the standardrepr after i've defined __repr__?

sven.

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


Re: Synchronous/Asynchrnous Audio play with pymedia

2005-09-19 Thread sven
At 01:22 19.09.2005, Ron Provost wrote:
>Hello,
>
>I'm developing a piece of software to assist illiteraate adults to learn to
>read.  I'm trying to figure out how, if possible, to make audio playback
>asynchrnous but still controllable.  I'm using python 2.4 with pymedia on
>XP.

there's a pymedia mailing list at: 
https://lists.sourceforge.net/lists/listinfo/pymedia-users
better ask there, the author of pymedia is generally very helpful in 
answering question.

sven.


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


Re: Question About Logic In Python

2005-09-19 Thread sven
At 02:20 19.09.2005, James H. wrote:
>Greetings!  I'm new to Python and am struggling a little with "and" and
>"or" logic in Python.  Since Python always ends up returning a value
>and this is a little different from C, the language I understand best
>(i.e. C returns non-zero as true, and zero as false), is there anything
>I should be aware of given Python's different approach?  Namely any
>pitfalls or neat tricks that make the Python approach cool or save my
>butt.

to make sure that an operation yields a boolean value wrap a bool() 
around an expression.
None, 0 and objects which's len is 0 yield False.
so you can also do stuff like that:

 >>> a = []
 >>> b = [1,2,3]
 >>> a or b
[1, 2, 3]

 >>> class Foo:
... def __len__(self): return 0
...
 >>> class Bar:
... def __len__(self): return 1
...
 >>> foo = Foo()
 >>> bar = Bar()
 >>> foo or bar
<__main__.Bar instance at 0x7D289940>

sven. 

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


Re: subclassable types

2013-02-22 Thread Sven
I believe it's a matter of choice by BDFL when it comes to bool. These
might answer your question:
http://mail.python.org/pipermail/python-dev/2002-March/020822.html
http://mail.python.org/pipermail/python-dev/2004-February/042537.html

specifically:

I thought about this last night, and realized that you shouldn't be
allowed to subclass bool at all!  A subclass would only be useful when
it has instances, but the mere existance of an instance of a subclass
of bool would break the invariant that True and False are the only
instances of bool!  (An instance of a subclass of C is also an
instance of C.)  I think it's important not to provide a backdoor to
create additional bool instances, so I think bool should not be
subclassable.

as for range, that's not a type but a built in function (do a print range)

I would suggest that instead of using introspection you could handle
the exception TypeError that is thrown.




On 22 February 2013 09:35, Wolfgang Maier <
wolfgang.ma...@biologie.uni-freiburg.de> wrote:

> Dear all,
> I am wondering what the rules are that determine whether a built-in type is
> subclassable or not.
> As examples, why can you base your classes on int or set,
> but not on bool or range?
> Also: can you use introspection to find out whether a type is valid as a
> base type?
> Thanks for your help!
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: nested loops

2013-02-26 Thread Sven
Here's one solution

import time
count_timer = int(raw_input('how many seconds?: '))
for i in range(count_timer, 0, -1):
print i,
print "*" * i
time.sleep(1)
print 'blast off!'


On 25 February 2013 22:46, leonardo  wrote:

> hi everyone,
>
> i have the following program:
>
> import time
> count_timer = int(raw_input('how many seconds?: '))
> for i in range(count_timer, 0, -1):
> print i
> time.sleep(1)
> print 'blast off!'
>
>
> this is the result:
>
> how many seconds?: 5
> 5
> 4
> 3
> 2
> 1
> blast off!
>
> how can i have it print  a row of stars beside each number, like this?:
>
> how many seconds?: 5
> 5 * * * * *
> 4 * * * *
> 3 * * *
> 2 * *
> 1 *
> blast off!
>
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



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


What are the Dos and Don'ts

2013-02-27 Thread Sven
Hello,

As I am new to this list I was wondering what the rules are about what you
can/can't post on this list.

Is it general python, i.e. questions, information, links to
articles/programs you have written yourself etc are all ok as long as they
are Python related

or is it more a Q&A where the point is to talk about python, help people
rather than anything else.

TIA

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


Re: "Daemonizing" an application.

2013-02-27 Thread Sven
On 27 February 2013 11:03, Chris Angelico  wrote:

> On Wed, Feb 27, 2013 at 9:52 PM, Gilles Lenfant
>  wrote:
> > Hello,
> >
> > Sorry for the obscure title, but I can't make short to explain what I'm
> searching for. :)
> >
> > I made an app (kind of proxy) that works without UI within it's process.
> So far, so good.
> >
> > Now I need to change "live" some controls of this application, without
> stopping it.
> >
> > So my app will be split in two :
> >
> > * A control app (say "appctl") for a console UI
> > * A daemon (or agent ?) that runs the core of the app (say "appd"),
> processing inputs and outputs
>
> Daemonizing is a fairly specific operation (forking and disconnecting
> from the console), which may well be a part of what you're asking for,
> but on the other hand may be unnecessary (if, for instance, you let
> your core app be invoked by Upstart directly).
>
> What form of control do you need? With many apps of this nature, the
> only control required is Unix signals - particularly SIGHUP, to say
> "I've edited your config files, go reread them". Your front end might
> do the editing, or you could even abolish the control app altogether
> and simply edit the configs manually. But if you need more, you'll
> need to work out how you want them to communicate with each other.
>
> What platform or platforms do you need this to run on?
>
> Regardless of your answers to the above, I would say that in all
> probability *yes*, you will be able to do this with just Python and
> the standard library. There are a lot of batteries included with
> Python :)
>

One solution is to use XMLRPC to communicate with the daemonized process.
This does involve the daemon listening on the local network. The GUI can
then connect to the daemon and send it commands which essentially is
calling functions on the daemon. These can then change certain behaviors of
the daemon process without restarting it. If you want to be hardcore you
can use sockets. There are other networking libs like Twisted and RabbitMQ,
but they might be a bit overkill for your purpose.

But whether any of this is ok depends on your use case. The signals Chris
mentioned will also work. Alternatively there are a number of filewatching
libraries like watchdog or https://github.com/seb-m/pyinotify which you can
use to monitor changes to a config file if that's the way you want to go.

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


Re: Twisted or Tornado?

2013-03-01 Thread Sven
Although these articles are a _little_ old they are probably useful to help
you decide which solution is most suitable for you in terms of performance

http://nichol.as/benchmark-of-python-web-servers
http://nichol.as/asynchronous-servers-in-python

I would also be interested if any one on this list has any idea if the
results above would be any different these days or whether the benchmarks
are still fairly representative.


On 1 March 2013 00:28, Jake Angulo  wrote:

> I have to say it first: I am not trolling :P
>
> Im working on a server project (with IOS client) and would like to create
> a custom, lean and mean server - real Quick!
>
> My requirements for this framework in descending order:
> 1) Easy to use API
> 2) Widely available documentation / Examples / Community contributions
> 3) Feature-wise - kinda most that you commonly need is there
>
> Your opinions will be valuable, if possible cite examples or URL
> references, Pls!
>
> I prefer opinion from those who have programmed real projects in it - not
> just read some blog or Slashdot :P
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


iterating over a list as if it were a circular list

2013-03-07 Thread Sven
I was wondering what the best approach for the following might be.

Say you have a list P of points and another list N of other items. You can
always assume that

len(N) <= len(P)

Now I would like to iterate over P and place one N at each point. However
if you run out of N I'd like to restart from N[0] and carry on until all
the points have been populated.
So far I've got

for point in points:


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


iterating over a list as if it were a circular list

2013-03-07 Thread Sven
Stupid keyboard shortcuts, sent it too early. Apologies


I was wondering what the best approach for the following might be.

Say you have a list P of points and another list N of other items. You can
always assume that

len(N) <= len(P)

Now I would like to iterate over P and place one N at each point. However
if you run out of N I'd like to restart from N[0] and carry on until all
the points have been populated.
So far I've got (pseudo code)

i = 0
for point in points:
put N[i] at point
if i > len(N):
i = 0

is this the most pythonic way to accomplish this?

Additionally, what if I wanted to pull a random element from N, but I want
to ensure all elements from N have been used before starting to pick
already chosen random elements again.
So far I thought of duplicating the list and removing the randomly chosen
elements from the list, and when it's empty, re-copying it. But that seems
a little "wrong" if you know what I mean.

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


Re: Unable to connect to internet URL behind firewall

2013-03-07 Thread Sven
On 6 March 2013 16:28,  wrote:

> Hi,
>
> I am using below two approaches to connect to read the content of internet
> url.
> These two approaches work for me when the internet explorer session is
> open.
>
> When the internet explorer window is closed, below code gives me 407 error.
> I have also set the HTTP_PROXY environment variables as
> http://proxy-example.com:3128
>

>From experience the environment variable name is in lowercase. Try
http_proxy instead.

Don't ask me why this environment variable is lowercase when most others
aren't.

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


Re: iterating over a list as if it were a circular list

2013-03-07 Thread Sven
On 7 March 2013 09:31, Chris Rebert  wrote:

> On Mar 7, 2013 1:24 AM, "Sven"  wrote:
> >
> > I was wondering what the best approach for the following might be.
> >
> > Say you have a list P of points and another list N of other items. You
> can always assume that
> >
> > len(N) <= len(P)
> >
> > Now I would like to iterate over P and place one N at each point.
> However if you run out of N I'd like to restart from N[0] and carry on
> until all the points have been populated.
>
> Untested due to the late hour:
>
> import itertools
>
> for p, n in itertools.izip(P, itertools.cycle(N)):
> # do whatever
>

I knew there was a more sensible way to do it. Thanks.




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


Re: Why is Ruby on Rails more popular than Django?

2013-03-07 Thread Sven
On 7 March 2013 09:28, Rui Maciel  wrote:

> rusi wrote:
>
> > Anyone who's used emacs will know this as the bane of FLOSS software
> > -- 100 ways of doing something and none perfect -- IOW too much
> > spurious choice.
>
>
> This is a fallacy.  Just because someone claims that "there are 100 ways of
> doing something and none perfect", it doesn't mean that restricting choice
> leads to perfection.  It doesn't.  It only leads to getting stuck with a
> poor solution with no possibility of improving your life by switching to a
> better alternative.
>

This thread reminds me of an article I read recently:

http://rubiken.com/blog/2013/02/11/web-dev-a-crazy-world.html

It's mostly a matter of having enough time to evaluate what's best for you.
In the case of RoR vs Django, you will (assuming zero knowledge) need to
learn a language, then a framework. That's quite a time consuming task.
Personally I've opted for Django because I've used Python for years. I've
written some Ruby in the past, but I not enough to make me choose RoR over
Django to get stuff done.

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


Re: working with dict : incrementing dict dynamically

2013-03-11 Thread Sven
On 11 March 2013 15:23, inshu chauhan  wrote:

> I am trying to create a dictionary with a key and its values seraching
> from a data set. But something is going wrong. This is the first time I am
> working with dicts.
>
> My code is :
>
> import cv
> def Computesegclass(segimage):
> num_pixel = 0
> for y in xrange(0, segimage.height):
> for x in xrange(0, segimage.width):
>
> if segimage[y,x] == (0.0, 0.0, 0.0):
> continue
> else:
> color = segimage[y,x]
> blue = color[0]
> green = color[1]
> red = color[2]
> region_num = blue + 256 * green + 65536 * red
> print region_num
> segments = dict({region_num : num_pixel})
> if region_num == region_num:
> num_pixel = +1
> print segments
>
> if __name__== "__main__":
> segimage =
> cv.LoadImageM("Z:/Segmentation/segmentation_numbers_0.tif",
> cv.CV_LOAD_IMAGE_UNCHANGED)
> print segimage
> Computesegclass(segimage)
>
>
> here I am traversing through an image which is 3000 x 3000. for each pixel
> I calculate a region number. What I am trying to do is increase the
> num_pixel by 1 if that pixel falls in the same region which is identified
> by region_num. How can I do it in dict created ?
>
> Thanx in Advance
>
>
If I am understanding you correctly you want to accumulate a pixel count
for each region. I would suggest a default dict, and that you do something
like

from collections import defaultdict
def ComputeSegClass(seqimage):
segments = defaultdict(int)

if region_num == region_num:
segments[region_num] += 1

But as John mentioned, your comparison here will always be true, so you
will need to fix this to test for your case.

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


Re: Problem this random seed()

2013-03-19 Thread Sven
On 19 March 2013 10:54, NZach  wrote:

> @eli m : The problem is that i execute on lines 83 and 90 the main() and
> although the seed value is the same, equal to 12345, i receive different
> results from lines 85 and 92.
>
> @alex23: I changed the code, http://codeviewer.org/view/code:30d4, but i
> still receive have the same problem. The results are different.
>
> Any idea please
>

have you actually tried printing out the return value of

G.Rnd.expovariate(MachineClass.SrvRate)

?

I'm not sure as I have not used SimPy before, but the values you are
printing out at the bottom seem to be related to the timing, specifically
now(), which would give you a different result each time.

If you print out or inspect the result of expovariate, it should be the
same each time you run main.

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


Re: Problem this random seed()

2013-03-19 Thread Sven
On 19 March 2013 13:50, NZach  wrote:

> Sorry, my previous reply was completely wrong. The time is initialized
> through the initialize() to 0. So, each time i call main() the simulation
> time is initialized to 0.
>
> I changed the code in order to print and check the values of
>
> G.Rnd.expovariate(MachineClass.SrvRate) and
> G.Rnd.expovariate(ArrivalClass.ArvRate)
>
> here is the code and the changes i made :
> http://codeviewer.org/view/code:30d8
>
> The values are not the same.
>
> The result i take is the following:
>
> Result from main() call No. 1 is 0.0452927906737
> Result from main() call No. 2 is 0.0588336669949
> 2
> First time Execution of Main Main
> [0.07267291894782457, 0.019146562687989536, 0.034780398625615376,
> 0.005528912370370478, 0.023636815811338075]
> [0.13472907136407936, 0.0025553071735785462, 0.08868344131130483,
> 0.05381286556098766, 0.044091180681591464]
> Second time Execution of Main
> [0.0335704752213292, 0.1321512230812724, 0.16025979406301488,
> 0.029210377271523574, 0.006680846943670858]
> [0.20642889529587374, 0.047894131266223446, 0.10958802111803392,
> 0.02393344456847461, 0.13280785022932287]
>

In the new code you are creating one instance of G which you seed with 1234
and then calling  expovariate on it each time you call main without
reseeding. You're only seeding it once and reusing it, so you would get
different values. What you had before, where you seeded G.Rnd in the main
was fine.

I also suggest you change one thing at a time, rather than reworking large
parts each iteration. All I was suggesting was a simple print statement in
the Run method like you had it before


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


Re: Problem this random seed()

2013-03-19 Thread Sven
On 19 March 2013 14:44, NZach  wrote:

> OK, i changed the code again. Delete the G class (The purpose of G class
> was to refer to global variables). Add Rnd.seed(12345) in main() function.
> The new code : http://codeviewer.org/view/code:30da
>
> i print the Rnd.expovariate(ArrivalClass.ArvRate).
>
> The output i get be executing the above code is the following :
> ---
> 0.134729071364
> 0.00255530717358
> 0.0886834413113
>
> Result =  0.0571622124959
> 0.134729071364
> 0.00255530717358
> 0.0886834413113
>
> Result =  0.0453791550084
> ---
>
>
> So, the problem is probably with time (which is what @Stev mentioned
> before).
>
> But i still cant understand the reason. From the SimPy documentation :
> http://simpy.sourceforge.net/SimPyDocs/Manuals/SManual.html
> it says for the initialize(): "The initialize statement initialises global
> simulation variables and sets the software clock to 0.0. It must appear in
> your program before any SimPy process objects are activated."
>
> Any idea why that happens
>

I am guessing it's because now gives you the current clock value. Yes,
initialise sets it to 0.0, but on execution now will change to the time
since initialise(), so you will get varying values. That's my best guess

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


Re: Problem this random seed()

2013-03-19 Thread Sven
On 19 March 2013 15:09, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Tue, 19 Mar 2013 07:44:47 -0700, NZach wrote:
>
> > OK, i changed the code again. Delete the G class (The purpose of G class
> > was to refer to global variables). Add Rnd.seed(12345) in main()
> > function. The new code : http://codeviewer.org/view/code:30da
> >
> > i print the Rnd.expovariate(ArrivalClass.ArvRate).
> >
> > The output i get be executing the above code is the following : ---
> > 0.134729071364
> > 0.00255530717358
> > 0.0886834413113
> >
> > Result =  0.0571622124959
> > 0.134729071364
> > 0.00255530717358
> > 0.0886834413113
> >
> > Result =  0.0453791550084
> > ---
> >
> >
> > So, the problem is probably with time (which is what @Stev mentioned
> > before).
>
> Who is "Stev"? If you mean me, Steve or Steven, I did not say anything
> about time. I mentioned the random number generator *seed*.
>
>
I think he meant me.


> > But i still cant understand the reason. From the SimPy documentation :
> > http://simpy.sourceforge.net/SimPyDocs/Manuals/SManual.html it says for
> > the initialize(): "The initialize statement initialises global
> > simulation variables and sets the software clock to 0.0. It must appear
> > in your program before any SimPy process objects are activated."
>
> That has nothing to do with the random numbers generated by expovariate().
>
>
No, but in early versions he was printing out the time (or a time related
term) and was wondering why that is different too.

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


Processing user input as it's entered

2013-03-26 Thread Sven
Hello,

Is there a way (ideally cross platform but a *nix OS solution would be
great) to process user input as they type?
What I aim to achieve is to count the number of characters a user has
entered and display it while they are typing. The entered text will also
need to be captured once the user has finished typing.

This is a gui-less CLI tool for python 2.7

I've seen some information on tty.setraw but I'm not sure how you'd go
about wiring that up.

Thanks

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


Re: Processing user input as it's entered

2013-03-26 Thread Sven
On 26 March 2013 14:41, Arnaud Delobelle  wrote:

> On 26 March 2013 10:07, Sven  wrote:
> > Hello,
> >
> > Is there a way (ideally cross platform but a *nix OS solution would be
> > great) to process user input as they type?
> > What I aim to achieve is to count the number of characters a user has
> > entered and display it while they are typing. The entered text will also
> > need to be captured once the user has finished typing.
> >
> > This is a gui-less CLI tool for python 2.7
> >
> > I've seen some information on tty.setraw but I'm not sure how you'd go
> about
> > wiring that up.
>
> Can you use curses (http://docs.python.org/2/library/curses.html




This could work. I've not used it before so I am having some issues echoing
out the text. I assume I can use this without having to create an ncurses
UI?

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


Getting USB volume serial number from inserted device on OSX

2013-04-02 Thread Sven
Hello,

I am using Python 2.7 with pyobjc on Lion and NSNotification center to
monitor any inserted USB volumes. This works fine.

I've also got some ideas how to get a device's serial number, but these
involve just parsing all the USB devices ('system_profiler SPUSBDataType'
command). However I'd like to specifically query the inserted device only
(the one creating the notification) rather than checking the entire USB
device list. The latter seems a little inefficient and "wrong".

Can this be accomplished in a sensible way? The NSNotification object
passed to my handler function doesn't have that kind of information and
I've not been able to find any information on doing the above with the
information provided by the NSNotification object.

I've tried DBus (I use this for the linux handler) but I've not had much
luck getting it to work reliably on OS X and installing it wasn't as
straightforward as I hoped.

I have no requirement to use pyobjc so other suggestions welcome as long as
it's straightforward to install and without too many other dependencies.
I'd like to keep installation straightforward for the end users.
Thanks

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


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

2013-04-03 Thread Sven
Apologies. The main app is in python, and I would like to know any
alternative methods to do this in Python on OS X. Doesn't have to use the
OS X APIs.

I'll try elsewhere too though. Thanks


On 3 April 2013 00:37, Ned Deily  wrote:

> In article
> ,
>  Sven  wrote:
> > I am using Python 2.7 with pyobjc on Lion and NSNotification center to
> > monitor any inserted USB volumes. This works fine.
> [...]
>
> Since your question really is about OS X APIs and not Python or even
> PyObjC, you're more likely to get a meaningful answer elsewhere.  Try
> StackOverflow or one of the OS X lists.
>
> --
>  Ned Deily,
>  n...@acm.org
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


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

2013-04-05 Thread Sven
On 5 April 2013 06:20, Tim Roberts  wrote:

> John Nagle  wrote:
> >
> >   That would be useful to have as a portable function for all USB
> >devices.  Serial port devices are particularly annoying, because their
> >port number is somewhat random when there's more than one, and changes
> >on hot-plugging.
>
> There is no portable solution.  Every operating system handles this kind of
> this very differently.  Remember, the operating system abstractions are all
> designed to hide this from you.  When you open a serial port or an audio
> device or use a file system, you aren't supposed to KNOW that there is a
> USB device behind it
>

Indeed. Which means I have a working solution under Linux, but I am
struggling to find one under OS  X.

Looks like I might have to resort to just parsing the USB tree until I find
the device that was inserted.

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


USBLock : lock/unlock your computer with a USB key

2013-04-08 Thread Sven
I've been working on a little project and have a working Linux
implementation so far. Basically it allows a user to use any USB stick as a
key to lock and unlock their computer. More info in the repo or PyPi
https://pypi.python.org/pypi/USBLock

Basically run the program with -a to add a device (added once you insert
it), then run it without any arguments. Insert the key again, and when you
remove it your computer will lock. Insert the key again and it will unlock.
It's not intended to provide military grade security, it's more of a
convenience tool to launch built in screen locking software.

Currently it locks a Linux box with xlock, pending a better solution.

I wrote it as an exercise in playing around with USB media and events, and
also because I needed a use for these old USB keys I have lying around :)

Always looking for contributions, suggestions and improvements. Especially
OS X and Win support.

Repo:
https://github.com/Svenito/usblock

Thanks for your time.

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


Re: USBLock : lock/unlock your computer with a USB key

2013-04-11 Thread Sven
Thanks for taking an interest.

Yes, I had the idea to add bluetooth too, removes the whole plugging and
unplugging spiel. I might start work on that, and if anyone else wants to
dive in and help, feel free. I will probably need to refactor the Listener
a little, or create a USB and BT listener class.

Cheers


On 11 April 2013 10:20, Dylan Evans  wrote:

> This looks cool, would actual be pretty useful. I see you did it as a usb
> project but probably bluetooth would be better so you could just pair it to
> your phone and know that your PC will lock when you walk away.
>
>
>
> On Tue, Apr 9, 2013 at 1:21 AM, Sven  wrote:
>
>> I've been working on a little project and have a working Linux
>> implementation so far. Basically it allows a user to use any USB stick as a
>> key to lock and unlock their computer. More info in the repo or PyPi
>> https://pypi.python.org/pypi/USBLock
>>
>> Basically run the program with -a to add a device (added once you insert
>> it), then run it without any arguments. Insert the key again, and when you
>> remove it your computer will lock. Insert the key again and it will unlock.
>> It's not intended to provide military grade security, it's more of a
>> convenience tool to launch built in screen locking software.
>>
>> Currently it locks a Linux box with xlock, pending a better solution.
>>
>> I wrote it as an exercise in playing around with USB media and events,
>> and also because I needed a use for these old USB keys I have lying around
>> :)
>>
>> Always looking for contributions, suggestions and improvements.
>> Especially OS X and Win support.
>>
>> Repo:
>> https://github.com/Svenito/usblock
>>
>> Thanks for your time.
>>
>> --
>> ./Sven
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
>
> --
> "The UNIX system has a command, nice ... in order to be nice to the other
> users. Nobody ever uses it." - Andrew S. Tanenbaum
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Re: The node.js Community is Quietly Changing the Face of Open Source

2013-04-16 Thread Sven
On 16 April 2013 17:25, Ned Batchelder  wrote:

>  On 4/16/2013 12:02 PM, Rodrick Brown wrote:
>
>  I came across this article which sums up some of the issues I have with
> modern programming languages. I've never really looked at Javascript for
> anything serious or Node itself but I found this article really
> informational.
>
>  "The “Batteries included” philosophy of Python was definitely the right
> approach during the mid 90’s and one of the reasons that I loved Python so
> much; this was a time before modern package management, and before it was
> easy to find and install community-created libraries.  Nowadays though I
> think it’s counter-productive.  Developers in the community rarely want to
> bother trying to compete with the standard library, so people are less
> likely to try to write libraries that improve upon it."
>
>
>
> http://caines.ca/blog/programming/the-node-js-community-is-quietly-changing-the-face-of-open-source/
>
>
>
> I don't want to get into a package pissing match, but this math is just
> silly:
>
> *python*:  29,720 packages / 22 years =* 1351 packages per year*
>
> *ruby*:  54,385 packages / 18 years =*3022 packages per year*
>
> *node.js*  26,966 packages / 4 years =   *6742 packages per year
> *
> If you want to know how fast something is growing, you don't measure 22
> years and divide by 22.  You look at the number of packages added in the
> last year (or month).  Also the assertion that people don't want to compete
> with the stdlib seems like pure supposition.  There are plenty of
> well-loved packages that "compete" with the stdlib.  Lxml, Requests,
> Twisted, etc, and plenty of packages in the stdlib that started as outside
> "competition".
>

Even looking at the last year/month might be give skewed results.
If a technology is new, there's a lot more packages that need writing than
if it's been around for 22 years, thus I'd expect to see the first year or
second year as a good comparison point.

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


urlretrieve get file name

2006-11-09 Thread Sven
Hi guys and gals,

I'm wrestling with the urlretrieve function in the urllib module. I
want to download a file from a web server and save it locally with the
same name. The problem is the URL - it's on the form
http://www.page.com/?download=12345. It doesn't reveal the file name.
Some hints to point me in the right direction are greatly appreciated.

Sven

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


Re: urlretrieve get file name

2006-11-09 Thread Sven
Hello Gabriel,

Thanks for your help, but I'm a guy with no luck. :-) I can't get the
file name from response header...

On Nov 10, 12:39 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Thursday 9/11/2006 19:11, Sven wrote:
>
> >I'm wrestling with the urlretrieve function in the urllib module. I
> >want to download a file from a web server and save it locally with the
> >same name. The problem is the URL - it's on the form
> >http://www.page.com/?download=12345. It doesn't reveal the file name.
> >Some hints to point me in the right direction are greatly appreciated.The 
> >file name *may* come in the Content-Disposition header (ex:
> Content-Disposition: attachment; filename="budget.xls")
> Use urlopen to obtain a file-like object; its info() method gives you
> those headers.
>
> --
> Gabriel Genellina
> Softlab SRL
>
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
> ¡Abrí tu cuenta ya! -http://correo.yahoo.com.ar

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


Re: urlretrieve get file name

2006-11-10 Thread Sven
Yes the browser suggests a file name, but I did a little research using
http://web-sniffer.net/. The Response Header contains roughly this:

HTTP Status Code: HTTP/1.1 302 Found
Location: http://page.com/filename.zip
Content-Length: 0
Connection: close
Content-Type: text/html

The status code 302 tells the browser where to find the file. The funny
thing is that calling the info() function, on the file-like response
object, in Python doesn't return the same header. I'm so stuck. :-)
Thanks for your help.

On 10 Nov, 01:27, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Thursday 9/11/2006 20:52, Sven wrote:
>
> >Thanks for your help, but I'm a guy with no luck. :-) I can't get the
> >file name from response header...Try using a browser and "Save as..."; if it 
> >suggests a file name, it
> *must* be in the headers - so look again carefully.
> If it does not suggests a filen ame, the server is not providing one
> (there is no obligation to do so).
>
> --
> Gabriel Genellina
> Softlab SRL
>
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
> ¡Abrí tu cuenta ya! -http://correo.yahoo.com.ar

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


Re: urlretrieve get file name

2006-11-11 Thread Sven
> You can use the geturl() method to obtain the true URL used (that
> would behttp://page.com/filename.zip) and then rename the file.

Thanks mate, this was exactly what I needed. A realy clean and simple
solution to my problem. :-)

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


sending keystrokes to gtk window

2006-01-25 Thread sven
hi list,
i'd like to send keystrokes to a (terminal) window.
the windowmanager is gnome (ubuntu).
what i want to do is to control dvgrab which can be
started in interactive mode.
thx in advance,

sven.

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


subprocess.Popen() output to logging.StreamHandler()

2008-04-10 Thread sven _
Version: Python 2.5.1 (r251:54863, Mar  7 2008, 04:10:12)

My goal is to have stdout and stderr written to a logging handler.
This code does not work:

# START
import logging, subprocess
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
# END

Traceback (most recent call last):
  File "log.py", line 5, in 
   subprocess.call(['ls', '-la'], 0, None, None, ch, ch)
  File "/usr/lib/python2.5/subprocess.py", line 443, in call
   return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.5/subprocess.py", line 586, in __init__
   errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.5/subprocess.py", line 941, in _get_handles
   c2pwrite = stdout.fileno()
AttributeError: StreamHandler instance has no attribute 'fileno'


This is because subprocess.Popen() expects file descriptors to write
to, and logging.StreamHandler() does not supply it. The StreamHandler
could supply its own stdout file descriptor, but then Popen() would
write directly to that file, bypassing all the logging fluff.

A possible solution would be to make a named pipe (os.mkfifo()), have
Popen() write to that, and then have some horrendous hack run select()
or similar on the fifo to read from it and finally pass it to
StreamHandler.

Are there better solutions?

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


Working around buffering issues when writing to pipes

2008-04-22 Thread sven _
Keywords: subprocess stdout stderr unbuffered pty tty pexpect flush setvbuf

I'm trying to find a solution to http://bugs.python.org/issue1241>. In
short: unless specifically told not to, normal C stdio will use full output
buffering when connected to a pipe. It will use default (typically
unbuffered) output when connected to a tty/pty.

This is why subprocess.Popen() won't work with the following program when
stdout and stderr are pipes:

#include 
#include 
int main()
{
 int i;
 for(i = 0; i < 5; i++)
 {
   printf("stdout ding %d\n", i);
   fprintf(stderr, "stderr ding %d\n", i);
   sleep(1);
 }
 return 0;
}

Then

  subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

is read using polling, but the pipes don't return any data until the
program is done. As expected, specifying a bufsize of 0 or 1 in the Popen()
call has no effect. See end of mail for example Python scripts.

Unfortunately, changing the child program to flush stdout/err or specifying
setvbuf(stdout,0,_IONBF,0); is an undesired workaround in this case.

I went with pexpect and it works well, except that I must handle stdout and
stderr separately. There seems to be no way to do this with pexpect, or am
I mistaken?

Are there alternative ways of solving this? Perhaps some way of

I'm on Linux, and portability to other platforms is not a requirement.

s


#Test script using subprocess:
import subprocess
cmd = '/tmp/slow' # The C program shown above
print 'Starting...'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
lineout = proc.stdout.readline()
lineerr = proc.stderr.readline()
exitcode = proc.poll()
if (not lineout and not lineerr) and exitcode is not None: break
if not lineout == '': print lineout.strip()
if not lineerr == '': print 'ERR: ' + lineerr.strip()
print 'Done.'


#Test script using pexpect, merging stdout and stderr:
import sys
import pexpect
cmd = '/home/sveniu/dev/logfetch/bin/slow'
print 'Starting...'
child = pexpect.spawn(cmd, timeout=100, maxread=1, logfile=sys.stdout)
try:
while True: child.expect('\n')
except pexpect.EOF: pass
print 'Done.'
--
http://mail.python.org/mailman/listinfo/python-list


Difference between mutex.mutex and threading.Lock

2009-12-04 Thread sven
Hi,

what is the difference between mutex.mutex and threading.Lock?
Neither the documentation nor a Google search gave me any clue.

Another issue: The documentation of mutex in version 2.6.4 says:

"Deprecated since version The: mutex module has been removed in Python
3.0."

Maybe it should also say what to use instead (probably
threading.Lock?).  Also the "version The" part seems a bit strange.

Greetings,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cancelling a python thread (revisited...)

2009-11-08 Thread sven
On Nov 8, 4:27 am, Carl Banks  wrote:
> It doesn't sound like the thread is communicating with the process
> much.  Therefore:

There is quite a bit of communication -- the computation results are
visulized while they are generated.

> 1. Run the C code in a separate process, or
> 2. Create the thread from a C extension, maybe even straight from
> ctypes, and kill it from C or ctypes.

The second option is a good idea.  Thanks a lot, Carl!

> > And why on earth doesn't that cancel method exist? There *are* good
> > reasons to cancel a thread, just google for "terminate a Python
> > thread" for tons of examples.
>
> Arguing that there are good reasons to allow killing threads isn't
> going to get you very far.  The language developers already know
> killing a thread is useful, yet the disallowed it anyway.  The
> drawbacks were judged too severe (it makes enforcing invariants pretty
> much impossible).

I really don't get that.  If the reason would be that it is too much
work to
implement, then I could accept it.  But saying: We know it is useful,
but we
won't allow to do it, just does not seem reasonable.  Thread
cancellation
might be generally unsafe, but there are cases when it is safe.  It
should be
up to the user to decide it.  There are many things that do harm if
you don't
use them correctly, and of course it would be a bad idea to remove all
of
them from Python.

Well, I won't complain too much.  At least some volunteers created
that
great language and gave it away for free :)

Thanks again for your suggestion.

Cheers,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cancelling a python thread (revisited...)

2009-11-08 Thread sven
On Nov 8, 2:50 pm, exar...@twistedmatrix.com wrote:
> I'm curious how this visualization works, since earlier you said
> something to the affect that there were no shared resources.  If you
> kill a thread and it had opened a window and was drawing on it, with
> most toolkits, you'll end up with a window stuck in your screen, won't
> you?

The Python code passes an array to the C library which in the end
contains the computation results.  This array only contains some kind
of counts which are incremented during the computation.  The PyGTK GUI
simply visualizes the current state of this array in regular
intervals.  The C library does not do any GUI stuff.  Cancelling the
thread really would not do any harm -- the thread only allocates
memory on the stack, and the stack will vanish with the thread.

> The CPython philosophy sort of follows the guideline that you should be
> allowed to do bad stuff if you want, except when that bad stuff would
> crash the interpreter (clearly ctypes is an exception to this rule of
> thumb).

Well, I am really glad about that exception.  And following the hint
of Carl, I will use it to call pthread_cancel or pthread_kill directly
from the library.  (Most certainly I also have to use ctypes to create
my threads to be able to do this.)

Cheers,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse subparser problem

2010-11-18 Thread Sven

On 2010-11-16 14:35:01 -0500, Neal Becker said:


I want to have subparsers, but I also want to be able to say:

myprogram --version
and get the version #


Would it not be possible to print the version number and then exit the 
program before building the subparser?



---

import argparse

def stop():
pass

parser = argparse.ArgumentParser()
parser.add_argument ('--version', action='store_true')


# if --version print version
# sys.exit(0)


subparsers = parser.add_subparsers()

parser_stop = subparsers.add_parser ('stop')
parser_stop.add_argument ('stop', action='store_true')
parser_stop.set_defaults (func=stop)


opt = parser.parse_args (['--version'])
--



--
./Sven

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


Re: Remove whitespaces and line breaks in a XML file

2011-02-11 Thread Sven

On 2011-02-07 18:46:17 -0500, Josh English said:

I found the code posted at 


http://infix.se/2007/02/06/gentlemen-indent-your-xml

quite helpful in turning my xml into human-readable structures. It works
best for XML-Data.


lxml, which the code is using, already has a pretty_print feature 
according to this http://codespeak.net/lxml/tutorial.html which would 
do the same, would it not?


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


Re: How to run another python script?

2011-02-14 Thread Sven
On Mon, 14 Feb 2011 07:56:53 -0800, rantingrick wrote:

> On Feb 14, 9:51 am, Dan Lee  wrote:
> 
>> AAA : generate zip file
>> BBB : delete old file.
>>
>> AAA is done.
>> Now I'm going to code BBB file. and I will fix AAA to call BBB to
>> delete dump file at the end.
>> Please let me know How can I call the BBB file from AAA file.
> 
> Simple: Make a call using the underlying os from the aptly named "os"
> module (or other!). OR import BBB and execute the code.

I would however recommend using the subprocess module instead of the os 
module.

http://docs.python.org/library/subprocess.html




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


Development Vs Release

2010-11-10 Thread Sven

Hi,

When developing tools I often also work on a module that I need to 
import into that tool. Once the work is complete both (or more) files 
go to a release location on the network.


The question I have is: what is the easiest way to adjust the import 
path depending on whether it's a release or dev version.


Right now I am using a custom env var (PYDEV) that I have to manually 
set when I work on the project that will insert the development module 
path into sys.path.
This way the released version will not append the path and use the 
system wide PYTHONPATH


Are there any better ways of doing this? I don't like the idea of flags 
inside the code as they can often get missed when developers release 
their code, ending up with released versions that import modules from 
the developer's working directory.


Thanks

--
./Sven

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


Re: Am I The Only One Who Keeps Reading ?Numpy? as ?Numpty??

2010-11-10 Thread Sven

On 2010-11-10 01:53:58 -0500, Lawrence D'Oliveiro said:


Sorry...


no.

--
./Sven

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


wxPython ListCtrl_edit and TextEditMixin on mac OS X 10.4

2005-08-04 Thread Sven Tissot
Hello,

I am trying to build an editable ListCtrl_edit via TextEditMixin.
It displays o.k. and I can edit the first field with this is the code piece:

class VokabelListCtrl(wxListCtrl,
listmix.ListCtrlAutoWidthMixin,
listmix.TextEditMixin):

 def __init__(self, parent, ID, pos=wxDefaultPosition,
  size=wxDefaultSize, style=0):
 wxListCtrl.__init__(self, parent, ID, pos, size, style)
 listmix.ListCtrlAutoWidthMixin.__init__(self)
 #listmix.TextEditMixin.__init__(self)


uncommenting the TextEditMixin still renders the ListCtrl, but as soon 
as I click into the grid the application crashes with a

IndexError: tuple index out of range

Traceback (innermost last):

File "/Users/einstein/python/wing/projects/vokabeln/wxVokabelApp.py", 
line 1, in ?
   #!/usr/bin/env python
File "/Users/einstein/python/wing/projects/vokabeln/wxVokabelApp.py", 
line 26, in ?
   main()
File "/Users/einstein/python/wing/projects/vokabeln/wxVokabelApp.py", 
line 23, in main
   application.MainLoop()
File "/Library/Python/2.3/wx-2.6-mac-unicode/wx/_core.py", line 7493, in 
MainLoop
   wx.PyApp.MainLoop(self)
File "/Library/Python/2.3/wx-2.6-mac-unicode/wx/_core.py", line 6926, in 
MainLoop
   return _core_.PyApp_MainLoop(*args, **kwargs)
File "/Library/Python/2.3/wx-2.6-mac-unicode/wx/lib/mixins/listctrl.py", 
line 497, in OnLeftDown
   x,y = evt.GetPosition()
File "/Library/Python/2.3/wx-2.6-mac-unicode/wx/_core.py", line 1117, in 
__getitem__
   def __getitem__(self, index):return self.Get()[index]


what is my mistake ??? Can anybody give me a hint ?

P.S. I installed the curent wxPython release and applied the following

 *  download and install 
http://pythonmac.org/packages/TigerPython23Compat.pkg.zip

 * used multiversion install via adding
   o import wxversion
   o wxversion.select("2.6")


kind regards,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


Tiny fonts in wxPython app

2005-04-18 Thread Sven Kobow
Hello,

I'm not yet a python programmer but a python user. I faced a problem
with tiny fonts in a wxPython app on a GNU/Debian system. Under Gentoo
Linux the fonts are displayed in a normal readable size. Only on that
Debian system fonts in the whole app are rather tiny. I spend quite a
long time googling for a solution and found several hints on font
problem issues in wxPython but none fitted to that mentioned above. Does
anybody has a clue what can be wrong?

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


Re: Tiny fonts in wxPython app

2005-04-18 Thread Sven Kobow
Jeff Reavis wrote:
> Sven,
> It may be the default gtk font settings. This can be changed in the
> .gtkrc file.
> 
> -jjr
> 
I'm not sure but the gnome font in general looks okay? Could be
something about proportional fonts? Or maybe a Unicode issue? I read
something about that.

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


-2146826246 in win32com.client for empty #N/A cell in Excel

2015-08-16 Thread Sven Boden

Anyone know how to handle "#N/A" in Excel from win32com.client.

I'm extracting data from an Excel file using win32com.client. Everything works 
fine except for when the value "#N/A" is entered in excel. An empty cell. I 
assumed I do something as 

if ws.Cells(r, c).Value is None:
...

But that doesn't seem to work. When I debug the piece of code while handling 
#N/A in a cell the type of the cell according to win32com.client is int and the 
value in the cell is -2146826246. Chances are small just this number will 
appear in Excel, but it looks dirty to depend on that value to decide if a cell 
is empty. Looked around the net for a solution, but nothing came up so far.

Anyone knows how to handle a "#N/A" cell in Excel in the proper way?

Regards,
Sven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: -2146826246 in win32com.client for empty #N/A cell in Excel

2015-08-17 Thread Sven Boden
On Sun, Aug 16, 2015 at 7:27 PM, Albert-Jan Roskam 
wrote:

>
>
>
> > Date: Sun, 16 Aug 2015 09:53:32 -0700
> > Subject: -2146826246 in win32com.client for empty #N/A cell in Excel
> > From: sven.bo...@gmail.com
> > To: python-list@python.org
> >
> >
> > Anyone know how to handle "#N/A" in Excel from win32com.client.
> >
> > I'm extracting data from an Excel file using win32com.client. Everything
> works fine except for when the value "#N/A" is entered in excel. An empty
> cell. I assumed I do something as
> >
> > if ws.Cells(r, c).Value is None:
> > ...
> >
> > But that doesn't seem to work. When I debug the piece of code while
> handling #N/A in a cell the type of the cell according to win32com.client
> is int and the value in the cell is -2146826246. Chances are small just
> this number will appear in Excel, but it looks dirty to depend on that
> value to decide if a cell is empty. Looked around the net for a solution,
> but nothing came up so far.
> >
> > Anyone knows how to handle a "#N/A" cell in Excel in the proper way?
> >
> > Regards,
> > Sven
> > --
> > https://mail.python.org/mailman/listinfo/python-list
>
>
> Hello,
>
> Does that number happen to be -1 * sys.maxint?
>
> Regards,
> Albert-Jan
>
>
> On python 3.x sys.maxint is gone... sys.maxsize is a lot larger on Windows
64bit (same laptop I run the code on).

Regards,
Sven
-- 
https://mail.python.org/mailman/listinfo/python-list


Iterating generator from C

2006-06-17 Thread sven . suursoho
Does messing with signal handlers and longjmp affect Python
interpreter?

I'm trying to find solution for problem, described in
http://groups.google.com/group/comp.lang.python/browse_thread/thread/98cbae94ca4beefb/9d4d96fd0dd9fbc3
and came up with test application. It works well but i'm not sure it is
ok for long-running python interpreter?

#include 
#include 
#include 

const char *py_source =
"def fn():\n"
"yield 1\n";

jmp_buf env;
enum _ { detect, no, yes } has_buggy_gen_iternext = detect;

static sighandler_t old_abrt = SIG_DFL;

void
signal_handler (int sig)
{
  if (sig == SIGABRT)
  longjmp(env, 1);
}


int
main (int argc, char *argv[])
{
  Py_Initialize();

  PyObject *globals = PyDict_New();

  // insert function code into interpreter
  PyObject *code = PyRun_String(py_source, Py_file_input, globals,
NULL);
  Py_DECREF(code);

  // compile call to the function
  code = Py_CompileString("fn()", "", Py_eval_input);

  // do call
  PyObject *gen = PyEval_EvalCode((PyCodeObject *)code, globals, NULL);
  gen = PyObject_GetIter((PyObject *)gen);

  // detect if we are using bad Python interpreter
  if (has_buggy_gen_iternext == detect) {
  if (setjmp(env) == 0)
  // first time, set signal handler
  old_abrt = signal(SIGABRT, signal_handler);
  else {
  // jumped here from signal handler -- bad Python
  has_buggy_gen_iternext = yes;
  signal(SIGABRT, old_abrt);
  }
  }

  if (has_buggy_gen_iternext == yes)
  printf("generators are disabled\n");
  else {
  // iterate result
  PyObject *item;
  while ((item = PyIter_Next(gen))) {
  printf("> %ld\n", PyInt_AsLong(item));
  Py_DECREF(item);
  }

  if (has_buggy_gen_iternext == detect) {
  // ok, restore old signal handler
  has_buggy_gen_iternext = no;
  signal(SIGABRT, old_abrt);
  }
  }

  Py_DECREF(gen);
  Py_DECREF(code);
  Py_DECREF(globals);
  
  Py_Finalize();
  return 0;
}

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


Newbie question: PyQt & Form::init()

2006-09-25 Thread Sven Ehret
Hello List,

I am trying to learn Python and followed the tutorial at
http://www.cs.usfca.edu/~afedosov/qttut/. Being happy that it works, I am
now trying to do my own project, but I am having problems with
initialization of my form.

I want to automatically fill a couple of comboboxes upon starting the
program. I read on the net that I simply have to add a function
called »Form1.Init()« with the content I wish to have executed at start
time. However, it never gets executed, so it seems. When I re-write the
application to have the code executed at the press of a button, it works.
What am I doing wrong?

Sorry for my newbieness ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: PyQt & Form::init()

2006-09-25 Thread Sven Ehret
Diez B. Roggisch wrote:

> Sven Ehret wrote:
> 
>> Hello List,
>> 
>> I am trying to learn Python and followed the tutorial at
>> http://www.cs.usfca.edu/~afedosov/qttut/. Being happy that it works, I am
>> now trying to do my own project, but I am having problems with
>> initialization of my form.
>> 
>> I want to automatically fill a couple of comboboxes upon starting the
>> program. I read on the net that I simply have to add a function
>> called »Form1.Init()« with the content I wish to have executed at start
>> time. However, it never gets executed, so it seems. When I re-write the
>> application to have the code executed at the press of a button, it works.
>> What am I doing wrong?
> 
> Show us more code, and we show you the problem. At least we can try then,
> until someone finally implements
> 
> from __future__ import mindreading
> 
> Diez

Oh, sorry. *blush*
here is my code (two files):

form1.py:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'form1.ui'
#
# Created: Mo Sep 25 15:38:56 2006
#  by: The PyQt User Interface Compiler (pyuic) 3.14.1
#
# WARNING! All changes made in this file will be lost!


from qt import *


class Form1(QDialog):
def __init__(self,parent = None,name = None,modal = 0,fl = 0):
QDialog.__init__(self,parent,name,modal,fl)

if not name:
self.setName("Form1")



self.pushButton1 = QPushButton(self,"pushButton1")
self.pushButton1.setGeometry(QRect(410,340,80,30))

self.comboBox1 = QComboBox(0,self,"comboBox1")
self.comboBox1.setGeometry(QRect(310,10,120,31))
self.comboBox1.setSizeLimit(12)
self.comboBox1.setMaxCount(12)

self.comboBox2 = QComboBox(0,self,"comboBox2")
self.comboBox2.setGeometry(QRect(431,10,60,31))

self.buttonGroup1 = QButtonGroup(self,"buttonGroup1")
self.buttonGroup1.setGeometry(QRect(10,50,480,200))

self.pushButton3 = QPushButton(self,"pushButton3")
self.pushButton3.setGeometry(QRect(200,320,101,24))

self.textLabel1 = QLabel(self,"textLabel1")
self.textLabel1.setGeometry(QRect(71,10,160,30))

self.languageChange()

self.resize(QSize(504,380).expandedTo(self.minimumSizeHint()))
self.clearWState(Qt.WState_Polished)

self.connect(self.pushButton1,SIGNAL("clicked()"),self.close)
self.connect(self.comboBox1,SIGNAL("activated(const
QString&)"),self.AddMonthsToCombo)
   
self.connect(self.pushButton3,SIGNAL("clicked()"),self.AddMonthsToCombo)


def languageChange(self):
self.setCaption(self.__tr("Form1"))
self.pushButton1.setText(self.__tr("Beenden"))
self.buttonGroup1.setTitle(QString.null)
self.pushButton3.setText(self.__tr("pushButton3"))
self.textLabel1.setText(self.__tr("textLabel1"))


def AddMonthsToCombo(self):
import time
self.comboBox1.insertItem("Januar")
self.comboBox1.insertItem("Februar")
self.comboBox1.insertItem("MÀrz")
self.comboBox1.insertItem("April")
self.comboBox1.insertItem("Mai")
self.comboBox1.insertItem("Juni")
self.comboBox1.insertItem("Juli")
self.comboBox1.insertItem("August")
self.comboBox1.insertItem("September")
self.comboBox1.insertItem("Oktober")
self.comboBox1.insertItem("November")
self.comboBox1.insertItem("Dezember")
self.comboBox2.insertItem("2005")
self.comboBox2.insertItem("2006")
self.comboBox2.insertItem("2007")
self.comboBox2.insertItem("2008")
s = time.strftime("%B")
t = time.strftime("%Y")
self.comboBox1.setCurrentText(s)
self.comboBox2.setCurrentText(t)


def __tr(self,s,c = None):
return qApp.translate("Form1",s,c)




this gets executed by this »wrapper«-script as shown to me in the tutorial:

mygui.py

from qt import *
from form1 import *
import time
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = Form1()
f.show()
app.setMainWidget(f)
app.exec_loop()



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


Re: Newbie question: PyQt & Form::init() SOLVED

2006-09-25 Thread Sven Ehret
Diez B. Roggisch wrote:

> Sven Ehret wrote:
> 
>> Diez B. Roggisch wrote:
>> 
>>> Sven Ehret wrote:
>>> 
>>>> Hello List,
>>>> 
>>>> I am trying to learn Python and followed the tutorial at
>>>> http://www.cs.usfca.edu/~afedosov/qttut/. Being happy that it works, I
>>>> am now trying to do my own project, but I am having problems with
>>>> initialization of my form.
>>>> 
>>>> I want to automatically fill a couple of comboboxes upon starting the
>>>> program. I read on the net that I simply have to add a function
>>>> called »Form1.Init()« with the content I wish to have executed at start
>>>> time. However, it never gets executed, so it seems. When I re-write the
>>>> application to have the code executed at the press of a button, it
>>>> works. What am I doing wrong?
>>> 
>>> Show us more code, and we show you the problem. At least we can try
>>> then, until someone finally implements
>>> 
>>> from __future__ import mindreading
>>> 
>>> Diez
>> 
>> Oh, sorry. *blush*
>> here is my code (two files):
>> 
>> form1.py:
>> # -*- coding: utf-8 -*-
>> 
>> # Form implementation generated from reading ui file 'form1.ui'
>> #
>> # Created: Mo Sep 25 15:38:56 2006
>> #  by: The PyQt User Interface Compiler (pyuic) 3.14.1
>> #
>> # WARNING! All changes made in this file will be lost!
>> 
>> 
>> from qt import *
>> 
>> 
>> class Form1(QDialog):
>> def __init__(self,parent = None,name = None,modal = 0,fl = 0):
>> QDialog.__init__(self,parent,name,modal,fl)
>> 
>> if not name:
>> self.setName("Form1")
>> 
>> 
>> 
>> self.pushButton1 = QPushButton(self,"pushButton1")
>> self.pushButton1.setGeometry(QRect(410,340,80,30))
>> 
>> self.comboBox1 = QComboBox(0,self,"comboBox1")
>> self.comboBox1.setGeometry(QRect(310,10,120,31))
>> self.comboBox1.setSizeLimit(12)
>> self.comboBox1.setMaxCount(12)
>> 
>> self.comboBox2 = QComboBox(0,self,"comboBox2")
>> self.comboBox2.setGeometry(QRect(431,10,60,31))
>> 
>> self.buttonGroup1 = QButtonGroup(self,"buttonGroup1")
>> self.buttonGroup1.setGeometry(QRect(10,50,480,200))
>> 
>> self.pushButton3 = QPushButton(self,"pushButton3")
>> self.pushButton3.setGeometry(QRect(200,320,101,24))
>> 
>> self.textLabel1 = QLabel(self,"textLabel1")
>> self.textLabel1.setGeometry(QRect(71,10,160,30))
>> 
>> self.languageChange()
>> 
>> self.resize(QSize(504,380).expandedTo(self.minimumSizeHint()))
>> self.clearWState(Qt.WState_Polished)
>> 
>> self.connect(self.pushButton1,SIGNAL("clicked()"),self.close)
>> self.connect(self.comboBox1,SIGNAL("activated(const
>> QString&)"),self.AddMonthsToCombo)
> 
> When you just invoke
> 
> 
>   self.AddMonthsToCombo()
> 
> here, things should work.
> 
> Diez


thank you, but,

I think I was able to sort it out for myself. I had to add the function
using the QtDesigner GUI (Add Slot). Then it gets recognised as
initialization module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling ksh script from python

2005-06-04 Thread Sven Mascheck
(fup'2 set) In comp.unix.shell Donn Cave wrote:

> Portability [ksh]
> "echo" seems to mimic the behavior of sh on its host platform.

Rather: both usually mimic echo(1) - some shells even inspect PATH
(e.g. /usr/ucb/, /usr/5bin/ vs. /usr/bin/) and act accordingly.
-- 
http://mail.python.org/mailman/listinfo/python-list


find out all threads?

2007-05-11 Thread Sven Rech
Hi,

I have a written a C program which makes use of python embedding.
I want to find out all threads that a loaded module has started. 
But I can't find anything about this in the docs. Is it possible?



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


Problems with thread safety

2007-05-12 Thread Sven Rech
Hi,

In my C program, I want to use python scripts. This scripts should also
have the ability to start threads.

So at the initilisation phase I do:
PyEval_InitThreads();
PyEval_ReleaseLock();

With the second call I want to release lock, for that the python threads
can also do their work.

But then, when I call a method in a script which starts a thread then, I
get the following error:
Fatal Python error: PyEval_AcquireThread: non-NULL old thread state
Aborted (core dumped)

What did I wrong?

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


python embedding and threads

2007-01-18 Thread Sven Rech
Hi,

I'm the author of an application written in C, which should now be 
extended with a python plugin system.
It already works very good, but I now have a problem:
Threading functionality within the python modules, that my C app loads 
and calls, doesn't work. This means, the threads do not run (the same 
python code works correct if I just start it with the normal python 
interpreter).


Is there something I must be aware of, if I want to use (python) threads 
with embedded python? (for example call a special function or something 
like that)

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


2.5a1 import of .dlls

2006-04-18 Thread sven . nystrom
I've re-built an extension module (as a .dll) using the 2.5a1 release.
Unexpectedly, I'm not able to simply import it (not the way I can when
building it for 2.3). Using imp.load_dynamic() the import succeeds.

>>> import minx # Implemented in a .dll - fails
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named minx
>>> import imp# Workaround
>>> import os
>>> minx = imp.load_dynamic('minx', os.getcwd() + '\\minx.dll')
>>>

I couldn't find anything to indicate this is by design in 2.5a1 (I did
read the PEP 328: Absolute and Relative Imports) - am I doing something
wrong?

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


pythoncode in matlab

2006-05-11 Thread Sven Jerzembeck
Hello guys,
is there any possibiliy using Phython code in Matlab. I couldnt find
any helpful stuff. Its not graphical stuff I am doing just
calculations with arrays and strings.

Thanks for  answering in advance

Sven


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


Iterating generator from C

2006-05-13 Thread Sven Suursoho
Hi,


I am working on project that has embedded python interpreter to run  
user-specified python procedures. Those procedures might return any  
iterable object with set of result data -- basically everything for which  
iter() returns valid object (list, tuple, dict, iterator etc)

It works ok, except generator under Python 2.4 with debugging enabled (see  
http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470).

Is there any way to rewrite following program to handle returned generator  
without hitting this bug?
Error handling is omitted for clarity.

#include 

const char *py_source =
 "def fn():\n"
 "   yield 1\n";

int main ()
{
   Py_Initialize();

   PyObject *globals = PyDict_New();

   // insert function code into interpreter
   PyObject *code = PyRun_String(py_source, Py_file_input, globals, NULL);
   Py_DECREF(code);

   // do call
   code = Py_CompileString("fn()", "", Py_eval_input);
   PyObject *gen = PyEval_EvalCode((PyCodeObject *)code, globals, NULL);

   // iterate result
   PyObject *item;
   while ((item = PyIter_Next(gen))) {
   printf("> %ld\n", PyInt_AsLong(item));
   Py_DECREF(item);
   }

   Py_DECREF(gen);
   Py_DECREF(code);
   Py_DECREF(globals);

   Py_Finalize();
   return 0;
}


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


Re: Iterating generator from C

2006-05-15 Thread Sven Suursoho
Mon, 15 May 2006 16:53:12 +0300, Christian Tismer <[EMAIL PROTECTED]>:

>>   I am working on project that has embedded python interpreter to run   
>> user-specified python procedures. Those procedures might return any   
>> iterable object with set of result data -- basically everything for  
>> which  iter() returns valid object (list, tuple, dict, iterator etc)
>>  It works ok, except generator under Python 2.4 with debugging enabled  
>> (see  
>> http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470).
>>  Is there any way to rewrite following program to handle returned  
>> generator  without hitting this bug?
>
> I found this bug as well, and I think the fix should be
> back-ported.
> This problem can only show up when you are comiling a C
> extension, anyway.
> Why don't you just apply the fix and compile your own?
> It is just a wrong assertion, anyway.

Unfortunately, this is not an option because I can't control used  
environment: I'm trying to improve PostgreSQL's stored procedure language  
PL/Python and this software can be used everywhere.

At first I tried to block using generators if Py_DEBUG is defined. But  
this wouldn't work because of another, overlapping bug in Fedora Core 4's  
RPM packaging system (didn't check other versions) -- it disables Py_DEBUG  
but strips -DNDEBUG from compiler's command-line i.e. no Py_DEBUG and  
still active asserts().

See:
http://archives.postgresql.org/pgsql-patches/2006-05/msg00042.php
http://archives.postgresql.org/pgsql-patches/2006-05/msg00105.php


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


using FFTW3 with Numeric on Windows

2006-05-28 Thread sven koenig
hi list,
as the subject says, I'm trying to find a way to use
FFTW3 with Numeric arrays.
I'm not very familiar with C(++) - I think ctypes is the
way to go, but I don't really have a clue how to do it.
Has somebody already tried this?

thx,
sven.

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


Re: Python surpasses Perl in popularity?

2008-11-30 Thread Sven Mascheck
In comp.unix.shell Stephane CHAZELAS wrote:

> The Bourne shell, as can still be found on some systems either in some
> non-standard place (/bin on Solaris, /usr/old/bin on HPUX) or named
> differently [...]

What do you mean with "non-standard place" here?
--
http://mail.python.org/mailman/listinfo/python-list


Python and Glade: window not showing

2009-05-30 Thread Sven Arduwie
Can anyone help a python newbie and tell me why the simple window I
created in Glade is not showing?

This is the XML generated by Glade 3:


  
  
  
True


  

  


And this is the Python code:
#!/usr/bin/env python

import pygtk
pygtk.require("2.0")
import gtk

class HelloWorld(object):
def getWindow(self):
return self.window

def setWindow(self, window):
self.window = window

window = property(getWindow, setWindow)

def __init__(self):
builder = gtk.Builder()
builder.add_from_file("helloWorld.glade")
builder.connect_signals({"on_helloWorld_destroy" :
self.onHelloWorldDestroy})
self.window = builder.get_object("helloWorld")
self.window.show()

def onHelloWorldDestroy(self):
pass

I ran this in a terminal on Ubuntu 9.04 like this:
s...@dell:~$ cd ./gvfs/python\ on\ sven/
s...@dell:~/gvfs/python on sven$ python ./helloWorld.py
s...@dell:~/gvfs/python on sven$
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Glade: window not showing

2009-05-30 Thread Sven Arduwie
On 30 mei, 17:02, Sven Arduwie  wrote:
> Can anyone help a python newbie and tell me why the simple window I
> created in Glade is not showing?
>
> This is the XML generated by Glade 3:
> 
> 
>   
>   
>   
>     True
>     
>     
>       
>     
>   
> 
>
> And this is the Python code:
> #!/usr/bin/env python
>
> import pygtk
> pygtk.require("2.0")
> import gtk
>
> class HelloWorld(object):
>         def getWindow(self):
>                 return self.window
>
>         def setWindow(self, window):
>                 self.window = window
>
>         window = property(getWindow, setWindow)
>
>         def __init__(self):
>                 builder = gtk.Builder()
>                 builder.add_from_file("helloWorld.glade")
>                 builder.connect_signals({"on_helloWorld_destroy" :
> self.onHelloWorldDestroy})
>                 self.window = builder.get_object("helloWorld")
>                 self.window.show()
>
>         def onHelloWorldDestroy(self):
>                 pass
>
> I ran this in a terminal on Ubuntu 9.04 like this:
> s...@dell:~$ cd ./gvfs/python\ on\ sven/
> s...@dell:~/gvfs/python on sven$ python ./helloWorld.py
> s...@dell:~/gvfs/python on sven$

Okay I'm mad at myself for forgetting this:

if __name__ == "__main__":
helloWorld = HelloWorld()
gtk.main()

When I add that, a new problem arises: the terminal floods with:
  File "./helloWorld.py", line 12, in setWindow
self.window = window
  File "./helloWorld.py", line 12, in setWindow
self.window = window
  File "./helloWorld.py", line 12, in setWindow
self.window = window
ad infinitum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Glade: window not showing

2009-05-30 Thread Sven Arduwie
On 30 mei, 21:02, Dave Angel  wrote:
> Sven Arduwie wrote:
> > On 30 mei, 17:02, Sven Arduwie  wrote:
>
> >> Can anyone help a python newbie and tell me why the simple window I
> >> created in Glade is not showing?
>
> >> This is the XML generated by Glade 3:
> >> 
> >> 
> >>   
> >>   
> >>   
> >>     True
> >>     
> >>     
> >>       
> >>     
> >>   
> >> 
>
> >> And this is the Python code:
> >> #!/usr/bin/env python
>
> >> import pygtk
> >> pygtk.require("2.0")
> >> import gtk
>
> >> class HelloWorld(object):
> >>         def getWindow(self):
> >>                 return self.window
>
> >>         def setWindow(self, window):
> >>                 self.window =indow
>
> >>         window =roperty(getWindow, setWindow)
>
> >>         def __init__(self):
> >>                 builder =tk.Builder()
> >>                 builder.add_from_file("helloWorld.glade")
> >>                 builder.connect_signals({"on_helloWorld_destroy" :
> >> self.onHelloWorldDestroy})
> >>                 self.window =uilder.get_object("helloWorld")
> >>                 self.window.show()
>
> >>         def onHelloWorldDestroy(self):
> >>                 pass
>
> >> I ran this in a terminal on Ubuntu 9.04 like this:
> >> s...@dell:~$ cd ./gvfs/python\ on\ sven/
> >> s...@dell:~/gvfs/python on sven$ python ./helloWorld.py
> >> s...@dell:~/gvfs/python on sven$
>
> > Okay I'm mad at myself for forgetting this:
>
> > if __name__ ="__main__":
> >    helloWorld =elloWorld()
> >    gtk.main()
>
> > When I add that, a new problem arises: the terminal floods with:
> >   File "./helloWorld.py", line 12, in setWindow
> >     self.window =indow
> >   File "./helloWorld.py", line 12, in setWindow
> >     self.window =indow
> >   File "./helloWorld.py", line 12, in setWindow
> >     self.window =indow
> > ad infinitum
>
> You have infinite recursion because setWindow is defined indirectly in
> terms of itself.  It uses the property 'window', which is defined to use
> setWindow.
>
> The cure for it is simple.  If you want to have a private data
> attribute, use a leading underscore.  Don't call it the same thing that
> the public is going to use.
>
> class HelloWorld(object):
>          def getWindow(self):
>                  return self._window
>
>          def setWindow(self, window):
>                  self._window = window
>
>          window = property(getWindow, setWindow)
>
>          def __init__(self):
>                  builder = gtk.Builder()
>                  builder.add_from_file("helloWorld.glade")
>                  builder.connect_signals({"on_helloWorld_destroy" :
>  self.onHelloWorldDestroy})
>                  self._window = builder.get_object("helloWorld")
>                  self._window.show()
>
>          def onHelloWorldDestroy(self):
>                  pass
>
> (untested)

That solved the problem, thanks!

I assume that the getWindow and setWindow can be bypassed by using the
_window property directly and that Python has no visibility keywords
like private or protected. Sort of like PHP 4. (Not that I want to
compare Python to anything like that mess, lol ;))
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE 3.0a5 has problems with Unicode

2008-05-11 Thread Sven Siegmund
Hello,

I am testing Python 3.0a5's handling of unicode strings. Since SPE is
not yet for Python 3.0, I have begun to write in IDLE 3.0a5.

I have a source code which IDLE 3.0a5 cannot parse, but Python 3.0a5
can:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def načtiSlovník(zdroj='slovník.txt'):
soubor = open(zdroj, mode='r', encoding='utf_8')
řádky = soubor.readlines()
for řádek in řádky:
print(řádek, end='')

načtiSlovník()
# End of source code

I have set up Default Source Encoding to UTF-8 in IDLE's general
configuration. Still, when I open that source code and try to run it,
IDLE complains about "invalid character in identifier" and highlights
"zdroj" red in the first line (sic!).

However, when I run the source code from command line (by "python
"), it gets executed well and does what it shall do.

I should probably add, that I have installed py3k:62932M, May 9 2008,
16:23:11 [MSC v.1500 32 bit (Intel)] on win32. I use Windows XP SP 3.

Is this a known bug if IDLE 3.0a5 which will be fixed in the final
release?

Greetings,

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


Re: IDLE 3.0a5 has problems with Unicode

2008-05-11 Thread Sven Siegmund
> I have a source code which IDLE 3.0a5 cannot parse, but Python 3.0a5
> can:

Oh I see the posts in this newsgroup do not yet support Unicode. Most
of the special characters in my source code have been messed up. But
anyway, those who know Czech can handle it. The error is replicable
even with the messed-up characters.

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


Re: IDLE 3.0a5 has problems with Unicode

2008-05-11 Thread Sven Siegmund
> No, it's now a known bug (at least I don't know it). Whether or not it
> gets fixed might depend on whether or not it gets reported to
> bugs.python.org.

Ok, I'll repost it there.

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


Cannot run Python 3.0a5 )-:

2008-05-12 Thread Sven Siegmund
Hi, I just tried to install Python 3.0a5 an another Windows PC. I did
what I have done yesterday at home:

1. Downloaded the daily snapshot 
http://svn.python.org/snapshots/msi/python-3.0.14011.msi
2. Installed to C:\Python30
3. Added C:\Python30 to the Path environment for all users.

when I run python from the command line, it says: The system cannot
execute the specified program.

I don't understand this.

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


Re: Cannot run Python 3.0a5 )-:

2008-05-12 Thread Sven Siegmund
Ah, I solved it. I was wrong. I did not do the same as yesterday.
Yesterday I downloaded Python 3.0a5 from 
http://www.python.org/ftp/python/3.0/python-3.0a5.msi
and not the daily build.

I can python again now (-:

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


Cancelling a python thread (revisited...)

2009-11-07 Thread Sven Marnach
Hi,

the Python threading module does not seem to provide a means to cancel
a running thread.  There are many discussions on the web dealing with
this issue and many solutions are offered, but none of them seems to
be applicable to my situation, which is as follows:

I have a C library which does some very computationally intensive
stuff.  Some functions in this library might run for a long time, and
the code in the library is optimized for speed.  The library is used
in C programs and also from a PyGTK GUI program.  In the GUI, you can
choose the computation parameters and than start the computation.  It
is run in a separate thread, which calls a function in the C library
via ctypes.

Now it should be possible to cancel the computation from the GUI.  In
the C programs, I can just kill or cancel the thread (there is no
cleanup to be done -- the thread does not use any system resources
apart from CPU time).  In Python, this is not possible.  The solutions
for this problem I found on the web usually recommend to have the
thread regularly check some variable and exit if this variable
indicates to do so.  This would have to be included in the C library
and would include quite a bit of code refactoring.  The check cannot
be included in the inner loop because it would lead to significant
performance loss.  Furthermore, I just do not want to mess up an
elegant and efficient library design which works perfect when used
from C just to make up for shortcomings in Python.

So do I really have to refactor my C library just because Python
Thread objects lack a cancel method?  Is there really no other way?
And why on earth doesn't that cancel method exist?  There *are* good
reasons to cancel a thread, just google for "terminate a Python
thread" for tons of examples.

I would be grateful for any suggestions.

Greetings from Germany and have a nice day,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


argparse: delimiter for argparse list arguments

2021-08-02 Thread Sven R. Kunze

Hi everyone,

maybe, I am missing something here but is it possible to specify a 
delimiter for list arguments in argparse:


https://docs.python.org/3/library/argparse.html

Usually, '--' is used to separate two lists (cf. git).

Cheers,
Sven

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


Re: argparse: delimiter for argparse list arguments

2021-08-03 Thread Sven R. Kunze

It could be but I've seen them used somewhere else.

I wouldn't bikeshed on this yet, as I haven't found a way to do this so 
far. Let's imagine the following parser:


parser.add_argument('things',action='append')
parser.add_argument('stuff',action='append')

At least from my point of view, I don't any way to separate both lists 
on this command call:



cool-script.py thing1 thing2 stuff1 stuff2


Do I miss something here?


Best
Sven

On 03.08.21 01:49, Dan Stromberg wrote:


Isn't -- usually used to signal the end of options?

On Mon, Aug 2, 2021 at 12:52 PM Sven R. Kunze <mailto:srku...@mail.de>> wrote:


Hi everyone,

maybe, I am missing something here but is it possible to specify a
delimiter for list arguments in argparse:

https://docs.python.org/3/library/argparse.html
<https://docs.python.org/3/library/argparse.html>

Usually, '--' is used to separate two lists (cf. git).

Cheers,
Sven

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

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


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


Re: [Python-ideas] Inconsistencies

2016-09-11 Thread Sven R. Kunze

On 10.09.2016 15:00, Chris Angelico wrote:

Some things are absolute hard facts. There is no way in which 1 will
ever be greater than 2, ergo "1 is less than 2" is strictly true, and
not a matter of opinion. If you hear someone trying to claim
otherwise, would you let him have his opinion, or would you treat it
as incorrect?


I don't know exactly if it's clear that one would need to make a 
distinction between real/physical-world facts and pure-logic facts.


"1 < 2" is by definition "true" (construction of natural numbers) not by 
real-world evidence. IIRC, the quote is about real-world matters.



There is some merit in this. For instance, Python 2 had a lower-level
consistency in the division operator than Python 3 has. According to
Py2, integers and floats are fundamentally different beasts, and when
you divide an int by an int, you get an int, not a float. Py3 says
"well, you probably REALLY meant to divide a number by a number", so
it gives you a float back, unless you explicitly ask for floor
division.

Py2 is more consistent on a lower level of abstraction. Py3 is more
consistent on a higher level of abstraction (modulo the oddities at
extremely large numbers). Both have merit, but in a high level
language, the Py3 way is usually [1] better.

But the consistency of call-by-object-reference is at the same high
level as the consistency of call-by-value or call-by-name. I can
explain Python's assignment model to someone fairly easily, using
pencil and paper, without any reference to "low level" or "high level"
concepts. And Python is extremely internally consistent; *every*
assignment behaves the exact same way. How does "import x" compare
with "from x import y"? Easy: the former is "x = some_module_object",
and the latter is "y = some_module_object.y", and either way, it's
regular assignment. How does parameter passing work? You take the
value of the argument as evaluated in the caller, and assign it to the
parameter in the function. What about default arguments? They're
evaluated when the function's defined, and assigned to the parameter
when it's called. Function definition itself is the same thing - it's
assigning a function object to a name. Python handles every one of
them the same way.

I don't care one iota about how voltages inside a CPU operate. I don't
generally even care about machine code - let other people worry about
that, people more expert than I am. Discussions about how the core dev
and the novice see Python's consistencies are nothing to do with those
levels. To go back to your original point, that a newbie is better at
recognizing inconsistencies... maybe, in a sense, but they also get a
lot of false positives. Ultimately, "consistent" means that there's a
single pattern that explains everything; if you're unaware of that
pattern, you won't know that it's consistent.

ChrisA


[1] Even in Python, there are places where low-level consistency is
better, because Python is a glue language. But in general, it's better
for Python to be consistent with humans than with C APIs.


The last sentence is the part why I love Python.  :)

I could not agree more with what you said above, so I hope this will put 
the discussion in better perspective, especially when people here trying 
to be overly absolute in their views (which was the quote about).


Cheers,
Sven

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


Re: Which are best, well-tested ways to create REST services, with Json, in Python?

2016-03-29 Thread Sven R. Kunze
Not heard of any but I can recommend django-restframework. We've got 
good experience with that.


On 28.03.2016 23:06, David Shi via Python-list wrote:

Has anyone done a recent reviews of creating REST services, in Python?
Regards.
David


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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze



On 29.03.2016 06:13, Michael Torrie wrote:

On 03/28/2016 06:44 PM, Steven D'Aprano wrote:

http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/

I have the same problem as the writer.  Working in Python makes me
really dislike working in any other language!



Python = English


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


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 11:39, Peter Otten wrote:

My question to those who know a bit of C#: what is the state-of-the-art
equivalent to

"\n".join(foo.description() for foo in mylist
  if foo.description() != "")



Using LINQ, I suppose: 
https://en.wikipedia.org/wiki/Language_Integrated_Query

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


Re: newbie question

2016-03-29 Thread Sven R. Kunze



On 28.03.2016 17:34, ast wrote:


"Matt Wheeler"  a écrit dans le message de 
news:mailman.92.1458825746.2244.python-l...@python.org...

On Thu, 24 Mar 2016 11:10 Sven R. Kunze,  wrote:


On 24.03.2016 11:57, Matt Wheeler wrote:
>>>> import ast
>>>> s = "(1, 2, 3, 4)"
>>>> t = ast.literal_eval(s)
>>>> t
> (1, 2, 3, 4)

I suppose that's the better solution in terms of safety.



It has the added advantage that the enquirer gets to import a module 
that

shares their name ;)



I had a look at that "ast" module doc, but I must admit that
I didn't understood a lot of things.


If there were a module "srkunze", I think, I would be equally surprised. ;)

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


Re: Threading is foobared?

2016-03-29 Thread Sven R. Kunze

On 27.03.2016 05:01, Steven D'Aprano wrote:

Am I the only one who has noticed that threading of posts here is severely
broken? It's always been the case that there have been a few posts here and
there that break threading, but now it seems to be much more common.


I agree. Didn't we both already have a conversation about this? I 
thought it is my thunderbird messing things up.


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


Re: Exclude every nth element from list?

2016-03-29 Thread Sven R. Kunze

On 26.03.2016 18:06, Peter Otten wrote:

beliavsky--- via Python-list wrote:


I can use x[::n] to select every nth element of a list. Is there a
one-liner to get a list that excludes every nth element?

del x[::n]

;)


Actually quite nice.
--
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 12:18, Sven R. Kunze wrote:

On 29.03.2016 11:39, Peter Otten wrote:

My question to those who know a bit of C#: what is the state-of-the-art
equivalent to

"\n".join(foo.description() for foo in mylist
  if foo.description() != "")



Using LINQ, I suppose: 
https://en.wikipedia.org/wiki/Language_Integrated_Query


Friend of mine told me something like this:

String.Join("\n", mylist.Where(foo => 
!String.IsNullOrEmpty(foo.description)).Select(foo => foo.description))


[untested, but from what I know of quite correct]

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


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 18:05, Peter Otten wrote:

Reformatting it a bit

String.Join(
 "\n",
 mylist.Where(
 foo => !String.IsNullOrEmpty(foo.description)
 ).Select(
 foo => foo.description))

this looks like a variant of Python's

str.join(
"\n",
map(lambda foo: foo.description,
filter(lambda foo: foo.description, mylist)))

Assuming it's type-safe and can perhaps reshuffle the where and select part
into something optimised there is definitely progress.

But still, Python's generator expressions are cool..


Haha, sure. But don't get stuck there. Learn something new from time to 
time; even a new language.



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


Re: Threading is foobared?

2016-03-30 Thread Sven R. Kunze

On 30.03.2016 01:43, Steven D'Aprano wrote:

On Tue, 29 Mar 2016 09:26 pm, Sven R. Kunze wrote:


On 27.03.2016 05:01, Steven D'Aprano wrote:

Am I the only one who has noticed that threading of posts here is
severely broken? It's always been the case that there have been a few
posts here and there that break threading, but now it seems to be much
more common.

I agree. Didn't we both already have a conversation about this? I
thought it is my thunderbird messing things up.

I'm not using Thunderbird, so whatever the cause of the problem, it is not
specific to Thunderbird.






Haha, how nice. My thread view shows your reply as a sibling not a child 
to my mail. I assume you replied to my mail. How strange.



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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-30 Thread Sven R. Kunze

On 30.03.2016 01:29, Eric S. Johansson wrote:



On 3/29/2016 6:05 AM, Sven R. Kunze wrote:


Python = English

As someone who writes English text and code using speech recognition, 
I can assure you that Python is not English. :-)


:D Interesting. Never thought of how Python sounds when spoken.

Btw. the equivalence was more meant in the context of this thread. ;)

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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-30 Thread Sven R. Kunze

On 30.03.2016 12:14, Tim Golden wrote:

Not that you quite meant this, but I'm always amused (and still a little
startled) when I listen to talks recorded from, say, PyCon and hear
people with American accents pronouncing Python with the stress on the
slightly longer second syllable.

(I don't know how other English-speaking groups say the word, but in
England the first syllable is stressed and the second is the
conventional short "uh" sound).

TJG


I recognize this too. I also started with the England variant but now I 
am not so sure anymore. :D


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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-30 Thread Sven R. Kunze

On 30.03.2016 12:21, BartC wrote:

On 30/03/2016 11:07, Sven R. Kunze wrote:

On 30.03.2016 01:29, Eric S. Johansson wrote:



On 3/29/2016 6:05 AM, Sven R. Kunze wrote:


Python = English


As someone who writes English text and code using speech recognition,
I can assure you that Python is not English. :-)


:D Interesting. Never thought of how Python sounds when spoken.


Among other things, it becomes case insensitive...



Now that you mention it... ;)

You do coding with speech recognition, too?


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


Re: Slice equivalent to dict.get

2016-03-31 Thread Sven R. Kunze

On 31.03.2016 17:07, Steven D'Aprano wrote:

Sometimes people look for a method which is equivalent to dict.get, where
they can set a default value for when the key isn't found:


py> d = {1: 'a', 2: 'b'}
py> d.get(999, '?')
'?'


The equivalent for sequences such as lists and tuples is a slice. If the
slice is out of range, Python returns a empty sequence:


I see what you are trying to achieve here. What do you think about this?

[1, 2, 3].get(999, '?')


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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-31 Thread Sven R. Kunze

On 31.03.2016 18:30, Travis Griggs wrote:



British:  http://www.oxforddictionaries.com/definition/english/python
American: http://www.dictionary.com/browse/python?s=t

That does it. If I ever make some sort of open source module for pythun/pythawn 
I’ll be sure to call it either tuhmayto/tomawto. Or maybe I’ll call it 
puhtayto/potawto.


Isn't it more like "Pythn"?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Best Practices for Internal Package Structure

2016-04-04 Thread Sven R. Kunze

Hi Josh,

good question.

On 04.04.2016 18:47, Josh B. wrote:

My package, available at https://github.com/jab/bidict, is currently laid out 
like this:

bidict/
├── __init__.py
├── _bidict.py
├── _common.py
├── _frozen.py
├── _loose.py
├── _named.py
├── _ordered.py
├── compat.py
├── util.py


I'd like to get some more feedback on a question about this layout that I originally 
asked here: <https://github.com/jab/bidict/pull/33#issuecomment-193877248>:

What do you think of the code layout, specifically the use of the _foo modules? 
It seems well-factored to me, but I haven't seen things laid out this way very 
often in other projects, and I'd like to do this as nicely as possible.

It does kind of bug me that you see the _foo modules in the output when you do 
things like this:
[code]


we had a similar discussion internally. We have various packages 
requiring each other but have some internals that should not be used 
outside of them.


The _ signifies that actually clearly but it looks weird within the 
package itself.


We haven't found a solution so far. Maybe others do.


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


Re: Best Practices for Internal Package Structure

2016-04-05 Thread Sven R. Kunze

On 05.04.2016 03:43, Steven D'Aprano wrote:

The purpose of packages isn't enable Java-style "one class per file" coding,
especially since *everything* in the package except the top level "bidict"
module itself is private. bidict.compat and bidict.util aren't flagged as
private, but they should be, since there's nothing in either of them that
the user of a bidict class should care about.

(utils.py does export a couple of functions, but they should be in the main
module, or possibly made into a method of BidirectionalMapping.)

Your package is currently under 500 lines. As it stands now, you could
easily flatten it to a single module:

bidict.py


I don't recommend this.

The line is blurry but 500 is definitely too much. Those will simply not 
fit on a 1 or 2 generous single screens anymore (which basically is our 
guideline). The intention here is to always have a bit more of a full 
screen of code (no wasted pixels) while benefiting from switching to 
another file (also seeing a full page of other code).


This said, and after having a look at your packages code, it's quite 
well structured and you have almost always more than 1 name defined in 
each submodule. So, it's fine. _frozen and _loose are a bit empty but 
well don't let's stretch rules here too far.


I remember us having some years ago file that regularly hit the 3000 or 
4000 lines of code. We systematically split those up, refactored them 
and took our time to name those module appropriately. Basically we 
started with:


base.py << trashcan for whatever somebody might need

to

base.py << really the base
domain_specific1.py  << something you can remember
domain_specific2.py  << ...
domain_specific3.py
domain_specific4.py



Unless you are getting some concrete benefit from a package structure, you
shouldn't use a package just for the sake of it.


I agree.


Even if the code doubles
in size, to 1000 lines, that's still *far* below the point at which I
believe a single module becomes unwieldy just from size. At nearly 6500
lines, the decimal.py module is, in my opinion, *almost* at the point where
just size alone suggests splitting the file into submodules. Your module is
nowhere near that point.


I disagree completely. After reading his package, the structure really 
helped me. So, I see a benefit.



I agree with Steven that hiding where a name comes from is a bit 
problematic. Additionally, as we use PyCharm internally, 1) we don't see 
imports regularly 2) we don't create/optimize them manually anymore 3) 
we just don't care if the import is too long. So, it's fine to us and as 
PyCharm tried not to be overly clever when it comes to detecting names, 
we like the direct way.


In case of our PyPI module, usability is really important for newbies 
and people not using sophisticated IDEs. So, making it really easy for 
them is a must. :)


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


Re: Best Practices for Internal Package Structure

2016-04-05 Thread Sven R. Kunze

On 05.04.2016 19:59, Chris Angelico wrote:

On Wed, Apr 6, 2016 at 3:38 AM, Sven R. Kunze  wrote:

Your package is currently under 500 lines. As it stands now, you could
easily flatten it to a single module:

bidict.py


I don't recommend this.

The line is blurry but 500 is definitely too much. Those will simply not fit
on a 1 or 2 generous single screens anymore (which basically is our
guideline). The intention here is to always have a bit more of a full screen
of code (no wasted pixels) while benefiting from switching to another file
(also seeing a full page of other code).

Clearly this is a matter of opinion. I have absolutely no problem with
a 500-lne file. As soon as you force people to split things across
files, you add a new level of indirection that causes new problems.


Guidelines. No forcing.


I'd rather keep logically-related code together rather than splitting
across arbitrary boundaries;


That's a good advice and from what I can see bidict adheres to that. ;)


you can always search within a file for the bit you want.


If you work like in the 80's, maybe. Instead of scrolling, (un)setting 
jumppoints, or use splitview of the same file, it's just faster/easier 
to jump between separate files in todays IDEs if you need to jump 
between 4 places within 3000 lines of code.



When you split a file into two, you duplicate the
headers at the top (imports and stuff), so you'll split a 100-line
file into two 60-line files or so. Do that to several levels in a big
project and you end up with a lot more billable lines of code, but no
actual improvement.


Who cares about the imports? As I said somewhere else in my response, 
it's hidden from sight if you use a modern IDE. We call that folding. ;)


Who bills lines of code? Interesting business model. ;)


I guess that's worth doing - lovely billable hours
doing the refactoring,


Refactoring is not just splitting files if that concept is new to you.

Refactoring it not an end to itself. It serves a purpose.


more billable hours later on when you have to
read past the migration in source control ("where did this line come
from" gets two answers all the time), and more billable hours dealing
with circular imports when two fragments start referring to each
other. Sounds like a plan.


It appears to me as if you like messy code then. ;)

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


Re: Best Practices for Internal Package Structure

2016-04-05 Thread Sven R. Kunze

On 05.04.2016 20:40, Ethan Furman wrote:


(utils.py does export a couple of functions, but they should be in 
the main

module, or possibly made into a method of BidirectionalMapping.)

Your package is currently under 500 lines. As it stands now, you could
easily flatten it to a single module:

bidict.py


Yup... well, actually you could just stick it in __init__.py.


Interesting. We did (and I started it) a similar thing for some packages 
which then grew unbearably in a single year.



Now, everybody in team agrees with: 'who idiot put this stuff in 
__ini__.py?' It was me who started it so I take it with a smile. But 
it's definitely a wart.


So, we have a new guideline since then: "empty __init__.py" if possible 
of course; you sometimes need to collect/do magic imports but that's a 
separate matter.



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


Re: Best Practices for Internal Package Structure

2016-04-06 Thread Sven R. Kunze

On 06.04.2016 09:28, Michael Selik wrote:

On Wed, Apr 6, 2016, 2:51 AM Steven D'Aprano  wrote:


On Wed, 6 Apr 2016 05:56 am, Michael Selik wrote:

[Michael]

When you made that suggestion earlier, I immediately guessed that you

were

using PyCharm. I agree that the decision to split into multiple files or
keep everything in just a few files seems to be based on your development
tools. I use IPython and SublimeText, so my personal setup is more suited
to one or a few files.


Interesting to know. I remember us while looking for our next IDE, we 
investigated Sublime as well. I don't remember the exact reasons anymore 
but I remember this lightweight feeling of control and doing all sorts 
of boilerplatey, distracting things extremely easily and most 
importantly extremely fast. It just feels like doing plain'ol files 
editing but with less typing; you can think more (mental activity) than 
you need to write (physical activity). That brought us to another level 
when designing stuff. Keeps us able to handle the workload.


Thus, I use it for my small PyPI projects as well. Why should I use less 
capable tools for those projects:


https://github.com/srkunze/xheap
https://github.com/srkunze/fork
https://github.com/srkunze/xcache

They are small but deserve the same professionalism I daresay.


How does PyCharm make the use of many files easier?

I'll let Sven answer that one. I don't know, but I've noticed the
correlation of habit to IDE.


Definitely true. I think that's natural and doing otherwise would impair 
the productivity improvements provided by the tools.


About the "many files easier" question: not sure what I said exactly, 
but one could also ask: "what makes the alternatives harder?"


1) learning them and using them regularly
2) you need "switching to a file" as a requirement for those other 
alternatives I mentioned in the other post


So, you before you can even start learning the alternatives, you do 1000 
times "switch to a file".



Moreover, if you split things up properly, you don't need to jump 
between 20 files at once. Usually you fix a problem/build a feature in a 
narrow slot of your code (1-4 files). If you don't do that regularly, 
it's an indication you've split your stuff up the wrong way. ;-)



Last but not least, you basically don't look for files anymore. You look 
for names, and PyCharm opens the file you need. You jump from code 
position to code position by interacting (clicking, shortcuts, etc.) 
with the code. In one file, you have only one cursor. So, when PyCharm 
jumps within in a single file, you loose your previous cursor position 
(You can jump back but that's not permanent - especially when you do 
something else in the same file). If you have two files open, you have 
two cursors and you almost always reside at the same spot there. You 
COULD do that with a single view (split view as mentioned in the last 
post) but yeah that's not as easy as just another file.



Again this is a just an attempt of explaining an observation.

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


Re: Best Practices for Internal Package Structure

2016-04-06 Thread Sven R. Kunze

On 06.04.2016 01:47, Chris Angelico wrote:

Generally, I refactor code not because the files are getting "too
large" (for whatever definition of that term you like), but because
they're stretching the file's concept. Every file should have a
purpose; every piece of code in that file should ideally be supporting
exactly that purpose.


Well said.

The definition of purpose and concept are blurry, though. So, what is 
within the boundary of a concept is hard to define.



@Steven
You might not understand the purpose of the guideline. That's what makes 
them so valuable. It's hard to get them right and it's hard to 
understand them if you don't have any experience with them.




An attempt of an explanation (which maybe in itself not 100% correct): 
there are two different forces acting on the source code:


1) make it short and concise (the 2-pages guideline)
2) keep conceptually close things together (cf. Chris)

So, there's always a bargaining of what can be put in/removed from a 
module in the first place:


"just these 14 lines, please; we need that feature"
"but the module already has 310 lines"
"only this one last one, please; it belongs here"
"but it's an if-else and another def; nasty nesting and more complexity"
"hmm, what if we remove those 5 over here? we don't need them anymore"
"really? then, we can remove 2 superfluous newlines and 2 import lines 
as well"

"I could even squeeze those 14 lines to 10 using dict comprehensions"
"that's even more readable; +1 line, that's okay"

Life is full of compromises.

This guideline is more about discussing, shaping existing code and 
extracting the essence (with yourself or with colleagues) to keep things 
on a usable level.


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


How to remove item from heap efficiently?

2016-01-08 Thread Sven R. Kunze

Hi everybody,

suppose, I need items sorted by two criteria (say timestamp and 
priority). For that purpose, I use two heaps (heapq module):


heapA # items sorted by timestamp
heapB # items sorted by priority

Now my actual problem. When popping an item of heapA (that's the oldest 
item), I need to remove the very same item from heapB, regardlessly 
where it is in heapB. And vice versa.


Is there a datastructure or a simple trick to achieve that in an 
efficient matter?


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


Re: How to remove item from heap efficiently?

2016-01-09 Thread Sven R. Kunze

Thanks for your suggestion.

On 08.01.2016 14:21, srinivas devaki wrote:

You can create a single heap with primary key as timestamp and
secondary key as priority, i.e by creating a tuple
insert the elements into the heap as
(timestamp, priority)

I think I cannot use that because I need the list sorted by both criteria.

If there is any underlying meaning for creating 2 heaps. please mention.


I use two heaps because I need to insert arbitrary items fast and remove 
the ones fast which are too old (timestamp) or are next in order (priority).


Basically a task scheduler where tasks can be thrown away once they are 
too long in the queue.



On Fri, Jan 8, 2016 at 4:22 AM, Sven R. Kunze  wrote:

Hi everybody,

suppose, I need items sorted by two criteria (say timestamp and priority).
For that purpose, I use two heaps (heapq module):

heapA # items sorted by timestamp
heapB # items sorted by priority

Now my actual problem. When popping an item of heapA (that's the oldest
item), I need to remove the very same item from heapB, regardlessly where it
is in heapB. And vice versa.

Is there a datastructure or a simple trick to achieve that in an efficient
matter?

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


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


Re: graphs

2016-01-09 Thread Sven R. Kunze

Hi Saski,

Python's dataset processing machine is *pandas*.

Have a look at this cookbook entry here:

http://nbviewer.ipython.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%204%20-%20Find%20out%20on%20which%20weekday%20people%20bike%20the%20most%20with%20groupby%20and%20aggregate.ipynb

Best,
Sven


On 07.01.2016 16:36, Saini, Sakshi wrote:

I  have a complex dataset and I wish to write a code to create different graphs 
from it. I was wondering if it is possible for Python/ matplotlib/ seaborn to 
return a cumulative or mean distribution bar graph based on values in your 
dataset?
E.g. I have a certain volume in m3 for each rainfall event in mm, and I wish to 
plot the total volume OR average volume for different rainfall depths; somewhat 
like the following:
[cid:image002.jpg@01D14937.476CB2F0]

Any tips please?



Sakshi Saini, BASc, EIT
Water Resources Project Coordinator | Credit Valley Conservation

The information contained in this Credit Valley Conservation electronic message 
is directed in confidence solely to the person(s) named above and may not be 
otherwise distributed, copied or disclosed including attachments.  The message 
may contain information that is privileged, confidential and exempt from 
disclosure under the Municipal Freedom of Information and Protection and 
Privacy Act and by the Personal Information Protection Electronic Documents 
Act. The use of such personal information except in compliance with the Acts, 
is strictly prohibited. If you have received this message in error, please 
notify the sender immediately advising of the error and delete the message 
without making a copy. Thank you.


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


Re: How to remove item from heap efficiently?

2016-01-09 Thread Sven R. Kunze

Thanks for your reply.

On 08.01.2016 14:26, Peter Otten wrote:

Sven R. Kunze wrote:


Hi everybody,

suppose, I need items sorted by two criteria (say timestamp and
priority). For that purpose, I use two heaps (heapq module):

heapA # items sorted by timestamp
heapB # items sorted by priority

Now my actual problem. When popping an item of heapA (that's the oldest
item), I need to remove the very same item from heapB, regardlessly
where it is in heapB. And vice versa.

Is there a datastructure or a simple trick to achieve that in an
efficient matter?

The heapq docs mention marking as deleted as an alternative to removing.
That is how I do it for now. However, the heap continues to grow which 
needs a periodic clean up.

Another option is to try sorted lists and bisect.

The docs tell me that insertion is not really fast then. :/


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


Re: How to remove item from heap efficiently?

2016-01-10 Thread Sven R. Kunze

Wow. That's an impressive reply.

On 08.01.2016 20:26, srinivas devaki wrote:

So you need a task scheduler with expiration and priority on each task.
Interesting Problem..

as peter said about marking the task in heapB to be deleted. but this
needs searching everytime you pop off an old item [complexity:
O(len(heapB))]. you may as well use python del on it as complexity is
same.
But if you already know the where to look in the heapB then you can
avoid searching and thereby reducing the complexity. you can do this
by saving the references of heapB in heapA and viceversa

and if you marking delete on a number of low priority tasks, then it
can increase your heapB enormously because being low priority items
they can stagnate. to resolve this error you have to perform linear
checking iterations at every critical length (this critical length can
be obtained mathmatically), so that your amortized complexity of push,
pop remains log(number_of_valid_tasks_at_any_time);
the number of valid tasks at any time are those tasks which are not
expired at the time.

My Algorithm:
version_a: https://gist.github.com/9ce7a0e534c6e768239e
this version has simple scheduler which has methods for popping high
priority one and popping oldest task.
But this version has a disadvantage, i.e If lets say you are pushed
some 10**5 tasks with priority 2, and then pushed some 10**5 tasks
with priority 1. and then you decided to pop the oldest 10**5 items.
in this version that 10**5 elements will stagnate in priority heap if
in future all priorities are less than 1.
now this is not a big issue but if you are running a webserver and
over a span of 5 days there could be 10**10 tasks, and even if half of
those tasks stagnate your server is going to crash with out of memory.

version_b: https://gist.github.com/99b4d590753ba234eeed
this version resolved that stagnation. this one will run sweeps
whenever there are more than half of useless items, thereby giving us
an amortized complexity of O(log(n)) for push, pop, etc

but this version doesn't have the feature of expiration.

version_c: https://gist.github.com/9dfd0d291672c0ffa5c3
in this one we simply keep a variable expiration, and relieve the
expired tasks on any operation. i have coded it in such a way that
expiration is specific time, you can change it to delta time if you
want to.

Time Complexity: O(log(n)) insertion, O(log(n)) deletion   [amortized]
Space Complexity: O(n)  [amortized]
here n is number of valid items i.e which are not expired.

I hope this helps with your problem


Indeed. I already do the sweep method as you suggested. ;)

Additionally, you provided me with a reasonable condition when to do the 
sweep in order to achieve O(log n). Thanks much for that. I currently 
used a time-bases approached (sweep each 20 iterations).


PS: Could you add a note on how you got to the condition ( 
2*self.useless_b > len(self.heap_b))?



PS:
sorry for posting links, it's just that the code is large for email.
I'm using minimum number has highest priority convention.


I like Web technology, so no problem here. :)


On Fri, Jan 8, 2016 at 10:15 PM, Sven R. Kunze  wrote:

Thanks for your suggestion.

On 08.01.2016 14:21, srinivas devaki wrote:

You can create a single heap with primary key as timestamp and
secondary key as priority, i.e by creating a tuple
insert the elements into the heap as
(timestamp, priority)

I think I cannot use that because I need the list sorted by both criteria.

If there is any underlying meaning for creating 2 heaps. please mention.


I use two heaps because I need to insert arbitrary items fast and remove the
ones fast which are too old (timestamp) or are next in order (priority).

Basically a task scheduler where tasks can be thrown away once they are too
long in the queue.



On Fri, Jan 8, 2016 at 4:22 AM, Sven R. Kunze  wrote:

Hi everybody,

suppose, I need items sorted by two criteria (say timestamp and
priority).
For that purpose, I use two heaps (heapq module):

heapA # items sorted by timestamp
heapB # items sorted by priority

Now my actual problem. When popping an item of heapA (that's the oldest
item), I need to remove the very same item from heapB, regardlessly where
it
is in heapB. And vice versa.

Is there a datastructure or a simple trick to achieve that in an
efficient
matter?

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




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


  1   2   3   >