Re: solutions manual and test banks

2014-04-09 Thread Carlin Li
Approximately how much do you charge for these solutions manuals?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread James Brewer
On Tue, Apr 8, 2014 at 7:19 PM, Chris Angelico  wrote:

> On Wed, Apr 9, 2014 at 6:19 AM, James Brewer  wrote:
> > You're an interesting fellow.
>
> Rick's one of our resident... uhh... characters. Don't take his words to
> heart.
>
> > Also, I didn't graduate; I dropped out.
>
> I dropped out of high school. Never went to uni/college/etc.
>
> ChrisA


One thing I have picked up is to take what everyone says with a grain of
salt, taking only that advice which is helpful. People like Rick are
awesome because they say things that other people only think; and sometimes
these things are the most helpful.

:)

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


Re: solutions manual and test banks

2014-04-09 Thread Chris Angelico
On Wed, Apr 9, 2014 at 5:47 PM, Carlin Li  wrote:
> Approximately how much do you charge for these solutions manuals?
>

You're responding to a spambot. I advise against it :) Most of us
didn't even see the original post (I certainly didn't), and you really
don't want to be inviting more spam.

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


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread Larry Hudson

On 04/08/2014 08:02 AM, Chris Angelico wrote:

On Wed, Apr 9, 2014 at 12:28 AM, Larry Martell  wrote:

I've worked at places where:


Add to that list:

- Some of the programmers really aren't programmers, but the boss just
hasn't figured it out yet.

That was my last job, until said non-programmer decided to quit.

ChrisA



This reminds me of one of the stories on the Computer Stupidities website.  (The site says these 
anecdotes are public domain, so I can copy it here.)



Since I teach nights at a local community college, I get a lot of professional programmers in my 
classes upgrading their education. One student, who was one such person, attended every lecture 
and smiled and nodded and took notes. But he only turned in his first assignment. The results of 
his first test were horrid. Out of curiosity, I asked my wife, who barely knew how to turn a 
computer on much less program one, to take the test (which was mostly true/false and multiple 
choice questions). My wife scored higher than this guy.


The semester's end came, and he flubbed his final, too. A few weeks later, I got a call from him 
complaining about his 'F'. I pointed out he hadn't turned in any of his assignments, and those 
counted 75% of the grade.


"Did you hear me say something besides what the other students heard?" I asked.

"Well, I thought my test grades would carry me," he replied.

It had turned out his company had paid for him to take the course. Since he failed, it suddenly 
came to the attention of his employer that he didn't know how to program, and now his job was in 
jeopardy. As I hung up the phone, I mused that his company shouldn't fire him. It was a perfect 
match: a programmer who couldn't program and a company that couldn't figure out sooner that he 
couldn't.



If you have some leisure time, this site is well worth at least a quick skim--lots of hilarious 
stories and of course some just so-so (like broken cup holders).  And I suspect some are 
apocryphal, but a lot of fun stuff.  The home page is http://rinkworks.com/stupid/  This story 
is in the Miscellaneous Dumbness section.


 -=- Larry -=-

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


Python and Unicode

2014-04-09 Thread wxjmfauth
Well, there is a (serious) problem somewhere...

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


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread Mark Lawrence

On 08/04/2014 21:19, James Brewer wrote:

On Tue, Apr 8, 2014 at 12:47 PM, Rick Johnson
mailto:rantingrickjohn...@gmail.com>> wrote:

You're an interesting fellow. Also, I didn't graduate; I dropped out.



try:
print('rr is okay when discussing IDLE or tkinter')
except TrollingError:
print('just ignore him')

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Python and Unicode

2014-04-09 Thread Mark Lawrence

On 09/04/2014 09:07, wxjmfa...@gmail.com wrote:

Well, there is a (serious) problem somewhere...

jmf



Look in a mirror and you'll see it as it'll be staring you in the face.

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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread Mark Lawrence

On 09/04/2014 01:02, alex23 wrote:

On 9/04/2014 3:29 AM, Chris Angelico wrote:

My code would make for terrible PHP. :)


Don't feel bad about that. It's a truism for every language, including PHP.


Yep.  And the worst thing about terrible code is when you first realise 
just how bad it is and wonder why you wrote it like that in the first place.


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Python and Unicode

2014-04-09 Thread Steve Hayes
On Wed, 9 Apr 2014 01:07:20 -0700 (PDT), wxjmfa...@gmail.com wrote:

>Well, there is a (serious) problem somewhere...

As there is with pandas and infertility.


-- 
Terms and conditions apply. 

Steve Hayes
hayesm...@hotmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


is there more simple way to do?

2014-04-09 Thread length power
x='name,sex,birthday\n\nx1,male,1948/05/28\n\nx2,female,1952/03/27
\n\nx3,female,1994/12/09'
x.replace("\n\n","\n").splitlines()

is there more simple way to replace  `x.replace("\n\n","\n").splitlines()` ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keeping track of things with dictionaries

2014-04-09 Thread Gene Heskett
On Wednesday 09 April 2014 05:47:37 Ian Kelly did opine:

> On Tue, Apr 8, 2014 at 9:31 PM, Gene Heskett  wrote:
> >> 'Pneumonoultramicroscopicsilicovolcanoconiosis' has them all beat.
> > 
> > Source citation please?
> 
> http://en.wikipedia.org/wiki/Pneumonoultramicroscopicsilicovolcanoconios
> is
> http://www.oxforddictionaries.com/definition/english/pneumonoultramicro
> scopicsilicovolcanoconiosis
> http://dictionary.reference.com/browse/Pneumonoultramicroscopicsilicovo
> lcanoconiosis

Damn, I should know better than call your bluff.  Serves me right. :(

Boil that down to its essence and it might be used for one of the miners 
lung problems (black or white lung) they eventually die from.  I have a 
friend doing that as I type.  And getting very close to the end of his 
rope.

Cheers, Gene
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page 
US V Castleman, SCOTUS, Mar 2014 is grounds for Impeaching SCOTUS
-- 
https://mail.python.org/mailman/listinfo/python-list


how to insert the elements in a list properly?

2014-04-09 Thread length power
word=["x1","x2","x3","x4","x5"]
w=word[-2:]
del word[-2:]
word.insert(2,w)
word
['x1', 'x2', ['x4', 'x5'], 'x3']

what i want to get is
['x1', 'x2', 'x4', 'x5', 'x3']

how can i insert them ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to insert the elements in a list properly?

2014-04-09 Thread Peter Otten
length power wrote:

> word=["x1","x2","x3","x4","x5"]
> w=word[-2:]
> del word[-2:]
> word.insert(2,w)
> word
> ['x1', 'x2', ['x4', 'x5'], 'x3']
> 
> what i want to get is
> ['x1', 'x2', 'x4', 'x5', 'x3']
> 
> how can i insert them ?

Make the left-hand side an empty slice:

>>> words = ["x1", "x2", "x3", "x4", "x5"]
>>> w = words[-2:]
>>> del words[-2:]
>>> words[2:2] = w
>>> words
['x1', 'x2', 'x4', 'x5', 'x3']

Or note that the operation is equivalent to moving the third item to the 
end:

>>> words = ["x1", "x2", "x3", "x4", "x5"]
>>> words.append(words.pop(2))
>>> words
['x1', 'x2', 'x4', 'x5', 'x3']


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


Re: is there more simple way to do?

2014-04-09 Thread Peter Otten
length power wrote:

> x='name,sex,birthday\n\nx1,male,1948/05/28\n\nx2,female,1952/03/27
> \n\nx3,female,1994/12/09'
> x.replace("\n\n","\n").splitlines()
> 
> is there more simple way to replace  `x.replace("\n\n","\n").splitlines()`
> ?

One alternative that ignores all empty lines is

[line for line in x.splitlines() if line]

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


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread Antoon Pardon
On 08-04-14 15:58, alister wrote:
> On Tue, 08 Apr 2014 13:47:12 +, Grant Edwards wrote:
>
>> On 2014-04-08, Chris Angelico  wrote:
>>> On Tue, Apr 8, 2014 at 5:07 PM, James Brewer  wrote:
>>>
 Basically, I want to be a better engineer. Where can I find someone
 willing to point me in the right direction and what can I offer in
 return?
>>> Right here on this list! And all you have to offer in return is
>>> interesting questions.
>> Actually, I've noticed that the questions usually don't even have to be
>> very good or interesting.  Ask anything.  You'll get genneraly get
>> answers to:
>>
>>  the question you asked
>>
>>  the question you thought you were asking
>>
>>  the question you should have asked
>>
>>  a few other questions only tangentially related to the above
> I would agree with 1 & 4, but 2 & 3 only happen if you are really lucky 
> :-)

No wonder, because when they do happen, chances are someone will complain
about that person not answering the question actually asked.

-- 
Antoon Pardon

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


Re: "Latching" variables in function

2014-04-09 Thread William Ray Wing
On Apr 9, 2014, at 12:35 AM, Terry Reedy  wrote:

> On 4/8/2014 4:09 PM, Grawburg wrote:
>> 
>> I've probably used the wrong term - I'm thinking of what I do when writing 
>> PLC code - so I can't find how to do this in my reference books.
>> This is part of a project I'm working on with a Raspberry Pi and an MCP23017 
>> port expander.
>> I have a N/O pushbutton that I want to "latch" a value to a variable when 
>> it's been pressed.  I have this function that gets called periodically in
>> a 'while True' statement:
>> 
>> def button():
>>pushbutton = 0
>>   button_value = 0
>>pushbutton=bus.read_byte_data(address,GPIOB)
>>if pushbutton > 0:
>> button_value = 1
>>return button_value
>> 
>> I need button_value to become '1' when the button is pressed and to remain 
>> '1' until the entire program (only about 25 lines) ends with a sys.exit()
>> 
>> What do I use to 'latch' button_value?
> 
> It depends on whether you can set up your system so that pushing the button 
> generates an interrupt. But I know little about R.Pi and less about the 'port 
> expander'. If there were an interrupt, you would just have to write an 
> interrupt handler. When possible, this is much better than polling.
> 
> -- 
> Terry Jan Reedy
> 

I think what the OP was asking for was a way in standard Python to “lock" the 
value of an instance variable, which of course, you really can’t do. However, 
what he (I assume it’s a he) could do is arrange his calling program so that 
after the button method returns a “1”, the method isn’t called again.  That is, 
test for truth of button = 1 in the calling program, and if true, skip the 
call.  The next time the program runs, the button value will be re-initialized 
to zero and everything is back to square one.

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


Re: threading

2014-04-09 Thread Frank Millman

"Marko Rauhamaa"  wrote in message 
news:877g70wg8p@elektro.pacujo.net...
> Dennis Lee Bieber :
>
>> That's been my experience too... Threading works for me... My
>> attempts at so called asyncio (whatever language) have always led to
>> my having to worry about losing data if some handler takes too long to
>> return.
>>
>> To me, asyncio is closer to a polling interrupt handler, and I
>> still need a thread to handle the main processing.
>
> Yes, asynchronous processing results in complex, event-driven state
> machines that can be hard to get right. However, my experience is that
> that's the lesser evil.
>
> About a handler taking too long: you need to guard each state with a
> timer. Also, you need then to handle the belated handler after the timer
> has expired.
>

Can I ask a newbie question here?

I understand that, if one uses threading, each thread *can* block without 
affecting other threads, whereas if one uses the async approach, a request 
handler must *not* block, otherwise it will hold up the entire process and 
not allow other requests to be handled.

How does one distinguish betwen 'blocking' and 'non-blocking'? Is it 
either/or, or is it some arbitrary timeout - if a handler returns within 
that time it is non-blocking, but if it exceeds it it is blocking?

