Re: What could cause a plot fail in my code?

2015-12-22 Thread Denis McMahon
On Mon, 21 Dec 2015 09:15:38 -0800, Robert wrote:

> Hi,
> 
> I find a useful code snippet on link:
> 
> http://stackoverflow.com/questions/25126444/logistic-regression-in-
pymc/34400966#34400966
> 
> but it has error on plot function. The error message is as following:

>6192 ymin = np.amin(m[m != 0])
>6193 # filter out the 0 height bins
> -> 6194 ymin = max(ymin*0.9, minimum) if not input_empty
> else minimum
>6195 ymin = min(ymin0, ymin)
>6196 self.dataLim.intervaly = (ymin, ymax)
> 
> UnboundLocalError: local variable 'ymin' referenced before assignment
> /
> 
> I have no clue at all on debug it. Could you help me?
> Thanks,

It looks as if ymin may be defined in a conditional block, and you've 
managed to reach line 6194 without going through that block.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: return from function

2015-12-22 Thread Denis McMahon
On Sun, 20 Dec 2015 12:34:40 +, Emil Natan wrote:

> I'm completely new to Python.

> parent_domain = domainname.partition('.')[2]
> try:
> print('Test for parent domain %s' % parent_domain)
> z = dns.resolver.query(parent_domain, 'SOA')
> print('the parent domain we use is: %s' % parent_domain)
> return parent_domain
> except dns.resolver.NXDOMAIN:
> print('NXDOMAIN: invoke find_parent_domain recursively')
> find_parent_domain(parent_domain)

None is being returned in this case!

> except dns.resolver.NoAnswer:
> print('NoAnswer: invoke find_parent_domain recursively')
> find_parent_domain(parent_domain)

And in this case.

Do you want to return None in the NXDOMAIN and NoAnswer cases? If not, a 
return statement might help in returning a value.

When you recurse back into a function you still need to return the result 
of the recursion.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-20 Thread Denis McMahon
On Sat, 12 Dec 2015 01:05:01 -0800, Harbey Leke wrote:

> Create a class called BankAccount
> 
> .Create a constructor that takes in an integer and assigns this to a
> `balance` property.
> 
> .Create a method called `deposit` that takes in cash deposit amount and
> updates the balance accordingly.
> 
> .Create a method called `withdraw` that takes in cash withdrawal amount
> and updates the balance accordingly. if amount is greater than balance
> return `"invalid transaction"`
> 
> .Create a subclass MinimumBalanceAccount of the BankAccount class
> 
> Please i need help on this i am a beginer into python programming.

It sounds like you're taking a python course. Your course should have 
taught you all you need to carry out this programming task before setting 
this exercise.

If you have not been paying attention, have failed to attend some 
sessions, or have not been keeping up with the course in some way, that 
might explain your difficulty.

Perhaps you should approach the course tutors and ask for some remedial 
assistance.

Alternatively, if you have so far been a fully attending, attentive and 
straight A student on this course, perhaps they are setting exercises for 
which they have not previously provided the necessary tuition. If that is 
the case, I suggest you ask them to reimburse your course fees, and then 
go and find better tutors.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hangman Code.

2015-12-17 Thread Denis McMahon
On Thu, 17 Dec 2015 05:28:23 -0800, trkaplan24 wrote:

> Hello, I created a python code for a simple hangman game. Was wondering
> if anyone could edit to help me make it multiplayer so when one person
> guesses a letter incorrectly, the next player can then guess a letter.

First you need to prompt for the number of players, and store this in a 
variable.

Next you need a variable to keep track of the current player. Set this to 
1 at the start of the program, because we're humans and we like to be 
player 1 ... player n, not player 0 ... player n-1.

Use the current player variable value to prompt for the next player.

After each player takes a turn, add 1 to the current player. If this is 
greater than the number of players, set it back to 1.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How does one distribute Tkinter or Qt GUI apps Developed in Python

