Re: TypeError: can only concatenate str (not "int") to str

2023-02-27 Thread Thomas Passin

On 2/27/2023 2:15 PM, avi.e.gr...@gmail.com wrote:

Karsten,

There are limits to the disruption a group should tolerate even from people
who may need some leeway.

I wonder if Hen Hanna has any idea that some of the people he is saying this
to lost most of their family in the Holocaust and had parents who barely
survived passing through multiple concentration camps, I doubt he would
change his words or attitude in the slightest as some of his other gems
indicate a paranoid view of the world at best.


This whole paragraph is about a person with speculation on his views. 
Please let's deprecate writing about people this way :)




It is disproportionate to call everyone a Nazi at the slightest imagined
slight. But we are not here in this forum to discuss world affairs or
politics or how to replace python with the same language they have been
using and likely abusing. Like every resource, it is best used as intended
and that tends to mean not treating all the recipients as being willing to
receive every thought you have had since breakfast followed by demanding
everyone stop responding to him privately or in public or disagreeing in any
way.

I apologize for my part in even bothering to try to help him as it clearly
is a thankless task and a huge waste of andwidth.


Again, this paragraph is commentary and speculation about another 
poster. It's so easy to write things like this without even realizing 
we're doing it (I'm not immune).



-Original Message-
From: Python-list  On
Behalf Of Karsten Hilbert
Sent: Monday, February 27, 2023 6:32 AM
To: python-list@python.org
Subject: Re: TypeError: can only concatenate str (not "int") to str

Am Sun, Feb 26, 2023 at 08:56:28AM -0800 schrieb Hen Hanna:


so far,  i think  Paul Rubin's post (in another thread) was esp.
concise, informative, --- but he's also made a comment
about   'shunting'  beginners  (questions) to a
concentration camp, and sounded  a bit  like a cold-hearted (or
warm-hearted)  Nazi  officer / scientist.


Now, I have a lot of sympathy -- not least from a professional point of view
-- and see quite some leeway for people acting neuro-atypically, but the
last line of the above really isn't necessary to be read on this list.

Best,
Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
--
https://mail.python.org/mailman/listinfo/python-list



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


RE: TypeError: can only concatenate str (not "int") to str

2023-02-27 Thread avi.e.gross
Karsten,

There are limits to the disruption a group should tolerate even from people
who may need some leeway.

I wonder if Hen Hanna has any idea that some of the people he is saying this
to lost most of their family in the Holocaust and had parents who barely
survived passing through multiple concentration camps, I doubt he would
change his words or attitude in the slightest as some of his other gems
indicate a paranoid view of the world at best.

It is disproportionate to call everyone a Nazi at the slightest imagined
slight. But we are not here in this forum to discuss world affairs or
politics or how to replace python with the same language they have been
using and likely abusing. Like every resource, it is best used as intended
and that tends to mean not treating all the recipients as being willing to
receive every thought you have had since breakfast followed by demanding
everyone stop responding to him privately or in public or disagreeing in any
way.

I apologize for my part in even bothering to try to help him as it clearly
is a thankless task and a huge waste of andwidth.

-Original Message-
From: Python-list  On
Behalf Of Karsten Hilbert
Sent: Monday, February 27, 2023 6:32 AM
To: python-list@python.org
Subject: Re: TypeError: can only concatenate str (not "int") to str

Am Sun, Feb 26, 2023 at 08:56:28AM -0800 schrieb Hen Hanna:

> so far,  i think  Paul Rubin's post (in another thread) was esp. 
> concise, informative, --- but he's also made a comment
> about   'shunting'  beginners  (questions) to a
> concentration camp, and sounded  a bit  like a cold-hearted (or 
> warm-hearted)  Nazi  officer / scientist.

Now, I have a lot of sympathy -- not least from a professional point of view
-- and see quite some leeway for people acting neuro-atypically, but the
last line of the above really isn't necessary to be read on this list.

Best,
Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
--
https://mail.python.org/mailman/listinfo/python-list

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-27 Thread Karsten Hilbert
Am Sun, Feb 26, 2023 at 08:56:28AM -0800 schrieb Hen Hanna:

> so far,  i think  Paul Rubin's post (in another thread) was
> esp. concise, informative, --- but he's also made a comment
> about   'shunting'  beginners  (questions) to a
> concentration camp, and sounded  a bit  like a cold-hearted
> (or warm-hearted)  Nazi  officer / scientist.

Now, I have a lot of sympathy -- not least from a
professional point of view -- and see quite some leeway for
people acting neuro-atypically, but the last line of the
above really isn't necessary to be read on this list.

Best,
Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Thomas Passin

On 2/26/2023 8:40 PM, MRAB wrote:

On 2023-02-26 16:56, Hen Hanna wrote:


On Sunday, February 26, 2023 at 6:41:01 AM UTC-8, Thomas Passin wrote:
On 2/25/2023 8:12 PM, Hen Hanna wrote: > 2. the rude guy ('dn') 
hasn't offered a single word of comment that's directly relevant to 
it. > >  but he did offer related stuff which he   thinks i 
should be [grateful] for



Please let's stop the ad hominem messages. If someone doesn't like a 
particular person's messages, send them to spam or don't read them. 
If too many people start to get too rude or personal, remind the 
whole list of the guidelines for respectful participation. If you 
feel that someone's contribution was especially helpful in part 
because it was concise and to the point, you could say that.



yes.   let's stop...


If you  (Thomas Passin)   feel that  someone's contribution was 
especially helpful in part because it was

  concise and to the point, you could say that.
 and pls don't hesitate to reproduce such a 
comment.





i'm sure a few others were also rude, but  it was the rudest of them 
all ('dn')  that   told me to read some [Code of Conduct] document.   
 Do not EVER  do that  again.



Another rude guy who "asked"  me why i write in a Hard-to-read 
way  Why don't you at least   also make a comment that's  
On-Topic  besides  the insulting remark ?





so far,  i think  Paul Rubin's post (in another thread) was esp. 
concise, informative, --- but he's also made a comment about   
'shunting'  beginners  (questions) to a concentration camp, and 
sounded  a bit  like a cold-hearted (or warm-hearted)  Nazi  officer / 
scientist.



Oh dear. An example of Godwin's Law.


+1 Nicely put!

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Larry Martell
On Sun, Feb 26, 2023 at 5:46 PM Chris Angelico  wrote:

> On Mon, 27 Feb 2023 at 12:44, MRAB  wrote:
> > Oh dear. An example of Godwin's Law.
>
> Yeah, is that finally enough to get this user banned ?


I hope so

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Chris Angelico
On Mon, 27 Feb 2023 at 12:44, MRAB  wrote:
> Oh dear. An example of Godwin's Law.

Yeah, is that finally enough to get this user banned already?

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread MRAB

On 2023-02-26 16:56, Hen Hanna wrote:


On Sunday, February 26, 2023 at 6:41:01 AM UTC-8, Thomas Passin wrote:
On 2/25/2023 8:12 PM, Hen Hanna wrote: 
> 2. the rude guy ('dn') hasn't offered a single word of comment that's directly relevant to it. 
> >  but he did offer related stuff which he   thinks i should be [grateful] for



Please let's stop the ad hominem messages. If someone doesn't like a 
particular person's messages, send them to spam or don't read them. If 
too many people start to get too rude or personal, remind the whole list 
of the guidelines for respectful participation. If you feel that 
someone's contribution was especially helpful in part because it was 
concise and to the point, you could say that.



yes.   let's stop...


If you  (Thomas Passin)   feel that  someone's contribution was especially 
helpful in part because it was
  concise and to the point, you could say that.
 and pls don't hesitate to reproduce such a comment.




i'm sure a few others were also rude, but  it was the rudest of them all ('dn') 
 that   told me to read some [Code of Conduct] document.    Do not EVER 
 do that  again.


Another rude guy who "asked"  me why i write in a Hard-to-read way  Why 
don't you at least   also make a comment that's  On-Topic  besides  the insulting remark ?




so far,  i think  Paul Rubin's post (in another thread) was esp. concise, 
informative, --- but he's also made a comment about   'shunting'  beginners 
 (questions) to a concentration camp, and sounded  a bit  like a 
cold-hearted (or warm-hearted)  Nazi  officer / scientist.


Oh dear. An example of Godwin's Law.
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Hen Hanna

On Sunday, February 26, 2023 at 6:41:01 AM UTC-8, Thomas Passin wrote:
> On 2/25/2023 8:12 PM, Hen Hanna wrote: 
> > 2. the rude guy ('dn') hasn't offered a single word of comment that's 
> > directly relevant to it. 
> > >  but he did offer related stuff which he   thinks i should be 
> > > [grateful] for


> Please let's stop the ad hominem messages. If someone doesn't like a 
> particular person's messages, send them to spam or don't read them. If 
> too many people start to get too rude or personal, remind the whole list 
> of the guidelines for respectful participation. If you feel that 
> someone's contribution was especially helpful in part because it was 
> concise and to the point, you could say that.


yes.   let's stop...


If you  (Thomas Passin)   feel that  someone's contribution was especially 
helpful in part because it was 
 concise and to the point, you could say that.
and pls don't hesitate to reproduce such a comment.




i'm sure a few others were also rude, but  it was the rudest of them all ('dn') 
 that   told me to read some [Code of Conduct] document.    Do not EVER 
 do that  again.


Another rude guy who "asked"  me why i write in a Hard-to-read way  Why 
don't you at least   also make a comment that's  On-Topic  besides  the 
insulting remark ?




so far,  i think  Paul Rubin's post (in another thread) was esp. concise, 
informative, --- but he's also made a comment about   'shunting'  beginners 
 (questions) to a concentration camp, and sounded  a bit  like a 
cold-hearted (or warm-hearted)  Nazi  officer / scientist.


I think you can speed this up by building two sets and intersecting them:

from itertools import combinations

ww = "JSOYOMFUBELR SCDUARWDRLYE DASNAGEFERTY CLULOOTSCEHN USENEARSEYNE".split()
ss = set(''.join(s) for w in ww for s in combinations(w.lower(),6))
d6 = set(d.strip().lower() for d in open('/usr/share/dict/words') if len(d)==7)
print(ss & d6)


i too often use  short Var names   x, xx, w,ww,s,ss ..
   and also long ones.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread avi.e.gross
Alan,

Good tack. By not welcoming someone who is paranoid about being welcomed you
are clearly the right kind of welcoming!

Kidding aside, you have a point about one of the barrage of messages
probably not getting a great answer on your tutor forum. It is the MANY
messages often about fairly simple aspects of python, taken together, that
lead to the conclusion that this person is fairly new to python and still
thinking about things from a lifetime of experience using other languages.

I will say that at this point, it does not matter where they post as I
cannot imagine anyone having to pay them $1,000/hour for the privilege of
trying to tutor them.

There are topics raised that can be informative and lead to good discussions
amicably and as far as I can tell, many agree it would be nice if some
"error" messages provided more detail and perhaps some eventually will. But
as has been pointed out, these messages are only a small part of the python
environment and lots of other tools are typically used to debug that do
allow access to all kinds of details at breakpoints. 

I think many would be satisfied with some of the answers provided here and
note, FEW OR NONE OF US here (or am I wrong) are necessarily in a position
to make changes like this to the current or next versions of python. We are
all users who take what we get and work with it or look for a way around
things. The example used did not strike me as hard to figure out which of
X/Y was an int/str and what their values were. More time is wasted demanding
and debating a feature that is not there rather than solving the problem in
other ways.

In the interest of civility, I find removing myself sometimes works well. We
are volunteers and I don't need to volunteer to help any particular person
who does not seem to appreciate it. And if a forum fills up with nonsense so
the signal is hard to find amid the noise, why bother contributing?

Avi

-Original Message-
From: Python-list  On
Behalf Of Alan Gauld
Sent: Sunday, February 26, 2023 4:15 AM
To: python-list@python.org
Subject: Re: TypeError: can only concatenate str (not "int") to str

On 26/02/2023 00:54, Greg Ewing via Python-list wrote:
> On 26/02/23 10:53 am, Paul Rubin wrote:
>> I'm not on either list but the purpose of the tutor list is to shunt 
>> beginner questions away from the main list.

I'm not sure that's why we set it up but it is certainly a large part of our
remit. But protecting newbies from overly complex responses and covering
wider topics (beyond pure Pyhon) is also a large part of our purpose.

> There's a fundamental problem with tutor lists. They rely on 
> experienced people, the ones capable of answering the questions, to go 
> out of their way to read the tutor list -- something that is not of 
> personal benefit to them.

In practice, the "tutors" tend to be split between folks who inhabit both
lists and those who only interact on the tutor list. eg. I lurk here and
only occasionally partake.

But the problem with this particular thread is that, if directed to the
tutor list, the OP would simply be told that "that's the way Python works".
The tutor list is not for discussing language enhancements etc. It is purely
about answering questions on how to use the language (and standard library)
as it exists.
(We also cover beginner questions about programming in general.)

So this thread is most definitely in the right place IMHO.

--
Alan G
Tutor list moderator


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

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Thomas Passin

On 2/25/2023 8:12 PM, Hen Hanna wrote:

2. the rude guy ('dn') hasn't  offered  a single word of comment   that's 
directly relevant to it.
>    but he did  offer related stuff  which he 

thinks i should be  [grateful] for

Please let's stop the ad hominem messages. If someone doesn't like a 
particular person's messages, send them to spam or don't read them.  If 
too many people start to get too rude or personal, remind the whole list 
of the guidelines for respectful participation.  If you feel that 
someone's contribution was especially helpful in part because it was 
concise and to the point, you could say that.


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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Alan Gauld
On 26/02/2023 00:54, Greg Ewing via Python-list wrote:
> On 26/02/23 10:53 am, Paul Rubin wrote:
>> I'm not on either list but the purpose of the tutor list is to shunt
>> beginner questions away from the main list.

I'm not sure that's why we set it up but it is
certainly a large part of our remit. But protecting newbies
from overly complex responses and covering wider topics
(beyond pure Pyhon) is also a large part of our purpose.

> There's a fundamental problem with tutor lists. They rely on
> experienced people, the ones capable of answering the questions,
> to go out of their way to read the tutor list -- something that
> is not of personal benefit to them.

In practice, the "tutors" tend to be split between folks
who inhabit both lists and those who only interact on the tutor
list. eg. I lurk here and only occasionally partake.

But the problem with this particular thread is that, if directed
to the tutor list, the OP would simply be told that "that's the
way Python works". The tutor list is not for discussing
language enhancements etc. It is purely about answering questions
on how to use the language (and standard library) as it exists.
(We also cover beginner questions about programming in general.)

So this thread is most definitely in the right place IMHO.

-- 
Alan G
Tutor list moderator


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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-25 Thread Hen Hanna
On Saturday, February 25, 2023 at 1:54:14 PM UTC-8, Paul Rubinwrote:
> Hen Hanna  writes: 
> > is this guy (dn) always this rude??? is he even more rude on this 
> > Python-Tutor list ?

> I'm not on either list but the purpose of the tutor list is to shunt 
> beginner questions away from the main list. Yes your questions do seem 
> excessively frequent even here on Usenet. I have mostly been ignoring 
> them after seeing the first few.


not sure...  what you mean by "either" list

this rude guy ('dn'  who writes poorly) is someone i want to see posting less 
(and fewer),