In my environment, most requests involve a database lookup. I endeavour to 
ensure that a response is returned quickly (however one defines quickly) but 
I cannot guarantee it if the database server is under stress. Is this a good 
candidate for async, or not?

Thanks for any insights.

Frank Millman



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


Re: "Latching" variables in function

2014-04-09 Thread Tim Chase
On 2014-04-08 16:09, Grawburg wrote:
> def button():
>    pushbutton = 0
>   button_value = 0
>    pushbutton=bus.read_byte_data(address,GPIOB)
>    if pushbutton > 0:
>         button_value = 1
>    return button_value
> 
> I need button_value to become '1' when the button is pressed and to
> remain '1' until the entire program (only about 25 lines) ends with
> a sys.exit()
> 
> What do I use to 'latch' button_value?

If I understand what you want, you could do something like

  class LatchButton:
def __init__(self, address):
  self.value = 0
  self.address = address
def __call__(self):
  if not self.value:
if bus.read_byte_data(self.address, GPIOB) > 0:
  self.value = 1
  return self.value

  button1 = LatchButton(address1)
  button2 = LatchButton(address2)
  for i in range(10):
print button1(), button2()
time.sleep(3)

-tkc






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


Re: how to insert the elements in a list properly?

2014-04-09 Thread length power
words = ["x1", "x2", "x3", "x4", "x5"]
words.append(words.pop(2))
words.append(words.pop(2))
words
['x1', 'x2', 'x5', 'x3', 'x4']
why i can't write it as:

[words.append(words.pop(2)) for i in range(0,2)]

>>> [words.append(words.pop(2)) for i in range(0,2)]
[None, None]


2014-04-09 18:46 GMT+08:00 Peter Otten <__pete...@web.de>:

> length power wrote:
>
> > word=["x1","x2","x3","x4","x5"]
> > w=word[-2:]
> > del word[-2:]
> > word.insert(2,w)
> > word
> > ['x1', 'x2', ['x4', 'x5'], 'x3']
> >
> > what i want to get is
> > ['x1', 'x2', 'x4', 'x5', 'x3']
> >
> > how can i insert them ?
>
> Make the left-hand side an empty slice:
>
> >>> words = ["x1", "x2", "x3", "x4", "x5"]
> >>> w = words[-2:]
> >>> del words[-2:]
> >>> words[2:2] = w
> >>> words
> ['x1', 'x2', 'x4', 'x5', 'x3']
>
> Or note that the operation is equivalent to moving the third item to the
> end:
>
> >>> words = ["x1", "x2", "x3", "x4", "x5"]
> >>> words.append(words.pop(2))
> >>> words
> ['x1', 'x2', 'x4', 'x5', 'x3']
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to insert the elements in a list properly?

2014-04-09 Thread Dan Sommers
On Wed, 09 Apr 2014 21:09:37 +0800, length power wrote:

> words = ["x1", "x2", "x3", "x4", "x5"]
> words.append(words.pop(2))
> words.append(words.pop(2))
> words
> ['x1', 'x2', 'x5', 'x3', 'x4']
> why i can't write it as:
> 
> [words.append(words.pop(2)) for i in range(0,2)]
> 
 [words.append(words.pop(2)) for i in range(0,2)]
> [None, None]

You can, but you don't want to.  At this point, even though the
comprehension returned something else, words contains what you want.

HTH,
Dan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Mark Lawrence

On 08/04/2014 17:38, Paul Rubin wrote:

Sturla Molden  writes:

As it turns out, if you try hard enough, you can always construct a race
condition, deadlock or a livelock. If you need to guard against it, there
is paradigms like BSP, but not everything fits in. a BSP design.


Software transactional memory (STM) may also be of interest, though
it's not that great a fit with Python.



The pypy folks have been looking at this see 
http://pypy.readthedocs.org/en/latest/stm.html


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: threading

2014-04-09 Thread Neil D. Cerutti

On 4/8/2014 9:09 PM, Rick Johnson wrote:

I warn you that not only will "it" impede the interpretation
of your ideas, "it" will also degrade your ability to think
clearly when expressing yourself and slow (or completely
halt) your linguistic evolution.

 HAVE YOU NOTICED THAT YOUR INNER MONOLOGUE NEVER USES "IT"?

Indeed!

That's because "it" is a habitual viral infestation of the
human communication interface.


It strikes me that that's not superior to it. It's ironic that that 
would be used in place of it in your rant.


Plus Rufus Xavier Sasparilla disagrees with it.

--
Neil Cerutti

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


Re: "Latching" variables in function

2014-04-09 Thread Mark H Harris

On 4/8/14 3:09 PM, Grawburg wrote:


I have a N/O pushbutton that I want to "latch" a value to a variable when it's 
been pressed.
I need button_value to become '1' when the button is pressed and to remain '1' 
until ...



What do I use to 'latch' button_value?


Philosophically speaking buttons don't latch. You push the button, an 
event is generated, and the call-back handles the event to do something 
in your project.


You might try setting a global variable on the button-push event.

Or, if I understand you, you might want to use a configurable, like a 
radio button or a check box, either of which are designed to be "latched".



marcus

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


Re: threading

2014-04-09 Thread Chris Angelico
On Wed, Apr 9, 2014 at 11:23 PM, Frank Millman  wrote:
> Can I ask a newbie question here?

You certainly can!

> I understand that, if one uses threading, each thread *can* block without
> affecting other threads, whereas if one uses the async approach, a request
> handler must *not* block, otherwise it will hold up the entire process and
> not allow other requests to be handled.

That would be correct.

> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it
> either/or, or is it some arbitrary timeout - if a handler returns within
> that time it is non-blocking, but if it exceeds it it is blocking?

No; a blocking request is one that waits until it has a response, and
a non-blocking request is one that goes off and does something, and
then comes back to you when it's done. When you turn on the kettle,
you can either stay there and watch until it's ready to make your
coffee (or, in my case, hot chocolate), or you can go away and come
back when it whistles at you to say that it's boiling. A third option,
polling, is when you put a pot of water on the stove, turn it on, and
then come back periodically to see if it's boiling yet. As the old
saying tells us, blocking I/O is a bad idea with pots of water,
because it'll never return.

> In my environment, most requests involve a database lookup. I endeavour to
> ensure that a response is returned quickly (however one defines quickly) but
> I cannot guarantee it if the database server is under stress. Is this a good
> candidate for async, or not?

No, that's a bad idea, because you have blocking I/O. If you have
multiple threads, it's fine, because the thread that's waiting for the
database will be blocked, and other threads can run (you may need to
ensure that you have separate database connections for your separate
threads); but in an asynchronous system, you want to be able to go and
do something else while you're waiting. Something like this:

def blocking_database_query(id):
print("Finding out who employee #%d is..."%id)
res = db.query("select name from emp where id=12345")
print("Employee #%d is %s."%(id,res[0].name))

def nonblocking_query(id):
print("Finding out who employee #%d is..."%id)
def nextstep(res):
print("Employee #%d is %s."%(id,res[0].name))
db.asyncquery(nextstep, "select name from emp where id=12345")

This is a common way to do asynchronous I/O. Instead of saying "Do
this and give me a result", you say "Do this, and when you have a
result, call this function". Then as soon as you've done that, you
return (to some main loop, probably). It's usually a bit more
complicated than this (eg you might need multiple callbacks or
additional arguments in case it times out or otherwise fails - there's
no way to throw an exception into a callback, the way the blocking
query could throw something instead of returning), but that's the
basic concept.

You may be able to get away with doing blocking operations in
asynchronous mode, if you're confident they'll be fairly fast. But you
have to be really REALLY confident, and it does create assumptions
that can be wrong. For instance, the above code assumes that print()
won't block. You might think "Duh, how can printing to the screen
block?!?", but if your program's output is being piped into something
else, it most certainly can :) If that were writing to a remote
socket, though, it'd be better to perform those operations
asynchronously too: attempt to write to the socket; once that's done,
start the database query; when the database result arrives, write the
response to the socket; when that's done, go back to some main loop.

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


Re: threading

2014-04-09 Thread Marko Rauhamaa
"Frank Millman" :

> I understand that, if one uses threading, each thread *can* block
> without affecting other threads, whereas if one uses the async
> approach, a request handler must *not* block, otherwise it will hold
> up the entire process and not allow other requests to be handled.

Yes.

> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it 
> either/or, or is it some arbitrary timeout - if a handler returns within 
> that time it is non-blocking, but if it exceeds it it is blocking?

Old-school I/O primitives are blocking by default. Nonblocking I/O is
enabled with the setblocking() method.

In the new asyncio package, I/O is nonblocking by default (I'm sure, but
didn't verify).

> In my environment, most requests involve a database lookup. I
> endeavour to ensure that a response is returned quickly (however one
> defines quickly) but I cannot guarantee it if the database server is
> under stress. Is this a good candidate for async, or not?

Database libraries are notoriously bad for nonblocking I/O. It's nothing
fundamental; it's only that the library writers couldn't appreciate the
worth of async communication. For that, asyncio provides special
support:

   https://docs.python.org/3.4/library/asyncio-dev.html#
   handle-blocking-functions-correctly>



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


Re: threading

2014-04-09 Thread Frank Millman

"Chris Angelico"  wrote in message 
news:captjjmqwhb8o8vq84mmtv+-rkc3ff1aqdxe5cs8y5gy02kh...@mail.gmail.com...
> On Wed, Apr 9, 2014 at 11:23 PM, Frank Millman  wrote:
>
>> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it
>> either/or, or is it some arbitrary timeout - if a handler returns within
>> that time it is non-blocking, but if it exceeds it it is blocking?
>
> No; a blocking request is one that waits until it has a response, and
> a non-blocking request is one that goes off and does something, and
> then comes back to you when it's done.

Does reading from disk count as blocking? Strictly speaking I would have 
thought 'yes'.

In other words, non-blocking implies that everything required to pass off 
the request to a handler and be ready to deal with the next one must already 
be in memory, and it must not rely on communicating with any outside 
resource at all. Is this correct?

>
> def blocking_database_query(id):
>print("Finding out who employee #%d is..."%id)
>res = db.query("select name from emp where id=12345")
>print("Employee #%d is %s."%(id,res[0].name))
>
> def nonblocking_query(id):
>print("Finding out who employee #%d is..."%id)
>def nextstep(res):
>print("Employee #%d is %s."%(id,res[0].name))
>db.asyncquery(nextstep, "select name from emp where id=12345")
>

In this example, what is 'db.asyncquery'?

If you mean that you have a separate thread to handle database queries, and 
you use a queue or other message-passing mechanism to hand it the query and 
get the result, then I understand it. If not, can you explain in more 
detail.

If I have understood correctly, then is there any benefit at all in my going 
async? I might as well just stick with threads for the request handling as 
well as the database handling.

Frank



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


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 12:30 AM, Frank Millman  wrote:
>
> "Chris Angelico"  wrote in message
> news:captjjmqwhb8o8vq84mmtv+-rkc3ff1aqdxe5cs8y5gy02kh...@mail.gmail.com...
>> On Wed, Apr 9, 2014 at 11:23 PM, Frank Millman  wrote:
>>
>>> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it
>>> either/or, or is it some arbitrary timeout - if a handler returns within
>>> that time it is non-blocking, but if it exceeds it it is blocking?
>>
>> No; a blocking request is one that waits until it has a response, and
>> a non-blocking request is one that goes off and does something, and
>> then comes back to you when it's done.
>
> Does reading from disk count as blocking? Strictly speaking I would have
> thought 'yes'.

What the operation actually *is* is quite immaterial. Reading from the
disk can be done as blocking or non-blocking; if you simply open a
file and call its read() method, that'll block by default (the open()
call can block, too, but you asked about reading). When you ask for
something to be done and expect a return value with the result, that
implies a blocking operation. Even simple work like floating-point
addition can be blocking or nonblocking; I learned some of the basics
of the 8087 coprocessor and how to do assembly-language floating
point, and it was, by default, a non-blocking operation - you say "Go
do this", and then you say "FWAIT" to block until the coprocessor is
done. But normally you want to be able to write this:

a = 12.3
b = 45.6
c = a + b
print("The sum is:",c)

rather than this:

add_async(a, b, lambda c: print("The sum is:",c))

> In other words, non-blocking implies that everything required to pass off
> the request to a handler and be ready to deal with the next one must already
> be in memory, and it must not rely on communicating with any outside
> resource at all. Is this correct?

Nope. It simply requires that communicating with an outside resource
be done asynchronously. You fire off the request and either check for
its completion periodically (polling) or get a notification when it's
done (callback, usually).

>> def nonblocking_query(id):
>>print("Finding out who employee #%d is..."%id)
>>def nextstep(res):
>>print("Employee #%d is %s."%(id,res[0].name))
>>db.asyncquery(nextstep, "select name from emp where id=12345")
>>
>
> In this example, what is 'db.asyncquery'?
>
> If you mean that you have a separate thread to handle database queries, and
> you use a queue or other message-passing mechanism to hand it the query and
> get the result, then I understand it. If not, can you explain in more
> detail.

It's an imaginary function that would send a request to the database,
and then call some callback function when the result arrives. If the
database connection is via a TCP/IP socket, that could be handled by
writing the query to the socket, and then when data comes back from
the socket, looking up the callback and calling it. There's no
additional thread here.

> If I have understood correctly, then is there any benefit at all in my going
> async? I might as well just stick with threads for the request handling as
> well as the database handling.

Threads are a convenient way to handle things, but they're an
alternative. You generally do one or the other. Occasionally you'll
use a bit of both, maybe because your database handler can't work
asynchronously, but ideally you shouldn't need to mix and match like
that.

I'm oversimplifying horribly, here, but hopefully helpfully :)

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


Re: threading

2014-04-09 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> For instance, the above code assumes that print() won't block. You 
> might think "Duh, how can printing to the screen block?!?", but if 
> your program's output is being piped into something else, it most 
> certainly can :)



Heh.  One day, a long time ago, I had to investigate why our Vax-11/750 
had crashed.  I vaguely recollect being called at home on a weekend and 
having to schlepp into work, but my memory may just be running in 
auto-story-embelishment mode.