2015-12-16 Thread Denis Akhiyarov
On Wednesday, December 16, 2015 at 6:45:50 PM UTC-6, Rick Johnson wrote:
> On Wednesday, December 16, 2015 at 6:03:55 PM UTC-6, Bruce Whealton wrote:
> 
> > Surely, one is going to want to create GUI apps for users
> > that are not Python Developers. I would not think to ask
> > someone to install Python on their system and make sure it
> > is added to the path. Maybe it is not so hard for the non-
> > technical, average users.
> > 
> > I would want to package in some way so that when launched,
> > it installs whatever is needed on the end user's computer.
> > How is this done? Are there common practices for this?
> 
> 
> Your assumptions are correct! In fact, in a language that was "supposedly" 
> designed to be an "applications language" (eat your heart out D'Aprano!!!), 
> one would think that distributing apps would not only be obvious, but also 
> intuitive!
> 
>  ALAS, THE CRUEL REALITIES OF INTERPRETED LANGUAGES SLAPS YOU IN THE PASTEY 
> WHITE FACE! 
> 
> Unlike a true "applications language", like say, um, *JAVA*, one cannot 
> simply compile an executable and distribute it in a teeny tiny binary form, 
> no, with Python, the end user must either (1) have Python on his machine 
> already, (2) download Python, or (3) you must package a Python interpreter 
> along with your script (and dependencies) -- which will end up being a very 
> large file just to run (what is in most cases) a very small script. 
> 
>  BOO-HISS!
> 
> But the good news is that, Python ships on many machines already. But of 
> course, you're seeking more consistency in your distribution QA than the 
> "wild guess" and the fickle nature of "lady luck". 
> 
> Many 3rd party libraries exist to solve your distribution issue. Google 
> probably knows about all (or at least most) of them.


if you did not notice Java/.NET ship with runtime VMs as well.
Even C/C++ have some requirements depending on the platform.
We should all switch to assembly to avoid any dependencies and port our code to 
each platform without hesitation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why my image is in bad quality ?

2015-12-16 Thread Denis McMahon
On Wed, 16 Dec 2015 06:04:37 -0800, fsn761304 wrote:

> I'm trying to make OCR-recognition on a screenshot, after screenshot
> taken it goes to pibxbuffer, which content goes to pytesseract.
> But after using pixbuffer image quality is bad

> image = image.resize((width*20,height*20), Image.ANTIALIAS)

This appears to attempt to extrapolate 400 pixels from each pixel in the 
original image.

That only works on TV crime dramas, you can't do it in real life.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue25841] In FancyURLopener error in example with http address.

2015-12-11 Thread Denis Savenko

New submission from Denis Savenko:

In documentation from this page 
https://docs.python.org/3.5/library/urllib.request.html#examples in examples 
uses default address to python site with http. ( http://python.org/ ). But now 
python.org use https. When i try use example in ipython i get I/0 error, but 
error is very simple - http change by https. I found this error on many pages, 
where use http://python.org/ address, but on FancyURLopener example compiller 
error very difficult for understanding.

--
assignee: docs@python
components: Documentation
messages: 256221
nosy: Denis Savenko, docs@python
priority: normal
severity: normal
status: open
title: In FancyURLopener error in example with http address.
versions: Python 3.3, Python 3.4, Python 3.5, Python 3.6

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25841>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Python variable assigning problems...

2015-12-10 Thread Denis McMahon
On Wed, 09 Dec 2015 09:49:26 -0800, ICT Ezy wrote:

> Pl refer question which attached image here:
> 
> link: https://drive.google.com/open?id=0B5L920jMv7T0dFNKQTJ2UUdudW8

I can't access the image with my G+ account because the image owner 
hasn't given me permission.

Perhaps you'd like to post a short self contained example of the problem 
here instead.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to set several list elements a same value with one line code

2015-12-03 Thread Denis McMahon
On Thu, 03 Dec 2015 16:30:25 -0800, Robert wrote:

> Hi,
> 
> I remember that there is a way to set several list elements a same value
> with
>  one line code. Excuse me, I don't remember the accurate syntax on the
>  code snippet. But the basic format looks like this.
> 
> 1. There is a four-element list, such as:
>bb=[[[]],[[]],[[]],[[]]]
> 2. An assignment line is here:
>bb[0]='a'
> 3. Then, all 4 element of bb is set with the above value.
>bb=[['a'],['a'],['a'],['a']]
> 
> The above three line codes are what I guess (I forgot the original
> tutorial
>  now). Do you remember there is such a list application?

bb = [ for i in range()]

will create bb as a list of size whatever elements each of which is 


eg:

>>> bb = [ ['a'] for i in range(4)]
>>> bb
[['a'], ['a'], ['a'], ['a']]
>>> bb = [ 0 for i in range(5)]
>>> bb
[0, 0, 0, 0, 0]
>>> 

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: filter a list of strings

2015-12-03 Thread Denis McMahon
On Thu, 03 Dec 2015 08:32:49 +0200, Jussi Piitulainen wrote:

> def isbad(item):
> return ( 'Banana' in item or
>  'Car' in item )
>
> def isgood(item)
> return not isbad(item)

badthings = [ 'Banana', 'Car', ]

def isgood(item)
for thing in badthings:
if thing in item:
return False
    return True

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: stuff and nonsense

2015-12-02 Thread Denis McMahon
On Wed, 02 Dec 2015 11:32:25 -0600, Ian Kelly wrote:

> In what way is discussion of a tangential topic feeding the troll? Said
> troll is not even participating in the discussion.

Reposting / responding / following up with the original subject boosts 
the visibility of the subject to internet search engines because of the 
way newsgroups get gated to websites.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: stuff and nonsense

2015-12-02 Thread Denis McMahon
On Thu, 03 Dec 2015 01:46:44 +0100, Laura Creighton wrote:

> In a message of Wed, 02 Dec 2015 22:51:13 +0000, Denis McMahon writes:
>>On Wed, 02 Dec 2015 11:32:25 -0600, Ian Kelly wrote:
>>
>>> In what way is discussion of a tangential topic feeding the troll?
>>> Said troll is not even participating in the discussion.
>>
>>Reposting / responding / following up with the original subject boosts
>>the visibility of the subject to internet search engines because of the
>>way newsgroups get gated to websites.

> That is not what I was told.  I was told that these days it is all done
> by References: lines.  Thus changing the Subject no longer has this
> effect.  Wrong?

Hmm, not sure on that bone, I heard that more instances of a phrase being 
found (eg in forums where a web page includes the subject in each 
message) helped increase the visibility of the phrase in some way, but I 
don't profess to understand how search engines score stuff, and I'm 
fairly sure few people do to be honest.

And what I heard might no longer be true if it ever was to be honest.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 16:18:49 -0500, Terry Reedy wrote:

> On 12/1/2015 3:32 PM, Denis McMahon wrote:
>> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>>
>>> In the case of:
>>>
>>>   tup[1] += [6, 7]
>>>
>>> what it's trying to do is:
>>>
>>>   tup[1] = tup[1].__iadd__([6, 7])
>>>
>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>>> then Python tries to put the result that the method returns into
>>> tup[1].
>>> That fails because tup itself is a tuple, which is immutable.
>>
>> I think I might have found a bug:
> 
> What you found is an specific example of what MRAB said in general
> above.
> 
>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
>> for more information.
>>>>> tup = [1,2,3],[4,5,6]
>>>>> tup
>> ([1, 2, 3], [4, 5, 6])
>>>>> tup[1]
>> [4, 5, 6]
>>>>> tup[1] += [7,8,9]
>> Traceback (most recent call last):
>>File "", line 1, in 
>> TypeError: 'tuple' object does not support item assignment
> 
> The bug is trying to replace a member of a tuple.  The correct code, to
> avoid the exception while extending the list, is
> 
> tup[1].extend([7,8,9])
> 
>>>>> tup[1]
>> [4, 5, 6, 7, 8, 9]

You snipped the important bit of my original post, which was the state of 
tup after the TypeError occurred.

After the error, 

>>> tup[1]
[4, 5, 6, 7, 8, 9]
>>> tup
([1, 2, 3], [4, 5, 6, 7, 8, 9])

The "bug" I refer to is that despite giving the TypeError, the tuple 
allowed the assignment of the mutated list to replace the original list.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 14:44:38 -0600, Ian Kelly wrote:

> On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon <denismfmcma...@gmail.com>
> wrote:
>> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>>
>>> In the case of:
>>>
>>>  tup[1] += [6, 7]
>>>
>>> what it's trying to do is:
>>>
>>>  tup[1] = tup[1].__iadd__([6, 7])
>>>
>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>>> then Python tries to put the result that the method returns into
>>> tup[1].
>>> That fails because tup itself is a tuple, which is immutable.
>>
>> I think I might have found a bug:
>>
>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
>> for more information.
>>>>> tup = [1,2,3],[4,5,6]
>>>>> tup
>> ([1, 2, 3], [4, 5, 6])
>>>>> tup[1]
>> [4, 5, 6]
>>>>> tup[1] += [7,8,9]
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> TypeError: 'tuple' object does not support item assignment
>>>>> tup[1]
>> [4, 5, 6, 7, 8, 9]
>>>>> tup
>> ([1, 2, 3], [4, 5, 6, 7, 8, 9])
>>>>> quit()
> 
> No, that's the expected result. As MRAB wrote, the list *is* mutated
> when its __iadd__ method is called. The TypeError happens afterward when
> the assignment is attempted.

The assignment succeeds. That's imo a bug. If it's a TypeError to try and 
assign a value to tup[1], then tup[1] should not allow the mutated list 
to be assigned.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:

> In the case of:
> 
>  tup[1] += [6, 7]
> 
> what it's trying to do is:
> 
>  tup[1] = tup[1].__iadd__([6, 7])
> 
> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
> then Python tries to put the result that the method returns into tup[1].
> That fails because tup itself is a tuple, which is immutable.

I think I might have found a bug:

$ python
Python 2.7.3 (default, Jun 22 2015, 19:33:41) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> tup = [1,2,3],[4,5,6]
>>> tup
([1, 2, 3], [4, 5, 6])
>>> tup[1]
[4, 5, 6]
>>> tup[1] += [7,8,9]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> tup[1]
[4, 5, 6, 7, 8, 9]
>>> tup
([1, 2, 3], [4, 5, 6, 7, 8, 9])
>>> quit()

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New JSON encoding method proposal for custom objects

2015-11-29 Thread Denis McMahon
On Sun, 29 Nov 2015 07:05:30 -0800, cescus92 wrote:

> In this day I stumbled upon a very simple task: I had a list of
> instances of a custom class and I had to convert i into a JSON.

That's all well and good, but firstly you need to both dumps and loads to 
work properly with json, and secondly there's no mechanism in json that 
tells you what class of object you have.

So you may have a __json_dumps__ that will dump your object out to a json 
string representation, but then how does json.loads recognise that it's 
loading your object to call your object's __json_loads__?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I can't understand re.sub

2015-11-29 Thread Denis McMahon
On Sun, 29 Nov 2015 13:36:57 -0800, Mr Zaug wrote:

> result = re.sub(pattern, repl, string, count=0, flags=0);

re.sub works on a string, not on a file.

Read the file to a string, pass it in as the string.

Or pre-compile the search pattern(s) and process the file line by line:

import re

patts = [
 (re.compile("axe"), "hammer"),
 (re.compile("cat"), "dog"),
 (re.compile("tree"), "fence")
 ]

with open("input.txt","r") as inf, open("output.txt","w") as ouf:
line = inf.readline()
for patt in patts:
line = patt[0].sub(patt[1], line)
ouf.write(line)

Not tested, but I think it should do the trick.

Or use a single patt and a replacement func:

import re

patt = re.compile("(axe)|(cat)|(tree)")

def replfunc(match):
if match == 'axe':
return 'hammer'
if match == 'cat':
return 'dog'
if match == 'tree':
return 'fence'
return match

with open("input.txt","r") as inf, open("output.txt","w") as ouf:
line = inf.readline()
line = patt.sub(replfunc, line)
ouf.write(line)

(also not tested)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with this program???

2015-11-27 Thread Denis McMahon
On Fri, 27 Nov 2015 01:43:53 -0800, justin bloomer wrote:

> Your program should contain a function that:
> 1. Seeks input from the user (via the keyboard);
> 2. To build a list of student exam results;
> 3. For each student their name (first and last), student number, and
> mark out of 100 should be captured;
> 4. For full marks regular expressions or similar mechanisms should be
> used to ensure the data appears valid.

Try writing a function that does the following:

1. Seeks input from the user (via the keyboard);
2. Builds a list of student exam results;
3. Captures name (first and last), student number, and mark out of 100 
for each student;
4. Uses regular expressions or similar mechanisms to ensure the data 
appears valid.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: reading from a txt file

2015-11-26 Thread Denis McMahon
On Thu, 26 Nov 2015 12:34:36 -0800, vincentypedro wrote:

> Hey, I'm wondering how to read individual strings in a text file.  I can
> read a text file by lines with .readlines() ,
> but I need to read specifically by strings, not including spaces. 
> Thanks in advance

How do you define a string? Is it just a line with the spaces removed?

>>> "".join("this is a teststring my friends".split(" "))
'thisisateststringmyfriends'

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Screen scraper to get all 'a title' elements

2015-11-26 Thread Denis McMahon
On Wed, 25 Nov 2015 12:42:00 -0800, ryguy7272 wrote:

> Hello experts.  I'm looking at this url:
> https://en.wikipedia.org/wiki/Wikipedia:Unusual_place_names
> 
> I'm trying to figure out how to list all 'a title' elements.

a is the element tag, title is an attribute of the htmlanchorelement.

combining bs4 with python structures allows you to find all the specified 
attributes of an element type, for example to find the class attributes 
of all the paragraphs with a class attribute:

stuff = [p.attrs['class'] for p in soup.find_all('p') if 'class' in 
p.attrs]

Then you can do this

for thing in stuff:
print thing

(Python 2.7)

This may be adaptable to your requirement.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: read 4D binary data

2015-11-26 Thread Denis McMahon
On Thu, 26 Nov 2015 15:15:43 -0200, jorge.conrado wrote:

> I'm startig in Python and I have a 4D binary data. The dimension of my
> data is:
> 
> 67 > longitude points 41 > latitude points 10 > pressure
> levels points 33 > time points
> 
> How can I read this data and what can I do to get a 2D array
> (longitude,latitude) for a specific pressure  and time dimension.

First of all, define the data structure you want to create.

I would have thought that for any given time, you would want a 2d array 
containing the pressure at each point (given by lat and lon) at that time.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Returning a result from 3 items in a list

2015-11-24 Thread Denis McMahon
On Tue, 24 Nov 2015 02:04:56 -0800, Cai Gengyang wrote:

> Here's a dictionary with 3 values :
> 
> results = {
>   "gengyang": 14,
>   "ensheng": 13, "jordan": 12
> }
> 
> How do I define a function that takes the last of the 3 items in that
> list and returns Jordan's results i.e. (12) ?

You open a web browser and google for "python dictionary"

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Denis McMahon
On Tue, 24 Nov 2015 03:04:09 -0800, Cai Gengyang wrote:

> results = {
>   "gengyang": { "maths": 10, "english": 15},
>   "ensheng": {"maths": 12, "english": 10}, "jordan": {"maths": 9,
>   "english": 13}
>   }
> 
> How do you get gengyang's maths scores ?

I refer to my previous answer. Open a web browser and google "python 
dictionary"

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How To Create A Endles List Of Lists In Python...???

2015-11-20 Thread Denis McMahon
On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote:

> Thanks In Advance, Robert...;)

Just keep appending child lists to parent list:

l = []

while True:
   l.append([])

Until you run out of memory

But I think that this answer although it appears accurate to the question 
is not a solution for anything useful, because it will just use all the 
memory up. So perhaps you need to express your question in a better 
manner.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: String format - resolve placeholders names

2015-11-20 Thread Denis McMahon
On Fri, 20 Nov 2015 16:53:47 +0100, Peter Otten wrote:

> Ervin Hegedüs wrote:

>> Python has a good string formatter, eg. I can do this:

>> s = "{who} likes {what}"
>> d = {'who': "Adam", 'what': "ants"}
>> s.format(**d)

>> result:
>> 'Adam likes ants'

>> Is it possible, and if yes, how to resolve the placeholders names in
>> string?

>>>> import string for item in string.Formatter().parse("{who} likes
>>>> {what}"):
> ... print(item)
> ...
> ('', 'who', '', None)
> (' likes ', 'what', '', None)

Or even:

>>> s = "{who} likes {what}"
>>> d = {'who': "Adam", 'what': "ants"}
>>> keys = [x[1] for x in string.Formatter().parse(s)]
>>> keys
['who', 'what']

then ...

for key in keys:
if key not in d:
raise KeyError("Missing key '{}' in format string '{}'".format
(key, s))

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I export data from a website and write the contents to a text file?

2015-11-18 Thread Denis McMahon
On Wed, 18 Nov 2015 08:37:47 -0800, ryguy7272 wrote:

> I'm trying the script below...

The problem isn't that you're over-writing the lines (although it may 
seem that way to you), the problem is that you're overwriting the whole 
file every time you write a link to it. This is because you open and 
close the file for every link you write, and you do so in file mode "wb" 
which restarts writing at the first byte of the file every time.

You only need to open and close the text file once, instead of for every 
link you output. Try moving the lines to open and close the file outside 
the outer for loop to change the loop from:

for item in soup.find_all(class_='lister-list'):
for link in item.find_all('a'):
# open file
# write link to file
# close file

to:

# open file
for item in soup.find_all(class_='lister-list'):
for link in item.find_all('a'):
# write link to file
# close file

Alternatively, use the with form:

with open("blah","wb") as text_file:
for item in soup.find_all(class_='lister-list'):
for link in item.find_all('a'):
    # write link to file

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about math.pi is mutable

2015-11-13 Thread Denis McMahon
On Fri, 13 Nov 2015 09:04:54 +1100, Steven D'Aprano wrote:

> On Fri, 13 Nov 2015 07:40 am, Thomas 'PointedEars' Lahn wrote:

> > [crap I expect]

> And you should consider the irony, and hypocrisy, of somebody who signs
> his posts "PointedEars" bitching about supposed "real names".

TPEL has been trolling html, php and javascript newsgroups for years, 
recently he seems to have discovered python newsgroups. :(

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Plotting timeseries from a csv file using matplotlib

2015-11-13 Thread Denis McMahon
On Thu, 12 Nov 2015 21:27:58 -0800, Karthik Sharma wrote:

> I have some csv data in the following format. ..

Does the following idea help?

Create a key from the key fields, remove the key fields from the row dic 
(so now it's a dic of just the data fields), and save that in the 
plotdata dict keyed by the key.

import csv

keybits = ["Ln","Dr","Tag","Lab"]

plotdata = {}

with open("lab.csv", 'r') as fin:
reader = csv.DictReader(fin)
for row in reader:
key = tuple([row[k] for k in keybits])
for k in keybits:
del row[k]
plotdata[key] = row

This generates a dictionary (plotdata) keyed by the key tuples where the 
value for each key is a dictionary of 0:0n : value

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: new to python, help please !!

2015-11-12 Thread Denis McMahon
On Thu, 12 Nov 2015 17:55:33 +, Quivis wrote:

> On Thu, 12 Nov 2015 13:58:35 +1100, Steven D'Aprano wrote:
> 
>> horribly inefficient
> 
> Assuming it was md5 values, who cares? Those are small.

A file of 160 million md5 hashes as 32 character hex strings is a huge 
file. Your method calculates the hash over both files to test whether the 
contents are different. If the input files are both lists of 160 million 
md5 hashes, you're calculating the hash of two 5 gigabyte files.

In your method the size of the lines of data is irrelevant to the 
execution time, the execution time varies with the size of the datafiles.
-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: new to python, help please !!

2015-11-12 Thread Denis McMahon
On Wed, 11 Nov 2015 08:34:30 -0800, Anas Belemlih wrote:

> i am  a beginning programmer,  i am trying to write a simple code to
> compare two character sets in 2 seperate files. ( 2 hash value files
> basically)

Why? If you simply wish to compare two files, most operating systems 
provide executable tools at the OS level which are more efficient than 
anything you will write in a scripting language.

Lesson 1 of computing. Use the right tool for the job. Writing a new 
program is not always the right tool.
-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting response by email reply message

2015-11-09 Thread Denis McMahon
On Mon, 09 Nov 2015 13:53:24 -0800, zljubisic wrote:

>> You have a couple options that occur to me:
>> 
>> 1) set up an SMTP server somewhere (or use the existing one you're
>> receiving this email at in the event you're getting it as mail rather
>> than reading it via NNTP or a web interface) to receive the mail, then
>> create a Python script to poll that inbox (usually POP3 or IMAP) for
>> messages addressed.  The mails can be extracted, parsed, and deleted
> 
> Why should I setup the SMTP server? If my email is on gmail server, I
> can read the messages from there from time to time.

Read more carefully!

The earlier poster suggested options that would work if you set up your 
own server, or already had one.

You can poll your gmail server using pop3 as the earlier reply suggested.

You may need to configure some options in your gmail account to allow 
pop3 access.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Extracting and summing student scores from a JSON file using Python 2.7.10

2015-11-09 Thread Denis McMahon
On Mon, 09 Nov 2015 15:52:45 -0800, Bernie Lazlo wrote:

> This should be a simple problem but I have wasted hours on it. Any help
> would be appreciated. [I have taken my code back to almost the very
> beginning.]
> 
> The student scores need to be summed.
> 
> import json import urllib url =
> "http://www.wickson.net/geography_assignment.json;
> response = urllib.urlopen(url)
> data = json.loads(response.read())
> lst1 = list(data.items())
> print lst1

I find that pprint.pprint is useful for looking at data structures.

Having looked at the data, and then using appropriate substitutions for 
 and  in the following:

sumscore = 0
students = 0

for dic in :
sumscore = sumscore + dic[]
students += 1

print 'Sum of', students, 'scores is', sumscore
print 'Average of', students, 'scores is', sumscore / students

It was trivial to generate:

Sum of 50 scores is 3028
Average of 50 scores is 60

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regular expressions

2015-11-03 Thread Denis McMahon
On Mon, 02 Nov 2015 22:17:49 -0500, Seymore4Head wrote:

> On Mon, 2 Nov 2015 20:42:37 -0600, Tim Chase
> <python.l...@tim.thechases.com> wrote:
> 
>>On 2015-11-02 20:09, Seymore4Head wrote:

>>> How do I make a regular expression that returns true if the end of the
>>> line is an asterisk

>>Why use a regular expression?

> Because that is the part of Python I am trying to learn at the moment.

The most important thing to learn about regular expressions is when to 
use them and when not to use them.

Returning true if the last character in a string is an asterisk is almost 
certainly a brilliant example of when not to use a regular expression. 
Here are some timings I tested:

#!/usr/bin/python

import re

import timeit

patt = re.compile("\*$")

start_time = timeit.default_timer()
for i in range(100):
x = re.match("\*$", "test 1")
elapsed = timeit.default_timer() - start_time
print "re, false", elapsed

start_time = timeit.default_timer()
for i in range(100):
x = re.match("\*$", "test *")
elapsed = timeit.default_timer() - start_time
print "re, true", elapsed

start_time = timeit.default_timer()
for i in range(100):
x = patt.match("test 1")
elapsed = timeit.default_timer() - start_time
print "compiled re, false", elapsed

start_time = timeit.default_timer()
for i in range(100):
x = patt.match("test *")
elapsed = timeit.default_timer() - start_time
print "compiled re, true", elapsed

start_time = timeit.default_timer()
for i in range(100):
x = "test 1"[-1] == "*"
elapsed = timeit.default_timer() - start_time
print "char compare, false", elapsed

start_time = timeit.default_timer()
for i in range(100):
x = "test *"[-1] == "*"
elapsed = timeit.default_timer() - start_time
print "char compare, true", elapsed

RESULTS:

re, false 2.4701731205
re, true 2.42048001289
compiled re, false 0.875837087631
compiled re, true 0.876382112503
char compare, false 0.26283121109
char compare, true 0.263465881348

The compiled re is about 3 times as fast as the uncompiled re. The 
character comparison is about 3 times as fast as the compiled re.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: If one IF is satisfied, skip the rest in the nest...

2015-10-21 Thread Denis McMahon
On Wed, 21 Oct 2015 10:31:04 -0700, bigred04bd3 wrote:

> So here what I have, I have a 3 IF's within the same level.  If one IF
> is satisfied, I would like to "skip" the other IFs and continue with my
> code.

c1 = wb1_sheet1.cell(row=cell + 1, column=2).value == 0 and 
 wb1_sheet1.cell(row=cell + 1, column=3).value == 0

c2 = wb1_sheet1.cell(row=cell + 2, column=2).value == 0 and 
 wb1_sheet1.cell(row=cell + 2, column=3).value == 0

c3 = wb1_sheet1.cell(row=cell + 3, column=2).value == 0 and 
 wb1_sheet1.cell(row=cell + 3, column=3).value == 0

if c1:
if c2:
if c3:
# c1 && c2 && c3
# 4 second open
else:
# c1 && c2
# 3 second open
else:
# only c1
# 2 second open

Each condition only gets evaluated once.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: If one IF is satisfied, skip the rest in the nest...

2015-10-21 Thread Denis McMahon
On Wed, 21 Oct 2015 20:07:21 +, Grant Edwards wrote:

> On 2015-10-21, Denis McMahon <denismfmcma...@gmail.com> wrote:
>> On Wed, 21 Oct 2015 10:31:04 -0700, bigred04bd3 wrote:
>>
>>> So here what I have, I have a 3 IF's within the same level.  If one IF
>>> is satisfied, I would like to "skip" the other IFs and continue with
>>> my code.
>>
>> c1 = wb1_sheet1.cell(row=cell + 1, column=2).value == 0 and
>>  wb1_sheet1.cell(row=cell + 1, column=3).value == 0
>>
>> c2 = wb1_sheet1.cell(row=cell + 2, column=2).value == 0 and
>>  wb1_sheet1.cell(row=cell + 2, column=3).value == 0
>>
>> c3 = wb1_sheet1.cell(row=cell + 3, column=2).value == 0 and
>>  wb1_sheet1.cell(row=cell + 3, column=3).value == 0
>>
>> if c1:
>> if c2:
>> if c3:
>> # c1 && c2 && c3 # 4 second open
>> else:
>> # c1 && c2 # 3 second open
>> else:
>> # only c1 # 2 second open
> 
> if c1 && c2 && c3:
> pass   # 4 seconds
> elif c1 && c2:
> pass   # 3 seconds
> elif c1:
> pass   # 2 seconds
> 
> Or if you want to be particulary obtuse:
> 
> seconds = {0b111:4, 0b110:3, 0b100:2}.get(c1<<2 | c2<<1 | c3<<0, None)

Not really valid, because #seconds n is simply a marker to indicate which 
branch of the OP's code to execute.

>> Each condition only gets evaluated once.
> 
> OK.

Yes, but in the structure I suggest, you can move the conditions back 
into the if statements and they still only each get evaluated once. Viz 
my alternative to the OP's code:

if wb1_sheet1.cell(row=cell + 1, column=2).value == 0 and wb1_sheet1.cell
(row=cell + 1, column=3).value == 0:

if wb1_sheet1.cell(row=cell + 2, column=2).value == 0 and 
wb1_sheet1.cell(row=cell + 2, column=3).value == 0:

if wb1_sheet1.cell(row=cell + 3, column=2).value == 0 and 
wb1_sheet1.cell(row=cell + 3, column=3).value == 0:

open += 3 
open_seconds += 4 
start = wb1_sheet1.cell(row=cell + 4, column=2).coordinate

else:

open += 3 
open_seconds += 3
start = wb1_sheet1.cell(row=cell + 3, column=2).coordinate 

else:

open += 3 
open_seconds += 2
start = wb1_sheet1.cell(row=cell + 2, column=2).coordinate 

Not trying to be obtuse here, trying to suggest a practical solution.

Of course, the benefit of reducing the number of times each lookup into 
the worksheet is performed by reducing the number of times each 
comparison evaluated is going to depend on the computational and memory 
manipulation cost of doing so (I assume the workbook is loaded in memory, 
so no IO costs), and how frequently this set of comparisons is being 
performed.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting tuple of lists of variable length into dictionary

2015-10-18 Thread Denis McMahon
On Sun, 18 Oct 2015 03:17:18 -0700, Beppe wrote:

> hi to everybody, I must turn a tuple of lists into a dictionary.

I went down a different path to Peter, and discovered something 
perplexing:

This failed:

d = { i: deepcopy(l).remove(i) for l in t for i in l }

So I tried to expand it out to see where the issue was, and ended up with 
two variants:

def f1(l, i):
m = deepcopy(l)
m.remove(i)
return m

d = { i: f1(l,i) for l in t for i in l }

def f2(l, i):
m = deepcopy(l).remove(i)
return m

d = { i: f2(l,i) for l in t for i in l }

The first variant using, m = deepcopy(l); m.remove(i) works fine, 
generating:

{'a': ['b', 'c', 'd', 'e', 'f'], 'c': ['a', 'b', 'd', 'e', 'f'], 'b': 
['a', 'c', 'd', 'e', 'f'], 'e': ['a', 'b', 'c', 'd', 'f'], 'd': ['a', 
'b', 'c', 'e', 'f'], 'g': ['h', 'i'], 'f': ['a', 'b', 'c', 'd', 'e'], 'i': 
['g', 'h'], 'h': ['g', 'i'], 'm': ['l', 'n', 'o'], 'l': ['m', 'n', 'o'], 
'o': ['l', 'm', 'n'], 'n': ['l', 'm', 'o']}

The second variant using, m = deepcopy(l).remove(i) fails thus:

{'a': None, 'c': None, 'b': None, 'e': None, 'd': None, 'g': None, 'f': 
None, 'i': None, 'h': None, 'm': None, 'l': None, 'o': None, 'n': None}

I'm not sure I understand why after m = deepcopy(l); m.remove(i); m is a 
different value to that which it as after m = deepcopy(l).remove(i).

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting tuple of lists of variable length into dictionary

2015-10-18 Thread Denis McMahon
On Sun, 18 Oct 2015 20:38:26 +, Denis McMahon wrote:

> On Sun, 18 Oct 2015 03:17:18 -0700, Beppe wrote:
> 
>> hi to everybody, I must turn a tuple of lists into a dictionary.
> 
> I went down a different path to Peter, and discovered something
> perplexing:

I just realised staring at it again that I'm getting the return value 
from the remove (ie None) in the failing case, because the remove is 
operating on the original list, rather than returning an updated copy.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue6331] Add unicode script info to the unicode database

2015-10-17 Thread Denis Jacquerye

Changes by Denis Jacquerye <moy...@gmail.com>:


--
nosy: +Denis Jacquerye

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue6331>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue22612] Add block info to unicodedata

2015-10-17 Thread Denis Jacquerye

Changes by Denis Jacquerye <moy...@gmail.com>:


--
nosy: +Denis Jacquerye

___
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue22612>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: pip problem

2015-10-16 Thread Denis McMahon
On Fri, 16 Oct 2015 11:50:11 +0300, Antti Lagus wrote:

> hello,
> 
> installed pyton3.5 to NOT default folder.
> tried to install cx_Freeze, but countered errors where pip tried to
> copy/import stuff from default install location.
> 
> please fix

Hi, I waved my magic wand, and your problem should be fixed. If your 
problem is not fixed, manual intervention may be needed. We can probably 
tell you what you need to do, but more details of the problem are needed 
first.

What OS?

Where did you get python from and What command are you using to install 
it?

Do you have all the permissions needed to write to the directories you're 
asking it to put files in?

Did you run the installation process with those permissions?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to repeat a loop once it is finished

2015-10-15 Thread Denis McMahon
On Thu, 15 Oct 2015 06:29:24 -0700, abbasmo wrote:

> what would be a small thing that I could add to make this thing run
> again?

See what happens when you run the following code. Then adapt it to your 
application.

stop = False
while not stop:
x = input("enter something, quit, stop or end to exit: ")
print("you entered: ", x)
if x in ["stop","quit","end"]:
stop = True
print("Finished now")

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to repeat a loop once it is finished

2015-10-15 Thread Denis McMahon
On Thu, 15 Oct 2015 14:51:05 +0100, Mark Lawrence wrote:

> On 15/10/2015 14:31, abba...@centralfoundationboys.co.uk wrote:
>> if you could write a small piece of code for me it would great
>>
>>
> If you used your favourite search engine in an attempt to write the code
> before you ask questions about it, then that would be even better.
> Knowing what piece of code would also help us to help you.  As a starter
> here is a small piece of code.
> 
> a = 1
> 
> Is that adequate?

If not, perhaps:

b = [c for c in range(20)]
d = {e:b for e in b}

can help?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trouble running

2015-10-07 Thread Denis McMahon
On Mon, 05 Oct 2015 19:06:04 +0100, Cameroni123 ™ wrote:

> Hi I have recently installed python on windows 10 and I’m trying to save
> in order to run the module and I cant I don’t know why, could you please
> help?

Based on the comprehensive problem description I have waved my magic 
wand. It should work now. If it still doesn't work, please provide more 
details about the problem.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Finding Blank Columns in CSV

2015-10-05 Thread Denis McMahon
On Mon, 05 Oct 2015 13:29:03 +, Jaydip Chakrabarty wrote:

> Hello,
> 
> I have a csv file like this.
> 
> Name,Surname,Age,Sex abc,def,,M ,ghi,,F jkl,mno,,
> pqr,,,F
> 
> I want to find out the blank columns, that is, fields where all the
> values are blank. Here is my python code.
> 
> fn = "tmp1.csv"
> fin = open(fn, 'rb')
> rdr = csv.DictReader(fin, delimiter=',')
> data = list(rdr)
> flds = rdr.fieldnames fin.close()
> mt = []
> flag = 0 for i in range(len(flds)):
> for row in data:
> if len(row[flds[i]]):
> flag = 0 break
> else:
> flag = 1
> if flag:
> mt.append(flds[i]) flag = 0
> print mt
> 
> I need to know if there is better way to code this.
> 
> Thanks.

Assuming all the records have the same number of fields:

I'd create a list of flags of length numfields, all set to 0

then for each record, I*d set flag[n] = 1 if field[n] has content

then I'd check if I still have any 0 flags, and if I do, process the next 
record

As soon as I have no 0 flags, I can stop processing records, as this 
means I have no empty columns.

It might be more efficient if, when checking a record, I only tested the 
fields for which flag was still 0.

Example (untested)

flags = [False for x in rdr.fieldnames]

for row in data:
blanks = False
for i in range(len(flags)):
if not flags[i]:
if len(row[i]) == 0:
flags[i] = True
else:
blanks = True
if not blanks:
break


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: function code snippet that has function calls I have never seen before. How does it work.

2015-10-03 Thread Denis McMahon
On Sat, 03 Oct 2015 10:40:57 -0700, Ronald Cosentino wrote:

> def funA(x,y,z):
> return (x+y) * z
> def funB(x,y):
> return(x-y)
> print(funA(4,funB(2,3), funB(3,2)))
> 
> the answer is 3. I don't know how it works.

def funA(x, y, z):
return (x+y) * z

def funB(x, y):
return (x-y)

# this line
# print(funA(4,funB(2,3), funB(3,2)))
# can be written as the following 4 lines:

a = funB(2, 3) # 2 - 3 -> -1

b = funB(3, 2) # 3 - 2 -> 1

c = funA(4, a, b) # (4 + -1) * 1 -> 3

print(c) # 3

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about regular expression

2015-10-02 Thread Denis McMahon
On Wed, 30 Sep 2015 23:30:47 +, Denis McMahon wrote:

> On Wed, 30 Sep 2015 11:34:04 -0700, massi_srb wrote:
> 
>> firstly the description of my problem. I have a string in the following
>> form: .
> 
> The way I solved this was to:
> 
> 1) replace all the punctuation in the string with spaces
> 
> 2) split the string on space
> 
> 3) process each thing in the list to test if it was a number or word
> 
> 4a) add words to the dictionary as keys with value of a default list, or
> 4b) add numbers to the dictionary in the list at the appropriate
> position
> 
> 5) convert the list values of the dictionary to tuples
> 
> It seems to work on my test case:
> 
> s = "fred jim(1) alice tom (1, 4) peter (2) andrew(3,4) janet( 7,6 )
> james ( 7 ) mike ( 9 )"
> 
> d = {'mike': (9, 0), 'janet': (7, 6), 'james': (7, 0), 'jim': (1, 0),
> 'andrew': (3, 4), 'alice': (0, 0), 'tom': (1, 4), 'peter': (2, 0),
> 'fred':
> (0, 0)}