and (from what i've seen) ,   Paul Rubin  is someone i wish to see posting more.

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-25 Thread Hen Hanna
On Saturday, February 25, 2023 at 4:54:36 PM UTC-8, Greg Ewing wrote:
> On 26/02/23 10:53 am, Paul Rubin wrote: 
> > I'm not on either list but the purpose of the tutor list is to shunt 
> >  beginner questions away from the main list.


> There's a fundamental problem with tutor lists. They rely on 
> experienced people, the ones capable of answering the questions, 
> to go out of their way to read the tutor list -- something that 
> is not of personal benefit to them. 
> 
> Also, pointing people towards tutor lists, if not done carefully, 
> can give the impression of saying "newcomers are not welcome here". 
> That's not a message we want to send to Python newcomers at all. 
> 
> -- 
> Greg



1.   i still think that  my original question  about   (not "int")   is  a good 
one.
  it may  seem like a  stupid  [beginner question] , 
but it really isn't.


2. the rude guy ('dn') hasn't  offered  a single word of comment   that's 
directly relevant to it.
     but he did  offer related stuff  which he thinks i 
should be  [grateful] for


3.   it's pretty clear  that  the rude guy ('dn')  intended-intends  to insult 
me as a Newbie... that much is certain.



___
 It'd be easy for the Error-Msg to include   the   VALUE   of the int.

A   LISP   programmer knows the value of everything,
  but the cost of nothing.



>>>   TypeError: can only join an iterable

  Here she's not even telling me the TYPE of the offending 
object.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can only concatenate str (not "int") to str

2023-02-25 Thread Hen Hanna

> PS are you aware that there is a Python-Tutor list for the use of people 
> learning Python?


is this guy (dn)  always this rude???is he even more rude  on this 
Python-Tutor list ?

he must have a reputation (for being rude)...  


On Friday, February 24, 2023 at 7:41:44 PM UTC-8, dn wrote:
> On 25/02/2023 09.36, Hen Hanna wrote: 
> > TypeError: can only concatenate str (not "int") to str 
> > 
> > thanks for the comments, --- esp. 2 or 3 (?) ppl who directly addressed it 
> > or commented on it.
> If you haven't already, please review the Python Software Foundation's 
> Code of Conduct https://www.python.org/psf/conduct/
> > py and pypy don't tell me what the (offending) int is 
> > 
> > (even tho' it'd be easy to show me the int, or number) 
> > 
> > because a Tuple, List... may produce a long output and they don't want to 
> > deal with ways of abbreviating it (with ... ) 
> > 
> > and because User-defined Class object may cause another error while 
> > printing it. 
> > 
> > 
> > 
> > _ 
> > TypeError: can only join an iterable 
> > 
> > Here too it'd help me if pypy (Jeannie) could tell me what the offending 
> > data object is.
> Observation: 
> - python doesn't tell you what you want 
> - correspondents are not telling you what you want and/or how you want 
> There's a common theme developing... 
> 
> Suggestion: if you want help, and at the frequency with which you've 
> been posting recently, would it be better not to sound like a 'troll'? 
> 
> 
> Please understand everyone here is volunteering time, in a bid to 
> provide you (and each-other) with benefit. 
> 
> Does the FACT that you have failed to answer several questions from 
> colleagues really entitle you to demand others only directly-address you 
> (and only your questions)? 
> 
> -- 
> Regards, 
> =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: TypeError: can only concatenate str (not "int") to str

2023-02-25 Thread avi.e.gross
Greg,

Yes, the forum should be open. The first requests from the person were
replied to politely.

At some point a pattern was emerging of lots of fairly irreverent posts by
someone who is having trouble shifting programming paradigms. The suggestion
was then made as a SUGGESTION by several people that "some" of their
questions might be better asked on the tutor list where others new to python
may have similar questions and can learn.

This forum has all kinds of people and of course many topics are of more
interest to some that others. Programming styles differ too and I note some
here reacted to a suggestion that maybe constants could be more efficiently
be initiated in ways that use less resources. Some insisted it makes more
sense to be able to type what you want more compactly. Yes, of course,
multiple ways are equally valid especially as now, efficiency is not seen as
a major goal.

The reality is that several mailing lists are intended to be used for
occasional questions and people who have more serious needs should be using
local resources or taking courses and reading books as their main learning
method. An occasional question is welcomed. A barrage is an position and a
barrage where most of the answers are ignored or claimed to be wrong, can
generate an "attitude" some of us find less than appealing.

I continue to believe that a programmers job is to learn how to use a
language well, or switch languages, and not to keep moaning why it does not
do what you want or expect. Many answers have suggested how the OP can solve
some issues and apparently that is not of interest to them and they just
keep complaining.

I speak for nobody except myself. As I have said, I have chosen to not
respond and become frustrated.


-Original Message-
From: Python-list  On
Behalf Of Greg Ewing via Python-list
Sent: Saturday, February 25, 2023 7:54 PM
To: python-list@python.org
Subject: Re: TypeError: can only concatenate str (not "int") to str

On 26/02/23 10:53 am, Paul Rubin wrote:
> I'm not on either list but the purpose of the tutor list is to shunt 
> beginner questions away from the main list.

There's a fundamental problem with tutor lists. They rely on experienced
people, the ones capable of answering the questions, to go out of their way
to read the tutor list -- something that is not of personal benefit to them.

Also, pointing people towards tutor lists, if not done carefully, can give
the impression of saying "newcomers are not welcome here".
That's not a message we want to send to Python newcomers at all.

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

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-25 Thread Greg Ewing via Python-list

On 26/02/23 10:53 am, Paul Rubin wrote:

I'm not on either list but the purpose of the tutor list is to shunt
beginner questions away from the main list.


There's a fundamental problem with tutor lists. They rely on
experienced people, the ones capable of answering the questions,
to go out of their way to read the tutor list -- something that
is not of personal benefit to them.

Also, pointing people towards tutor lists, if not done carefully,
can give the impression of saying "newcomers are not welcome here".
That's not a message we want to send to Python newcomers at all.

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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-24 Thread dn via Python-list

On 25/02/2023 09.36, Hen Hanna wrote:

  TypeError: can only concatenate str (not "int") to str

thanks for the comments,  ---   esp. 2 or 3 (?) ppl  who  directly addressed it 
or commented on it.


If you haven't already, please review the Python Software Foundation's 
Code of Conduct https://www.python.org/psf/conduct/




py   and pypy  don't tell me what the (offending)  int   is

(even tho'  it'd be easy to show me the int, or 
number)

because  a Tuple, List... may produce  a long output and they don't want to 
deal with ways of abbreviating  it   (with ... )

and because  User-defined  Class object may cause another error while printing 
it.



_
   TypeError: can only join an iterable

Here too it'd help me   if  pypy (Jeannie)  could tell me what the offending 
data object is.


Observation:
- python doesn't tell you what you want
- correspondents are not telling you what you want and/or how you want
There's a common theme developing...

Suggestion: if you want help, and at the frequency with which you've 
been posting recently, would it be better not to sound like a 'troll'?



Please understand everyone here is volunteering time, in a bid to 
provide you (and each-other) with benefit.


Does the FACT that you have failed to answer several questions from 
colleagues really entitle you to demand others only directly-address you 
(and only your questions)?


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


Re: TypeError: 'bytes' object is not callable error while trying to converting to bytes.

2021-12-04 Thread Wasia Maya
You have assigned a bytes value to the name bytes:

>>> bytes([10, 20, 30, 40])
b'\n\x14\x1e('
>>> bytes = bytes([10, 20, 30, 40])
>>> bytes([10, 20, 30, 40])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'bytes' object is not callable
bytes is now bound to the value b'\n\x14\x1e(', which is not callable. This 
global is shadowing the built-in. Delete it:

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


Re: TypeError: unhashable type: 'list'

2019-10-23 Thread David L Neil via Python-list

On 23/10/19 8:51 PM, joseph pareti wrote:

I am experimnenting with this (reproducer) code:
pattern_eur= ['Total amount']
mylines = []# Declare an empty list.
with open ('tmp0.txt', 'rt') as myfile: # Open tmp.txt for reading text.
 for myline in myfile:   # For each line in the file,
 mylines.append(myline.rstrip('\n')) # strip newline and add to list.
for element in mylines: # For each element in the list,
match_C = re.search(pattern_eur, element)
if match_C:
  element = element + 2
  print(element)
--
the input file being:
$ cat tmp0.txt
line 0
line 1
Total amount

5.00
linex

...

My intent is to locate the line containing "Total amount", skip the next
line, then print the eur value. The program terminates as follows:

...


Thanks for any insigths --



The first observation is that the two for loops are essentially 
identical, so why not condense?


However, what is described may be calling for a solution called "a 
finite state machine":


state 1: ignore unwanted data, until "Total amount" is found

state 2: skip blank line

state 3: grab the Euro value, and return to state 1


Being a simple-boy, I would avoid any reg-ex, because:

myline[ :11 ] == "Total amount"

is easier (and faster). Similarly, there is no need for rstrip-ping 
except at "state 3" (unless there are particular rules for the 
formatting of the total).



Another thought is that the problem is being visualised as a series of 
lines and this may complicate things. If instead, a "buffer" or indeed 
the entire file, could be read at a time (which is current code, per 
first comment above), the string.find() method could be employed 
(replacing "state 1"), and then (implicit assumption about spacing here) 
"state 2" becomes a matter of moving a few characters 'along', before 
grabbing the total; rinse and repeat...



Web-ref:
https://en.wikipedia.org/wiki/Finite-state_machine
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unhashable type: 'list'

2019-10-23 Thread DL Neil via Python-list

On 23/10/19 8:51 PM, joseph pareti wrote:

I am experimnenting with this (reproducer) code:
pattern_eur= ['Total amount']
mylines = []# Declare an empty list.
with open ('tmp0.txt', 'rt') as myfile: # Open tmp.txt for reading text.
 for myline in myfile:   # For each line in the file,
 mylines.append(myline.rstrip('\n')) # strip newline and add to list.
for element in mylines: # For each element in the list,
match_C = re.search(pattern_eur, element)
if match_C:
  element = element + 2
  print(element)
--
the input file being:
$ cat tmp0.txt
line 0
line 1
Total amount

5.00
linex

...

My intent is to locate the line containing "Total amount", skip the next
line, then print the eur value. The program terminates as follows:

...


Thanks for any insigths --



The first observation is that the two for loops are essentially 
identical, so why not condense?


However, what is described may be calling for a solution called "a 
finite state machine":


state 1: ignore unwanted data, until "Total amount" is found

state 2: skip blank line

state 3: grab the Euro value, and return to state 1


Being a simple-boy, I would avoid any reg-ex, because:

myline[ :11 ] == "Total amount"

is easier (and faster). Similarly, there is no need for rstrip-ping 
except at "state 3" (unless there are particular rules for the 
formatting of the total).



Another thought is that the problem is being visualised as a series of 
lines and this may complicate things. If instead, a "buffer" or indeed 
the entire file, could be read at a time (which is current code, per 
first comment above), the string.find() method could be employed 
(replacing "state 1"), and then (implicit assumption about spacing here) 
"state 2" becomes a matter of moving a few characters 'along', before 
grabbing the total; rinse and repeat...



Web-ref:
https://en.wikipedia.org/wiki/Finite-state_machine
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unhashable type: 'list'

2019-10-23 Thread Peter Otten
joseph pareti wrote:

> I am experimnenting with this (reproducer) code:
> pattern_eur= ['Total amount']

Make that 

pattern_eur = 'Total amount'

>match_C = re.search(pattern_eur, element)

The first argument to re.search() should be a string, not a list of strings:

>>> import re
>>> re.search("foo", "bar")
>>> re.search(["foo"], "bar")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.4/re.py", line 170, in search
return _compile(pattern, flags).search(string)
  File "/usr/lib/python3.4/re.py", line 282, in _compile
p, loc = _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'


> element = element + 2

This will be your next problem; you are adding 2 to a string.

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


Re: TypeError: unhashable type: 'list'

2019-10-23 Thread Joel Goldstick
On Wed, Oct 23, 2019 at 3:54 AM joseph pareti  wrote:
>
> I am experimnenting with this (reproducer) code:
> pattern_eur= ['Total amount']

the above line can't contain a list -- just a string

see help(re.search)

> mylines = []# Declare an empty list.
> with open ('tmp0.txt', 'rt') as myfile: # Open tmp.txt for reading text.
> for myline in myfile:   # For each line in the file,
> mylines.append(myline.rstrip('\n')) # strip newline and add to list.
> for element in mylines: # For each element in the list,
>match_C = re.search(pattern_eur, element)
>if match_C:
>  element = element + 2
>  print(element)
> --
> the input file being:
> $ cat tmp0.txt
> line 0
> line 1
> Total amount
>
> 5.00
> linex
> line z
> line c
> Total amount
>
> 43598
> line
> line m
>
> Total amount
>
> 32000
> line end -1
> line end 0
> line end 1
> line end 2
>
> --
>
> My intent is to locate the line containing "Total amount", skip the next
> line, then print the eur value. The program terminates as follows:
> Traceback (most recent call last):
>   File "search_then_advance.py", line 8, in 
> match_C = re.search(pattern_eur, element)
>   File
> "c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\lib\re.py",
> line 183, in search
> return _compile(pattern, flags).search(string)
>   File
> "c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\lib\re.py",
> line 276, in _compile
> return _cache[type(pattern), pattern, flags]
> TypeError: unhashable type: 'list'
>
> Thanks for any insigths --
> --
> Regards,
> Joseph Pareti - Artificial Intelligence consultant
> Joseph Pareti's AI Consulting Services
> https://www.joepareti54-ai.com/
> cell +49 1520 1600 209
> cell +39 339 797 0644
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

2019-09-03 Thread MRAB

On 2019-09-03 17:29, Terry Reedy wrote:

On 9/3/2019 12:02 PM, alberto wrote:

Hi,
I produce a script to elaborate data

but command line $ python3.4 PlotnhvsvdBTP1.py

I have this error

Traceback (most recent call last):
File "PlotnhvsvdBTP1.py", line 31, in 
UCvol = np.loadtxt(outputtransfile,skiprows=26,max_rows=1,usecols=[1])
TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

How could fix it?


Don't do what the message says is the wrong thing to do.  Really.

In particular, don't pass 'max_rows=1'.  To find out what *to* do, read
the doc for the loadtxt function.  From 'skiprows' and 'usecols', with
no underscore, I suspect you should pass 'maxrows=1'.


No, the documentation says "max_rows".

Apparently, consistency, like the argument, is optional. :-)
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

2019-09-03 Thread MRAB

On 2019-09-03 17:02, alberto wrote:

Hi,
I produce a script to elaborate data

but command line $ python3.4 PlotnhvsvdBTP1.py

I have this error

Traceback (most recent call last):
File "PlotnhvsvdBTP1.py", line 31, in 
UCvol = np.loadtxt(outputtransfile,skiprows=26,max_rows=1,usecols=[1])
TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

How could fix it?

I attacched my files

https://drive.google.com/file/d/1PgOcuEMFsaAuKTsbU0i0gwg04mDCJJoK/view?usp=sharing
https://drive.google.com/file/d/13E7vcGQtrOS1lw9RupGThGQ2vSGRfTFG/view?usp=sharing
https://drive.google.com/file/d/1Z6GKYtHthAyPO3wFHUFK10QweRpclu29/view?usp=sharing


The "max_rows" keyword argument is new in numpy version 1.16.0.

Which version do you have?

Try:

import numpy
print(numpy.__version__)
to find out.
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

2019-09-03 Thread Terry Reedy

On 9/3/2019 12:02 PM, alberto wrote:

Hi,
I produce a script to elaborate data

but command line $ python3.4 PlotnhvsvdBTP1.py

I have this error

Traceback (most recent call last):
File "PlotnhvsvdBTP1.py", line 31, in 
UCvol = np.loadtxt(outputtransfile,skiprows=26,max_rows=1,usecols=[1])
TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

How could fix it?


Don't do what the message says is the wrong thing to do.  Really.

In particular, don't pass 'max_rows=1'.  To find out what *to* do, read 
the doc for the loadtxt function.  From 'skiprows' and 'usecols', with 
no underscore, I suspect you should pass 'maxrows=1'.


--
Terry Jan Reedy

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


Re: TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

2019-09-03 Thread Rhodri James

On 03/09/2019 17:02, alberto wrote:

I have this error