Turns out, the machine hadn't really crashed, but it was hung.  The 
console was a LA-120 (http://tinyurl.com/mljyegv), on which was printed 
various log messages from time to time.  It had run out of paper, which 
was detected by the little out-of-paper microswitch, so it stopped 
printing.  When its input buffer got full, it sent a control-s, which 
tells the thing on the other end of the serial line to stop sending.  
Which of course caused the kernel tty driver output buffer to fill, 
which eventually caused all the print statements by the various system 
loggers to block, and eventually the whole mess ground to a halt.

I put in new paper.  The printer proceeded to spit out several hours 
worth of buffered log messages and the system picked up where it left 
off.



At Songza, we've been using gevent to do asynchronous I/O.  It's an 
interesting concept.  Basically, you write your application code as you 
normally would, using blocking I/O calls.  Gevent then monkey-patches 
the heck out of the Python library to intercept every call that could 
possibly block and splice it into a asynchronous task scheduler 
framework.  The amazing thing is that it works.  It let us reduce the 
number of gunicorn worker processes we use by a factor of 6, and handle 
the same amount of traffic.

Of course, monkey-patching is black magic, and sometimes we get hit by 
really bizarre and difficult to track down bugs.  But, to go back to my 
"technology evolution" scale, gevent is somewhere between avant-garde 
and what the kewl kids are using (version 1.0 was released in December), 
so that shouldn't be too surprising.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Frank Millman

"Marko Rauhamaa"  wrote in message 
news:87lhveobeq@elektro.pacujo.net...
> "Frank Millman" :
>
>> I understand that, if one uses threading, each thread *can* block
>> without affecting other threads, whereas if one uses the async
>> approach, a request handler must *not* block, otherwise it will hold
>> up the entire process and not allow other requests to be handled.
>
> Yes.
>
>> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it
>> either/or, or is it some arbitrary timeout - if a handler returns within
>> that time it is non-blocking, but if it exceeds it it is blocking?
>
> Old-school I/O primitives are blocking by default. Nonblocking I/O is
> enabled with the setblocking() method.
>
> In the new asyncio package, I/O is nonblocking by default (I'm sure, but
> didn't verify).
>
>> In my environment, most requests involve a database lookup. I
>> endeavour to ensure that a response is returned quickly (however one
>> defines quickly) but I cannot guarantee it if the database server is
>> under stress. Is this a good candidate for async, or not?
>
> Database libraries are notoriously bad for nonblocking I/O. It's nothing
> fundamental; it's only that the library writers couldn't appreciate the
> worth of async communication. For that, asyncio provides special
> support:
>
>   https://docs.python.org/3.4/library/asyncio-dev.html#
>   handle-blocking-functions-correctly>
>

Thanks for the reply, Marko.

I did have a look at the link you provided, but at the moment my brain is 
'blocking' on this, so I will need to read it a few times to get back into 
'async' mode.

As I asked Chris, (so you don't have to respond if he already has), I am 
finding difficulty in understanding the benefit of going async in my case. 
If most requests require a blocking handler, it seems that I might as well 
stick with each request being handled by a thread, independent of all other 
threads.

Frank



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


Re: threading

2014-04-09 Thread Roy Smith
In article ,
 "Frank Millman"  wrote:

> "Chris Angelico"  wrote in message 
> news:captjjmqwhb8o8vq84mmtv+-rkc3ff1aqdxe5cs8y5gy02kh...@mail.gmail.com...
> > On Wed, Apr 9, 2014 at 11:23 PM, Frank Millman  wrote:
> >
> >> How does one distinguish betwen 'blocking' and 'non-blocking'? Is it
> >> either/or, or is it some arbitrary timeout - if a handler returns within
> >> that time it is non-blocking, but if it exceeds it it is blocking?
> >
> > No; a blocking request is one that waits until it has a response, and
> > a non-blocking request is one that goes off and does something, and
> > then comes back to you when it's done.
> 
> Does reading from disk count as blocking? Strictly speaking I would have 
> thought 'yes'.

Of course it does.  But, the bigger question is, "What counts as reading 
from disk?"

In the old days, all Unix system calls were divided up into two groups, 
based on whether they were "fast" or "slow".  Processes executing a 
"fast" system call would block, and could not be interrupted; i.e. any 
signals delivered to them would be queued up and delivered after the 
system call had finished.  Typically, that meant, if you typed 
Control-C, your process wouldn't get killed until the system call it was 
executing completed.

Disk reads were considered fast.  You type Control-C, the read takes 
another few ms to finish, then your process gets whacked.  You never 
even notice the delay.  But, a read on a tty was slow.  It would sit 
there forever, until you hit return.  Slow system calls got interrupted.

Then, along came the network, and everything got confusing.  If I open a 
file that lives on an NFS server, and read from it, am I doing a disk 
read?  Should I be able to interrupt an NFS operation?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Sturla Molden
"Frank Millman"  wrote:

> If I have understood correctly, then is there any benefit at all in my going 
> async? I might as well just stick with threads for the request handling as 
> well as the database handling.

1. There is a scalability issue with threads, particularly if you don't
have enough RAM or use a 32 bit system.

2. Earlier Linux kernels did not perform well if they had to schedule
10,000 threads. 

3. It is nice to be able to abort a read or write that hangs (for whatever
reason). Killing a thread with pthread_cancel or TerminateThread is not
recommended.


Sturla

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


Re: "Latching" variables in function

2014-04-09 Thread alister
On Wed, 09 Apr 2014 08:53:19 -0500, Mark H Harris wrote:

> On 4/8/14 3:09 PM, Grawburg wrote:
> 
>> I have a N/O pushbutton that I want to "latch" a value to a variable
>> when it's been pressed.
>> I need button_value to become '1' when the button is pressed and to
>> remain '1' until ...
> 
>> What do I use to 'latch' button_value?
> 
> Philosophically speaking buttons don't latch. You push the button, an
> event is generated, and the call-back handles the event to do something
> in your project.
> 
> You might try setting a global variable on the button-push event.
> 
> Or, if I understand you, you might want to use a configurable, like a
> radio button or a check box, either of which are designed to be
> "latched".
> 
> 
> marcus

How familiar are you with oop?
a class would sort this quite nicely

Class Button(object)
def __init__(self,bit):
self.pressed=False:
self.bit=bit

def check_button(self):
if bus.read_byte_data(bit):
self.pressed=True


button=Button(address.GPIOB)
while not button.pressed:
button.check button()

once button.pressed has been set True it will remain True until you reset 
it with button.pressed=False

+ with a bit of tweaking you should be able to create multiple button 
objects for each switch you connect


*note this code has been typed direct & not tested so may contain minor 
errors.




-- 
Imbalance of power corrupts and monopoly of power corrupts absolutely.
-- Genji
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Rick Johnson
On Wednesday, April 9, 2014 8:50:59 AM UTC-5, Neil D. Cerutti wrote:
> [...]
> Plus Rufus Xavier Sasparilla disagrees with it.

If you think you're going to argue in such an implicit manner
as to the benefits of pronouns, then you should expect that
an astute logician such as myself will tear you to shreds.


#WARNING:  #

# You cannot wave shiny objects in front of MY eyes and#
# expect me to fold like a lawn-chair! #


And whist i admit your snarky comment is founded on a
*superficial* fact that cannot be denied,(that is: the fact
that pronouns remove superfluous repetition from
communications), most people will be so distracted by the
initial emotional response of laughter, that they will lose
their logical focus and fortitude, and forget to confirm the
validity of your assertion.

Your comment is a fine example of why people like Bill Mahr,
Steve Colbert, and , uh, that other guy??? can pacify
otherwise intelligent people via comedy whist their civil
liberties are robbed from them and justice is ignored. Does
"fiddling" and "Rome" ring a bell people?


#Summary:  #

# You comment is cleaver propaganda, but (as we shall all   #
# learn soon) in no way shape or form is your assertion#
# *logical* or *resilient* to interrogations.   #


Now, before i utterly destroy you, we must first *ALL* take
a lesson in linguistics.


#   Define Noun:   #

# a word (other than a pronoun) used to identify any of a  #
# class of people, places, or things   #



#Define "Pronoun": #

# In linguistics and grammar, a pronoun is a word or form  #
# that substitutes for a noun or noun phrase.  #


Pronouns are simply shorthands versions of nouns. We use
them to reduce the amount of atomic repetition in our speech
and writing, at that's a good thing! No one wants to inject
superfluous repetition into their prose. This, is the very
argument that my good friend "Mr. Cerutti" is presenting
with his *esoteric* reference to "Rufus Xavier Sasparilla"
-- of whom I will refer to from now on as "Mr.RXS"

Whist i agree with my opponent and "MR.RXS" on this one tiny
aspect of pronouns, we must dig deeper to understand why
"Mr. Cerutti's" argument is invalid to the subject matter
for which he is replying. The only way Mr Cerutti's comment
could be valid is if i argued that *ALL* pronouns are
evil, and that is NOT my argument.  MY ARGUMENT IS HIGHLY
SPECIFIC!


#  Inquisitive Joe asks:   #

# "But why do you single out "it" for excommunication  #
# Rick? What is so bad about "it"?"#


My argument is simply that the pronoun "it", is a
superfluously implicit use of pronouns! Since "it" can refer
to either a "person", a "place" or even a "thing", it
therefor injects too much ambiguity EVEN when "properly"[1]
used.

But not only is the ambiguity of the "it" pronoun an
unfortunate ubiquity, the manner in which the pronoun "it"
is referenced will many times manifest itself in confusing
manners. Observe the following three sentences which use
"it" in  illogically ascending orders of incomprehensibility:

1. I ate a burger, and it was good.

The first example is not terribly difficult to grok
since the noun "burger" is defined before the pronoun
"it" is declared and then logically bound to "burger".

2. It was a good day today.

In the second example we have the "it" at the very
beginning of the sentence, therefore, i must not only
read and comprehend the remainder of the sentence, but, i
must also remember that i need to find the antecedent of
the initial unbound pronoun "it".


3. It irks me that language designers pay no attention
   to consistency.

And the evil incarnation of the IMPLICIT PRONOUN raises
it's ugly head!!!

Again we have the pronoun "it" declared as the very first

Re: threading

2014-04-09 Thread Terry Reedy

On 4/9/2014 10:30 AM, Frank Millman wrote:


In other words, non-blocking implies that everything required to pass off
the request to a handler and be ready to deal with the next one must already
be in memory, and it must not rely on communicating with any outside
resource at all. Is this correct?


Chris said no, I would have said yes, but I think we understand the 
above differently. The important point is that there are two goals.


The first is to avoid having the cpu sitting idle when there is work to 
be done. Switching processes, switching threads within a process, and 
switching tasks within a thread are all aimed at this. (So are compiler 
code rearrangements that aim to keep various parts of a cpu, such 
integer and float arithmetic units, active simultaneously.)


The second, usually, is to keep the system responsive by not letting any 
particular work unit hog the cpu. But note that is work units are made 
too small, cpu time is wasted in excessive switching overhead.


A handler should neither waste nor monopolize cpu time. If input data is 
needed for a long computation, the handler should store the data where 
it needs to be for the computation but leave the actual computation to a 
background or idle task that runs when there is nothing else to do.


--
Terry Jan Reedy


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


Unpacking U-Boot image file

2014-04-09 Thread trewio
How to extract files from U-Boot image file, LZMA-compressed?

Is there a Python script that can do this properly?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 2:14 AM, Terry Reedy  wrote:
> On 4/9/2014 10:30 AM, Frank Millman wrote:
>
>> In other words, non-blocking implies that everything required to pass off
>> the request to a handler and be ready to deal with the next one must
>> already
>> be in memory, and it must not rely on communicating with any outside
>> resource at all. Is this correct?
>
>
> Chris said no, I would have said yes, but I think we understand the above
> differently.

I said no because I see asynchronous I/O as a perfectly viable
structure for a program, which means that a non-blocking handler is
allowed to communicate with outside resources. Conversely, if you see
"a non-blocking handler" as meaning the one small piece that runs
uninterruptibly, then you might say that yes, it must not rely on any
outside resource.

Of course, it depends on where you're looking. Memory is itself an
outside resource that can potentially take a long time to give a
result - just look at what happens when you dip into swap space, and
RAM accesses become disk accesses. But generally, you go asynchronous
in order to increase your throughput; and if you're churning through
your page file, well, that's going to kill throughput whichever way
you look at it. It's generally safe enough to pretend that RAM can be
accessed in-line, and worry about the slowdowns elsewhere.

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


Re: threading

2014-04-09 Thread Sturla Molden
Sturla Molden  wrote:
 
> 3. It is nice to be able to abort a read or write that hangs (for whatever
> reason). Killing a thread with pthread_cancel or TerminateThread is not
> recommended.

While "graceful timeout" is easy to do on Unix, using fcntl.fcntl or
signal.alarm, on Windows it requires overlapped I/O. This means the normal
Python file objects cannot be used for this purpose on Windows.

Sturla

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


Re: threading

2014-04-09 Thread Marko Rauhamaa
"Frank Millman" :

> Does reading from disk count as blocking? Strictly speaking I would
> have thought 'yes'.

You have touched upon a very interesting topic there.

I can't speak for Windows, but linux doesn't really let you control the
blocking of disk access. In fact, linux doesn't really let you control
the blocking of RAM access, either. RAM and the disk are considered two
sides of the same coin. It is very difficult to guarantee that a process
has all of its memory "cached" in RAM short of not having a physical
disk mounted.

There is what's known as AIO, and it's supposedly supported in linux,
but I have never seen anybody use it, and I don't know how well tested
it is. Also, I don't know how well it integrates with regular asyncio.

On the other hand, you don't know if disk access ever blocks. Quite
often you will find that the whole active part of the file system is
kept in RAM by linux.

My rule of thumb, two processes per CPU, should alleviate disk blocking
issues. When that isn't enough, you may be forced to write a small file
server that translates disk access to socket/pipe access.

Sockets and pipes are different beasts because, unlike files, they are
allocated memory buffers in the kernel memory. Also, they are accessed
strictly sequentially while files can be sought back and forth.

I do think it would be a nice addition to linux if they added a, say,
AF_FILE socket type that provided a buffered socket abstraction for
physical files.


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


Re: Unpacking U-Boot image file

2014-04-09 Thread Rustom Mody
On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
> How to extract files from U-Boot image file, LZMA-compressed?
> 
> Is there a Python script that can do this properly?

For lzma theres this (recent) python library
https://docs.python.org/dev/library/lzma.html

Though you might just be better off with the command-line xz unxz etc

After that.. whats the U-boot format?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unpacking U-Boot image file

2014-04-09 Thread Adnan Sadzak
I belive you are trying to decompress some router images or router
backup/config files?
Check if maybe LZS.

Rustom gave You starting point.



On Wed, Apr 9, 2014 at 7:18 PM, Rustom Mody  wrote:

> On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
> > How to extract files from U-Boot image file, LZMA-compressed?
> >
> > Is there a Python script that can do this properly?
>
> For lzma theres this (recent) python library
> https://docs.python.org/dev/library/lzma.html
>
> Though you might just be better off with the command-line xz unxz etc
>
> After that.. whats the U-boot format?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Marko Rauhamaa
"Frank Millman" :

> I am finding difficulty in understanding the benefit of going async in
> my case. If most requests require a blocking handler, it seems that I
> might as well stick with each request being handled by a thread,
> independent of all other threads.

When the underlying facilities only provide blocking access, you are
forced to use threads (or processes).

One area where asynchronous programming was always the method of choice
is graphical user interfaces. The GUI of an application must always be
responsive to the user and must be prepared to handle any of numerous
stimuli.

Network protocol layers are also usually implemented asynchronously. The
protocol standards read like asynchronous programs so the translation
into executable programs is most natural in the asynchronous style.
Here, too, the networking entities must be ready for different stimuli
in any state, so threads are usually not a good fit.

Kernel programming makes use of threads and processes. However, the
asynchronous style is there in a big way in the form of interrupt
handlers, hooks and system calls.

Really, the threading model is only good for a relatively small subset
of programming objectives, and over the lifetime of the solution, you
will often come to realize threading wasn't that good a fit after all.
Namely, in any given state, you will have to be prepared to handle more
than one stimulus. Also, over time you will learn to dread the race
conditions that are endemic in thread programming. Those are the kinds
of problems that make you check out the current job postings. Only
there's no escape: in your next job, they are going to make you find and
fix the race conditions in your predecessor's code.


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


Re: threading

2014-04-09 Thread MRAB

On 2014-04-09 16:51, Rick Johnson wrote:
[snip]


 3. It irks me that language designers pay no attention
to consistency.

 And the evil incarnation of the IMPLICIT PRONOUN raises
 it's ugly head!!!


The pronoun isn't implicit, because it's actually present!

(And it's "its ugly head", BTW.)


Again we have the pronoun "it" declared as the very first
word of the sentence, however, the referent is missing, and
instead must be intuited! But the fun does not stop there
people, NO-NO-NO, after you go to all the work required to
intuit the referent, you then immediately realize that the
referent is *SUPERFLUOUS* and needs garbage collection! What
sort of sick joke is this? Heck, we have not even considered
the emotional states that must be mustered to empathize
with the authors' intent!!!


The referent isn't missing. The "it" refers to the postcedent clause
"that language designers..." that's the subject of the verb "irks". (A
postcedent is like an antecendent, except that it refers forwards to
something that follows instead of backwards to something that preceded.)

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


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 3:31 AM, Marko Rauhamaa  wrote:
> Really, the threading model is only good for a relatively small subset
> of programming objectives, and over the lifetime of the solution, you
> will often come to realize threading wasn't that good a fit after all.
> Namely, in any given state, you will have to be prepared to handle more
> than one stimulus. Also, over time you will learn to dread the race
> conditions that are endemic in thread programming. Those are the kinds
> of problems that make you check out the current job postings. Only
> there's no escape: in your next job, they are going to make you find and
> fix the race conditions in your predecessor's code.

People with a fear of threaded programming almost certainly never grew
up on OS/2. :) I learned about GUI programming thus: Write your
synchronous message handler to guarantee that it will return in an
absolute maximum of 0.1s, preferably a lot less. If you have any sort
of heavy processing to do, spin off a thread. It was simply the normal
way to do things. Normal handling was done on Thread 0, and two
sequential events would be processed sequentially on that thread (so
if your handler for the Enter keypress message clears out an entry
field, the next key pressed is guaranteed to happen on an empty
field), and everything else, it's considered normal to spawn threads
and let them run to completion.

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


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 3:47 AM, MRAB  wrote:
> On 2014-04-09 16:51, Rick Johnson wrote:
>>  And the evil incarnation of the IMPLICIT PRONOUN raises
>>  it's ugly head!!!
>>
> (And it's "its ugly head", BTW.)

Fundamental rule of the internet: If you criticize someone else's
spelling or grammar, you will make a blooper yourself, usually of
paper-bag proportions.

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


Re: threading

2014-04-09 Thread Sturla Molden
Chris Angelico  wrote:

> People with a fear of threaded programming almost certainly never grew
> up on OS/2. :) I learned about GUI programming thus: Write your
> synchronous message handler to guarantee that it will return in an
> absolute maximum of 0.1s, preferably a lot less. If you have any sort
> of heavy processing to do, spin off a thread. It was simply the normal
> way to do things. 

That is still the best way to do it, IMHO. 

As I recall, on BeOS the operating system would even spawn a new thread to
handle each GUI event. Pervasive multithreading is great for creating
responsive user interfaces and running multimedia.

Sturla

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


Re: Unpacking U-Boot image file

2014-04-09 Thread trewio
I need decompress image(modem), and I deciced use some Python script or utility 
which capable run on Python for Windows OS.



 
> - Original Message -
> From: Adnan Sadzak
> Sent: 04/09/14 08:33 PM
> To: python-list
> Subject: Re: Unpacking U-Boot image file
> 
> I belive you are trying to decompress some router images or router
> backup/config files?
> Check if maybe LZS.
> 
> Rustom gave You starting point.
> 
> 
> 
> On Wed, Apr 9, 2014 at 7:18 PM, Rustom Mody  wrote:
> 
> > On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
> > > How to extract files from U-Boot image file, LZMA-compressed?
> > >
> > > Is there a Python script that can do this properly?
> >
> > For lzma theres this (recent) python library
> > https://docs.python.org/dev/library/lzma.html
> >
> > Though you might just be better off with the command-line xz unxz etc
> >
> > After that.. whats the U-boot format?
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >

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


Re: Unpacking U-Boot image file

2014-04-09 Thread trewio
U-Boot format: hmm, I'm not sure, can someone specify Python script that will 
help me deterermine U-boot format used? [for Python for Windows OS]

Note: I need Python script for Python under Windows OS.


> - Original Message -
> From: Rustom Mody
> Sent: 04/09/14 08:18 PM
> To: python-list@python.org
> Subject: Re: Unpacking U-Boot image file
> 
> On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
> > How to extract files from U-Boot image file, LZMA-compressed?
> > 
> > Is there a Python script that can do this properly?
> 
> For lzma theres this (recent) python library
> https://docs.python.org/dev/library/lzma.html
> 
> Though you might just be better off with the command-line xz unxz etc
> 
> After that.. whats the U-boot format?
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


CommandLine Option in Python for filtering values from Column

2014-04-09 Thread rohan bareja
I want to write a function in Python for a tab delimited file I am dealing 
with,to filter out values from a column, and put that parameter as a command 
line option while running the script.

So,if the limit is 10,the filter out all the rows with values less than 10.
Also,I want to check if the number entered is numeric or not else display the 
message "its not numeric".


So,the command line would be:

    python script.py file --quality [limit]

    
  The Python script:

    import sys
    arg = []
        for a in sys.argv:
    arg.append(a) 
            quality = arg[2]


To be more specific,the file I am dealing with is a Samfile,and using package 
Pysam,which has mapping quality limits in the 5th column.

https://media.readthedocs.org/pdf/pysam/latest/pysam.pdf

Commandline:

      python script.py samfile --quality [limit]

 I am reading the samfile using this:

     samfile = pysam.Samfile(arg[1], "rb" )
     mapqlim = arg[2]

I am a Python beginner,but saw one of the modules,argparse. How can I 
accomplish this using argparse in Python?-- 
https://mail.python.org/mailman/listinfo/python-list


imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Grant Edwards
Connecting to Exchange server fails like this:

 File "/usr/lib64/python2.7/imaplib.py", line 1148, in __init__
   IMAP4.__init__(self, host, port)
 SSLError: [Errno 1] _ssl.c:1419: error:1408F10B:SSL 
routines:SSL3_GET_RECORD:wrong version number

Experiments show that when calling ssl.wrap_socket() I have to specify
ssl_version=PROTOCOL_TLSv1 to avoid the above error.

How do I tell imaplib to use TLS1 instead of SSL3?

-- 
Grant Edwards   grant.b.edwardsYow! UH-OH!!  We're out
  at   of AUTOMOBILE PARTS and
  gmail.comRUBBER GOODS!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Grant Edwards
On 2014-04-09, Grant Edwards  wrote:
> Connecting to Exchange server fails like this:
>
>  File "/usr/lib64/python2.7/imaplib.py", line 1148, in __init__
>IMAP4.__init__(self, host, port)
>  SSLError: [Errno 1] _ssl.c:1419: error:1408F10B:SSL 
> routines:SSL3_GET_RECORD:wrong version number
>
> Experiments show that when calling ssl.wrap_socket() I have to specify
> ssl_version=PROTOCOL_TLSv1 to avoid the above error.
>
> How do I tell imaplib to use TLS1 instead of SSL3?

I'm not too keen on this approach, but monkey-patching the open()
method seems to work:

def my_imap4_ssl_open(self, host = '', port = 993):
self.host = host
self.port = port
self.sock = socket.create_connection((host, port))
self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, 
ssl_version=ssl.PROTOCOL_TLSv1)
self.file = self.sslobj.makefile('rb')

imaplib.IMAP4_SSL.open = my_imap4_ssl_open 

-- 
Grant Edwards   grant.b.edwardsYow! I hope the
  at   ``Eurythmics'' practice
  gmail.combirth control ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Method(s) called by square brackets, slice objects

2014-04-09 Thread John Ladasky
I would like to build a multi-dimensional array that allows numpy-style 
indexing and, ideally, uses Python's familiar square-bracket and slice 
notations.

For example, if I declare a two-dimensional array object, x, then x[4,7] 
retrieves the element located at the 4th row and the 7th column.  If I ask for 
x[3:6,1:3], I get a 3 x 2 array object consisting of the intersection of the 
3rd-5th rows, and the 1st-2nd columns, of x.

In this case I'm not allowed to use numpy, I have to restrict myself to the 
standard library.  I thought that I might achieve the desired behavior by 
defining an object with specific __getitem__ and/or __getslice__ methods.  
However, the documentation of these methods that I am reading suggests that the 
arguments are pre-parsed into certain formats which may not allow me to do 
things numpy's way.  Is this true?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Tim Chase
On 2014-04-09 20:12, Grant Edwards wrote:
>  File "/usr/lib64/python2.7/imaplib.py", line 1148, in __init__
>IMAP4.__init__(self, host, port)
>  SSLError: [Errno 1] _ssl.c:1419: error:1408F10B:SSL
> routines:SSL3_GET_RECORD:wrong version number
> 
> Experiments show that when calling ssl.wrap_socket() I have to
> specify ssl_version=PROTOCOL_TLSv1 to avoid the above error.
> 
> How do I tell imaplib to use TLS1 instead of SSL3?

Sounds like you'd need to make a subclass, something like

  class IMAP4_TLS(imaplib.IMAP4_SSL):
def open(self, host="", port=IMAP4_SSL_PORT):
  self.host = host
  self.port = port
  self.sock = socket.create_connection((host, port))
  self.sslobj = ssl.wrap_socket(
self.sock,
self.keyfile,
self.certfile,
ssl_version=PROTOCOL_TLSv1,
)
  self.file = self.sslobj.makefile('rb')

Alternatively, you could genericify it something like


  class IMAP4_TLS(imaplib.IMAP4_SSL):
def open(self, host="",
port=IMAP4_SSL_PORT,
ssl_version=PROTOCOL_SSLv23,
):
  self.host = host
  self.port = port
  self.sock = socket.create_connection((host, port))
  self.sslobj = ssl.wrap_socket(
self.sock,
self.keyfile,
self.certfile,
ssl_version=ssl_version,
)
  self.file = self.sslobj.makefile('rb')

and then call .open(..., ssl_version=PROTOCOL_TLSv1) or specify any
other protocol that you need.

-tkc




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


Re: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Tim Chase
On 2014-04-09 20:20, Grant Edwards wrote:
> I'm not too keen on this approach, but monkey-patching the open()
> method seems to work:
> 
> def my_imap4_ssl_open(self, host = '', port = 993):
> self.host = host
> self.port = port
> self.sock = socket.create_connection((host, port))
> self.sslobj = ssl.wrap_socket(self.sock, self.keyfile,
> self.certfile, ssl_version=ssl.PROTOCOL_TLSv1) self.file =
> self.sslobj.makefile('rb')
> 
> imaplib.IMAP4_SSL.open = my_imap4_ssl_open 

Our messages passed in the ether.  You don't have to feel dirty
for monkey-patching, as you can just do it with inheritance.

-tkc


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


Re: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Grant Edwards
On 2014-04-09, Tim Chase  wrote:
> On 2014-04-09 20:20, Grant Edwards wrote:
>> I'm not too keen on this approach, but monkey-patching the open()
>> method seems to work:
>> 
>> def my_imap4_ssl_open(self, host = '', port = 993):
>> self.host = host
>> self.port = port
>> self.sock = socket.create_connection((host, port))
>> self.sslobj = ssl.wrap_socket(self.sock, self.keyfile,
>> self.certfile, ssl_version=ssl.PROTOCOL_TLSv1) self.file =
>> self.sslobj.makefile('rb')
>> 
>> imaplib.IMAP4_SSL.open = my_imap4_ssl_open 
>
> Our messages passed in the ether.

Yep saw that.  Thanks for the answers. 

> You don't have to feel dirty for monkey-patching, as you can just do
> it with inheritance.

Doh. I don't know why I didn't think of that...

-- 
Grant Edwards   grant.b.edwardsYow! I wonder if there's
  at   anything GOOD on tonight?
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Method(s) called by square brackets, slice objects

2014-04-09 Thread Ethan Furman

On 04/09/2014 01:24 PM, John Ladasky wrote:


I would like to build a multi-dimensional array that allows numpy-style
 indexing and, ideally, uses Python's familiar square-bracket and slice
 notations.

For example, if I declare a two-dimensional array object, x, then x[4,7]
 retrieves the element located at the 4th row and the 7th column.  If I
 ask for x[3:6,1:3], I get a 3 x 2 array object consisting of the inter-
section of the 3rd-5th rows, and the 1st-2nd columns, of x.

In this case I'm not allowed to use numpy, I have to restrict myself to
 the standard library.  I thought that I might achieve the desired behavior
 by defining an object with specific __getitem__ and/or __getslice__ methods.
However, the documentation of these methods that I am reading suggests that
 the arguments are pre-parsed into certain formats which may not allow me to
 do things numpy's way.  Is this true?


Nope.  Whatever you put between the square brackets is what gets passed into __getitem__; the only caveat is that 
anything with : will be turned into a slice:


Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
--> class GetIndex(object):
...   def __getitem__(self, thing):
... print thing
... return None
...
--> test = GetIndex()

--> test[1]
1

--> test [1,2]
(1, 2)

--> test[1:3, 4:5]
(slice(1, 3, None), slice(4, 5, None))

--> test[range(3)]
[0, 1, 2]

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


Re: Unpacking U-Boot image file

2014-04-09 Thread laguna-mc
I know about Binwalk, it can run on Linux OS only. I am looking for Python 
script that can run on Windows too.

Thank you.
- Original Message -
From: Adnan Sadzak
Sent: 04/09/14 11:37 PM
To: trewio
Subject: Re: Unpacking U-Boot image file

Oh then see Craig's page [0]. You can find in deepth explanation about some 
tools (Linux) that is used to desompress and mount filesystems/images. From my 
experience you should find first read modem tehnical documentation. Find out 
what kind of firmware is using. You won't find just script to decompress those 
images.

[0] 
http://www.devttys0.com/2011/05/reverse-engineering-firmware-linksys-wag120n/ 

Cheers

On Wed, Apr 9, 2014 at 7:53 PM, trewio < laguna...@mail.com > wrote:U-Boot 
format: hmm, I'm not sure, can someone specify Python script that will help me 
deterermine U-boot format used? [for Python for Windows OS]

Note: I need Python script for Python under Windows OS.

> - Original Message -
> From: Rustom Mody
> Sent: 04/09/14 08:18 PM
> To:  python-list@python.org 
> Subject: Re: Unpacking U-Boot image file
>

> On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
> > How to extract files from U-Boot image file, LZMA-compressed?
> >
> > Is there a Python script that can do this properly?
>
> For lzma theres this (recent) python library
> https://docs.python.org/dev/library/lzma.html 
>
> Though you might just be better off with the command-line xz unxz etc
>
> After that.. whats the U-boot format?
> --
> 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: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Grant Edwards
On 2014-04-09, Grant Edwards  wrote:
> On 2014-04-09, Tim Chase  wrote:
>> On 2014-04-09 20:20, Grant Edwards wrote:
>>> I'm not too keen on this approach, but monkey-patching the open()
>>> method seems to work:
>>> 
>>> def my_imap4_ssl_open(self, host = '', port = 993):
>>> self.host = host
>>> self.port = port
>>> self.sock = socket.create_connection((host, port))
>>> self.sslobj = ssl.wrap_socket(self.sock, self.keyfile,
>>> self.certfile, ssl_version=ssl.PROTOCOL_TLSv1) self.file =
>>> self.sslobj.makefile('rb')
>>> 
>>> imaplib.IMAP4_SSL.open = my_imap4_ssl_open 
>>
>> Our messages passed in the ether.
>
> Yep saw that.  Thanks for the answers. 
>
>> You don't have to feel dirty for monkey-patching, as you can just do
>> it with inheritance.
>
> Doh. I don't know why I didn't think of that...

Now I remember...

I left out a relevent fact: I'm not the one calling IMAP4_.

That's being done by the imapclient library.  There's no way to pass
imapclient a custom class to use.  It's hard-waired to call either
imaplib.IMAP4_stream(), imaplib.IMAP4(), or imaplib.IMAP4_SSL().  I
could create an IMAP4_TLS1 class, but I would then have to sub-class
imapclient.IMAPClient and override its _create_IMAP4() method to make
it call my IMAP4_TLS1() class instead of calling imaplib.IMAP4_SSL().

Monkey-patching imaplib seems a little better since it it doesn't
depend on assumptions about the internal workings of imapclient (other
than the fact that it uses imaplib.IMAP4_SSL).

-- 
Grant Edwards   grant.b.edwardsYow! MMM-MM!!  So THIS is
  at   BIO-NEBULATION!
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


2014 PyCamps

2014-04-09 Thread Chris Calloway
PyCamp is an ultra-low-cost, five-day, intensive Python boot camp 
program by a user group for user groups. PyCamp has taught Python 
fundamentals to thousands of beginners for nine years while sponsoring 
Python regional conferences, symposia, sprints, scholarships, and user 
groups. You can get up to speed on the most modern programming language 
at PyCamp.


This year choose from two PyCamps:

Wisconsin PyCamp 2014, June 13-17, University of Wisconsin-Oshkosh
http://tripython.org/wiscpy14
Wisconsin PyCamp 2014 is a training program of Plone Symposium Midwest.
http://midwest.plonesymp.org
Wisconsin PyCamp 2014 is all-day catered (breakfast, lunch, snacks).

or

PyOhio PyCamp 2014, July 21-25, The Ohio State University
http://tripython.org/pyohio14
PyOhio PyCamp 2014 is a pre-conference training program of PyOhio
http://pyohio.org
Scholarships for women and minorities are available for PyOhio PyCamp

--
Sincerely,

Chris Calloway http://nccoos.org/Members/cbc
office: 3313 Venable Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
--
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Gregory Ewing

Roy Smith wrote:
In the old days, all Unix system calls were divided up into two groups, 
based on whether they were "fast" or "slow".  Processes executing a 
"fast" system call would block, and could not be interrupted;


That doesn't really have anything to do with blocking vs.
non-blocking, though. The system call blocks in both cases;
the only difference is whether the kernel bothers to allow
for aborting the blocked operation part way through. The
calling process doesn't see any difference.

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


Re: threading

2014-04-09 Thread Gregory Ewing

On 2014-04-09 16:51, Rick Johnson wrote:

Again we have the pronoun "it" declared as the very first
word of the sentence, however, the referent is missing, and
instead must be intuited!


Pronoun referents *always* need to be intuited. There are
no mechanical rules for finding the referent of a pronoun
in an English sentence; you have to figure it out from what
makes the most sense given the context.


(A
postcedent is like an antecendent, except that it refers forwards to
something that follows instead of backwards to something that preceded.)


Then there are even weirder cases, such as "It is raining
today", where the referent ("the weather" in this case) is
never explicitly mentioned at all!

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


Re: threading

2014-04-09 Thread Roy Smith
In article ,
 Gregory Ewing  wrote:

> > On 2014-04-09 16:51, Rick Johnson wrote:
> >> Again we have the pronoun "it" declared as the very first
> >> word of the sentence, however, the referent is missing, and
> >> instead must be intuited!
> 
> Pronoun referents *always* need to be intuited. There are
> no mechanical rules for finding the referent of a pronoun
> in an English sentence; you have to figure it out from what
> makes the most sense given the context.
> 
> > (A
> > postcedent is like an antecendent, except that it refers forwards to
> > something that follows instead of backwards to something that preceded.)
> 
> Then there are even weirder cases, such as "It is raining
> today", where the referent ("the weather" in this case) is
> never explicitly mentioned at all!

It's even more ambiguous in Spanish.  Esta lloviendo.  Not only do you 
get to intuit the referrent, you get to intuit the pronoun too :-)