Oh yeah, the code:

#!/usr/bin/python

import re

s = 'fred jim(1) alice tom (1, 4) peter (2) andrew(3,4) janet( 7,6 ) james
( 7 ) mike ( 9 ) jon  (  6  ,  3  )   charles(0,12)'

bits = s.replace('(', ' ').replace(',', ' ').replace(')', ' ').split(' ')

d = {}

namep = re.compile('^[A-Za-z]+$')
numbp = re.compile('^[0-9]+$')

for bit in bits:
if namep.match(bit):
d[bit] = [0,0]
w = bit
nums = 0
if numbp.match(bit):
n = int(bit)
d[w][nums] = n
nums += 1

d = {x:tuple(d[x]) for x in d}

print s
print d

It uses regex to determine if the list element being processed is a name 
or a number, which makes for 2 very simple patterns.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.5.0 (32-bit) Setup error

2015-10-02 Thread Denis McMahon
On Fri, 02 Oct 2015 12:32:14 +1000, Hadassah Harland wrote:

> The python for windows setup program is constantly opening on my
> computer,
> every couple seconds. Nothing I can do will make it stop. Please, make
> it stop.

Based on the comprehensive and thorough information that you have given, 
I have waved my magic wand. If this didn't work, the information you 
supplied was insufficient.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about regular expression