Traceback (most recent call last):
File "PlotnhvsvdBTP1.py", line 31, in 
UCvol = np.loadtxt(outputtransfile,skiprows=26,max_rows=1,usecols=[1])
TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

How could fix it?


A quick google search suggests that you aren't using a recent enough 
version of numpy.  The "max_rows" keyword argument was added to 
loadtxt() in version 1.16.0; you must be using an older version than 
that.  Your options are to upgrade the version of numpy you have (don't 
ask me how, I've never used it) or delete the "max_rows=1" and accept 
the inefficiency.


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: loadtxt() got an unexpected keyword argument 'max_rows'

2019-09-03 Thread Joel Goldstick
On Tue, Sep 3, 2019 at 12:06 PM alberto  wrote:
>
> Hi,
> I produce a script to elaborate data
>
> but command line $ python3.4 PlotnhvsvdBTP1.py
>
> I have this error
>
> Traceback (most recent call last):
> File "PlotnhvsvdBTP1.py", line 31, in 
> UCvol = np.loadtxt(outputtransfile,skiprows=26,max_rows=1,usecols=[1])
> TypeError: loadtxt() got an unexpected keyword argument 'max_rows'
>
> How could fix it?
>
> I attacched my files
>
> https://drive.google.com/file/d/1PgOcuEMFsaAuKTsbU0i0gwg04mDCJJoK/view?usp=sharing
> https://drive.google.com/file/d/13E7vcGQtrOS1lw9RupGThGQ2vSGRfTFG/view?usp=sharing
> https://drive.google.com/file/d/1Z6GKYtHthAyPO3wFHUFK10QweRpclu29/view?usp=sharing
>
> regard
>
> Alberto

Please don't attach files.  Cut and paste code as text into email body
along with copy and pasted traceback.

That said I found this:.. versionadded:: 1.14.0
max_rows : int, optional

Check your version of loadtxt()?
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: expected string or Unicode object, NoneType found

2018-05-19 Thread Terry Reedy

On 5/19/2018 12:47 PM, Peter Otten wrote:

subhabangal...@gmail.com wrote:


I wrote a small piece of following code

import nltk
from nltk.corpus.reader import TaggedCorpusReader
from nltk.tag import CRFTagger


To implement Peter's suggestion:


def NE_TAGGER():


def tagger(stop):


 reader = TaggedCorpusReader('/python27/', r'.*\.pos')
 f1=reader.fileids()
 print "The Files of Corpus are:",f1
 sents=reader.tagged_sents()
 ls=len(sents)
 print "Length of Corpus Is:",ls
 train_data=sents[:300]
 test_data=sents[301:350]


Offtopic: not that sents[300] is neither in the training nor in the test
data; Python uses half-open intervals.


  train_data=sents[:stop]
  test_data=sents[stop:max+50]


 ct = CRFTagger()
 crf_tagger=ct.train(train_data,'model.crf.tagger')

This code is working fine.
Now if I change the data size to say 500 or 3000 in  train_data by giving
train_data=sents[:500] or
  train_data=sents[:3000] it is giving me the following error.


What about sents[:499], sents[:498], ...?


Do a rough binary search for the first stop value that raises.

tagger(400)
tagger(350 or 450, depending)
...

You could automate with bisect module, but bisection by eye should be 
faster.



I'm not an nltk user, but to debug the problem I suggest that you identify
the exact index that triggers the exception, and then print it

print sents[minimal_index_that_causes_typeerror]

Perhaps you can spot a problem with the input data.
  
(In the spirit of the "offtopic" remark: if sents[:333] triggers the failure

you have to print sents[332])


Or mentally subtract 1 from minimal failing stop value.




Traceback (most recent call last):
   File "", line 1, in 
 NE_TAGGER()
   File "C:\Python27\HindiCRFNERTagger1.py", line 20, in NE_TAGGER
 crf_tagger=ct.train(train_data,'model.crf.tagger')
   File "C:\Python27\lib\site-packages\nltk\tag\crf.py", line 185, in train
 trainer.append(features,labels)
   File "pycrfsuite\_pycrfsuite.pyx", line 312, in
   pycrfsuite._pycrfsuite.BaseTrainer.append
   (pycrfsuite/_pycrfsuite.cpp:3800) File "stringsource", line 53, in
   vector.from_py.__pyx_convert_vector_from_py_std_3a__3a_string
   (pycrfsuite/_pycrfsuite.cpp:10738) File "stringsource", line 15, in
   string.from_py.__pyx_convert_string_from_py_std__in_string
   (pycrfsuite/_pycrfsuite.cpp:10633)
TypeError: expected string or Unicode object, NoneType found




I have searched for solutions in web found the following links as,
https://stackoverflow.com/questions/14219038/python-multiprocessing-typeerror-expected-string-or-unicode-object-nonetype-f
or
https://github.com/kamakazikamikaze/easysnmp/issues/50

reloaded Python but did not find much help.

I am using Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC
v.1500 32 bit (Intel)] on win32

My O/S is, MS-Windows 7.

If any body may kindly suggest a resolution.






--
Terry Jan Reedy

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


Re: TypeError: expected string or Unicode object, NoneType found

2018-05-19 Thread Peter Otten
subhabangal...@gmail.com wrote:

> I wrote a small piece of following code
> 
> import nltk
> from nltk.corpus.reader import TaggedCorpusReader
> from nltk.tag import CRFTagger
> def NE_TAGGER():
> reader = TaggedCorpusReader('/python27/', r'.*\.pos')
> f1=reader.fileids()
> print "The Files of Corpus are:",f1
> sents=reader.tagged_sents()
> ls=len(sents)
> print "Length of Corpus Is:",ls
> train_data=sents[:300]
> test_data=sents[301:350]

Offtopic: not that sents[300] is neither in the training nor in the test 
data; Python uses half-open intervals.

> ct = CRFTagger()
> crf_tagger=ct.train(train_data,'model.crf.tagger')
> 
> This code is working fine.
> Now if I change the data size to say 500 or 3000 in  train_data by giving 
> train_data=sents[:500] or
>  train_data=sents[:3000] it is giving me the following error.

What about sents[:499], sents[:498], ...? 

I'm not an nltk user, but to debug the problem I suggest that you identify 
the exact index that triggers the exception, and then print it

print sents[minimal_index_that_causes_typeerror]

Perhaps you can spot a problem with the input data.
 
(In the spirit of the "offtopic" remark: if sents[:333] triggers the failure 
you have to print sents[332])


> Traceback (most recent call last):
>   File "", line 1, in 
> NE_TAGGER()
>   File "C:\Python27\HindiCRFNERTagger1.py", line 20, in NE_TAGGER
> crf_tagger=ct.train(train_data,'model.crf.tagger')
>   File "C:\Python27\lib\site-packages\nltk\tag\crf.py", line 185, in train
> trainer.append(features,labels)
>   File "pycrfsuite\_pycrfsuite.pyx", line 312, in
>   pycrfsuite._pycrfsuite.BaseTrainer.append
>   (pycrfsuite/_pycrfsuite.cpp:3800) File "stringsource", line 53, in
>   vector.from_py.__pyx_convert_vector_from_py_std_3a__3a_string
>   (pycrfsuite/_pycrfsuite.cpp:10738) File "stringsource", line 15, in
>   string.from_py.__pyx_convert_string_from_py_std__in_string
>   (pycrfsuite/_pycrfsuite.cpp:10633)
> TypeError: expected string or Unicode object, NoneType found
 
> 
> I have searched for solutions in web found the following links as,
> https://stackoverflow.com/questions/14219038/python-multiprocessing-typeerror-expected-string-or-unicode-object-nonetype-f
> or
> https://github.com/kamakazikamikaze/easysnmp/issues/50
> 
> reloaded Python but did not find much help.
> 
> I am using Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:22:17) [MSC
> v.1500 32 bit (Intel)] on win32
> 
> My O/S is, MS-Windows 7.
> 
> If any body may kindly suggest a resolution.


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


Re: TypeError with map with no len()

2017-09-26 Thread john polo

On 9/25/2017 5:37 PM, Thomas Jollans wrote:

On 25/09/17 18:44, john polo wrote:

Python List,

I am trying to make practice data for plotting purposes. I am using
Python 3.6. The instructions I have are

import matplotlib.pyplot as plt
import math
import numpy as np
t = np.arange(0, 2.5, 0.1)
y1 = map(math.sin, math.pi*t)

If you use np.sin instead of math.sin, you don't have to use map: Most
numpy functions operate elementwise on arrays (for example, you're
multiplying math.pi with an array - something that wouldn't work with a
list).

Here's the numpy way of doing this:

t = np.arange(0, 2.5, 0.1)
y1 = np.sin(np.pi * t)

Without using numpy at all, this might be

t = [i * 0.1 for i in range(25)]
y1 = [math.pi * a for a in t]

The numpy way looks like a great alternative. Thank you, Thomas.

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


Re: TypeError with map with no len()

2017-09-25 Thread Thomas Jollans
On 25/09/17 18:44, john polo wrote:
> Python List,
>
> I am trying to make practice data for plotting purposes. I am using
> Python 3.6. The instructions I have are
>
> import matplotlib.pyplot as plt
> import math
> import numpy as np
> t = np.arange(0, 2.5, 0.1)
> y1 = map(math.sin, math.pi*t)

If you use np.sin instead of math.sin, you don't have to use map: Most
numpy functions operate elementwise on arrays (for example, you're
multiplying math.pi with an array - something that wouldn't work with a
list).

Here's the numpy way of doing this:

t = np.arange(0, 2.5, 0.1)
y1 = np.sin(np.pi * t)

Without using numpy at all, this might be

t = [i * 0.1 for i in range(25)]
y1 = [math.pi * a for a in t]

> plt.plot(t,y1)
>
> However, at this point, I get a TypeError that says
>
> object of type 'map' has no len()
>
> In [6]: t
> Out[6]:
> array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9,  1. ,
> 1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. ,  2.1,
> 2.2,  2.3,  2.4])
> In [7]: y1
> Out[7]: 
> In [8]: math.pi*t
> Out[8]:
> array([ 0.,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
> 1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
> 3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
> 4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
> 6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])
>
> At the start of creating y1, it appears there is an array to iterate
> through for the math.sin function used in map(), but y1 doesn't appear
> to be saving any values. I expected y1 to hold a math.sin() output for
> each item in math.pi*t, but it appears to be empty. Am I
> misunderstanding map()? Is there something else I should be doing
> instead to populate y1?
>
>
> John
>

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


Re: TypeError with map with no len()

2017-09-25 Thread john polo

On 9/25/2017 12:03 PM, Paul Moore wrote:

You're using Python 3, and I suspect that you're working from
instructions that assume Python 2. In Python 3, the result of map() is
a generator, not a list (which is what Python 2's map returned). In
order to get an actual list (which appears to be what you need for
your plot call) you just need to call the list constructor:

y1 = list(map(math.sin, math.pi*t))

Although given that you're using numpy, it may be that there's a more
idiomatic numpy way of doing this. I'm not a numpy expert though, so I
can't help on that.

Paul

Paul,
Thank you very much for the explanation.

best regards,
John
--
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError with map with no len()

2017-09-25 Thread Paul Moore
You're using Python 3, and I suspect that you're working from
instructions that assume Python 2. In Python 3, the result of map() is
a generator, not a list (which is what Python 2's map returned). In
order to get an actual list (which appears to be what you need for
your plot call) you just need to call the list constructor:

y1 = list(map(math.sin, math.pi*t))

Although given that you're using numpy, it may be that there's a more
idiomatic numpy way of doing this. I'm not a numpy expert though, so I
can't help on that.

Paul

On 25 September 2017 at 17:44, john polo  wrote:
> Python List,
>
> I am trying to make practice data for plotting purposes. I am using Python
> 3.6. The instructions I have are
>
> import matplotlib.pyplot as plt
> import math
> import numpy as np
> t = np.arange(0, 2.5, 0.1)
> y1 = map(math.sin, math.pi*t)
> plt.plot(t,y1)
>
> However, at this point, I get a TypeError that says
>
> object of type 'map' has no len()
>
> In [6]: t
> Out[6]:
> array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9,  1. ,
> 1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. ,  2.1,
> 2.2,  2.3,  2.4])
> In [7]: y1
> Out[7]: 
> In [8]: math.pi*t
> Out[8]:
> array([ 0.,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
> 1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
> 3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
> 4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
> 6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])
>
> At the start of creating y1, it appears there is an array to iterate through
> for the math.sin function used in map(), but y1 doesn't appear to be saving
> any values. I expected y1 to hold a math.sin() output for each item in
> math.pi*t, but it appears to be empty. Am I misunderstanding map()? Is there
> something else I should be doing instead to populate y1?
>
>
> John
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError with map with no len()

2017-09-25 Thread Grant Edwards
On 2017-09-25, john polo  wrote:
> Python List,
>
> I am trying to make practice data for plotting purposes. I am using 
> Python 3.6. The instructions I have are
>
> import matplotlib.pyplot as plt
> import math
> import numpy as np
> t = np.arange(0, 2.5, 0.1)
> y1 = map(math.sin, math.pi*t)
> plt.plot(t,y1)
>
> However, at this point, I get a TypeError that says
>
> object of type 'map' has no len()

you probably need to convert y1 from a 'map' object (a type of an
iterator) to an array.

y1 = map(math.sin, math.pi*t)
y1 = np.fromiter(y1, float)

-- 
Grant Edwards   grant.b.edwardsYow! Will this never-ending
  at   series of PLEASURABLE
  gmail.comEVENTS never cease?

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


Re: TypeError with map with no len()

2017-09-25 Thread Peter Otten
john polo wrote:

> Python List,
> 
> I am trying to make practice data for plotting purposes. I am using
> Python 3.6. The instructions I have are
> 
> import matplotlib.pyplot as plt
> import math
> import numpy as np
> t = np.arange(0, 2.5, 0.1)
> y1 = map(math.sin, math.pi*t)
> plt.plot(t,y1)
> 
> However, at this point, I get a TypeError that says
> 
> object of type 'map' has no len()
> 
> In [6]: t
> Out[6]:
> array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9,  1. ,
>  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. ,  2.1,
>  2.2,  2.3,  2.4])
> In [7]: y1
> Out[7]: 
> In [8]: math.pi*t
> Out[8]:
> array([ 0.,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
>  1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
>  3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
>  4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
>  6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])
> 
> At the start of creating y1, it appears there is an array to iterate
> through for the math.sin function used in map(), but y1 doesn't appear
> to be saving any values. I expected y1 to hold a math.sin() output for
> each item in math.pi*t, but it appears to be empty. Am I
> misunderstanding map()? Is there something else I should be doing
> instead to populate y1?

map() is "lazy" in Python 3, i. e. it calculates the values when you iterate 
over it, not before:

>>> def noisy_square(x):
... print("calculating {0} * {0}".format(x))
... return x * x
... 
>>> squares = map(noisy_square, [1, 3, 2])
>>> for y in squares:
... print(y)
... 
calculating 1 * 1
1
calculating 3 * 3
9
calculating 2 * 2
4

While you can convert y1 to a list with

y1 = list(y1)

the better approach is to use numpy:

y1 = np.sin(t * math.pi)

Now y1 is a numpy.array and can be fed to pyplot.plot() directly.

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


Re: TypeError with map with no len()

2017-09-25 Thread Ned Batchelder

On 9/25/17 12:44 PM, john polo wrote:

Python List,

I am trying to make practice data for plotting purposes. I am using 
Python 3.6. The instructions I have are


import matplotlib.pyplot as plt
import math
import numpy as np
t = np.arange(0, 2.5, 0.1)
y1 = map(math.sin, math.pi*t)
plt.plot(t,y1)

However, at this point, I get a TypeError that says

object of type 'map' has no len()

In [6]: t
Out[6]:
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9, 1. ,
    1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. , 2.1,
    2.2,  2.3,  2.4])
In [7]: y1
Out[7]: 
In [8]: math.pi*t
Out[8]:
array([ 0.    ,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
    1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
    3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
    4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
    6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])