Natural language is a wonderfully expressive thing.  I open the window, 
stick my head out, look up at the sky, and say, "Raining".  Forget the 
pronoun, I don't even have a verb.  And yet everybody understands 
exactly what I mean.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Andrew Berg
On 2014.04.09 18:53, Roy Smith wrote:
> It's even more ambiguous in Spanish.  Esta lloviendo.  Not only do you 
> get to intuit the referrent, you get to intuit the pronoun too :-)
And in this particular instance, you have to figure out that 'está' (verb) was 
meant instead of 'esta' (adjective). :)

-- 
CPython 3.4.0 | Windows NT 6.2.9200 / FreeBSD 10.0
-- 
https://mail.python.org/mailman/listinfo/python-list


Re:Unpacking U-Boot image file

2014-04-09 Thread Dave Angel
"trewio"  Wrote in message:
> How to extract files from U-Boot image file, LZMA-compressed?
> 
> Is there a Python script that can do this properly?
> 

Use the lzma module in Python 3.3 for starters

-- 
DaveA

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


webapp stuck on 1 cpu

2014-04-09 Thread johannes falcone
do python web frameworks green thread but are stuck on 1 cpu

or like aolserver

do they use os threads and then maybe a combo of green and events ? so that a 
webapp can use a 64 cpu machine with out pain?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unpacking U-Boot image file