2015-10-01 Thread Denis McMahon
On Thu, 01 Oct 2015 01:48:03 -0700, gal kauffman wrote:

> items = s.replace(' (', '(').replace(', ',',').split()
> 
> items_dict = dict()
> for item in items:
> if '(' not in item:
> item += '(0,0)'
> if ',' not in item:
> item = item.replace(')', ',0)')
> 
> name, raw_data = item.split('(') data_tuple = tuple((int(v) for v in
> raw_data.replace(')','').split(',')))
> 
> items_dict[name] = data_tuple

Please don't top post.

What happens if there's more whitespace than you allow for preceding a 
'(' or following a ',', or if there's whitespace following '('?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about regular expression

2015-10-01 Thread Denis McMahon
On Thu, 01 Oct 2015 15:53:38 +, Rob Gaddi wrote:

> There's a quote for this.  'Some people, when confronted with a problem,
> think “I know, I'll use regular expressions.”  Now they have two
> problems.'

I actually used 2 regexes:

wordpatt = re.compile('[a-zA-Z]+')

numpatt = re.compile('[0-9]+')

replace all '(', ',' and ')' in the string with spaces

split the string on space

create an empty dict d

process each thing in the split list setting d[word]=[0,0] for each word 
element (wordpatt.match(thing)) (a list because I want to be able to 
modify it)

setting d[word][n] = int(num) for each num element (numpatt.match(thing)) 
with n depending on whether it was the first or second num following the 
previous word

then:

d = {x:tuple(d[x]) for x in d}

to convert the lists in the new dic to tuples

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error code 0x80070570

2015-09-30 Thread Denis McMahon
On Wed, 30 Sep 2015 23:06:13 +0530, Rusiri Jayalath wrote:

> Error code 0x80070570 appears when installing python 3.5.0 (32-bit)
> setup for my windows 8.1 system. Please help me to solve this problem.

This seems to be a windows error, not a python issue. Try google.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about regular expression

2015-09-30 Thread Denis McMahon
On Wed, 30 Sep 2015 11:34:04 -0700, massi_srb wrote:

> firstly the description of my problem. I have a string in the following
> form: .

The way I solved this was to:

1) replace all the punctuation in the string with spaces

2) split the string on space

3) process each thing in the list to test if it was a number or word

4a) add words to the dictionary as keys with value of a default list, or
4b) add numbers to the dictionary in the list at the appropriate position

5) convert the list values of the dictionary to tuples

It seems to work on my test case:

s = "fred jim(1) alice tom (1, 4) peter (2) andrew(3,4) janet( 7,6 ) james
( 7 ) mike ( 9 )"

d = {'mike': (9, 0), 'janet': (7, 6), 'james': (7, 0), 'jim': (1, 0), 
'andrew': (3, 4), 'alice': (0, 0), 'tom': (1, 4), 'peter': (2, 0), 'fred': 
(0, 0)}




-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Check if a given value is out of certain range

2015-09-29 Thread Denis McMahon
On Tue, 29 Sep 2015 10:16:04 +0530, Laxmikant Chitare wrote:

> Is there any similar elegant way to check if a value is out of certain
> range?

What about:

if not (0 < x < 10):

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-25 Thread Denis McMahon
On Fri, 25 Sep 2015 12:03:43 -0700, Cody Cox wrote:

> #Design a modular program that asks the user to enter a distance in
> kilometers and then covert it to miles # Miles = Kilometers * 0.6214