At the start of creating y1, it appears there is an array to iterate 
through for the math.sin function used in map(), but y1 doesn't appear 
to be saving any values. I expected y1 to hold a math.sin() output for 
each item in math.pi*t, but it appears to be empty. Am I 
misunderstanding map()? Is there something else I should be doing 
instead to populate y1?


In Python 2, map() produced a list. In Python 3, it returns a lazy 
iterator instead.  You can run the iterator with list():


    y1 = list(map(math.sin, math.pi*t))

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


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-30 Thread dieter
Terry Reedy  writes:
> ...
>> The problem seems to come from my expectation that a file
>> is its own iterator and in python3 that is no longer true
>> for a NamedTemporaryFile.
> ...
>> Should this be considered a bug?
>
> No.  The doc for NamedTemporaryFile does not even claim that the
> return is iterable.

I think, it should: the name suggests that "NamedTemporaryFile" is
a "File" and therefore should behave like one.

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


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-29 Thread eryk sun
On Fri, Jul 29, 2016 at 7:34 PM, Terry Reedy  wrote:
> On 7/29/2016 7:59 AM, eryk sun wrote:
>>
>> On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
>>  wrote:
>>>
>>> The problem seems to come from my expectation that a file
>>> is its own iterator and in python3 that is no longer true
>>> for a NamedTemporaryFile.
>>
>> For some reason it uses a generator function for __iter__
>
> This is a common idiom for having iterable.__iter__ return an iterator
> without writing and instanciating an iterator class.

Yes, using a generator function is a simple way to create multiple
iterators of an iterable, which is especially useful for a sequence
that's independently reiterable. However a Python io file is its own
iterator because it's based on a synchronous operating system File
that maintains a file pointer. (Python io files don't support Windows
asynchronous file access, which doesn't update the File pointer, and
even the low-level _winapi and _overlapped implementations don't
support this.)

In this case there's no point that I can see in using a generator
function for __iter__. If you call iter() again on the
tempfile._TemporaryFileWrapper, it doesn't produce a new iteration of
the underlying file until seek(0) is called to reset the file pointer.
So __iter__ may as well  return `self` and have __next__ proxy
next(self.file).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-29 Thread Terry Reedy

On 7/29/2016 7:59 AM, eryk sun wrote:

On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
 wrote:


The problem seems to come from my expectation that a file
is its own iterator and in python3 that is no longer true
for a NamedTemporaryFile.


For some reason it uses a generator function for __iter__


This is a common idiom for having iterable.__iter__ return an iterator 
without writing and instanciating an iterator class.



instead of

> returning self, which would allow it to proxy the wrapped file's

__next__ method. There may be a good reason for that design decision,
but at the moment I don't see it,


For statements, usually the preferred way to iterator through an 
iterable, always call iter() on the iterable, before calling next on the 
result.  Collections are generally written as iterables.  If one is 
going to explicitly call next, then one should also call iter explicity.



so I'd simply try the following:


Not nearly as simple as either calling iter() or using a simple for loop 
with a one-line body.  (See response to Antoon.)


[snip complex solution]

--
Terry Jan Reedy

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


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-29 Thread Terry Reedy

On 7/29/2016 4:43 AM, Antoon Pardon wrote:

Below is a short program that illustrate the problem
It works with python2, whether you use the -c option or not.
It only works with python3 if you use the -c option.

The problem seems to come from my expectation that a file
is its own iterator and in python3 that is no longer true
for a NamedTemporaryFile.


As Eryk Sun said, a _TemporaryFileWrapper is an iterable, but not an 
iterator.



Should this be considered a bug?


No.  The doc for NamedTemporaryFile does not even claim that the return 
is iterable.



=

from tempfile import NamedTemporaryFile
import sys

def main(tmp):
write = sys.stdout.write
if tmp:
tstfl = NamedTemporaryFile("w+", prefix = 'tmptest-')
else:
tstfl = open("Temporary", "w+")

for nr in range(10):
tstfl.write("This is line %d\n" % nr)

tstfl.seek(0)


Either add "tstfl_it = iter(tstfl)" and call next on what is now 
guaranteed to be an iterator, if one is possible.




try:
while True:
ln = next(tstfl)
write(ln)
except StopIteration:
pass


Or replace the above with the much easier to write and more idiomatic

for line in tstfl:
write(line)


if __name__ == "__main__":
tmp = True
if len(sys.argv) > 1:
# if -c option is passed a normal file will be
# used instead of a NamedTemporaryFile
if sys.argv[1] == '-c':
tmp = False
main(tmp)




--
Terry Jan Reedy

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


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-29 Thread eryk sun
On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
 wrote:
>
> The problem seems to come from my expectation that a file
> is its own iterator and in python3 that is no longer true
> for a NamedTemporaryFile.

For some reason it uses a generator function for __iter__ instead of
returning self, which would allow it to proxy the wrapped file's
__next__ method. There may be a good reason for that design decision,
but at the moment I don't see it, so I'd simply try the following:

import tempfile
import functools

class _TemporaryFileWrapper(tempfile._TemporaryFileWrapper):
def __iter__(self):
return self
def __next__(self):
return next(self.file)

@functools.wraps(tempfile.NamedTemporaryFile, assigned=['__doc__'])
def NamedTemporaryFile(*args, **kwds):
f = tempfile.NamedTemporaryFile(*args, **kwds)
f.__class__ = _TemporaryFileWrapper
return f

if __name__ == '__main__':
with NamedTemporaryFile('w+', prefix='tmptest-') as f:
for n in range(10):
f.write('This is line %d.\n' % n)
f.seek(0)
try:
while True:
print(next(f), end='')
except StopIteration:
pass
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: '_TemporaryFileWrapper' object is not an iterator

2016-07-29 Thread Antoon Pardon
Below is a short program that illustrate the problem
It works with python2, whether you use the -c option or not.
It only works with python3 if you use the -c option.

The problem seems to come from my expectation that a file
is its own iterator and in python3 that is no longer true
for a NamedTemporaryFile.

Should this be considered a bug?
 
=

from tempfile import NamedTemporaryFile
import sys

def main(tmp):
write = sys.stdout.write
if tmp:
tstfl = NamedTemporaryFile("w+", prefix = 'tmptest-')
else:
tstfl = open("Temporary", "w+")

for nr in range(10):
tstfl.write("This is line %d\n" % nr)

tstfl.seek(0)
try:
while True:
ln = next(tstfl)
write(ln)
except StopIteration:
pass

if __name__ == "__main__":
tmp = True
if len(sys.argv) > 1:
# if -c option is passed a normal file will be
# used instead of a NamedTemporaryFile
if sys.argv[1] == '-c':
tmp = False 
main(tmp)

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


Re: TypeError: unorderable types: function() < int()

2016-05-10 Thread Steven D'Aprano
On Tue, 10 May 2016 11:47 pm, Chris Angelico wrote:

> On Tue, May 10, 2016 at 11:40 PM, Steven D'Aprano 
> wrote:
>> You are asking the player to hit enter at 10 seconds. *Exactly* ten
>> seconds. The computer can measure time to well under a millionth of a
>> second, I'm pretty sure that nobody, no matter how skillful, can be
>> expected to hit enter after exactly 10.00 seconds, not 10.01 or
>> 9.99 seconds.
>>
> 
> But the times were being calculated at one-second resolution, which
> solves that but raises its own issues.

Ah, I didn't realise that time.strftime("%S") was one-second resolution
(obvious in hindsight, duh!) and the call to time.time() is apparently
unused.



-- 
Steven

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


Re: TypeError: unorderable types: function() < int()

2016-05-10 Thread Chris Angelico
On Tue, May 10, 2016 at 11:40 PM, Steven D'Aprano  wrote:
> You are asking the player to hit enter at 10 seconds. *Exactly* ten seconds.
> The computer can measure time to well under a millionth of a second, I'm
> pretty sure that nobody, no matter how skillful, can be expected to hit
> enter after exactly 10.00 seconds, not 10.01 or 9.99 seconds.
>

But the times were being calculated at one-second resolution, which
solves that but raises its own issues.

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


Re: TypeError: unorderable types: function() < int()

2016-05-10 Thread Steven D'Aprano
Hello George, and welcome!


On Tue, 10 May 2016 07:01 pm, George Molsom wrote:

> I have created a program in class 'make a game that tests how good people
> are at guessing when 10 seconds has elapsed.'
> 
> The following are the code I currently have and the error produced when I
> attempt to run it. I have tried everything I can think of to resolve the
> issue, and I have also run the code through a checker, which has said that
> there are no mistakes. I have also shown a friend who is a programmer, and
> he cannot find a problem with it. The teacher doesn't actually know the
> solution to the problem so I was wondering if someone could point me in
> the right direction to get this working please?

Neither your friend who is a programmer nor the teacher can read an error
message?

> TypeError: unorderable types: function() < int()

In fairness, it is a bit of a rubbish error message. But what is it saying
it that you are trying to check whether a function is less than a number.
You are not comparing the *result* of calling the function with the number,
but the function itself.

For example, suppose we have a function that (to keep it simple) always
returns 3.

def func():
return 3

Now you go to check whether it is less than some other number:

if func() < 9:
print("smaller")


That's what you *meant* to do, but unfortunately you left off the round
brackets (parentheses), which means that instead of calling the function
and then comparing the result of that with 9, you compare the FUNCTION
itself with 9. 

if func < 9: ...

Obviously this is nonsense. You can't compare functions with integers, the
question is ludicrous. So Python rightly complains with an error message.

The immediate fix is to add the brackets in so that you call the function
first to get a result, and then compare the result with the number.


Another comment about your game:

You are asking the player to hit enter at 10 seconds. *Exactly* ten seconds.
The computer can measure time to well under a millionth of a second, I'm
pretty sure that nobody, no matter how skillful, can be expected to hit
enter after exactly 10.00 seconds, not 10.01 or 9.99 seconds.

I think it is reasonable to give them a little bit of slack to be above or
under 10 seconds by a fraction of a second. So you should round the time to
one decimal place:

totaltime = round(totaltime, 1)

before checking whether it is equal to 10.



-- 
Steven

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


Re: TypeError: unorderable types: function() < int()

2016-05-10 Thread Chris Angelico
On Tue, May 10, 2016 at 10:19 PM, Dennis Lee Bieber
 wrote:
> You invoke strftime() [in default: use current time mode], but pass it
> a format that is not defined in the documentation (or wasn't in Python 2.7
> which I'm still running).   #2
>  %s (lowercase) formats the seconds field of the time of day. And worst,
> since you don't return the result, it just gets thrown away.#3
>

Sorry to nitpick, but this isn't the case. time.strftime("%S") is what
you're talking about (getting the "seconds since beginning of current
minute"). There is a "%s" format string, but it's not supported on all
platforms; it actually would be more useful here, as it represents the
time as seconds since 1970 (aka "Unix time").

Of course, time.time() would still be far more useful here, as you
subsequently recommended.

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


Re: TypeError: unorderable types: function() < int()

2016-05-10 Thread Ben Finney
George Molsom  writes:

> I have created a program in class 'make a game that tests how good
> people are at guessing when 10 seconds has elapsed.'

Welcome! You may want to join the dedicated beginners forum
 where we
collaboratively teach foundational Python concepts.

> Traceback (most recent call last):
>   File "E:/Computing/Python/Little book of challenges/Challenge 6 10 seconds 
> experiment.py", line 20, in 
> if totaltime < 10:
> TypeError: unorderable types: function() < int()

That's right. The ‘totaltime’ name refers to a function. To ask whether
an integer object is less than a function object is not a meaningful
comparison.

If you want to *call* the function, use the “call this function”
syntax::

totaltime()

That will evaluate to the return value when you call it, so use the
return value::

if totaltime() < 10:
# …

-- 
 \  “There's a certain part of the contented majority who love |
  `\anybody who is worth a billion dollars.” —John Kenneth |
_o__)Galbraith, 1992-05-23 |
Ben Finney

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


Re: TypeError: not all arguments converted during string formatting

2016-02-18 Thread Ganesh Pal
On Wed, Feb 17, 2016 at 7:32 PM, Chris Angelico  wrote:

> The print statement/function happily accepts multiple arguments, and
> will join them according to a set of predefined rules. The logging
> functions don't have those rules, so they take one message and some
> optional parameters. Try this, instead:
>
> logging.info("%r %r %r", out, err, ret)
>

Thanks this solved my issue :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: not all arguments converted during string formatting

2016-02-17 Thread Chris Angelico
On Thu, Feb 18, 2016 at 12:58 AM, Ganesh Pal  wrote:
> Iam on python 2.6 and Linux  ,  I had replaced print out, err ret with
>   logging.info(out, err ,ret)   in the below code . I am getting
>
> "TypeError: not all arguments converted during string formatting"
> error any quick suggestion
>

The print statement/function happily accepts multiple arguments, and
will join them according to a set of predefined rules. The logging
functions don't have those rules, so they take one message and some
optional parameters. Try this, instead:

logging.info("%r %r %r", out, err, ret)

and then tweak the format string according to requirements. For a
quick dump, this will serve you well.

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


Re: TypeError: not all arguments converted during string formatting

2016-02-17 Thread Ganesh Pal
I think  logging.info(out) works the problem is when I add
logging.info(out,err,ret) ,may be there is a better way to supply this
arguments

On Wed, Feb 17, 2016 at 7:28 PM, Ganesh Pal  wrote:
> Hi Team,
>
>
> Iam on python 2.6 and Linux  ,  I had replaced print out, err ret with
>   logging.info(out, err ,ret)   in the below code . I am getting
>
> "TypeError: not all arguments converted during string formatting"
> error any quick suggestion
>
>
> try:
> out, err, ret = run(cmd, timeout=60)
> # New line added below
> logging.info(out, err ,ret)
> if ret != 0:
> logging.error("Can't run %s got %s (%d)!" % (cmd, err, ret))
> raise Exception("Preparing cluster failed...Exiting !!!")
> except Exception as e:
> logging.exception("Failed to run %s got %s" % (cmd, e))
> sys.exit("Preparing cluster failed")
> logging.info("Preparing Cluster.Done !!!")
>
>
> (Pdb) c
> Traceback (most recent call last):
>   File "/usr/local/lib/python2.6/logging/__init__.py", line 755, in emit
>   File "/usr/local/lib/python2.6/logging/__init__.py", line 637, in format
>   File "/usr/local/lib/python2.6/logging/__init__.py", line 425, in format
>   File "/usr/local/lib/python2.6/logging/__init__.py", line 295, in getMessage
> TypeError: not all arguments converted during string formatting
>
>
> Regards,
> Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'float' object is not iterable

2015-12-16 Thread Ben Finney
scarrer...@gmail.com writes:

> Someone stealing my points, I don't know how someone do it, but they
> had stolen some of my points.

Make new points, summarise them succinctly in the Subject field, and be
prepared to defend them.

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\ Brain, but there's still a bug stuck in here from last time.” |
_o__)   —_Pinky and The Brain_ |
Ben Finney

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


Re: TypeError: 'float' object is not iterable

2015-12-15 Thread scarrera53
Someone stealing my points, I don't know how someone do it, but they had stolen 
some of my points.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'float' object is not iterable

2015-12-15 Thread Chris Angelico
On Wed, Dec 16, 2015 at 4:40 PM,   wrote:
> Someone stealing my points, I don't know how someone do it, but they had 
> stolen some of my points.

They were floating. You should fix them down.

Also, you're replying to a years-old thread with no context.

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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread MRAB

On 2015-08-30 17:31, kbtyo wrote:

On Saturday, August 29, 2015 at 10:50:18 PM UTC-4, MRAB wrote:

On 2015-08-30 03:05, kbtyo wrote:
 I am using Jupyter Notebook and Python 3.4. I have a data structure in the 
format, (type list):

 [{'AccountNumber': N,
 'Amount': '0',
   'Answer': '12:00:00 PM',
'ID': None,
'Type': 'WriteLetters',
'Amount': '10',
{'AccountNumber': Y,
'Amount': '0',
'Answer': ' 12:00:00 PM',
 'ID': None,
'Type': 'Transfer',
'Amount': '2'}]

 The end goal is to write this out to CSV.

 For the above example the output would look like:

 AccountNumber, Amount, Answer, ID, Type, Amount
 N,0,12:00:00 PM,None,WriteLetters,10
 Y,2,12:00:00 PM,None,Transfer,2

 Below is the function that I am using to write out this data structure. Please excuse 
any indentation formatting issues. The data structure is returned through the function 
construct_results(get_just_xml_data).

 The data that is returned is in the format as above. 
construct_headers(get_just_xml_data) returns a list of headers. Writing out the row for 
headers_list works.

 The list comprehension data is to maintain the integrity of the column 
headers and the values for each new instance of the data structure (where the keys in the 
dictionary are the headers and values - row instances). The keys in this specific data 
structure are meant to check if there is a value instance, and if there is not - place an ''.

 def write_to_csv(results, headers):

  headers = construct_headers(get_just_xml_data)
  results = construct_results(get_just_xml_data)
  headers_list = list(headers)

  with open('real_csv_output.csv', 'wt') as f:
  writer = csv.writer(f)
  writer.writerow(headers_list)
  for row in results:
  data = [row.get(index, '') for index in results]
  writer.writerow(data)



 However, when I run this, I receive this error:

 ---
 TypeError Traceback (most recent call last)
 ipython-input-747-7746797fc9a5 in module()
  1 write_to_csv(results, headers)

 ipython-input-746-c822437eeaf0 in write_to_csv(results, headers)
9 writer.writerow(headers_list)
   10 for item in results:
 --- 11 data = [item.get(index, '') for index in results]
   12 writer.writerow(data)

 ipython-input-746-c822437eeaf0 in listcomp(.0)
9 writer.writerow(headers_list)
   10 for item in results:
 --- 11 data = [item.get(index, '') for index in results]
   12 writer.writerow(data)

 TypeError: unhashable type: 'dict'


 I have done some research, namely, the following:

 https://mail.python.org/pipermail//tutor/2011-November/086761.html

 http://stackoverflow.com/questions/27435798/unhashable-type-dict-type-error

 
http://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python

 However, I am still perplexed by this error. Any feedback is welcomed. Thank 
you.

You're taking the index values from 'results' instead of 'headers'.


Would you be able to elaborate on this? I partially understand what you mean. 
However, each dictionary (of results) has the same keys to map to (aka, headers 
when written out to CSV). I am wondering if you would be able to explain how 
the index is being used in this case?


In the list comprehension on line 11, you have item.get(index, '').

What is 'index'?

You have for index in results in the list comprehension, and 'results' 
is a list of dicts, therefore 'index' is a _dict_.


That means that you're trying to look up an entry in the 'item' dict
using a _dict_ as the key.

Oh, and incidentally, line 12 should be indented to the same level as
line 11.

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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread Laura Creighton
In a message of Sun, 30 Aug 2015 10:34:18 -0700, kbtyo writes:

@Laura - thank you. I observed this earlier. Please see my reply to Ben and 
MRAB for the most up to date status. 

For the more general problem of 'how do I parse my XML'
download and use this package.
https://pypi.python.org/pypi/xmlutils/1.1

It is all set up for reading xml and for writing csv, leaving you
with the manipulation in between (if any) you need.

Laura

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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread kbtyo
On Sunday, August 30, 2015 at 1:16:12 PM UTC-4, MRAB wrote:
 On 2015-08-30 17:31, kbtyo wrote:
  On Saturday, August 29, 2015 at 10:50:18 PM UTC-4, MRAB wrote:
  On 2015-08-30 03:05, kbtyo wrote:
   I am using Jupyter Notebook and Python 3.4. I have a data structure in 
   the format, (type list):
  
   [{'AccountNumber': N,
   'Amount': '0',
 'Answer': '12:00:00 PM',
  'ID': None,
  'Type': 'WriteLetters',
  'Amount': '10',
  {'AccountNumber': Y,
  'Amount': '0',
  'Answer': ' 12:00:00 PM',
   'ID': None,
  'Type': 'Transfer',
  'Amount': '2'}]
  
   The end goal is to write this out to CSV.
  
   For the above example the output would look like:
  
   AccountNumber, Amount, Answer, ID, Type, Amount
   N,0,12:00:00 PM,None,WriteLetters,10
   Y,2,12:00:00 PM,None,Transfer,2
  
   Below is the function that I am using to write out this data structure. 
   Please excuse any indentation formatting issues. The data structure is 
   returned through the function construct_results(get_just_xml_data).
  
   The data that is returned is in the format as above. 
   construct_headers(get_just_xml_data) returns a list of headers. 
   Writing out the row for headers_list works.
  
   The list comprehension data is to maintain the integrity of the column 
   headers and the values for each new instance of the data structure 
   (where the keys in the dictionary are the headers and values - row 
   instances). The keys in this specific data structure are meant to check 
   if there is a value instance, and if there is not - place an ''.
  
   def write_to_csv(results, headers):
  
headers = construct_headers(get_just_xml_data)
results = construct_results(get_just_xml_data)
headers_list = list(headers)
  
with open('real_csv_output.csv', 'wt') as f:
writer = csv.writer(f)
writer.writerow(headers_list)
for row in results:
data = [row.get(index, '') for index in results]
writer.writerow(data)
  
  
  
   However, when I run this, I receive this error:
  
   ---
   TypeError Traceback (most recent call 
   last)
   ipython-input-747-7746797fc9a5 in module()
    1 write_to_csv(results, headers)
  
   ipython-input-746-c822437eeaf0 in write_to_csv(results, headers)
  9 writer.writerow(headers_list)
 10 for item in results:
   --- 11 data = [item.get(index, '') for index in results]
 12 writer.writerow(data)
  
   ipython-input-746-c822437eeaf0 in listcomp(.0)
  9 writer.writerow(headers_list)
 10 for item in results:
   --- 11 data = [item.get(index, '') for index in results]
 12 writer.writerow(data)
  
   TypeError: unhashable type: 'dict'
  
  
   I have done some research, namely, the following:
  
   https://mail.python.org/pipermail//tutor/2011-November/086761.html
  
   http://stackoverflow.com/questions/27435798/unhashable-type-dict-type-error
  
   http://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python
  
   However, I am still perplexed by this error. Any feedback is welcomed. 
   Thank you.
  
  You're taking the index values from 'results' instead of 'headers'.
 
  Would you be able to elaborate on this? I partially understand what you 
  mean. However, each dictionary (of results) has the same keys to map to 
  (aka, headers when written out to CSV). I am wondering if you would be able 
  to explain how the index is being used in this case?
 
 In the list comprehension on line 11, you have item.get(index, '').
 
 What is 'index'?
 
 You have for index in results in the list comprehension, and 'results' 
 is a list of dicts, therefore 'index' is a _dict_.
 
 That means that you're trying to look up an entry in the 'item' dict
 using a _dict_ as the key.
 
 Oh, and incidentally, line 12 should be indented to the same level as
 line 11.

Yes, as mentioned in my OP, please forgive formatting issues with indentation:

I feel that I need to provide some context to avoid any confusion over my 
motivations for choosing to do something. 

My original task was to parse an XML data structure stored in a CSV file with 
other data types and then add the elements back as headers and the text as row 
values. I went back to drawing board and creating a results list of 
dictionaries where the keys have values as lists using this. 

def convert_list_to_dict(get_just_xml_data): 
d = {} 
for item in get_just_xml_data(get_all_data): 
for k, v in item.items(): 
try: 
d[k].append(v) 
except KeyError: 
d[k] = [v] 
return d 

This creates a dictionary for each XML tag - for example: 
{ 
 'Number1': ['0'], 
 'Number2': ['0'], 
 'Number3': ['0'], 
 

Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread Laura Creighton
When you get TypeError: unhashable type: 'dict'
it almost always means that you are trying to use a dict as
a key for a different dict.


Python 2.7.10 (default, Jul  1 2015, 10:54:53)
[GCC 4.9.2] on linux2
Type help, copyright, credits or license for more information.
  d={1:'one', 2:'two', 3:'three'}
  d1={1:'A', 2:'B', 3:'C'}

 This doesn't work.
 
  print d1[d]
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: unhashable type: 'dict'

This does.

  for index in d:
   ... print d1[index]
   ...
   A
   B
   C

HTH,
Laura




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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread kbtyo
On Saturday, August 29, 2015 at 11:04:53 PM UTC-4, Ben Finney wrote:
 kbtyo writes:
 
  I am using Jupyter Notebook and Python 3.4.
 
 Thank you for saying so! It is not always required, but when it matters,
 this information is important to state up front.
 
  I have a data structure in the format, (type list):
 
  [{'AccountNumber': N,
  'Amount': '0',
   'Answer': '12:00:00 PM',
'ID': None,
'Type': 'WriteLetters',
'Amount': '10',
{'AccountNumber': Y,
'Amount': '0',
'Answer': ' 12:00:00 PM',   
 'ID': None,
'Type': 'Transfer',
'Amount': '2'}]
 
  The end goal is to write this out to CSV.
 
 So that assumes that *every* item will be a mapping with all the same
 keys. CSV is limited to a sequence of records which all have the same
 fields in the same order.

This clue tipped me off that I wasn't collecting the newly generate key value 
pairs from my XML parser properly. I was using the dictionary built in method 
update to update the keys. The terrible thing was that the returned dictionary 
was only updated with the last keys and values. What a couple of hours of shut 
eye can do for the mind and body. 

 
  The list comprehension data is to maintain the integrity of the
  column headers and the values for each new instance of the data
  structure (where the keys in the dictionary are the headers and values
  - row instances). The keys in this specific data structure are meant
  to check if there is a value instance, and if there is not - place an
  ''.
 
 
 [...]
  for row in results:
  data = [row.get(index, '') for index in results]
 
 The 'for' statement iterates over 'results', getting an item each time.
 The name 'row' is bound to each item in turn.
 
 Then, each time through the 'for' loop, you iterate *again* over
 'results'. The name 'index' is bound to each item.
 
 You then attempt to use the dict (each item from 'results' is itself a
 dict) as a key into that same dict. A dict is not a valid key; it is not
 a hashable type i.e. a type with a fixed value, that can produce a
 hash of the value).

I discovered that. I need to iterate again to access the keys and values. 
 
 So you're getting dicts and attempting to use those dicts as keys into
 dicts. That will give the error TypeError: unhashable type: 'dict'.
 
 I think what you want is not items from the original sequence, but the
 keys from the mapping::
 
 for input_record in results:
 output_record = [input_record.get(key, ) for key in input_record]
 
 But you're then throwing away the constructed list, since you do nothing
 with it before the end of the loop.
 
  writer.writerow(data)
 
 This statement occurs only *after* all the items from 'results' have
 been iterated. You will only have the most recent constructed row.
 
 Perhaps you want::
 
 for input_record in results:
 output_record = [input_record.get(key, ) for key in input_record]
 writer.writerow(output_record)
 

I tried this and some of the values maintained integrity and some were 
rewritten by a previous dictionary's values. 


 -- 
  \   An idea isn't responsible for the people who believe in it. |
   `\  --Donald Robert Perry Marquis |
 _o__)  |
 Ben Finney

@BenFinney:

I feel that I need to provide some context to avoid any confusion over my 
motivations for choosing to do something. 

My original task was to parse an XML data structure stored in a CSV file with 
other data types and then add the elements back as headers and the text as row 
values. I went back to drawing board and creating a results list of 
dictionaries where the keys have values as lists using this. 

def convert_list_to_dict(get_just_xml_data):
d = {}
for item in get_just_xml_data(get_all_data):
for k, v in item.items():
try:
d[k].append(v)
except KeyError:
d[k] = [v]
return d 

This creates a dictionary for each XML tag - for example: 
{
 'Number1': ['0'],
 'Number2': ['0'],
 'Number3': ['0'],
 'Number4': ['0'],
 'Number5': ['0'],
 'RepgenName': [None],
 'RTpes': ['Execution', 'Letters'],
 'RTID': ['3', '5']}


I then used this to create a headers set (to prevent duplicates to be added) 
and the list of dictionaries that I mentioned in my OP. 


I achieve this via:

#just headers
def construct_headers(convert_list_to_dict):
header = set()
with open('real.csv', 'rU') as infile:
  reader = csv.DictReader(infile)
  for row in reader:
xml_data = convert_list_to_dict(get_just_xml_data) 
#get_just_xml_data(get_all_data)
row.update(xml_data) 
header.update(row.keys())
return header