2014-04-09 Thread Dave Angel
"trewio"  Wrote in message:
> U-Boot format: hmm, I'm not sure, can someone specify Python script that will 
> help me deterermine U-boot format used? [for Python for Windows OS]
> 
> Note: I need Python script for Python under Windows OS.
> 
> 
>> - Original Message -
>> From: Rustom Mody
>> Sent: 04/09/14 08:18 PM
>> To: python-list@python.org
>> Subject: Re: Unpacking U-Boot image file
>> 
>> On Wednesday, April 9, 2014 9:36:40 PM UTC+5:30, trewio wrote:
>> > How to extract files from U-Boot image file, LZMA-compressed?
>> > 
>> > Is there a Python script that can do this properly?
>> 
>> For lzma theres this (recent) python library
>> https://docs.python.org/dev/library/lzma.html
>> 
>> Though you might just be better off with the command-line xz unxz etc
>> 
>> After that.. whats the U-boot format?
>> -- 
>> https://mail.python.org/mailman/listinfo/python-list
> 
> 

Good job starting 3 separate threads for same question.  Sorry I
 answered the first one. 
-- 
DaveA

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


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-09 Thread alex23

On 9/04/2014 6:55 PM, Mark Lawrence wrote:

And the worst thing about terrible code is when you first realise
just how bad it is and wonder why you wrote it like that in the first
place.


For me, it's nearly always due to time constraints. Usually caused by a 
comment like: "we absolutely need this extensive feature added before 
launch, can you start it right now? oh and we're still good for release 
tomorrow, right? Because we promised the client etc etc etc"


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


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 9:44 AM, Dennis Lee Bieber
 wrote:
> On Wed, 9 Apr 2014 23:47:04 +1000, Chris Angelico 
> declaimed the following:
>
>>won't block. You might think "Duh, how can printing to the screen
>>block?!?", but if your program's output is being piped into something
>>else, it most certainly can :) If that were writing to a remote
>
> Heck, even if it isn't blocking per se, it may still be enough to slow
> down the whole system (over the past year I've had to characterize through
> put on some systems -- and the console logging of "exceptions"* slowed the
> overall data rate significantly)

Oh yes, definitely. Console output can be *slow*. Back in my earliest
programming days, I'd often have a program that iterated over sub-jobs
from either 0 or 1 up to some unknown top (so I can't show a
percent-done), and the obvious thing to do is (rewritten in Python):

i = 0
while stuff_to_do():
i += 1
print(i, end="\r")
do_more_stuff()
print(i)

Hmm, that's really slow. I know! I'll speed this up by printing out
only once a second. That should be way faster, right? Let's see.

i = time_printed = 0
while stuff_to_do():
i += 1
if int(time.time()) != time_printed:
print(i, end="\r")
time_printed = int(time.time())
do_more_stuff()
print(i)

And that made it... wy slower. Turns out clock querying (at least
on those systems) is pretty slow too, even more so than console
output. Of course, what we ended up settling on was something like
this, which *does* make sense:

i = 0
while stuff_to_do():
i += 1
if i & 255 == 0: print(i, end="\r")
do_more_stuff()
print(i)

replacing 255 with any number one less than a power of two, so it'd
print out every however-many-th (in this case, every 256th), using
bitwise operations rather than division.

But yeah, console output isn't something you want when you're going
for maximum throughput. Heh.

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


How to display chinese character in 65001 in pytohn?

2014-04-09 Thread length power
I am in win7 +python3.3.

import os
os.system("chcp  936")
fh=open("test.ch","w",encoding="utf-8")
fh.write("你")
fh.close()
os.system("chcp 65001")
fh=open("test.ch","r",encoding="utf-8").read()
print(fh)
Äã
>>> print(fh.encode("utf-8"))
b'\xe4\xbd\xa0'

How can i display the chinese character  `你` in 65001?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: imaplib: how to specify SSL/TLS protocol version?

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 7:10 AM, Grant Edwards  wrote:
> I left out a relevent fact: I'm not the one calling IMAP4_.
>
> That's being done by the imapclient library.  There's no way to pass
> imapclient a custom class to use.  It's hard-waired to call either
> imaplib.IMAP4_stream(), imaplib.IMAP4(), or imaplib.IMAP4_SSL().  I
> could create an IMAP4_TLS1 class, but I would then have to sub-class
> imapclient.IMAPClient and override its _create_IMAP4() method to make
> it call my IMAP4_TLS1() class instead of calling imaplib.IMAP4_SSL().
>
> Monkey-patching imaplib seems a little better since it it doesn't
> depend on assumptions about the internal workings of imapclient (other
> than the fact that it uses imaplib.IMAP4_SSL).

That's an argument in favour of a minor case of serious
monkey-patching. Although if you do feel dirty, try to hold on to that
feeling because that is the proper reaction to being told that you're
monkey-patching.

ChrisA
okay, now I feel like a moron... not just a regular moron, though...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to display chinese character in 65001 in pytohn?

2014-04-09 Thread MRAB

On 2014-04-10 02:54, length power wrote:

I am in win7 +python3.3.

 import os
 os.system("chcp  936")
 fh=open("test.ch ","w",encoding="utf-8")
 fh.write("你")
 fh.close()
 os.system("chcp 65001")
 fh=open("test.ch ","r",encoding="utf-8").read()
 print(fh)
 Äã
 >>> print(fh.encode("utf-8"))
 b'\xe4\xbd\xa0'

How can i display the chinese character  `你` in 65001?


The "chcp 65001" tells the operating system to use UTF-8, but you also
have to tell Python to output UTF-8. Try this:

from codecs import getwriter
sys.stdout = getwriter('utf-8')(sys.stdout.detach())

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


Re: threading

2014-04-09 Thread Steven D'Aprano
On Wed, 09 Apr 2014 19:53:26 -0400, Roy Smith wrote:

> Natural language is a wonderfully expressive thing.  I open the window,
> stick my head out, look up at the sky, and say, "Raining".  Forget the
> pronoun, I don't even have a verb.  And yet everybody understands
> exactly what I mean.