#!/usr/bin/python

# main calls the input routine to get the km value, then 
# calls the conversion routine to convert the km value
# to miles, then prints the output

def main():
km = get_kms()
mi = convert_km_mi(k)
print "{} Km is {} miles.".format(km, mi)

# get_float_input() reads a float input using the supplied
# prompt.

def get_float_input(prompt):
return float(input(prompt))

# Get kms uses the generic get_float_input to read a km
# value

def get_kms():
return get_float_input("Enter Kms: ")

# generic conversion function

def convert_float_a_b(a, factor):
return float(a * factor)

# convert km_mi uses the generic converter
# to convert km to miles

def convert_km_mi(km):
return convert_float_a_b(km, 0.6214)

# now call main to kick it all off

main()

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python, convert an integer into an index?

2015-09-23 Thread Denis McMahon
On Tue, 22 Sep 2015 14:43:55 -0700, Chris Roberts wrote:

> results = 134523  #(Integer)

This appears to be an integer expressed (presumably) in base 10 with 6 
digits

> Desired:
> results = [1, 2, 3, 4, 5, 2, 3]   #(INDEX)

This appears to be a python list of 7 elements, with the first and the 
the third through seventh elements corresponding to the first and the 
second through sixth most significant digits respectively of the 
previously discussed integer.

I can't actually see any direct method of creating the list given from 
the number given.

However, if I understand the intent of the question you meant to ask, you 
might find that the following code does something interesting:

x = 9876543210
y = []

while x > 0:
y.append(x % 10)
x = int(x / 10)

y = list(reversed(y))
print y

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Einstein's Riddle

2015-09-20 Thread Denis McMahon
On Sat, 19 Sep 2015 21:27:47 -0600, Michael Torrie wrote:

> I read once of a university that, upon decomissioning a mainframe, found
> a job that had been in the queue for many years but had never run.
> Probably some poor grad student's job.

Somewhere there's a computer sitting in the corner of a Pentagon office 
that makes an unanswered modem call to a telephone somewhere once a week.

One day, someone will realise they have no idea why, and shut the 
computer off.

When the doomsday silo on the other end stops receiving it's weekly 
"everything is ok" message, it's going to nuke Beijing and Moscow .

(I really really really hope that this is indeed fiction!)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Add items from a python list to a javascript array

2015-09-19 Thread Denis McMahon
On Sat, 19 Sep 2015 00:25:20 -0700, Darryl Doherty wrote:

> I have a kiosk for digital signage which has a html index file with a
> javascript which rotates through other html files using iframe at timed
> intervals. What I want to do is edit the array in the index file with
> Python to add and remove the HTML file paths from the array. I have a
> list of all file paths in the python list, so I want to select a path
> from the list and add it to the javascript array. In addition I want to
> be able to use python to remove file paths from the array when needed.
> I'm new to Python so some code examples would be appreciated. Thanks.

I'm going to assume that the whole web page is being generated by python 
code with the web server, and that the list of files is available in the 
python code at the time of web page generation.

First of all, you need to create a python list of the file names to use. 
This will use whatever the current data is when the web page is generated.

Secondly, you need to write this list to a suitable javascript variable 
when you construct the web page. Assuming that all the file paths are 
standard ascii with no spaces etc in them, say you have a python list 
like this:

Here is a very simple code example for a method (and there are others) of 
embedding such a list of paths held in python within a javascript 
variable inside a script element in a web page:

#!/usr/bin/python

files = ["/a/a.htm", "/a/b.htm", "/a/c.htm"]

page = "\n"

fmt = "var frames=Array({});\n"

page += fmt.format(",".join(map(lambda x:'"'+x+'"', files)))

page += "\n"

print page


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to use the returned telnet object after creating the telnet session.

2015-09-13 Thread Denis McMahon
On Sun, 13 Sep 2015 00:38:03 -0700, manjunatha.mahalingappa wrote:

> Assume that I will pass IP and port information from a function to open
> the telnet session. have opened the telnet session and after opening the
> telnet session I returned telnet object to calling function.
> 
> Now in the calling function If I use that object to read or write to
> terminal I'm getting ERROR "AttributeError: 'NoneType' object has no
> attribute 'read_very_eager'".

My best guess would be that something failed and has returned None 
instead of the object / class you're expecting.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Phone Tree

2015-09-13 Thread Denis McMahon
On Sun, 13 Sep 2015 07:39:23 -0700, Azureaus wrote:

> Does anyone have any ideas for a more elegant solution? My thoughts are
> that I could use a tree data structure and hence make traversing the
> tree recursive based on yes or no answers. I'm happy to put the time in
> to explain these more complex ideas, I'm just hoping those with more
> expertise than myself could either help verify the idea or suggest
> alternatives.

The trick is to separate the data and the processing.

Each question has a yes, no answer, so start with a dictionary of data 
tuples (you could use a list, but using a dictionary makes the 
relationship slightly easier to walk through):

questions = {
1: (q1, response if yes, response if no),
2: (q2, response if yes, response if no)  }

The responses can be either a number of another question, or a result 
text.

Then your algorithm is broadly:

x = 1:
while x is numeric:
ask questions[x][0]
if answer is "yes":
x = questions[x][1]
if answer is "no":
x = questions[x][2]
answer is x

You can use a list instead of a dictionary, just remember 0 indexing when 
you're working out which question leads to which next question.

This way also makes for an interesting talking point about separating 
data and code, especially given the multiple if statements issue.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: convert element in a list to float

2015-09-13 Thread Denis McMahon
On Sun, 13 Sep 2015 23:02:55 +0200, Laura Creighton wrote:

> In a message of Sun, 13 Sep 2015 12:55:13 -0700, forums...@hotmail.com
> writes:
>>
>>For starters, I googled and saw a plethora of writings on how to convert
>>an entire list from string to float.   My interest is on select elements
>>in the list.  The output from the print statement: print scenarioList
>>  
>>is as follows
>>
>>[ '300', '"N"', '1140', '"E"' ]
>>
>>I need to convert the first and third element to float.
>>  lat = ( float ) scenarioList [ 0 ]
>>  lon = ( float ) scenarioList [ 2 ]
>>
>>fails (invalid syntax).  How can I achieve my objective.
>>
>>Thanks in advance
> 
> Does this help?
> 
>>>> l = [ '300', '"N"', '1140', '"E"' ]
>>>> [float(l[0]), l[1], float(l[2]), l[3]]
> [300.0, '"N"', 1140.0, '"E"']

Here's a method that will convert any value in a list that can be made a 
float into a float, and (I think) should leave all others as they are. It 
users a helper function and a list comprehension.

>>> def tofloat(x):
... try:
... return float(x)
... except ValueError:
... return None
... 
>>> l = [ '300', '"N"', '1140', '"E"' ]
>>> l = [ tofloat(x) or x for x in l ]
>>> l
[300.0, '"N"', 1140.0, '"E"']

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random MAC generator error

2015-09-12 Thread Denis McMahon
On Sun, 13 Sep 2015 00:50:24 +0530, Robert Clove wrote:

> import random #
> 
> global mac1 
> def randomMAC():
>   mac = [ 0x00, 0x16, 0x3e,
>   random.randint(0x00, 0x7f), random.randint(0x00, 0xff),
>   random.randint(0x00, 0xff) ]
>   return ':'.join(map(lambda x: "%02x" % x, mac))
> #
> print randomMAC()
> 
> for x in range(1,11):
> 
>  mac1 = randomMAC()
> 
>  print mac1
> 
> I got the following random mac generator script from the net (simple
> google search)
> 
> i want to use random mac in one of mine script.What i need is
> mac1=randomMAC() should give mac value to mac1 that i use in a function
> and this runs in a loop.

And you haven't told us what the "error" you're posting about is?

When I ran the code I got the following result:

00:16:3e:21:da:a4
00:16:3e:57:be:d2
00:16:3e:6b:e5:ae
00:16:3e:54:0e:f0
00:16:3e:57:5e:50
00:16:3e:21:99:6b
00:16:3e:12:e6:05
00:16:3e:53:02:6d
00:16:3e:79:17:1b
00:16:3e:02:ff:b8
00:16:3e:4e:ff:0d

Observation: No point in declaring mac1 as global in the global scope.

Is it possible that you've tried to run python 2.x code on python 3.x and 
hit an error due to 'print x' -> 'print(x)'?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Context-aware return

2015-09-10 Thread Denis McMahon
On Fri, 11 Sep 2015 03:54:14 +1000, Steven D'Aprano wrote:

> If I did this thing, would people follow me down the street booing and
> jeering and throwing things at me?

Yes

>>> x = func()
>>> x
>>> func()
>>> print x == func() 
>>> assert x == func()

Would you expect the last two calls to func() to return 999 or "Awesome"? 
Why? What is the material difference if any between interpreter (a) 
displaying the return value and (b) comparing the return value with 
another value.

Debugging nightmare!

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hi am new to python

2015-09-09 Thread Denis McMahon
On Tue, 08 Sep 2015 17:44:26 -0500, Nassim Gannoun wrote:

> My question is in a while loop; how do l sum all the numbers in the
> given list (list_a)?

You don't normally use a while loop or a counter to iterate over a list. 
Such a question should only be used as a precursor to discussing better 
methods of achieving the required result.

While loop:

> sum_a = 0 
> i = 0 
> while i < (len(list_a)):
> sum_a += list_a[i]
> i += 1
> print(sum_a)

Better, use a for loop:

s = 0
for i in list_a:
s += i
print (s)

Even better, use sum():

s = sum(list_a)
print (s)

And if you only want to display the answer:

print (sum(list_a))

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lesson 39 of Learning Python the Hard Way hangs

2015-09-09 Thread Denis McMahon
On Wed, 09 Sep 2015 20:45:57 +, John Gordon wrote:

> In any case, I saved your code and ran it, and did not get an error.

+1

I think "Execution Succesful!" might be coming from his IDE?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python

2015-09-07 Thread Denis McMahon
On Sun, 06 Sep 2015 16:09:42 -0700, babi pepek wrote:

> I wand update

update

There, now you have update.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can anyone help me run python scripts with http.server?

2015-09-06 Thread Denis McMahon
On Sun, 06 Sep 2015 23:23:14 +1000, Chris Angelico wrote:

> WSGIScriptAlias / /path/to/scripts/MinstrelHall/mh.wsgi

One wonders if the OP has mod_wsgi installed.

https://code.google.com/p/modwsgi/wiki/WhereToGetHelp might be useful too.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to compare lists

2015-09-01 Thread Denis McMahon
On Tue, 01 Sep 2015 07:08:48 +0200, Jahn wrote:

> 1.
> How can I save 256 lists, each list has 32 values( hexadecimal numbers)
> 2.
> How to compare the saved lists with another 256 lists ( that are read
> online and have the same structure as the list one)?
> ( the first list must be saved in the  previous step)

Develop code that works for smaller lists. Test it. When it works, try it 
on bigger lists.

For example, you seem to have two very separate requirements:

Save (and presumably read) a list. My favourite mechanism for saving data 
structures is json. Read the json module help. Gogling "python store list 
data" might bring you other suggestions.

Comparing two lists. One method is to step through the members of each 
list in turn, and see if it is in the other list. Another method is to 
check that the lists are the same length, and have the same value at each 
element position. Both may have flaws depending on the exact nature of 
your requirement - and what you consider to be identical lists. Googling 
"python compare lists" may lead you to some ideas.