#get all of the results
def construct_results(convert_list_to_dict):
header = set()
results = []

Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-30 Thread kbtyo
On Saturday, August 29, 2015 at 10:50:18 PM UTC-4, MRAB wrote:
 On 2015-08-30 03:05, kbtyo wrote:
  I am using Jupyter Notebook and Python 3.4. I have a data structure in the 
  format, (type list):
 
  [{'AccountNumber': N,
  'Amount': '0',
'Answer': '12:00:00 PM',
 'ID': None,
 'Type': 'WriteLetters',
 'Amount': '10',
 {'AccountNumber': Y,
 'Amount': '0',
 'Answer': ' 12:00:00 PM',
  'ID': None,
 'Type': 'Transfer',
 'Amount': '2'}]
 
  The end goal is to write this out to CSV.
 
  For the above example the output would look like:
 
  AccountNumber, Amount, Answer, ID, Type, Amount
  N,0,12:00:00 PM,None,WriteLetters,10
  Y,2,12:00:00 PM,None,Transfer,2
 
  Below is the function that I am using to write out this data structure. 
  Please excuse any indentation formatting issues. The data structure is 
  returned through the function construct_results(get_just_xml_data).
 
  The data that is returned is in the format as above. 
  construct_headers(get_just_xml_data) returns a list of headers. Writing 
  out the row for headers_list works.
 
  The list comprehension data is to maintain the integrity of the column 
  headers and the values for each new instance of the data structure (where 
  the keys in the dictionary are the headers and values - row instances). The 
  keys in this specific data structure are meant to check if there is a value 
  instance, and if there is not - place an ''.
 
  def write_to_csv(results, headers):
 
   headers = construct_headers(get_just_xml_data)
   results = construct_results(get_just_xml_data)
   headers_list = list(headers)
 
   with open('real_csv_output.csv', 'wt') as f:
   writer = csv.writer(f)
   writer.writerow(headers_list)
   for row in results:
   data = [row.get(index, '') for index in results]
   writer.writerow(data)
 
 
 
  However, when I run this, I receive this error:
 
  ---
  TypeError Traceback (most recent call last)
  ipython-input-747-7746797fc9a5 in module()
   1 write_to_csv(results, headers)
 
  ipython-input-746-c822437eeaf0 in write_to_csv(results, headers)
 9 writer.writerow(headers_list)
10 for item in results:
  --- 11 data = [item.get(index, '') for index in results]
12 writer.writerow(data)
 
  ipython-input-746-c822437eeaf0 in listcomp(.0)
 9 writer.writerow(headers_list)
10 for item in results:
  --- 11 data = [item.get(index, '') for index in results]
12 writer.writerow(data)
 
  TypeError: unhashable type: 'dict'
 
 
  I have done some research, namely, the following:
 
  https://mail.python.org/pipermail//tutor/2011-November/086761.html
 
  http://stackoverflow.com/questions/27435798/unhashable-type-dict-type-error
 
  http://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python
 
  However, I am still perplexed by this error. Any feedback is welcomed. 
  Thank you.
 
 You're taking the index values from 'results' instead of 'headers'.

Would you be able to elaborate on this? I partially understand what you mean. 
However, each dictionary (of results) has the same keys to map to (aka, headers 
when written out to CSV). I am wondering if you would be able to explain how 
the index is being used in this case?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-29 Thread MRAB

On 2015-08-30 03:05, kbtyo wrote:

I am using Jupyter Notebook and Python 3.4. I have a data structure in the 
format, (type list):

[{'AccountNumber': N,
'Amount': '0',
  'Answer': '12:00:00 PM',
   'ID': None,
   'Type': 'WriteLetters',
   'Amount': '10',
   {'AccountNumber': Y,
   'Amount': '0',
   'Answer': ' 12:00:00 PM',
'ID': None,
   'Type': 'Transfer',
   'Amount': '2'}]

The end goal is to write this out to CSV.

For the above example the output would look like:

AccountNumber, Amount, Answer, ID, Type, Amount
N,0,12:00:00 PM,None,WriteLetters,10
Y,2,12:00:00 PM,None,Transfer,2

Below is the function that I am using to write out this data structure. Please excuse any 
indentation formatting issues. The data structure is returned through the function 
construct_results(get_just_xml_data).

The data that is returned is in the format as above. 
construct_headers(get_just_xml_data) returns a list of headers. Writing out the row for 
headers_list works.

The list comprehension data is to maintain the integrity of the column 
headers and the values for each new instance of the data structure (where the keys in the 
dictionary are the headers and values - row instances). The keys in this specific data 
structure are meant to check if there is a value instance, and if there is not - place an 
''.

def write_to_csv(results, headers):

 headers = construct_headers(get_just_xml_data)
 results = construct_results(get_just_xml_data)
 headers_list = list(headers)

 with open('real_csv_output.csv', 'wt') as f:
 writer = csv.writer(f)
 writer.writerow(headers_list)
 for row in results:
 data = [row.get(index, '') for index in results]
 writer.writerow(data)



However, when I run this, I receive this error:

---
TypeError Traceback (most recent call last)
ipython-input-747-7746797fc9a5 in module()
 1 write_to_csv(results, headers)

ipython-input-746-c822437eeaf0 in write_to_csv(results, headers)
   9 writer.writerow(headers_list)
  10 for item in results:
--- 11 data = [item.get(index, '') for index in results]
  12 writer.writerow(data)

ipython-input-746-c822437eeaf0 in listcomp(.0)
   9 writer.writerow(headers_list)
  10 for item in results:
--- 11 data = [item.get(index, '') for index in results]
  12 writer.writerow(data)

TypeError: unhashable type: 'dict'


I have done some research, namely, the following:

https://mail.python.org/pipermail//tutor/2011-November/086761.html

http://stackoverflow.com/questions/27435798/unhashable-type-dict-type-error

http://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python

However, I am still perplexed by this error. Any feedback is welcomed. Thank 
you.


You're taking the index values from 'results' instead of 'headers'.

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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-29 Thread Mark Lawrence

On 30/08/2015 03:05, kbtyo wrote:

I am using Jupyter Notebook and Python 3.4. I have a data structure in the 
format, (type list):

[{'AccountNumber': N,
'Amount': '0',
  'Answer': '12:00:00 PM',
   'ID': None,
   'Type': 'WriteLetters',
   'Amount': '10',
   {'AccountNumber': Y,
   'Amount': '0',
   'Answer': ' 12:00:00 PM',
'ID': None,
   'Type': 'Transfer',
   'Amount': '2'}]

The end goal is to write this out to CSV.

For the above example the output would look like:

AccountNumber, Amount, Answer, ID, Type, Amount
N,0,12:00:00 PM,None,WriteLetters,10
Y,2,12:00:00 PM,None,Transfer,2

Below is the function that I am using to write out this data structure. Please excuse any 
indentation formatting issues. The data structure is returned through the function 
construct_results(get_just_xml_data).

The data that is returned is in the format as above. 
construct_headers(get_just_xml_data) returns a list of headers. Writing out the row for 
headers_list works.

The list comprehension data is to maintain the integrity of the column 
headers and the values for each new instance of the data structure (where the keys in the 
dictionary are the headers and values - row instances). The keys in this specific data 
structure are meant to check if there is a value instance, and if there is not - place an 
''.

def write_to_csv(results, headers):

 headers = construct_headers(get_just_xml_data)
 results = construct_results(get_just_xml_data)
 headers_list = list(headers)

 with open('real_csv_output.csv', 'wt') as f:
 writer = csv.writer(f)
 writer.writerow(headers_list)
 for row in results:
 data = [row.get(index, '') for index in results]
 writer.writerow(data)



However, when I run this, I receive this error:

---
TypeError Traceback (most recent call last)
ipython-input-747-7746797fc9a5 in module()
 1 write_to_csv(results, headers)

ipython-input-746-c822437eeaf0 in write_to_csv(results, headers)
   9 writer.writerow(headers_list)
  10 for item in results:
--- 11 data = [item.get(index, '') for index in results]
  12 writer.writerow(data)

ipython-input-746-c822437eeaf0 in listcomp(.0)
   9 writer.writerow(headers_list)
  10 for item in results:
--- 11 data = [item.get(index, '') for index in results]
  12 writer.writerow(data)

TypeError: unhashable type: 'dict'


I have done some research, namely, the following:

https://mail.python.org/pipermail//tutor/2011-November/086761.html

http://stackoverflow.com/questions/27435798/unhashable-type-dict-type-error

http://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python

However, I am still perplexed by this error. Any feedback is welcomed. Thank 
you.



I haven't looked too deeply into the problem as it's 03:45 and I'm just 
heading off to bed, but I suspect you'd make your life easier by using 
https://docs.python.org/3/library/csv.html#csv.DictWriter


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

Mark Lawrence

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


Re: TypeError: unhashable type: 'dict' when attempting to hash list - advice sought

2015-08-29 Thread Ben Finney
kbtyo ahlusar.ahluwa...@gmail.com writes:

 I am using Jupyter Notebook and Python 3.4.

Thank you for saying so! It is not always required, but when it matters,
this information is important to state up front.

 I have a data structure in the format, (type list):

 [{'AccountNumber': N,
 'Amount': '0',
  'Answer': '12:00:00 PM',
   'ID': None,
   'Type': 'WriteLetters',
   'Amount': '10',
   {'AccountNumber': Y,
   'Amount': '0',
   'Answer': ' 12:00:00 PM',   
'ID': None,
   'Type': 'Transfer',
   'Amount': '2'}]

 The end goal is to write this out to CSV.

So that assumes that *every* item will be a mapping with all the same
keys. CSV is limited to a sequence of “records” which all have the same
fields in the same order.

 The list comprehension data is to maintain the integrity of the
 column headers and the values for each new instance of the data
 structure (where the keys in the dictionary are the headers and values
 - row instances). The keys in this specific data structure are meant
 to check if there is a value instance, and if there is not - place an
 ''.


[…]
 for row in results:
 data = [row.get(index, '') for index in results]

The ‘for’ statement iterates over ‘results’, getting an item each time.
The name ‘row’ is bound to each item in turn.

Then, each time through the ‘for’ loop, you iterate *again* over
‘results’. The name ‘index’ is bound to each item.

You then attempt to use the dict (each item from ‘results’ is itself a
dict) as a key into that same dict. A dict is not a valid key; it is not
a “hashable type” i.e. a type with a fixed value, that can produce a
hash of the value).

So you're getting dicts and attempting to use those dicts as keys into
dicts. That will give the error “TypeError: unhashable type: 'dict'”.

I think what you want is not items from the original sequence, but the
keys from the mapping::

for input_record in results:
output_record = [input_record.get(key, ) for key in input_record]

But you're then throwing away the constructed list, since you do nothing
with it before the end of the loop.

 writer.writerow(data)

This statement occurs only *after* all the items from ‘results’ have
been iterated. You will only have the most recent constructed row.

Perhaps you want::

for input_record in results:
output_record = [input_record.get(key, ) for key in input_record]
writer.writerow(output_record)

-- 
 \   “An idea isn't responsible for the people who believe in it.” |
  `\  —Donald Robert Perry Marquis |
_o__)  |
Ben Finney

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


Re: TypeError: 'OldSample' object has no attribute '__getitem__'

2015-07-02 Thread Peter Otten
Hina Imran wrote:

 The data set looks something like this, The data is from openstack
 ceilometer python API
 
 [
  OldSample
   {
 counter_name': cpu_util',
  user_id': 7b',
  resource_id': ef',
  timestamp': 2015-07-02T08:13:55',
  counter_volume': 0.774,
   resource_metadata':
 {
  ramdisk_id': None',
  flavor.vcpus': 1',
   OS-EXT-AZ.availability_zone': nova',
   display_name': ubuntu-io',
   flavor.id': 596642d8-',
   status': active', ephemeral_gb': 0',
   flavor.name': m1.small.io',
   disk_gb': 20',
   kernel_id': None',
   image.id': 5776a360-',
   flavor.ram': 2048',
   host': host',
   flavor.ephemeral': 0',
image.name': ubuntu-io',
image_ref_url': http://b8dc',
image.links':
  [
  {
  'href': 'http://19',
  'rel': 'bookmark'
  }
  ],
  cpu_number': 1',
  flavor.disk': 20',
  root_gb': 20',
   name':
   instance-00d3',
   memory_mb': 2048',
   instance_type':
   596642d', vcpus': 1',
   image_ref': 5776a36',
   flavor.links':
   [
   {
   'href':
   'http://192.168.26.1',
   'rel': 'bookmark' }
   ]
   },
   source': openstack',
   counter_unit': %',
   recorded_at':
   
2015-07-02T08:13:55.485000',
   project_id': 1670f',
   message_id': 4849',
   4counter_type': gauge'
   }]
 
 My code looks something like this
 
 
 
 auth=v2.Password(auth_url=http://;, username=user, password=pass,
 tenant_id='id')
 
 # Pubnub instance initilize
 
 
 
 sess = session.Session(auth=auth,verify=False) #
 token = auth.get_token(sess)
 
 cclient = client.get_client(2, ceilometer_url=http:,
 token=token,verify=False)
 
 
 data = cclient.samples.list(meter_name ='cpu_util')
 
 
 thing = {}
 msg = {}
 cols = []
 
 def __unicode__(self):
   return unicode(self.data)
 
 for row in data:
 col = {}
 col['x'] = row['timestamp']
 col['y'] = row['counter_volume']
 cols.append(col)
 
 
 
 msg['columns'] = cols
 
 thing['message'] = msg
 
 print thing
 
 print json.dumps(thing)
 
 My intended out out something like this
 
 message: {
   columns: [
 [x: 123, y: 456],
 [y: 0.045, x: 2015-06-30T15:53:55]
   ]
 **here x is counter_volume and Y is timestamp**
 I need the output in this way because I want to plug this data into EON
 pubnub Charting Library. Problem is that no matter what I do it keeps on
 throwing me errors.I guess I need to learn some more how to manipulate
 list of dictionaries.

The problem is that you are not working with a dict, data seems to be a 
sequence of OldSample instances. Try changing

 col = {}
 col['x'] = row['timestamp']
 col['y'] = row['counter_volume']

to

col = {}
col['x'] = row.timestamp
col['y'] = row.counter_volume

If that 

Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Mark Lawrence

On 10/02/2015 14:28, Dave Angel wrote:

On 02/10/2015 06:35 AM, Mark Lawrence wrote:

On 10/02/2015 00:05, Ryan Stuart wrote:

Hi,





If you can show me a one tuple anywhere in the original code I'll
happily buy you a tipple of your choice.


print Menu[fav,RandomNum]

was in the original code





Thanks for the correction, I should have been more careful how I phrased 
my reply :(


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

Mark Lawrence

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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Dave Angel

On 02/10/2015 09:33 AM, Chris Angelico wrote:

On Wed, Feb 11, 2015 at 1:28 AM, Dave Angel da...@davea.name wrote:

If you can show me a one tuple anywhere in the original code I'll
happily buy you a tipple of your choice.



print Menu[fav,RandomNum]

was in the original code


That's not a one-tuple (as in, a tuple with one element), it's a
two-element tuple. The point is that (3) doesn't create a tuple,
it's just superfluous parentheses.


You're right of course. I didn't notice the meaning of one-tuple; I took 
Mark's comment as if he had said:


If you can show me a ruboutrubout one tuple anywhere ...

The original error message said there was a tuple;  I knew that fav 
wasn't the tuple, but the combination of fav and RandomNum was.



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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Ryan Stuart
Hi,

There is a lot of issues with this code. First, setting fav to a 1 tuples
with a string probably isn't what you want. What you probably mean is:

if restraunt == (Pizza):
fav = 1

Second, when you are trying to lookup items in Menu, you are using the
incorrect fav. Lists have int indicies (just like the error points out).
Values like (1) aren't integers.

Thirdly, Menu is a list of lists. To fetch Barbeque pizza from Menu, you
need to do Menu[0][0], not Menu[0, 0].

Finally, Python comes with a style guide which you can find in pep8
https://www.python.org/dev/peps/pep-0008/. Your code violates that guide
in many places. It might be worth working through the Python Tutorial
https://docs.python.org/3.4/tutorial/.

Cheers

On Tue Feb 10 2015 at 9:55:40 AM james8boo...@hotmail.com wrote:

 import random
 RandomNum = random.randint(0,7)
 restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease or
 Indian?)
 if restraunt == (Pizza):
 fav = (1)

 elif restraunt == (Chinease):
 fav = (2)

 elif restraunt == (Indian):
 fav = (3)

 else:
 print(Try using a capital letter, eg; 'Chinease')

 Menu = [[Barbeque pizza,Peparoni,Hawain],[
 Curry,Noodles,Rice],[Tika Masala,Special Rice,Onion Bargees]]

 print Menu[fav,RandomNum]
^
 TypeError: list indices must be integers, not tuple

 How do I set a variable to a random number then use it as a list indece,
 (I'm only a student in his first 6 months of using python)
 --
 https://mail.python.org/mailman/listinfo/python-list

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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Mark Lawrence

On 10/02/2015 00:05, Ryan Stuart wrote:

Hi,

There is a lot of issues with this code. First, setting fav to a 1
tuples with a string probably isn't what you want. What you probably
mean is:

if restraunt == (Pizza):
 fav = 1

Second, when you are trying to lookup items in Menu, you are using the
incorrect fav. Lists have int indicies (just like the error points out).
Values like (1) aren't integers.

Thirdly, Menu is a list of lists. To fetch Barbeque pizza from Menu,
you need to do Menu[0][0], not Menu[0, 0].

Finally, Python comes with a style guide which you can find in pep8
https://www.python.org/dev/peps/pep-0008/. Your code violates that
guide in many places. It might be worth working through the Python
Tutorial https://docs.python.org/3.4/tutorial/.

Cheers

On Tue Feb 10 2015 at 9:55:40 AM james8boo...@hotmail.com
mailto:james8boo...@hotmail.com wrote:

import random
RandomNum = random.randint(0,7)
restraunt = raw_input(What's your favourite takeaway?Pizza,
Chinease or Indian?)
if restraunt == (Pizza):
 fav = (1)

elif restraunt == (Chinease):
 fav = (2)

elif restraunt == (Indian):
 fav = (3)

else:
 print(Try using a capital letter, eg; 'Chinease')

Menu = [[Barbeque
pizza,Peparoni,Hawain],[__Curry,Noodles,Rice],[__Tika
Masala,Special Rice,Onion Bargees]]

print Menu[fav,RandomNum]
^
TypeError: list indices must be integers, not tuple

How do I set a variable to a random number then use it as a list
indece, (I'm only a student in his first 6 months of using python)
--
https://mail.python.org/__mailman/listinfo/python-list
https://mail.python.org/mailman/listinfo/python-list



If you can show me a one tuple anywhere in the original code I'll 
happily buy you a tipple of your choice.


Also please don't top post here, it makes following long threads 
difficult if not impossible to follow, thanks.


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

Mark Lawrence

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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Chris Angelico
On Wed, Feb 11, 2015 at 2:51 AM, Dave Angel da...@davea.name wrote:
 You're right of course. I didn't notice the meaning of one-tuple; I took
 Mark's comment as if he had said:

 If you can show me a ruboutrubout one tuple anywhere ...

Ah, yeah. I see the ambiguity. This is the downside of being so fluent
in Typo - sometimes you run into false cognates :)

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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Dave Angel

On 02/10/2015 01:48 PM, Chris Angelico wrote:

On Wed, Feb 11, 2015 at 2:51 AM, Dave Angel da...@davea.name wrote:

You're right of course. I didn't notice the meaning of one-tuple; I took
Mark's comment as if he had said:

If you can show me a ruboutrubout one tuple anywhere ...


Ah, yeah. I see the ambiguity. This is the downside of being so fluent
in Typo - sometimes you run into false cognates :)

ChrisA



If somebody were still doing py-quote-of-the-week, I'd nominate that 
sentence:


This is the downside of being so fluent
in Typo - sometimes you run into false cognates :)

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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Dave Angel

On 02/10/2015 06:35 AM, Mark Lawrence wrote:

On 10/02/2015 00:05, Ryan Stuart wrote:

Hi,





If you can show me a one tuple anywhere in the original code I'll
happily buy you a tipple of your choice.


print Menu[fav,RandomNum]

was in the original code



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


Re: TypeError: list indices must be integers, not tuple

2015-02-10 Thread Chris Angelico
On Wed, Feb 11, 2015 at 1:28 AM, Dave Angel da...@davea.name wrote:
 If you can show me a one tuple anywhere in the original code I'll
 happily buy you a tipple of your choice.


 print Menu[fav,RandomNum]

 was in the original code

That's not a one-tuple (as in, a tuple with one element), it's a
two-element tuple. The point is that (3) doesn't create a tuple,
it's just superfluous parentheses.

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


Re: TypeError: list indices must be integers, not tuple

2015-02-09 Thread Terry Reedy

On 2/9/2015 6:52 PM, james8boo...@hotmail.com wrote:

import random
RandomNum = random.randint(0,7)
restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease or 
Indian?)
if restraunt == (Pizza):
 fav = (1)


As a style note, putting parentheses around strings is worse than useless.


elif restraunt == (Chinease):
 fav = (2)

elif restraunt == (Indian):
 fav = (3)

else:
 print(Try using a capital letter, eg; 'Chinease')

Menu = [[Barbeque pizza,Peparoni,Hawain],[Curry,Noodles,Rice],[Tika 
Masala,Special Rice,Onion Bargees]]

print Menu[fav,RandomNum]
^
TypeError: list indices must be integers, not tuple

How do I set a variable to a random number then use it as a list indece, (I'm 
only a student in his first 6 months of using python)




--
Terry Jan Reedy

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


Re: TypeError: list indices must be integers, not tuple

2015-02-09 Thread Dave Angel

On 02/09/2015 07:02 PM, Ethan Furman wrote:

On 02/09/2015 03:52 PM, james8boo...@hotmail.com wrote:

import random
RandomNum = random.randint(0,7)
restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease or 
Indian?)
if restraunt == (Pizza):
 fav = (1)

elif restraunt == (Chinease):
 fav = (2)

elif restraunt == (Indian):
 fav = (3)

else:
 print(Try using a capital letter, eg; 'Chinease')



So just what is RandomNum supposed to represent?  You've selected it 
from an interval of 0 to 7, but you don't have 8 of anything.  The most 
logical possibility I can figure is you want to use it instead of 
whatever the user has typed into your raw input.  Like in the else 
clause.  If that's the case, you'd want to add a

 fav = RandomNum
line in the else clause.

Of course, as Ethan has pointed out, all the other assignments to fav 
want to be integer, not string.  You can't use a string to index a lis.



Menu = [[Barbeque pizza,Peparoni,Hawain],[Curry,Noodles,Rice],[Tika 
Masala,Special Rice,Onion Bargees]]

print Menu[fav,RandomNum]


Now that you've got a single value for fav, just say
print Menu[fav]
to print the submenu.

Now if Ethan has guessed right, that you wanted the random value to 
choose from the submenu, then you would/should have created it after you 
have the submenu, so you know how many possibilities there are.



Something like (untested):
RandomNum = random.randint(0, len(submenu)-1)



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


Re: TypeError: list indices must be integers, not tuple

2015-02-09 Thread Ethan Furman
On 02/09/2015 03:52 PM, james8boo...@hotmail.com wrote:
 import random
 RandomNum = random.randint(0,7)
 restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease or 
 Indian?)
 if restraunt == (Pizza):
 fav = (1)
 
 elif restraunt == (Chinease):
 fav = (2)  
 
 elif restraunt == (Indian):
 fav = (3)
 
 else:
 print(Try using a capital letter, eg; 'Chinease')
 
 Menu = [[Barbeque 
 pizza,Peparoni,Hawain],[Curry,Noodles,Rice],[Tika 
 Masala,Special Rice,Onion Bargees]]
 
 print Menu[fav,RandomNum]
^
 TypeError: list indices must be integers, not tuple
 
 How do I set a variable to a random number then use it as a list indece, (I'm 
 only a student in his first 6 months of using python) 

When you say

 Menu[fav,RandomNum]

the `fav,RandomNum` portion is a tuple.

`fav` should be 1 or 2 or 3, not 1 nor 2 nor 3.

`RandomNum` should be be `random.randint(0,2)`

Finally:

submenu = Menu[fav]

random_food = submenu[RandomNum]

--
~Ethan~



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


Re: TypeError: list indices must be integers, not tuple

2015-02-09 Thread Dave Angel

On 02/09/2015 10:05 PM, Dave Angel wrote:

On 02/09/2015 07:02 PM, Ethan Furman wrote:

On 02/09/2015 03:52 PM, james8boo...@hotmail.com wrote:

import random
RandomNum = random.randint(0,7)
restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease
or Indian?)
if restraunt == (Pizza):
 fav = (1)

elif restraunt == (Chinease):
 fav = (2)

elif restraunt == (Indian):
 fav = (3)

else:
 print(Try using a capital letter, eg; 'Chinease')



So just what is RandomNum supposed to represent?  You've selected it
from an interval of 0 to 7, but you don't have 8 of anything.  The most
logical possibility I can figure is you want to use it instead of
whatever the user has typed into your raw input.  Like in the else
clause.  If that's the case, you'd want to add a
  fav = RandomNum
line in the else clause.

Of course, as Ethan has pointed out, all the other assignments to fav
want to be integer, not string.  You can't use a string to index a lis.


Menu = [[Barbeque
pizza,Peparoni,Hawain],[Curry,Noodles,Rice],[Tika
Masala,Special Rice,Onion Bargees]]

print Menu[fav,RandomNum]


Now that you've got a single value for fav, just say
 print Menu[fav]
to print the submenu.

Now if Ethan has guessed right, that you wanted the random value to
choose from the submenu, then you would/should have created it after you
have the submenu, so you know how many possibilities there are.


Something like (untested):
RandomNum = random.randint(0, len(submenu)-1)





Perhaps it's worth suggesting that you use random.choice() instead, and 
use it directly on the sublist.  If you also make your data structure a 
dict of lists, then the whole thing becomes very simple.


(untested)

Menu = {
 Pizza : [Barbeque pizza,Peparoni,Hawain],
 Chinease : [Curry,Noodles,Rice],[Tika Masala,
 Indian : Special Rice,Onion Bargees]
   }

restraunt = raw_input(What's your favourite takeaway?Pizza, Chinease or 
Indian?)


submenu = menu[restraunt]
#you might want some error handling, in case they get it wrong
fooditem = random.choice(submenu)

print fooditem


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


Re: TypeError: unhashable type: 'list'

2014-12-22 Thread Chris Angelico
On Tue, Dec 23, 2014 at 10:10 AM,  ronald.kevin.bur...@gmail.com wrote:
 My problem is that I am not sure what the problem is. I can check the type of 
 'self' which is an object and the string 'Furnace Whistle' is obviously not a 
 list. The static function 'MeasureMaker.Code2Measure' is a simple factory:

 class MeasureMaker:

 def Code2Measure(measure_code, core):
 try:
 return {
 ...
 'Furnace Whistle': FurnaceWhistle(core)
 }[measure_code]
 except KeyError as error:
 return None
 Code2Measure = staticmethod(Code2Measure)

 What is the 'list' that is in the exception? Or how do I find out?

Does your MeasureMaker class define a __hash__ method? If so, what's
its definition? Possibly that's using some attributes and one of those
is a list.

Incidentally, is this actually how your code is laid out? What Python
versions do you need to support? Unless this code has to run on 2.3 or
earlier, you can replace the staticmethod call with a decorator:

@staticmethod
def Code2Measure(measure_code, core):
... code as above, but without the reassignment at the end ...

And if you were running this on 2.3, the except KeyError as error
syntax would be invalid anyway, so this should be a safe change :)

(You don't even need that try/except block, actually. If you use the
dict's .get() method, it'll return None instead of raising KeyError,
which is exactly what you need here.)

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


Re: TypeError: unhashable type: 'list'

2014-12-22 Thread Dave Angel

On 12/22/2014 06:10 PM, ronald.kevin.bur...@gmail.com wrote:

I am getting an exception that the traceback looks like:


Traceback (most recent call last):
   File C:\Projects\QA\robot_20141103\resources\assessment_utilities.py, line 
29, in create_new_project
 program = customer.add(program_code)
   File C:\Projects\QA\robot_20141103\resources\assessment_customer.py, line 
589, in add
 program = ProgramMaker.Code2Program(program_code, self)
   File C:\Projects\QA\robot_20141103\resources\programmaker.py, line 25, in 
Code2Program
 'ASSESS_PPL' : PPL(customer)
   File C:\Projects\QA\robot_20141103\resources\ppl.py, line 20, in __init__
 MeasureMaker.Code2Measure('Furnace Whistle', self)
TypeError: unhashable type: 'list'


My problem is that I am not sure what the problem is. I can check the type of 
'self' which is an object and the string 'Furnace Whistle' is obviously not a 
list. The static function 'MeasureMaker.Code2Measure' is a simple factory:

class MeasureMaker:

 def Code2Measure(measure_code, core):
 try:
 return {
...
 'Furnace Whistle': FurnaceWhistle(core)
 }[measure_code]
 except KeyError as error:
 return None
 Code2Measure = staticmethod(Code2Measure)

What is the 'list' that is in the exception? Or how do I find out?




I don't see enough pieces to tell the problem at all.  The two lowest 
levels of stack trace are on line 20 and 25, and you don't include 
either of those in your fragments.  Further, since many of your 
statements are multi-statement lines, the problem isn't necessarily 
showing in the stack trace, which only shows one line of the offending 
statement.


Finally, I suspect PPL is some form of alias, which you don't show 
either.  And the stack trace shows four different source files. 
Probably only the last two matter, but it'd be very useful to see the 
class/function definitions involved in their entirety, plus any from 
xxx import yyy type aliases that may be relevant.


Are you perhaps using Python 2.x ?  If so, you want to inherit from 
object.  I doubt that's your problem, but it's a missing clue.  Always 
state your Python version when describing a new problem.


BTW, using @staticmethod decorator is usually clearer than the way you 
have it here.  But that's no bug either.


--
DaveA

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


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-14 Thread alex23

On 13/10/2014 8:04 PM, Dave Angel wrote:

It would also help to spell it the same.  In the OP's
  implementation,  he defined kwargs, and tried to use it as
  kwarg.


That's perfectly okay, though: if `kwargs` is the name used to reference 
the dictionary of keyword arguments, `kwarg` would be an instance of a 
keyword argument.


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


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-13 Thread Dave Angel
Ian Kelly ian.g.ke...@gmail.com Wrote in message:
 On Sun, Oct 12, 2014 at 6:55 AM, roro codeath rorocode...@gmail.com wrote:
 How to implement it in my class?

 class Str(str):
 def __init__(self, *args, **kwargs):
 pass

 Str('smth', kwarg='a')
 
 The error is coming from the __new__ method. Because str is an
 immutable type, you should override the __new__ method, not __init__.
 Example:
 
 class Str(str):
 def __new__(cls, *args, **kwargs):
 return super().__new__(cls, args[0])
 
 Str('smth', kwarg='a')
 'smth'
 

It would also help to spell it the same.  In the OP's
 implementation,  he defined kwargs, and tried to use it as
 kwarg.


-- 
DaveA

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


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-13 Thread Peter Otten
Dave Angel wrote:

 Ian Kelly ian.g.ke...@gmail.com Wrote in
 message:
 On Sun, Oct 12, 2014 at 6:55 AM, roro codeath
 rorocode...@gmail.com wrote:
 How to implement it in my class?

 class Str(str):
 def __init__(self, *args, **kwargs):
 pass

 Str('smth', kwarg='a')
 
 The error is coming from the __new__ method. Because str is an
 immutable type, you should override the __new__ method, not __init__.
 Example:
 
 class Str(str):
 def __new__(cls, *args, **kwargs):
 return super().__new__(cls, args[0])
 
 Str('smth', kwarg='a')
 'smth'
 
 
 It would also help to spell it the same.  In the OP's
  implementation,  he defined kwargs, and tried to use it as
  kwarg.

That is consistent as should become clear when using something completely 
different:

 class Str(str):
... def __init__(self, *args, **kwargs): pass
... 
 Str(smth, alpha=beta)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'alpha' is an invalid keyword argument for this function


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


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-12 Thread Rustom Mody
Whats the problem??
Seems to work (python 2.7.8)

[Ive added a line so that that you can see]

class C:
   def __init__(self):
   pass

class C2(C):
def __init__(self, *args, **kwargs):
self.dic = kwargs
pass
x = C2(kwarg='a')
y = C2(kwarg='a', kwarg2=8)



 x.dic
{'kwarg': 'a'}
 y.dic
{'kwarg': 'a', 'kwarg2': 8}
 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-12 Thread Ian Kelly
On Sun, Oct 12, 2014 at 6:55 AM, roro codeath rorocode...@gmail.com wrote:
 How to implement it in my class?

 class Str(str):
 def __init__(self, *args, **kwargs):
 pass

 Str('smth', kwarg='a')

The error is coming from the __new__ method. Because str is an
immutable type, you should override the __new__ method, not __init__.
Example:

class Str(str):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, args[0])

 Str('smth', kwarg='a')
'smth'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'kwarg' is an invalid keyword argument for this function

2014-10-12 Thread Terry Reedy

On 10/12/2014 2:45 PM, Ian Kelly wrote:

On Sun, Oct 12, 2014 at 6:55 AM, roro codeath rorocode...@gmail.com wrote:

How to implement it in my class?

class Str(str):
 def __init__(self, *args, **kwargs):
 pass

Str('smth', kwarg='a')


The error is coming from the __new__ method. Because str is an
immutable type, you should override the __new__ method, not __init__.


or, if one is mere adding a method, do not add __new__ either.


Example:

class Str(str):
 def __new__(cls, *args, **kwargs):
 return super().__new__(cls, args[0])


Str('smth', kwarg='a')

'smth'




--
Terry Jan Reedy

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


Re: TypeError: 'bytes' object is not callable error while trying to converting to bytes.

2014-08-05 Thread Travis Griggs


 On Aug 4, 2014, at 22:57, Chris Angelico ros...@gmail.com wrote:
 
 On Tue, Aug 5, 2014 at 3:47 PM, Satish ML satishmlwiz...@gmail.com wrote:
 bytes = file.read()
 
 You've just shadowed the built-in type 'bytes' with your own 'bytes'.
 Pick a different name for this, and you'll be fine. 'data' would work.

Until python4 introduces the 'data' built in. :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'bytes' object is not callable error while trying to converting to bytes.

2014-08-05 Thread Chris Angelico
On Wed, Aug 6, 2014 at 3:31 PM, Travis Griggs travisgri...@gmail.com wrote:
 On Aug 4, 2014, at 22:57, Chris Angelico ros...@gmail.com wrote:

 On Tue, Aug 5, 2014 at 3:47 PM, Satish ML satishmlwiz...@gmail.com wrote:
 bytes = file.read()

 You've just shadowed the built-in type 'bytes' with your own 'bytes'.
 Pick a different name for this, and you'll be fine. 'data' would work.

 Until python4 introduces the 'data' built in. :)

Python 3.6 could introduce that, no need to wait for Python 4. :)
However, it wouldn't be critical to this code, unless the builtin's
meaning is also wanted; it'd be on par with the shadowing of 'file'
earlier - given how rarely Python programs actually need 'file'
(rather than 'open'), it's not a big deal to shadow that one.

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


Re: TypeError: 'bytes' object is not callable error while trying to converting to bytes.

2014-08-04 Thread Ben Finney
Satish ML satishmlwiz...@gmail.com writes:

 import struct
 file = open('data.bin', 'rb')

Here you re-bind the name ‘file’ to the return value from that call.

 bytes = file.read()

Here you re-bind the name ‘bytes’ to the return value from that call.

  records = [bytes([char] * 8) for char in b'spam']

Here you attempt to call ‘bytes’, which (as the error says) is not
callable.

You should choose names which are not already bound::

in_file = open('data.bin', 'rb')
in_file_content = in_file.read()
records = [bytes([char] * 8) for char in in_file_content]

When choosing names, try to communicate the *purpose* of the value, its
semantic meaning. The type should be of secondary importance, and almost
always should not be part of the name.

-- 
 \“Institutions will try to preserve the problem to which they |
  `\ are the solution.” —Clay Shirky, 2012 |
_o__)  |
Ben Finney

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


Re: TypeError: 'bytes' object is not callable error while trying to converting to bytes.

2014-08-04 Thread Chris Angelico
On Tue, Aug 5, 2014 at 3:47 PM, Satish ML satishmlwiz...@gmail.com wrote:
bytes = file.read()

You've just shadowed the built-in type 'bytes' with your own 'bytes'.
Pick a different name for this, and you'll be fine. 'data' would work.

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


Re: TypeError: 'NoneType' object is not callable

2014-07-29 Thread Peter Otten
Satish ML wrote:

 Hi,
 
 TypeError: 'NoneType' object is not callable? Why this error and what is
 the solution? Code:
 class SuperMeta:
 def __call__(self, classname, supers, classdict):
 print('In SuperMeta.call: ', classname, supers, classdict,
 sep='\n...') Class = self.__New__(classname, supers, classdict)
 self.__Init__(Class, classname, supers, classdict)
 class SubMeta(SuperMeta):
 def __New__(self, classname, supers, classdict):
 print('In SubMeta.new: ', classname, supers, classdict,
 sep='\n...') return type(classname, supers, classdict)
 def __Init__(self, Class, classname, supers, classdict):
 print('In SubMeta init:', classname, supers, classdict,
 sep='\n...') print('...init class object:',
 list(Class.__dict__.keys()))
 class Eggs:
 pass
 print('making class')
 class Spam(Eggs, metaclass=SubMeta()):
 data = 1
 def meth(self, arg):
 pass
 print('making instance')
 X = Spam()
 
 print('data:', X.data)
 Output:
 making class
 In SuperMeta.call:
 ...Spam
 ...(class '__main__.Eggs',)
 ...{'meth': function Spam.meth at 0x03539EA0, '__module__':
 '__main__', '__qualname__': 'Spam', 'data': 1} In SubMeta.new:
 ...Spam
 ...(class '__main__.Eggs',)
 ...{'meth': function Spam.meth at 0x03539EA0, '__module__':
 '__main__', '__qualname__': 'Spam', 'data': 1} In SubMeta init:
 ...Spam
 ...(class '__main__.Eggs',)
 ...{'meth': function Spam.meth at 0x03539EA0, '__module__':
 '__main__', '__qualname__': 'Spam', 'data': 1} ...init class object:
 ['meth', '__module__', 'data', '__doc__'] making instance
 Traceback (most recent call last):
   File C:/Users/Satish/Desktop/Python/Metaclasses7.py, line 21, in
   module
 X = Spam()
 TypeError: 'NoneType' object is not callable

As I have no idea what you are up to I can only list some adjustments you 
probably need to make:

- __init__() and __new__() are spelt in lowercase.
- do not instantiate the metaclass:
  class Spam(Eggs, metaclass=SubMeta): 
  ...
- The metaclasses of Spam and Eggs must share a common base. 
  This can be achieved with
  class SuperMeta(type): 
  ...


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


Re: TypeError expected in an augmented assignment

2014-07-03 Thread candide

   seq = [1,2]
 
   seq.extend((3,4))


OK, this feature is referenced in the Python Library reference here : 

https://docs.python.org/3.2/library/stdtypes.html#typesseq-mutable

not thoroughly referenced but, anyway, referenced.





 
   seq+= {5, 6}  # the order of extending is not determined
 
   seq
 
 [1, 2, 3, 4, 5, 6]
 
  

Good and interesting observation. But I can't find out where this feature is 
referenced in the Language/Library Reference. Because, as my first post 
explains, augmented assignment performs the binary operation associated to the 
augmented assignment, cf. 

https://docs.python.org/3.2/reference/simple_stmts.html#augmented-assignment-statements

so seq+= {5, 6} performs seq + {5, 6}, the later raising a TypeError.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError expected in an augmented assignment

2014-07-03 Thread Chris Angelico
On Thu, Jul 3, 2014 at 5:51 PM, candide c.cand...@laposte.net wrote:
 Good and interesting observation. But I can't find out where this feature is 
 referenced in the Language/Library Reference. Because, as my first post 
 explains, augmented assignment performs the binary operation associated to 
 the augmented assignment, cf.

 https://docs.python.org/3.2/reference/simple_stmts.html#augmented-assignment-statements

 so seq+= {5, 6} performs seq + {5, 6}, the later raising a TypeError.

From that link:


An augmented assignment expression like x += 1 can be rewritten as x =
x + 1 to achieve a similar, but not exactly equal effect. In the
augmented version, x is only evaluated once. Also, when possible, the
actual operation is performed in-place, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.


The significance here is that the augmented assignment may not
necessarily be at all comparable to the non-augmented version, but
ought to have *approximately* the same *intention*. There are plenty
of situations where the two will differ, eg when there are multiple
references to the same object:

 a = b = [1,2]
 a += [3]
 a,b
([1, 2, 3], [1, 2, 3])
 a = a + [4]
 a,b
([1, 2, 3, 4], [1, 2, 3])

In its simplest form, x += 1 - x = x + 1, but there are plenty of
ways to distinguish them.

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


Re: TypeError expected in an augmented assignment

2014-07-03 Thread candide


 From that link:
 
 
 
 
 
 An augmented assignment expression like x += 1 can be rewritten as x =
 
 x + 1 to achieve a similar, but not exactly equal effect. In the
 
 augmented version, x is only evaluated once. Also, when possible, the
 
 actual operation is performed in-place, meaning that rather than
 
 creating a new object and assigning that to the target, the old object
 
 is modified instead.
 
 
 
 
 
 The significance here is that the augmented assignment may not
 
 necessarily be at all comparable to the non-augmented version, but
 
 ought to have *approximately* the same *intention*. 


This is not my reading. 




 
 of situations where the two will differ, eg when there are multiple
 
 references to the same object:
 
 
 
  a = b = [1,2]
 
  a += [3]
 
  a,b
 
 ([1, 2, 3], [1, 2, 3])
 
  a = a + [4]
 
  a,b
 
 ([1, 2, 3, 4], [1, 2, 3])
 
 

OK but this behavior is in conformance with the Reference Manual (cf. your 
quote above : when possible, the actual operation is performed in-place). 
This is not my point because the doc explictly claims that an augmented 
assignment [...] performs the binary operation specific to the type of 
assignment on the two operands.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError expected in an augmented assignment

2014-07-03 Thread Mark Lawrence

On 03/07/2014 10:35, candide wrote:




From that link:





An augmented assignment expression like x += 1 can be rewritten as x =

x + 1 to achieve a similar, but not exactly equal effect. In the

augmented version, x is only evaluated once. Also, when possible, the

actual operation is performed in-place, meaning that rather than

creating a new object and assigning that to the target, the old object

is modified instead.





The significance here is that the augmented assignment may not

necessarily be at all comparable to the non-augmented version, but

ought to have *approximately* the same *intention*.



This is not my reading.






of situations where the two will differ, eg when there are multiple

references to the same object:




a = b = [1,2]



a += [3]



a,b


([1, 2, 3], [1, 2, 3])


a = a + [4]



a,b


([1, 2, 3, 4], [1, 2, 3])




OK but this behavior is in conformance with the Reference Manual (cf. your quote above : when 
possible, the actual operation is performed in-place). This is not my point because the doc 
explictly claims that an augmented assignment [...] performs the binary operation specific to 
the type of assignment on the two operands.



To get the wording changed to satisfy yourself, either raise an issue on 
the bug tracker at bugs.python.org and attach a patch file, or send an 
email with suggested wording to d...@python.org.


--
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: TypeError expected in an augmented assignment

2014-07-02 Thread Terry Reedy

On 7/2/2014 10:39 PM, candide wrote:

An hybrid list-tuple concatenation is not allowed


[]+(1, 2)

Traceback (most recent call last):
   File stdin, line 1, in module
TypeError: can only concatenate list (not tuple) to list






hence I was expecting (*) that the following code raises a TypeError :


x = []
x += (1, 2)
x

[1, 2]





Any explanation ?

 seq = [1,2]
 seq.extend((3,4))
 seq+= {5, 6}  # the order of extending is not determined
 seq
[1, 2, 3, 4, 5, 6]


--
Terry Jan Reedy

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


Re: TypeError in HMAC module.

2014-03-24 Thread Chris Angelico
On Tue, Mar 25, 2014 at 2:15 AM, Prabir Kr Sarkar
prabir.kr.sar...@gmail.com wrote:
 Hi,
I am trying to create a hashed message for authentication for a REST API
 call. I have got the key from a keyring as :-

 key = keyring.get_password('AWS_keyring','username')

  calculating the signature as :-
 signature = hmac(key, message.encode('UTF-8'),
 hashlib.sha1).digest().encode('base64')[:-1]

I can't import keyring, so either that's a module that isn't in the
Python standard library, or keyring is some object you've
instantiated. My crystal ball says this might be something to do with
Amazon Web Services, but it's hard to be sure. Can you please help us
out here by telling us all the dependencies of your code, and also
showing us a complete runnable program?

http://www.sscce.org/

Thanks!

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


Re: TypeError: can't multiply sequence by non-int of type 'tuple'

2014-03-13 Thread simiasaro
On Friday, February 21, 2014 1:31:53 AM UTC-5, Jaydeep Patil wrote:
 HI,
 
 
 
 I have a tuple. I need to make sqaure of elements of tuple and after that i 
 want add all suared tuple elements for total. When i trying to do it, below 
 error came.
 
 
 
 
 
 Code:
 
 seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), 
 (0.07,), (0.08,), (0.09,), (0.1,), (0.11,))
 
 
 
 x2 = [x * x for x in seriesxlist1];
 
 
 
 Error:
 
 Traceback (most recent call last):
 
   File pyshell#188, line 1, in module
 
 x2 = [x * x for x in seriesxlist1];
 
 TypeError: can't multiply sequence by non-int of type 'tuple'
 
 
 
 
 
 
 
 Please suggest me solution.