Not everybody. There's always someone like Rick, who I'm sure will claim 
that he cannot understand a sentence like "Raining". The curious thing 
is, his claim to have less understanding of his own native tongue than a 
two-year-old is probably put on to prove how he is so much smarter than 
everyone else.

"You people are SO DUMB!!! You cannot use plane English! Your so dumb i 
can't even understand you're sentences! Wake up sheeple and learn to 
right proper English!"



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


Re: Method(s) called by square brackets, slice objects

2014-04-09 Thread Steven D'Aprano
On Wed, 09 Apr 2014 13:24:32 -0700, John Ladasky wrote:

> I would like to build a multi-dimensional array that allows numpy-style
> indexing and, ideally, uses Python's familiar square-bracket and slice
> notations.
> 
> For example, if I declare a two-dimensional array object, x, then x[4,7]
> retrieves the element located at the 4th row and the 7th column.  If I
> ask for x[3:6,1:3], I get a 3 x 2 array object consisting of the
> intersection of the 3rd-5th rows, and the 1st-2nd columns, of x.
> 
> In this case I'm not allowed to use numpy, I have to restrict myself to
> the standard library.  I thought that I might achieve the desired
> behavior by defining an object with specific __getitem__ and/or
> __getslice__ methods.  

Use __getitem__, __getslice__ is deprecated in Python 2 and gone in 
Python 3.

https://docs.python.org/2/reference/datamodel.html#object.__getslice__


> However, the documentation of these methods that
> I am reading suggests that the arguments are pre-parsed into certain
> formats which may not allow me to do things numpy's way.  Is this true?

Why don't you try it in the interactive interpreter and see?


py> class Test(object):
... def __getitem__(self, thing):
... print thing
... 
py> obj = Test()
py> obj[1]
1
py> obj[1:2]
slice(1, 2, None)
py> obj[1:2:3]
slice(1, 2, 3)
py> obj[1,5:2:3]
(1, slice(5, 2, 3))
py> obj[1:2:3,4:5:6]
(slice(1, 2, 3), slice(4, 5, 6))
py> obj[1,2,3]
(1, 2, 3)
py> obj[1,2,"spam"]
(1, 2, 'spam')
py> obj[1,2,"spam":"eggs",3]
(1, 2, slice('spam', 'eggs', None), 3)




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


Re: How to display chinese character in 65001 in pytohn?

2014-04-09 Thread length power
i tried this way ,and post it in stackoverflow,please see:
maybe it is the best answer.
Codepage 65001 is generally broken in binary mode as used by Python 3,
since _write calls Win32 WriteFile, which calls WriteConsoleA, which
returns the number of characters written instead of the number of bytes.
That confuses Python. ANSICON  can hook
WriteFile to fix this for programs that you specify in an environment
variable, but that won't help with input.

http://stackoverflow.com/questions/22977409/how-to-display-chinese-character-in-65001-in-pytohn?noredirect=1#comment35087732_22977409


2014-04-10 10:27 GMT+08:00 MRAB :

> On 2014-04-10 02:54, length power wrote:
>
>> I am in win7 +python3.3.
>>
>>  import os
>>  os.system("chcp  936")
>>  fh=open("test.ch ","w",encoding="utf-8")
>>
>>  fh.write("你")
>>  fh.close()
>>  os.system("chcp 65001")
>>  fh=open("test.ch ","r",encoding="utf-8").read()
>>
>>  print(fh)
>>  Äã
>>  >>> print(fh.encode("utf-8"))
>>  b'\xe4\xbd\xa0'
>>
>> How can i display the chinese character  `你` in 65001?
>>
>>  The "chcp 65001" tells the operating system to use UTF-8, but you also
> have to tell Python to output UTF-8. Try this:
>
> from codecs import getwriter
> sys.stdout = getwriter('utf-8')(sys.stdout.detach())
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 12:43 PM, Steven D'Aprano  wrote:
> You cannot use plane English!

Cleared for takeoff...

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


Re: How to display chinese character in 65001 in pytohn?

2014-04-09 Thread length power
problem solved.if you enter python by python(command line),the problem
can't be solved.if you enter python by cmd ,and input python,no problem
happen.


2014-04-10 11:05 GMT+08:00 length power :

> i tried this way ,and post it in stackoverflow,please see:
> maybe it is the best answer.
> Codepage 65001 is generally broken in binary mode as used by Python 3,
> since _write calls Win32 WriteFile, which calls WriteConsoleA, which
> returns the number of characters written instead of the number of bytes.
> That confuses Python. ANSICON  can hook
> WriteFile to fix this for programs that you specify in an environment
> variable, but that won't help with input.
>
>
> http://stackoverflow.com/questions/22977409/how-to-display-chinese-character-in-65001-in-pytohn?noredirect=1#comment35087732_22977409
>
>
> 2014-04-10 10:27 GMT+08:00 MRAB :
>
> On 2014-04-10 02:54, length power wrote:
>>
>>> I am in win7 +python3.3.
>>>
>>>  import os
>>>  os.system("chcp  936")
>>>  fh=open("test.ch ","w",encoding="utf-8")
>>>
>>>  fh.write("你")
>>>  fh.close()
>>>  os.system("chcp 65001")
>>>  fh=open("test.ch ","r",encoding="utf-8").read()
>>>
>>>  print(fh)
>>>  Äã
>>>  >>> print(fh.encode("utf-8"))
>>>  b'\xe4\xbd\xa0'
>>>
>>> How can i display the chinese character  `你` in 65001?
>>>
>>>  The "chcp 65001" tells the operating system to use UTF-8, but you also
>> have to tell Python to output UTF-8. Try this:
>>
>> from codecs import getwriter
>> sys.stdout = getwriter('utf-8')(sys.stdout.detach())
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: threading

2014-04-09 Thread Steven D'Aprano
On Wed, 09 Apr 2014 08:51:09 -0700, Rick Johnson wrote:

> On Wednesday, April 9, 2014 8:50:59 AM UTC-5, Neil D. Cerutti wrote:
>> [...]
>> Plus Rufus Xavier Sasparilla disagrees with it.
> 
> If you think you're going to argue in such an implicit manner as to the
> benefits of pronouns, then you should expect that an astute logician
> such as myself will tear you to shreds.

This reminds me of Wile E. Coyote, announcing himself to others:

"Allow me to introduce myself, Wile E. Coyote, Super-Genius."

http://geekwisdom.wordpress.com/2013/03/16/wile-e-coyote-super-genius/


Rick, if you have to call yourself an astute logician for other to know, 
then you probably aren't.


> And whist i admit your snarky comment is founded on a *superficial* fact

"Whilst". Whist is a card game.

[...]
>  
> # You comment is cleaver propaganda, 

Damn those lying cleavers!

"Clever". A cleaver is a type of heavy chopping knife, usually used for 
cutting through bones.


[...]
> Now, before i utterly destroy you, we must first *ALL* take a lesson in
> linguistics.

Oh noes! I'm going to be destroyed by Rick, Super-Genius!

Rick, before you reform the English language, perhaps you ought to 
concentrate on an easier task. A few years ago you offered to fork Python 
and make it a better language. I promised to be a beta tester for you if 
you did so. How is that coming along? Do you have a repo where I can 
check out progress?



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


Re: threading

2014-04-09 Thread Chris Angelico
On Thu, Apr 10, 2014 at 1:44 PM, Steven D'Aprano  wrote:
>> Now, before i utterly destroy you, we must first *ALL* take a lesson in
>> linguistics.
>
> Oh noes! I'm going to be destroyed by Rick, Super-Genius!

I'll send him my business card as a salesman for Acme. Easiest job in
the world - just sell him stuff with no guarantees, isn't necessarily
of merchantable quality, and might even backfire and explode, and
he'll buy the lot.

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


Plotting the integer-and-fraction remainder of a function value modulo 360

2014-04-09 Thread Kim Plofker
How can I get Python to represent a value of a function in degrees, i.e., with 
values between 0 and 360, by taking the (non-integer) function expression mod 
360?

That is, I have a function with non-integer values, called Longitude, which is 
defined in terms of the variable t. I just want to plot Longitude modulo 360 
for a range of values of t: that is, for every value of t, plot the 
integer-AND-fraction remainder after dividing Longitude by 360.

But Python (in Sage) apparently won't let me use the int function or the // 
operator on functions defined in terms of a variable: I get a "cannot evaluate 
symbolic expression numerically" TypeError. How do I do this? There must be a 
simple way to tell Python that I want it to compute the value of Longitude for 
a given value of t and then take the integer-and-fraction remainder from 
dividing by 360.



Many thanks,
Kim-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Plotting the integer-and-fraction remainder of a function value modulo 360

2014-04-09 Thread Ben Finney
Kim Plofker  writes:

> How can I get Python to represent a value of a function in degrees,
> i.e., with values between 0 and 360, by taking the (non-integer)
> function expression mod 360?

In Python, you simply use the modulo (‘%’) operator::

>>> 45.0 % 360
45.0
>>> 700.0 % 360
340.0
>>> 

> That is, I have a function with non-integer values, called Longitude

If they're not integers, and you're not saying what they *are*, then I
can't know anything beyond “they will behave the way the Longitude class
defines them”.

> which is defined in terms of the variable t.

I don't understand what it means for a longitude value to be “defined in
terms of the variable t”.

Can you say more about how these values are defined? Since (as you say)
they're not integers, what *are* they?

> I just want to plot Longitude modulo 360 for a range of values of t:
> that is, for every value of t, plot the integer-AND-fraction remainder
> after dividing Longitude by 360.

What does it mean to “plot the integer-AND-fraction remainder”? It
sounds like you want to plot two numbers separately, the integer and the
fraction remainder. But that doesn't make much sense to me.

Do you mean simply that you want to plot numbers like ‘3.7’, ‘270.0’,
and ‘48.75’? In which case, this is supported by the native ‘float’
type, and (for better accuracy) by the ‘decimal.Decimal’ type from the
standard library::

>>> lon = decimal.Decimal("758.45")
>>> lon % 360
Decimal('38.45')

> But Python (in Sage) apparently won't let me use the int function or
> the // operator on functions defined in terms of a variable: I get a
> "cannot evaluate symbolic expression numerically" TypeError.

It sounds like this Sage is not behaving as the standard Python types
do, with regard to the modulo ‘%’ operator.