When you have written and tested your code, if it's not doing what you 
expect, you could come back here and post your code with a description of 
what you think it should do, what it actually does, and why you think 
that's wrong, and we'll try and help you fix.

What we won't do is write your application from scratch.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I download XML data from the web and save, in as CSV or TXT delimitation?

2015-08-19 Thread Denis McMahon
On Wed, 19 Aug 2015 04:57:44 -0700, ryguy7272 wrote:

[stuff]

Downloading xml from the web is easy

writing csv or txt is easy

The tricky bit is converting the xml you have into the csv or text data 
you want.

And to do that, you need to understand the structure of the xml data that 
you are receiving and how the xml nodes and their attributes and values 
should be mapped into the csv file you want to create.

Unfortunately I don't think that there is a single standard mechanism for 
doing that bit, although there are some tools and libraries that can help.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to model government organization hierarchies so that the list can expand and compress

2015-08-15 Thread Denis McMahon
On Thu, 13 Aug 2015 12:10:12 -0700, Alex Glaros wrote:

 What would the data model look like for this?

Define an organizational unit. Give it a unique name. Give it a list of 
superiors and a list of subordinates.

government = {

'president' : { 'superiors' : [], 'subordinates' : ['jcs', 'cia', 'fbi', 
'nsa', 'treasury', 'nasa' . ] },

'jcs' : { 'superiors': ['president', 'congress', 'senate', 'treasury'], 
'subordinates' : ['army', 'navy', 'air force', 'jsoc'] }, 

'navy' : { 'superiors' : ['jcs', 'nsa', 'cia'], 'subordinates' : 
['seals', 'marines', 'pacific fleet' ] }, 

}

The multiple parenting means that you need to use something as 
references. You can't represent the hierarchy as a simple tree, because 
in a simple tree a node only has one parent.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-13 Thread Denis McMahon
On Thu, 13 Aug 2015 02:41:55 -0700, Ltc Hotspot wrote:

 How do I define X?

 What are the values of X  Y from the code as follows:

 # print time: ['From', 'stephen.marqu...@uct.ac.za', 'Sat', 'Jan', '5', 
'09:14:16', '2008']

This is the data you need to look at.

X is the position in the printed list of the time information. If you can 
not determine the correct X value by inspection of the list having been 
told which element it should be, then you need to go back to the python 
documentation and read about the list data object and how elements within 
the list are referenced. Once you understand from the documentation how 
to reference the list elements, you will be able to determine by 
inspection of the above list the correct value for X.

Y is the position of the hours element within the time information when 
that information is further split using the ':' separator. You may need 
to refer to the documentation for the split() method of the string data 
object. Once you understand from the documentation how the string.split() 
function creates a list, and how to reference the list elements (as 
above), you will be able to determine by inspection the correct value for 
Y.

This is fundamental python knowledge, and you must discover it in the 
documentation and understand it. You will then be able to determine the 
correct values for X and Y.

Note that the code I posted may need the addition of a line something 
like:

if line.startswith(From ):

in a relevant position, as well as additional indenting to take account 
of that addition.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-13 Thread Denis McMahon
On Wed, 12 Aug 2015 16:46:32 -0700, Ltc Hotspot wrote:

 How do I define X?
 
-
 Traceback reads:
 
  10 f  = open(filename,'r')
  11 for l in f:
 --- 12  h = int(l.split()[X].split(':')[Y])
  13  c[h] = c[h] + 1 14 f.close()
 
 NameError: name 'X' is not defined

If you read the text that I posted with the solution, it tells you what X 
and Y are. They are numbers that describe the positions of elements in 
your input data.

This absolute refusal by you to read any explanations that are posted are 
exactly why you will never be a good programmer. To become a good 
programmer you need to read and understand the explanations.

In the post with that code example, I wrote:

It also assumes that there is a timestamp of the form hh:mm:ss that 
always appears at the same word position X in each line in the file, and 
that the hours record always at position Y in the timestamp.

You have to replace X and Y in that line with numbers that represent the 
positions in the lists returned by the relevant split commands of the 
actual text elements that you want to extract.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-12 Thread Denis McMahon
On Wed, 12 Aug 2015 11:35:03 -0700, Ltc Hotspot wrote:

 How do I define time in the revised code ?

I'm guessing that you have a line of input like:

word word word timestamp word word word word

and that timestamp looks something like:

hh:mm:ss

Start of by defining a list with 24 elements all integer 0.

Open the file.

for each line, first you trim it, then you split it on spaces, you take 
the relevant element of the list of bits as the timestamp, and then you 
split that on the ':' character, then you take the int value of the hours 
element of that list and use that as the index into your list to update 
the count.

Processing a file takes very few lines of actual code. There is no need 
to use a dictionary, you can do it with a single list and no sorting. 
This is a solution in 8 lines, and assumes that the actual requirement is 
to count, for each hour, the number of log messages generated in that 
hour, and then display, listed by hour, the number of messages generated 
in each hour during the day. It also assumes that there is a timestamp of 
the form hh:mm:ss that always appears at the same word position X in each 
line in the file, and that the hours record always at position Y in the 
timestamp.

c = [0 for i in range(24)]
f = open(filename,'r')
for l in f:
h = int(l.strip().split()[X].split(':')[Y])
c[h] = c[h] + 1
f.close()
for i in range(24):
print '{:02d} {}'.format(i, c[i])

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-12 Thread Denis McMahon
On Wed, 12 Aug 2015 09:29:50 -0700, Ltc Hotspot wrote:

 Using the attached file of a  diagram as a frame, why is there an
 attribute message?

Perhaps you should read the message. It's very clear.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-12 Thread Denis McMahon
On Wed, 12 Aug 2015 12:05:37 -0700, Ltc Hotspot wrote:

Have a look at assignment_10_2_v_06.py.

 What should I look at assignment_10_2_v_06.py.:

You shouldn't. You should instead approach your tutor and tell him you 
are too stupid to learn computer programming[1], and can you please 
transfer to floor-scrubbing 101.

[1] You have repeatedly ignored advice and instructions that you have 
been given. This is de-facto proof that you are not capable of learning 
to program computers.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-12 Thread Denis McMahon
On Tue, 11 Aug 2015 22:03:05 -0700, Ltc Hotspot wrote:

 Question: What sorted function should I write to produce the desired
 output, below:

Me, I'd start by declaring a dictionary to hold the data:

counts = { {:02d}.format(h):0 for h in range(24) }

Then I'd parse the strings in the log file(s), incrementing counts[x] 
where x is the hour field of the timestamp.

Then I'd create a list of tuples:

ncounts = [(k,v) for k,v in counts.items()]

sort it by the hour field:

ncounts.sort(key = lambda x: x[0])

and print it:

for x in ncounts:
print x[0], x1

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: AttributeError

2015-08-12 Thread Denis McMahon
On Tue, 11 Aug 2015 17:01:24 -0700, Ltc Hotspot wrote:

 What is the list equivalent to line 12: ncount.sort(reverse=True)
 
 count = dict()
 fname = raw_input(Enter file name: )#
 handle = open (fname, 'r')#
 for line in handle:
 if line.startswith(From ):
 address = line.split()[5]
 line = line.rstrip()
 count[address] = count.get(address, 0) + 1

At this point, count seems to be a dictionary of address: count of lines

 for key,val in count.items():
 ncount = (key,val) ncount.sort(reverse=True) print key,val

ncount is a single key-value pair. Why are you trying to sort ncount?

Do you want results ordered by count?

First, change your dictionary into a list of tuples:

ncount = [(a,c) for a,c in count.items()]

Then sort ncount on the second field of the tuple:

ncount.sort(key = lambda x: x[1], reverse=True)

print ncount

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Lea 2.1.2

2015-08-04 Thread Pierre Denis
I am pleased to announce the release of Lea 2.1.2!
There are NO known open bug in this version.
 
Please note the migration of the project to Bitbucket (see URL below), due to
the approaching end of Google Code.

What is Lea?

Lea is a Python package aiming at working with discrete probability
distributions in an intuitive way. It allows you to model a broad range of
random phenomenons, like dice throwing, coin tossing, gambling, weather, etc. It
offers several modelling features of a PPL (Probabilistic Programming Language),
including bayesian inference and Markov chains. Lea is open-source (LGPL) and
runs on Python 2 or 3. See project page below for more information
(installation, tutorials, examples,  etc).

Lea project page

https://bitbucket.org/piedenis/lea

Download Lea (PyPI)
---
http://pypi.python.org/pypi/lea

With the hope that Lea can make your fun less uncertain,

Pierre Denis
-- 
https://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: Logical Query JSON

2015-07-31 Thread Denis McMahon
On Fri, 31 Jul 2015 08:07:23 +0200, dieter wrote:

 Keep in mind that Python is a (more or less) general purpose language
 which does not know about jsonquery. It has and, or and not
 operators (defined in the language reference) *BUT* these are not the
 operators you are looking for.
 You will need a special jsonquery extension (search
 http://pypi.python.org; to find out whether there is something like
 this)
 which would provide appropriate support.

Actually it's not too hard. You can construct the json query syntax 
fairly easily from python once you understand it:

 import json

 query = json.dumps( { $and:[ { $gt: {age: 5} }, { $not: 
{name: curly} } ] } )

 query

'{$and: [{$gt: {age: 5}}, {$not: {name: curly}}]}'

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logical Query JSON

2015-07-30 Thread Denis McMahon
On Thu, 30 Jul 2015 06:32:01 -0700, subhabrata.banerji wrote:

 I am trying to query JSON with Logical operators.

Your post was an excellent example of asking for help without explaining 
what your problem was at all.

Please:

- show an example of what you tried;

- give the results you expected;

- show the results you actually got.

COPY and PASTE the code and results, do not re-type them, or summarise
them.

I found the examples quite easy to follow to create json queries, 
although as I don't have a db2 etc setup here iI'm unale to try feeding 
the resulting json query into a database to see what comes out.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Find Minimum for element in multiple dimensional array

2015-07-23 Thread Denis McMahon
On Wed, 22 Jul 2015 15:54:06 -0700, Robert Davis wrote:

 Given a set of arrays within an array how do I find the arrays with the
 minimum values based on two elements/columns in the array? Those two
 elements/columns are the destination zip code and distance.

create a new dictionary

for each source/destination pair in your list of source destination pairs:

if the destination zip code is not in the new dictionary, copy the entry 
to the new dictionary keyed on the destination zip code.

if the destination zip code is in the new dictionary, copy the entry to 
the new dictionary keyed on the destination zip code only if the distance 
is less than the distance of the current entry in the new dictionary.

convert the values of the new dictionary to a list.

write the list as csv

Here is an example, note that I'm just using 2 bits of data, the first 
bit of data in each sub list simulates the destination area code, and the 
second simulates the distance from the associated source zip code. 
Obviously you need to adjust these to match the actual parameters in your 
list of lists.

import csv

info = [['a',15],['a',17],['a',21],['b',96],['b',45],['b',38],['c',71],
['c',18],['c',54]]

tmp = {}

for thing in info:
if thing[0] in tmp:
if thing[1]  tmp[thing[0]][1]:
tmp[thing[0]] = thing
else:
tmp[thing[0]] = thing

with open(output.csv, wb) as f:
writer = csv.writer(f)
writer.writerows(tmp.values())

and lo:

$ cat output.csv
a,15
c,18
b,38
$ 


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: unexpected output while using list(and nested dictionary)