You may want to identify which of the tuple value you want to multiply, 
especially since the tuple has only one value:
x2 = [x[0] * x[0] for x in seriesxlist1]

Then, you can add the values in the list:
sum(x2)

or the quickest way:
sum(x[0] * x[0] for x in seriesxlist1)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can't multiply sequence by non-int of type 'tuple'

2014-02-20 Thread Rustom Mody
On Friday, February 21, 2014 12:01:53 PM UTC+5:30, Jaydeep Patil wrote:
 HI,

 I have a tuple. I need to make sqaure of elements of tuple and after that i 
 want add all suared tuple elements for total. When i trying to do it, below 
 error came.

 Code:
 seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), 
 (0.07,), (0.08,), (0.09,), (0.1,), (0.11,))

 x2 = [x * x for x in seriesxlist1];

 Error:
 Traceback (most recent call last):
 x2 = [x * x for x in seriesxlist1];
 TypeError: can't multiply sequence by non-int of type 'tuple'


 Please suggest me solution.

 x2 = [x * x for (x,) in seriesxlist1]
 x2
[0.0, 0.0001, 0.0004, 0.0009, 0.0016, 0.0025005, 0.0036, 
0.004901, 0.0064, 0.0081, 0.010002, 0.0121]
 

1 Why you are making singleton tuples dunno
2 And no need for semicolons in python
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can't multiply sequence by non-int of type 'tuple'