For help with Sage (I don't know what that is), you probably will get
better answers on a Sage-specific discussion forum.

From the perspective of Python, the standard types handle the
requirements you describe without any TypeError.

-- 
 \  “If you were going to shoot a mime, would you use a silencer?” |
  `\—Steven Wright |
_o__)  |
Ben Finney

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


Re: Plotting the integer-and-fraction remainder of a function value modulo 360

2014-04-09 Thread Steven D'Aprano
On Wed, 09 Apr 2014 21:32:27 -0700, Kim Plofker wrote:

> How can I get Python to represent a value of a function in degrees,
> i.e., with values between 0 and 360, by taking the (non-integer)
> function expression mod 360?
> 
> That is, I have a function with non-integer values, called Longitude,
> which is defined in terms of the variable t. I just want to plot
> Longitude modulo 360 for a range of values of t: that is, for every
> value of t, plot the integer-AND-fraction remainder after dividing
> Longitude by 360.
> 
> But Python (in Sage) apparently won't let me use the int function or the
> // operator on functions defined in terms of a variable: I get a "cannot
> evaluate symbolic expression numerically" TypeError. 

That's an issue with Sage itself, probably sympy. Python the language 
doesn't natively understand symbolic expressions, that's added by sympy, 
so you may need to ask some sympy experts.

It may help if you show the actual code you are using, and the full 
traceback generated by the error. When I try something similar, I get a 
different error message:

py> from sympy.abc import x
py> (x + 1) % 60
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for %: 'Add' and 'int'


which could mean I'm doing something different, or just a difference in 
version numbers.


> How do I do this?
> There must be a simple way to tell Python that I want it to compute the
> value of Longitude for a given value of t and then take the
> integer-and-fraction remainder from dividing by 360.

That's simple with numeric types: use the divmod function or % operator. 
But you're using some sort of symbolic library, so we need to know what 
the library is.


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


how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-09 Thread length power
>>> x=["a","b",["c","d"],"e"]
>>> y=x[2]
>>> y
['c', 'd']
>>> x.insert(2,y[0])
>>> x
['a', 'b', 'c', ['c', 'd'], 'e']
>>> x.insert(3,y[1])
>>> x
['a', 'b', 'c', 'd', ['c', 'd'], 'e']
>>> del x[4]
>>> x
['a', 'b', 'c', 'd', 'e']
>>>
maybe there is a more smart way to do.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: CommandLine Option in Python for filtering values from Column

2014-04-09 Thread balaji marisetti
sys.argv is itself a list. You can directly access the `quality` field
as sys.argv[2].

quality = int(sys.argv[2])

 However, if you want to use more command line options, then using
`argparse` module is better than accessing arguments using `sys.argv`.

Import `argparse` module and create a parser

import argparse
parser = argparse.ArgumentParser(description='My example command line
option parser')

#Add as many arguments as you want to parse (from the command line)
parser.add_argument('--quality', type=int, help='Quality score')
parser.add_argument("--some-other-option", help="Some other option for example")
...
...

#Parse the arguments (to be)given on the command line(when the script
is invoked)
args = parser.parse_args()

#Access all the arguments or options as `args.quality`,
`args.some_other_option`, etc.
print("quality =", args.quality)
print("some-other-option =", args.some_other_option)

Read the documentation of argparse for better understanding.
https://docs.python.org/2/library/argparse.html

On 10 April 2014 00:53, rohan bareja  wrote:
> I want to write a function in Python for a tab delimited file I am dealing
> with,to filter out values from a column, and put that parameter as a command
> line option while running the script.
>
> So,if the limit is 10,the filter out all the rows with values less than 10.
> Also,I want to check if the number entered is numeric or not else display
> the message "its not numeric".
>
>
> So,the command line would be:
>
> python script.py file --quality [limit]
>
>
>   The Python script:
>
> import sys
> arg = []
> for a in sys.argv:
>arg.append(a)
> quality = arg[2]
>
>
> To be more specific,the file I am dealing with is a Samfile,and using
> package
> Pysam,which has mapping quality limits in the 5th column.
>
> https://media.readthedocs.org/pdf/pysam/latest/pysam.pdf
>
> Commandline:
>
>   python script.py samfile --quality [limit]
>
>  I am reading the samfile using this:
>
>  samfile = pysam.Samfile(arg[1], "rb" )
>  mapqlim = arg[2]
>
> I am a Python beginner,but saw one of the modules,argparse. How can I
> accomplish this using argparse in Python?
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



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


Re: how to make ["a", "b", ["c", "d"], "e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-09 Thread Ben Finney
length power  writes:

> maybe there is a more smart way to do.

Maybe. But a way to do what, exactly?

You start with a list, but what is it exactly that you want to do with
that list?

>>> x = ["a", "b", ["c", "d"], "e"]

If I interpret your request *literally*, I can achieve it in a single
statement::

>>> y = ['a', 'b', 'c', 'd', 'e']

There! We got the second list you wanted.

Maybe you want to turn the second item in any list into ‘['c', 'd']’::

>>> y = x[:2] + ['c', 'd'] + x[3:]

Or maybe you want some other operation. It's not clear from your example.

So, thank you for providing an example of what you mean; but that
doesn't help with knowing what you mean *generally*.

What is the general operation you want to do? Please describe what input
you will get, and what the output should be in the same terms.

-- 
 \“Ubi dubium, ibi libertas.” (“Where there is doubt, there is |
  `\freedom.”) |
_o__)  |
Ben Finney

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


Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-09 Thread balaji marisetti
There was long thread discussing flattening of a list on this list :).
See the link below.

https://mail.python.org/pipermail/python-list/2014-March/669256.html

On 10 April 2014 10:44, length power  wrote:
 x=["a","b",["c","d"],"e"]
 y=x[2]
 y
> ['c', 'd']
 x.insert(2,y[0])
 x
> ['a', 'b', 'c', ['c', 'd'], 'e']
 x.insert(3,y[1])
 x
> ['a', 'b', 'c', 'd', ['c', 'd'], 'e']
 del x[4]
 x
> ['a', 'b', 'c', 'd', 'e']

> maybe there is a more smart way to do.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



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


Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-09 Thread Rustom Mody
On Thursday, April 10, 2014 10:55:10 AM UTC+5:30, balaji marisetti wrote:
> There was long thread discussing flattening of a list on this list :).
> See the link below.

I dont think that thread is relevant to this question:
1. That (started with) a strange/cute way of using names
2. It does not work for heterogenous lists

# One level flatten version
# like the earlier thread without strange naming
# needed by the recursive one below
>>> def fl1(l): return [y for x in l for y in x]


# recursive flatten
>>> def fr(l):
...   if not isinstance(l,list): return [l]
...   return fl1([fr(x) for x in l])


You can replace the list-comps by generator-comps 

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


EuroScipy Reminder: call for abstracts closes in 4 days

2014-04-09 Thread Nelle Varoquaux
Hello everyone,

Just a quick reminder that the EuroScipy call for abstracts closes on the
14th: don't forget to submit your talk proposal! It is in four days only!

In short, EuroScipy is a cross-disciplinary gathering focused on the use
and development of the Python language in scientific research. This event
strives to bring together both users and developers of scientific tools, as
well as academic research and state of the art industry.

EuroSciPy 2014, the Seventh Annual Conference on Python in Science, takes
place in *Cambridge, UK on 27 - 30 August 2014*. The conference features
two days of tutorials followed by two days of scientific talks. The day
after the main conference, developer sprints will be organized on projects
of interest to attendees.

The topics presented at EuroSciPy are very diverse, with a focus on
advanced software engineering and original uses of Python and its
scientific libraries, either in theoretical or experimental research, from
both academia and the industry. The program includes keynotes, contributed
talks and posters.

Submissions for talks and posters are welcome on our website (
http://www.euroscipy.org/2014/). In your abstract, please provide details
on what Python tools are being employed, and how. The deadline for
submission is 14 April 2014.

Also until 14 April 2014, you can apply for a sprint session on 31 August
2014. See https://www.euroscipy.org/2014/calls/sprints/ for details.

Thanks,

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


Re: Plotting the integer-and-fraction remainder of a function value modulo 360

2014-04-09 Thread Kim Plofker
Thanks!  As I recently posted in a followup message,


Here's an example of what goes wrong:

t = var('t')

L(t) = t*725.5%360.0


This produces the following error message:

...
TypeError: unsupported operand type(s) for %:
'sage.symbolic.expression.Expression' and
'sage.symbolic.expression.Expression'



So it looks like I've got a Sage-specific problem.  I still don't know how to 
fix it, but at least I understand the problem better!  

Many thanks,
Kim


 From: Steven D'Aprano 
To: python-list@python.org 
Sent: Thursday, April 10, 2014 1:01 AM
Subject: Re: Plotting the integer-and-fraction remainder of a function value 
modulo 360
 

On Wed, 09 Apr 2014 21:32:27 -0700, Kim Plofker wrote:

> How can I get Python to represent a value of a function in degrees,
> i.e., with values between 0 and 360, by taking the (non-integer)
> function expression mod 360?
> 
> That is, I have a function with non-integer values, called Longitude,
> which is defined in terms of the variable t. I just want to plot
> Longitude modulo 360 for a range of values of t: that is, for every
> value of t, plot the integer-AND-fraction remainder after dividing
> Longitude by 360.
> 
> But Python (in Sage) apparently won't let me use the int function or the
> // operator on functions defined in terms of a variable: I get a "cannot
> evaluate symbolic expression numerically" TypeError. 

That's an issue with Sage itself, probably sympy. Python the language 
doesn't natively understand symbolic expressions, that's added by sympy, 
so you may need to ask some sympy experts.

It may help if you show the actual code you are using, and the full 
traceback generated by the error. When I try something similar, I get a 
different error message:

py> from sympy.abc import x
py> (x + 1) % 60
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for %: 'Add' and 'int'


which could mean I'm doing something different, or just a difference in 
version numbers.


> How do I do this?
> There must be a simple way to tell Python that I want it to compute the
> value of Longitude for a given value of t and then take the
> integer-and-fraction remainder from dividing by 360.

That's simple with numeric types: use the divmod function or % operator. 
But you're using some sort of symbolic library, so we need to know what 
the library is.


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


Re: Plotting the integer-and-fraction remainder of a function value modulo 360

2014-04-09 Thread Kim Plofker
Thanks, the % operator is indeed what I want, but I want to use it with a 
function expression rather than with numbers alone.  And that seems to create a 
type error.

Here's an example of what goes wrong:

t = var('t')

L(t) = t*725.5%360.0


This produces the following error message:

...
TypeError: unsupported operand type(s) for %:
'sage.symbolic.expression.Expression' and
'sage.symbolic.expression.Expression'

I can use other arithmetic operators such as + and / in this function 
expression, but not %, and I don't understand why.  Is it indeed a 
Sage-specific problem rather than something I could work around in Python?

Many thanks again for any help.

Kim



 From: Ben Finney 
To: python-list@python.org 
Sent: Thursday, April 10, 2014 12:54 AM
Subject: Re: Plotting the integer-and-fraction remainder of a function value 
modulo 360
 

Kim Plofker  writes:

> How can I get Python to represent a value of a function in degrees,
> i.e., with values between 0 and 360, by taking the (non-integer)
> function expression mod 360?

In Python, you simply use the modulo (‘%’) operator::

    >>> 45.0 % 360
    45.0
    >>> 700.0 % 360
    340.0
    >>> 

> That is, I have a function with non-integer values, called Longitude

If they're not integers, and you're not saying what they *are*, then I
can't know anything beyond “they will behave the way the Longitude class
defines them”.

> which is defined in terms of the variable t.

I don't understand what it means for a longitude value to be “defined in
terms of the variable t”.

Can you say more about how these values are defined? Since (as you say)
they're not integers, what *are* they?

> I just want to plot Longitude modulo 360 for a range of values of t:
> that is, for every value of t, plot the integer-AND-fraction remainder
> after dividing Longitude by 360.

What does it mean to “plot the integer-AND-fraction remainder”? It
sounds like you want to plot two numbers separately, the integer and the
fraction remainder. But that doesn't make much sense to me.

Do you mean simply that you want to plot numbers like ‘3.7’, ‘270.0’,
and ‘48.75’? In which case, this is supported by the native ‘float’
type, and (for better accuracy) by the ‘decimal.Decimal’ type from the
standard library::

    >>> lon = decimal.Decimal("758.45")
    >>> lon % 360
    Decimal('38.45')

> But Python (in Sage) apparently won't let me use the int function or
> the // operator on functions defined in terms of a variable: I get a
> "cannot evaluate symbolic expression numerically" TypeError.

It sounds like this Sage is not behaving as the standard Python types
do, with regard to the modulo ‘%’ operator.

For help with Sage (I don't know what that is), you probably will get
better answers on a Sage-specific discussion forum.

From the perspective of Python, the standard types handle the
requirements you describe without any TypeError.

-- 
\      “If you were going to shoot a mime, would you use a silencer?” |
  `\                                                    —Steven Wright |
_o__)                                                                  |
Ben Finney

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