2015-07-22 Thread Denis McMahon
On Wed, 22 Jul 2015 17:09:21 -0500, max scalf wrote:

 I have posted a question on stack overflow for better readability ...
 but is intended for python list Please see question below...

It's quite obvious that your list and dictionary processing is not doing 
what you think it is.

However, the question you have posted is a long and complex one. Perhaps 
you could reduce it to a simpler example.

Your problem seems to be that in a list of dictionaries that is itself 
several levels of dictionary deep, you only see a single dictionary when 
you do the json conversion.

perhaps you could try a simpler structure, such as:

import json

d1 = {'c':'0.0.0.0', 'f':'1', 'p':'icmp', 't':'1'}
d2 = {'c':'1.1.1.1', 'f':'22', 'p':'tcp', 't':'22'}
l = [d1,d2]
d3 = {'g': 'text', 's': l}
d4 = {'p': d3}
d5 = {'r': d4}
print d5
print json.dumps(d5)

This correctly gives the following output, so I guess your problem is in 
how you create the list of dictionaries (l in my example).

{'r': {'p': {'s': [{'p': 'icmp', 'c': '0.0.0.0', 't': '1', 'f': '1'}, 
{'p': 'tcp', 'c': '1.1.1.1', 't': '22', 'f': '22'}], 'g': 'text'}}}

{r: {p: {s: [{p: icmp, c: 0.0.0.0, t: 1, f: 1}, 
{p: tcp, c: 1.1.1.1, t: 22, f: 22}], g: text}}}

I would suggest you look closely at your makesg function, and the data 
that you are actually feeding to it and how it is using that data.

makesg expects a collection as the third param, you seem to be passing it 
a list of one port element.

makesg returns a list of sg, with an entry for every port. You then use 
this as tsg.SecurityGroupIngress. However, the way your code is written, 
you process all the 'i' in mylist, and for each 'i' overwrite 
tsg.SecurityGroupIngress with a new single element list sg from makesg.

I suspect you've refactored some code from processing a list of things 
inside a function to processing them in the main body, or vice versa, or 
have just got confused about what you're processing where.

I suggest that you rename your makesg function to makesgr, and have it 
return the rule appropriate to one entry in mylist.

Then you can append the returned rule to tsg.SecurityGroupIngress with:

tsg.SecurityGroupIngress.append(mksgr(param,param,param))

Alternatively, pass mylist to makesg, and return the whole list of rules.

tsg.SecurityGroupIngress = mksg(mylist)

Either method will require some rewriting of both the mksg[r] function 
and the main code to work together, but as the existing problem is that 
they don't seem to work together to create the data structure you expect 
them to create, that's not going to be a bad thing.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


flipping string order

2015-07-19 Thread Denis McMahon
On Sun, 19 Jul 2015 17:35:03 +0100, MRAB wrote:

 rsplit - one line.

def lastWordFirst(s):
return  .join(reversed(s.rsplit( , 1)))

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need assistance

2015-07-18 Thread Denis McMahon
On Sat, 18 Jul 2015 12:35:10 +0200, Sibylle Koczian wrote:

 Am 18.07.2015 um 02:40 schrieb Denis McMahon:

 Having a list of words, get a copy of the list in reverse order. See
 the reversed function (and maybe the list function).

 That won't really help, because the desired order is, with the example
 the OP used: Sirna Daniel Craig. So here indexing is necessary, but
 indexing of the list elements, not of the characters in the string.

Oh, then it's even easier, yes, it's mainly a case of list indexing.

1) Split the original string into a list of words (string.split() method)
2) create a sublist (s1) of the last element
3) create another sublist (s2) of the first to penultimate elements
4) combine the two sublists
5) use the string.join() method to combine the sublist elements into a 
single string

I think most pythonistas would probably combine steps 2 through 4 in a 
single line of code, possibly even steps 2 through 5.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need assistance

2015-07-17 Thread Denis McMahon
On Thu, 16 Jul 2015 19:15:38 -0700, craig.sirna wrote:

 The assignment wants us to take a users first, middle and last name in a
 single input ( name=('enter your full name: )).
 
 Then we must display the full name rearranged in Last, First Middle
 order.

To generate a list of words from a string, split the string up on the 
spaces between words. See the split method of strings.

Having a list of words, get a copy of the list in reverse order. See the 
reversed function (and maybe the list function).

Note - reversed returns an iterable, list will convert the iterable to a 
list.

To join the elements of a list into a string, see the join method of 
strings.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: normalizing a value

2015-07-01 Thread Denis McMahon
On Wed, 01 Jul 2015 17:12:36 -0700, bvdp wrote:

 Not sure what this is called (and I'm sure it's not normalize). Perhaps
 scaling?
 
 Anyway, I need to convert various values ranging from around -50 to 50
 to an 0 to 12 range (this is part of a MIDI music program). I have a
 number of places where I do:
 
while x  0: x += 12 while x = 12: x -= 12
 
 Okay, that works. Just wondering if there is an easier (or faster) way
 to accomplish this.

Are you sure it works? Do you simply want to reduce it to the arbitrary 
range, or do you want to also retain the relationship between different x 
values such that if x1  x2, f(x1)  f(x2)?

Consider the following x values:

-11, -12, -13, 11, 12, 13

-11 - 1
-12 - 0
-13 - 11
11 - 11
12 - 0
13 - 1

So -13 gives the same output value as 11 in your current code. Is this 
what you want?

You could try the following:

# step 1, limit x to the range -50 .. 50
if x  -50:
x = -50.0
ix x = 50:
x = 50.0
# step 2, scale x to the range 0 .. 12
x = x * 0.12 + 6.0

If you want an integer value, you need to determine which method is most 
relevant. I would suggest rounding.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to fix TypeError: format requires a mapping

2015-07-01 Thread Denis McMahon
On Wed, 01 Jul 2015 14:57:14 -0700, hinaimran.mehr wrote:

 I am pulling my hair with this problem right now,
 
 I have the following Data structure
 
 [OldSample {u'counter_name': u'cpu_util', u'user_id': u'id',
 u'resource_id': u'id', u'timestamp': u'2015-06-30T15:53:55',
 u'counter_volume': 0.043}]

This isn't a print out of any python data structure that I recognise. I 
assume you have a list of dictionaries, and that each dictionary 
represents one sample.

 I need to make it something like this to put in EON pubnub charting
 libaray (see link: http://www.pubnub.com/developers/eon/chart/spline/)
 
 message: {
   columns: [
 [y: 0.043, x: 2015-06-30T15:53:55],
 [y: 0.045, x: 2015-06-30T15:53:55]
   ]
 
 Now I have the following code
 
 data = cclient.samples.list(meter_name ='cpu_util', limit=2)
 
 result_rows = []
 for row in data:
  formatted = [y: %(counter_volume)0.3f, x:
  %(timestamp)s] % (row)
  result_rows.append(formatted)
  
  print(',\n'.join(result_rows))
 
 
 clean_json(data)

I assume you want the output as json.

The solution may be to put the data into a suitable structure and dump 
the structure to json.

import json

thing = {}
msg = {}
cols = []

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)


-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to stacked values with one header)

2015-06-29 Thread Denis McMahon
On Sun, 28 Jun 2015 17:07:00 -0700, Ned Batchelder wrote:

 On Sunday, June 28, 2015 at 5:02:19 PM UTC-4, Denis McMahon wrote:

 things
   thingstring 3/thing
   thingstring 2/thing
   thingstring 1/thing
 /things

 Each thing is just a member of the collection things, the xml does
 not contain sufficient information to state that things is an ordered
 collection containing a specific sequence of thing.
 
 You are right that XML does not specify that things is an ordered
 collection.
 But XML does preserve the order of the children.  There are many XML
 schema that rely on XML's order-preserving nature.

But what we *don't* know is whether the order of the umpteen identical 
tags in the XML has any significance in terms of the original data, 
although the OP seems intent on assigning some significance to that order 
without any basis for doing so.

Consider the following tuple:

t = (tuplemember_1, tuplemember_2,  tuplemember_n)

Can we safely assume that if the tuple is ever converted to xml, either 
now or at some future date using whatever the code implementation is 
then, that the order of the items will be preserved:

tuple
  itemtuplemember_1/item
  itemtuplemember_2/item

  itemtuplemember_n/item
/tuple

And if we're reading that xml structure at some point in the future, is 
it safe to assume that the tuple members are in the same order in the xml 
as they were in the original tuple?

For sanity item should have an attribute specifying the sequence of the 
item in it's tuple.
-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to stacked values with one header)

2015-06-28 Thread Denis McMahon
On Sun, 28 Jun 2015 09:46:36 +0200, Stefan Behnel wrote:

 Denis McMahon schrieb am 26.06.2015 um 09:44:
 xml data is an unordered list, and are trying to assign an order to it.
 
 If the xml data was ordered, either each tag would be different, or
 each tag would have an attribute specifying a sequence number.
 
 XML is not unordered. The document order is well defined and entirely
 obvious from the data. Whether this order is relevant and has a meaning
 or not is, however, not part of XML itself but is left to the semantics
 of the specific document format at hand. Meaning, XML document formats
 can choose to ignore that order and define it as irrelevant. That
 doesn't mean it's not there for a given document, but it may mean that a
 re-transmission of the same document would be allowed to use a different
 order without changing the information.
 
 This property applies to pretty much all structured data formats and not
 just XML, by the way, also to CSV and other tabular formats.

The point I am trying to make to OP is that the following two XML 
fragments define the same data:

things
  thingstring 1/thing
  thingstring 2/thing
  thingstring 3/thing
/things

and:

things
  thingstring 3/thing
  thingstring 2/thing
  thingstring 1/thing
/things

Each thing is just a member of the collection things, the xml does not 
contain sufficient information to state that things is an ordered 
collection containing a specific sequence of thing.

Mechanisms such as node.firstChild and node.getChild(x) are all very well 
for manipulating the xml, but any specific ordering of the original data 
should be carried out by using an appropriate attribute of the ordered 
data elements at the point where the xml representation is created.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to stacked values with one header)

2015-06-26 Thread Denis McMahon
On Thu, 25 Jun 2015 11:39:53 -0700, kbtyo wrote:

 My question can be found here:
 
 http://stackoverflow.com/questions/31058100/enumerate-column-headers-in-
csv-that-belong-to-the-same-tag-key-in-python

I suggest you look on stack overflow for the answer.

You appear to have failed to comprehend (again) the fact that the xml 
data is an unordered list, and are trying to assign an order to it.

If the xml data was ordered, either each tag would be different, or each 
tag would have an attribute specifying a sequence number.

If the original data is ordered, then you need to go back to the code 
that creates the xml and make it add the ordering information to the xml 
(ideally as an attribute of the tags concerned) to specify the order.

You can not reliably and with any certainty of being accurate try and 
assign some sequence to the list of similarly named elements simply from 
their position in the list.

You don't know if the code that creates the xml is walking the array like 
this:

i = sizeof(arr);
while (i--) addXmlElement(arr[i]);

or like this:

for (i = 0; i  arr.len; i++) addXmlElement(arr[i]);

or even like this:

while (sizeof(arr)) addXmlElement(popArrElement(arr[sizeof(arr)/2]));

Granted the latter is unlikely and perverse, but still not wholly 
impossible. More perverse and less likely mechanisms are also available.

But my point remains - that if the ordering data is not passed into the 
xml, then you can not magically add it when you later use the xml.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue24504] os.listdir() error if the last folder starts not with the capital letter