2014-02-20 Thread Jaydeep Patil
On Friday, 21 February 2014 12:06:54 UTC+5:30, Rustom Mody  wrote:
 On Friday, February 21, 2014 12:01:53 PM UTC+5:30, Jaydeep Patil wrote:
 
  HI,
 
 
 
  I have a tuple. I need to make sqaure of elements of tuple and after that i 
  want add all suared tuple elements for total. When i trying to do it, below 
  error came.
 
 
 
  Code:
 
  seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), 
  (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,))
 
 
 
  x2 = [x * x for x in seriesxlist1];
 
 
 
  Error:
 
  Traceback (most recent call last):
 
  x2 = [x * x for x in seriesxlist1];
 
  TypeError: can't multiply sequence by non-int of type 'tuple'
 
 
 
 
 
  Please suggest me solution.
 
 
 
  x2 = [x * x for (x,) in seriesxlist1]
 
  x2
 
 [0.0, 0.0001, 0.0004, 0.0009, 0.0016, 0.0025005, 0.0036, 
 0.004901, 0.0064, 0.0081, 0.010002, 0.0121]
 
  
 
 
 
 1 Why you are making singleton tuples dunno
 
 2 And no need for semicolons in python


Answer: 
1. This tupple, i get it from excel range extraction.
e.g. seriesxlist = newws.Range(newws.Cells(3,2),newws.Cells(usedRows,2)).Value

2. i removed semicolon, still i am facing same error. I am unable to get 
multiplies values.

Please suggest. 
I have input as below tuple only.
seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), 
(0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError: 'list' object is not callable

2014-02-06 Thread Peter Otten
wilsonmo...@gmail.com wrote:

 TypeError: 'list' object is not callable

Hint:

 open = []

[...]

 with open(..., rb) as csvfile:


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


Re: TypeError: 'list' object is not callable

2014-02-06 Thread Gary Herron

On 02/06/2014 12:01 AM, wilsonmo...@gmail.com wrote:

import csv

date1 = []
open = []
high = []
low = []
close = []
data = []
with open(C:/Documents and Settings/wilson/My Documents/Downloads/execution.csv, 
rb) as csvfile:
fastreader = csv.reader(csvfile, delimiter = ,, skipinitialspace=True)
count = 0
for row in fastreader:
date1.append(row[0])
count = count + 1


TypeError: 'list' object is not callable


I'd be glad to help, but I'm not interested in guessing.  Pleas take the 
time to tell us what line produced that error?  That is: cut and paste 
the *full* traceback instead of hiding useful information when you are 
asking for help.


Gary Herron

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


Re: TypeError: 'list' object is not callable

2014-02-06 Thread wilsonmonde
Peter Otten於 2014年2月6日星期四UTC+8下午4時22分45秒寫道:
 wilsonmo...@gmail.com wrote:
 
 
 
  TypeError: 'list' object is not callable
 
 
 
 Hint:
 
 
 
  open = []
 
 
 
 [...]
 
 
 
  with open(..., rb) as csvfile:


i follow in
http://www.dyinglovegrape.com/data_analysis/part1/1da3.php

still have error

what is the correct writing?
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   >