2015-06-24 Thread Denis Gordeev

New submission from Denis Gordeev:

My code is:
mypath = 'Z:\Pr Files\norma'
file_list = [ f for f in listdir(mypath) if isfile(join(mypath,f))]

Error:
Traceback (most recent call last):
  File C:\Documents and Settings\Administrator\Desktop\uni\click zhenilo 
workshop\noise.py, line 13, in module
file_list = [ f for f in listdir(mypath) if isfile(join(mypath,f))]
WindowsError: [Error 123] The filename, directory name, or volume label syntax 
is incorrect: 'Z:\\Pr Files\norma/*.*'

It works all right, if the path is:
mypath = 'Z:\Pr Files\Norma'

--
components: Windows
messages: 245777
nosy: Denis Gordeev, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: os.listdir() error if the last folder starts not with the capital letter
versions: Python 2.7

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue24504
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: JSON Object to CSV File Troubleshooting

2015-06-23 Thread Denis McMahon
On Sun, 21 Jun 2015 16:56:27 -0700, Sahlusar wrote:

 Here is an example XML document that I am working with:

 You are welcome to contribute and provide me with feedback. Thank you
 for your continued feedback and guidance.

Your XML is invalid! You have a closing MO tag with no opening tag.

 This is the output that I seek:

  a,b   // headers 
  b,1 // data row 1 
  b,2 // data row 2

I assume from this that where you have a list of identical elements at 
the deepest nesting level of the XML file, you require one CSV record for 
each element in that list, and that you want all higher level element 
values and attributes duplicated in each CSV record.

I assume that you want to use the tag name of each element as the 
identifier for the text content of the element (where there is any), and 
that where an element has no text content, a 0 value is appropriate.

I also assume that as long as the relationship between the headers and 
the data is correct, it does not matter what order the headers are in, ie 
the data and headers can both be sorted by the header.

The output of my code generated once I had corrected your broken XML by 
inserting an 'MO' opening tag between the 'Response' opening tag and the 
'MonthDayCount' opening tag can be seen at:

http://www.sined.co.uk/tmp/xml_to_csv.txt

This was generated from xml file:

http://www.sined.co.uk/tmp/xml_data.txt

If you want the code that produced it, we can discuss fees, it took a few 
hours and for consultancy like this I expect a few 10s of $ per hour.

There may be a generic method to do what you want involving parsing the 
xml to a nested dictionary / list data object, and then flattening that 
object, but I don't see that generating you one line of CSV for each 
Int32 in MonthDayCount.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV file

2015-06-21 Thread Denis McMahon
On Sun, 21 Jun 2015 06:57:01 -0700, sahluwalia wrote:

 On Sunday, 21 June 2015 02:47:31 UTC-4, Denis McMahon  wrote:
 On Wed, 17 Jun 2015 08:00:11 -0700, Saran A wrote:
 
  I would like to have this JSON object written out to a CSV file so
  that the keys are header fields (for each of the columns) and the
  values are values that are associated with each header field.
 
  {
  CF: {
 ...
  CF: Fee,
 
 Your json object seems to have the same key used for two elements at
 the same level, are you sure this is legal json?

 I converted this from an XML file given to me from a third party. It is
 as is. I am not sure what you mean by valid; that is a very subjective
 measure for any form of quantitative or qualitative data.

Put it this way, when I feed your json object into a jason lint, the 
output is the following:

{
CF: Fee,
ID: 2
}

The second occurrence in the parent object of name CF with a value of 
string literal Fee overwrites the earlier name CF whose value is (in 
python terms) a dictionary or (in json terms) an object.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV File Troubleshooting

2015-06-21 Thread Denis McMahon
On Mon, 22 Jun 2015 00:55:11 +0300, Joonas Liik wrote:

 In xml for instance this is valid:

 a
  b1/b
 /a
 .. and so is this:
 a
  b1/b b2/b
 /a

What the OP needs to do is sit down with the XML and work out how it 
needs to be represented in CSV terms, and then code that transformation, 
but it appears that he's not listening.

ie, does your xml:

a
  b1/b b2/b
/a

translate to CSV:

a,b   // headers
b,1 // data row 1
b,2 // data row 2

or to CSV:

a, b, b // headers
, 1, 2  // data row

or even CSV:

b   // headers
1 // data row 1
2 // data row 2

If he can't codify that in a consistent manner across all the XML he 
wishes to process, then he really does need to find someone competent to 
do the job instead of wallowing around in json until the client gives up 
in despair at the lack of progress and finds someone else to do the job.

This should really have been defined by whoever set the task to do the 
conversion. If the job is to convert from some XML DTD to a CSV format, 
then there should be a clear description of what extracts from the XML 
are expected to be in which positions in the CSV.

This is the sort of data conversion code I generally turn out in a day or 
so, it's hardly rocket science as long as you have a clear description of 
what is required. If you don't have a clear description of what is 
required, you have to keep asking questions until you get one.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV File Troubleshooting

2015-06-21 Thread Denis McMahon
On Sun, 21 Jun 2015 07:38:13 -0700, Sahlusar wrote:

 It is difficult to explain this to someone asynchronously and without an
 in person meeting. Moreover, the strict guidelines for disclosing
 information make it difficult for me to explain the client's
 requirements and the problems that they face.
 
 I do agree with you Denis that this is an unconventional approach. I was
 wondering then that perhaps I should add additional functionality at the
 XML to JSON step? So far, with JSON objects without nested lists (as
 values) I have been successful with this (the following is rather
 lengthy):

No, step back and force yourself to answer these questions:

Why use JSON as an intermediate step?
What benefit does using JSON as an intermediate step bring me?

I see no evidence in any of your posts that the use of JSON as an 
intermediate format for the data brings any benefit whatsoever, however I 
have seen evidence that it may be introducing errors and potential data 
loss, and it is certainly adding coding complexity.

None of these are good reasons to do it, and all of them are good reasons 
not to do it.

If your data is in XML and your requirement is for CSV, then you should 
be converting from XML to CSV.

Also stop posting reams of code. No-one is reading it. If you have a 
specific error you need to fix, then post a shortest possible example of 
code that generates the error. This should never be more than about 10 
lines.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV File Troubleshooting

2015-06-21 Thread Denis McMahon
On Thu, 18 Jun 2015 18:47:30 -0700, Sahlusar wrote:

 I have a conundrum regarding JSON objects and converting them to CSV:

I think your conundrum is that you've taken on a coding task beyond your 
abilities to comprehend, and as a result not only can you not code it, 
you can't even adequately describe it.

At least, it seems that every time you do try and describe it either the 
data format or the task description changes.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV file

2015-06-21 Thread Denis McMahon
On Wed, 17 Jun 2015 08:00:11 -0700, Saran A wrote:

 I would like to have this JSON object written out to a CSV file so that
 the keys are header fields (for each of the columns) and the values are
 values that are associated with each header field.

 {
 CF: {
...
 CF: Fee,

Your json object seems to have the same key used for two elements at the 
same level, are you sure this is legal json?

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV File Troubleshooting

2015-06-21 Thread Denis McMahon
On Thu, 18 Jun 2015 18:47:30 -0700, Sahlusar wrote:

 I have a conundrum regarding JSON objects and converting them to CSV:
 
 Context
 
 I am converting XML files to a JSON object (please see snippet below)
 and then finally producing a CSV file. Here is a an example JSON object:

This is where you're going wrong. If you want CSV data, take the XML and 
generate CSV data from it. Converting and writing it out to JSON and then 
reading it back and converting to CSV involves an extra conversion step 
where errors can creep in.

If you want to convert XML to CSV, go straight from XML to CSV, there is 
little added value in using some arbitrary intermediate format unless 
you're actually going to use the data in the intermediate format for 
something other than converting to the final format.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to inverse a particle emitter

2015-06-07 Thread Denis McMahon
On Thu, 04 Jun 2015 16:15:20 -0700, stephenppraneel7 wrote:

 hey, i really need help, im a straight up beginner in scripting and i
 need to figure out how to make an inverted particle emitter using python
 in maya

An emitter of inverted particles? Or an inverted emitter?

Or an absorber / accepter / receiver of emitted particles?

I'm not quite sure what an inverted particle emitter is, but I don't 
think you can create one in software, you need lots of volts and magnets.

If you're trying to model some physical device using python as a 
scripting language inside some simulation environment, then the best 
place to look is probably forums dedicated to that simulation environment.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is considered an advanced topic in Python?

2015-06-01 Thread Denis McMahon
On Fri, 29 May 2015 09:01:55 -0700, Mike Driscoll wrote:

 I've been asked on several occasions to write about intermediate or
 advanced topics in Python and I was wondering what the community
 considers to be intermediate or advanced. I realize we're all
 growing in our abilities with the language, so this is going to be very
 subjective, but I am still curious what my fellow Python developers
 think about this topic.

Hmmm, in terms of learning about computer programming:

simplest: print hello world

then things get more advanced in steps:

(1) more instructions, but executed linearly, numbers and strings.

(2) conditional execution - if statement (including error trapping)

(3) loops, lists, dictionaries

(4) defining functions

(5) recursion

(6) sexy python stuff - things like list comprehensions, using iterators, 
importing modules etc

I think that's probably basic python covered in 6 steps (7 if you 
include hello world). Although you now have all the tools you need to 
write python code to do possibly very complex tasks, and thus to write 
very complex programs, you're using (IMO) basic python programming skills 
in doing so.

I guess that makes OOP / classes the advanced topic in my system.

I don't consider using library x to do y as advanced python, it's just 
gluing together existing functions with your own basic programming, no 
matter whether the library is for hardware IO, interfacing to a database 
etc.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is 'palindrome' defined?

2015-06-01 Thread Denis McMahon
On Sun, 31 May 2015 21:46:31 -0700, fl wrote:

 def palindrome(num):

Note carefully the spelling(1): palindrome

 parlindrome(a)

Note carefully the spelling(2): parlindrome

 NameError: name 'parlindrome' is not defined

Compare carefully spelling(1) and spelling(2).

palindrome is defined, pa_r_lindrome is not defined. The computer is not 
psychic yet, so it doesn't know that when you wrote pa_r_lindrome you 
meant palindrome, you have to spell it the same way every time for the 
computer to recognise that you mean the same name.

Now you also know that the error message:

NameError: name 'something' is not defined

means that you might have spelled something differently on the line in 
the error message to the word you meant, so next time you see this error 
message you know to carefully check the spellings of function names and 
variables.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What use for reversed()?

2015-05-31 Thread Denis McMahon
On Sun, 31 May 2015 12:40:19 -0700, fl wrote:

 Hi,
 
 I have a string b='1234'. I run: br=reversed(b)
 
 I hope that I can print out '4321' by:
 
 for br in b
 
 but it complains:
 SyntaxError: invalid syntax
 
 
 My questions:
 1. What use for reversed(). I do not find an example on web.
 
 2. If reversed() is wrong the my purpose, what method can do it? i.e.
 '4321'
 out.

reversed returns an iterator, not a list, so it returns the reversed list 
of elements one at a time. You can use list() or create a list from 
reversed and then join the result:

$ python
Python 2.7.3 (default, Dec 18 2014, 19:10:20) 
[GCC 4.6.3] on linux2
Type help, copyright, credits or license for more information.
 .join(list(reversed(fred)))
'derf'
 .join([x for x in reversed(fred)])
'derf'

So reversed can do it, but needs a little help

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   6   7   >