Gribouillis 1,391 Programming Explorer Team Colleague

now easyInstall is also installed correctly, reindent is also working and after reindenting the prolis.py file again when i open the prolis.py file in idle and run module then i get following error:
expected an indented block.

Can you post prolis.py (between code tags) ? Also python probably tells you the error's line number.

Gribouillis 1,391 Programming Explorer Team Colleague

getting following error when doing above:
'easy_install' is not recognized as an internal or external command,
operable program or batch file.

It could be a PATH problem. The easy_install documentation http://peak.telecommunity.com/DevCenter/EasyInstall#windows-notes says that C:\\Python2X\\Scripts must be in your path for easy_install to work (and perhaps reindent too ?) (replace Python2X by your own python folder)

It's worth having a working easy_install because you can install any package from pypi with it (something like 15000 packages) !

Gribouillis 1,391 Programming Explorer Team Colleague

installed the setuptools correctly, then environmental variables set up correctly.After that as told downloaded the reindent zip file, extracted it, and then installed it correctly using cmd.

Now the only problem is in last step where you told to enter reindent nameofthescript.py in cmd after moving to script directory.I am getting following error:
'reindent' is not recognized as an internal or external command,
operable program or batch file.

Try easy_install reindent first in a cmd tool (from any folder).

Gribouillis 1,391 Programming Explorer Team Colleague

set up the environmental variables using following cmd:
set PYTHONPATH=%PYTHONPATH%;C:\Python32

but again it gives the same previous error after i put setup.py install in cmd

If you don't have setuptools, get it from here. If your windows is 32 bits, simply download the .exe for your version of python and run it. http://pypi.python.org/pypi/setuptools#downloads

Gribouillis 1,391 Programming Explorer Team Colleague

thanks for reply, i am new to python programming.can you please clear the following:
what does it mean "Don't indent python code with tab characters"?
when you say configure your editor to insert 4 spaces instead of tab,what does it mean.
i have set the identation width to 4 spaces by going to options => configuring the idle.
and can you explain how you reindent the code from your command line.i have downloaded the zip file from the url given by you.after extracting i ran the reindent.py, but still i get the error.

If you extracted the zip file, open a cmd tool, navigate to the extracted folder and type python setup.py install . Then navigate to the folder containing your python script and type reindent nameofthescript.py . It should reindent your script (at least that's what happens in linux)...

Your initial post contains tab characters (\t) entered with the tab key by many editors. If you edit a program with idle, it should not indent with tabs.

Gribouillis 1,391 Programming Explorer Team Colleague

It would be great if someone already knowing about it could give me a better answer. I always try to get my answers from the source code and am left dazzled by the code in C. (last time I was trying to see how long was implemented)

Well, here is the C function that does the job (from timemodule.c in python 3.1.1)

static int
floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__EMX__)
	struct timeval t;
	double frac;
	frac = fmod(secs, 1.0);
	secs = floor(secs);
	t.tv_sec = (long)secs;
	t.tv_usec = (long)(frac*1000000.0);
	Py_BEGIN_ALLOW_THREADS
	if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
#ifdef EINTR
		if (errno != EINTR) {
#else
		if (1) {
#endif
			Py_BLOCK_THREADS
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
	}
	Py_END_ALLOW_THREADS
#elif defined(__WATCOMC__) && !defined(__QNX__)
	/* XXX Can't interrupt this sleep */
	Py_BEGIN_ALLOW_THREADS
	delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
	Py_END_ALLOW_THREADS
#elif defined(MS_WINDOWS)
	{
		double millisecs = secs * 1000.0;
		unsigned long ul_millis;

		if (millisecs > (double)ULONG_MAX) {
			PyErr_SetString(PyExc_OverflowError,
					"sleep length is too large");
			return -1;
		}
		Py_BEGIN_ALLOW_THREADS
		/* Allow sleep(0) to maintain win32 semantics, and as decreed
		 * by Guido, only the main thread can be interrupted.
		 */
		ul_millis = (unsigned long)millisecs;
		if (ul_millis == 0 ||
		    main_thread != PyThread_get_thread_ident())
			Sleep(ul_millis);
		else {
			DWORD rc;
			ResetEvent(hInterruptEvent);
			rc = WaitForSingleObject(hInterruptEvent, ul_millis);
			if (rc == WAIT_OBJECT_0) {
				/* Yield to make sure real Python signal
				 * handler called.
				 */
				Sleep(1);
				Py_BLOCK_THREADS
				errno = EINTR;
				PyErr_SetFromErrno(PyExc_IOError);
				return -1;
			}
		} …
Gribouillis 1,391 Programming Explorer Team Colleague

Don't indent python code with tab characters. Configure your editor to insert 4 spaces instead of a tab when you hit the tab key. Also reindent your code like this

def print_lol(movies):
    for each in movies:
        if isinstance(each,list):
            print_lol(each)
        else:
            print(each)

I used the "reindent" script to reindent the code from the command line http://pypi.python.org/pypi/Reindent/0.1.0

Gribouillis 1,391 Programming Explorer Team Colleague

You can look in the source code of timemodule.c in the python source. In linux, this is done by calling select() with NULL arguments.

Gribouillis 1,391 Programming Explorer Team Colleague

Hi all,
Forgive my pool English first...
I'm learning Python recently. But I met with a problem yesterday and I have liitle experience in solving this kind of problems.
Here are the code in Python Shell:

>>> "HuXiaoxiang\\0Nanjing University\03 Years.".replace("\0"," ")
'HuXiaoxiang\\0Nanjing University\x03 Years.'
>>> "HuXiaoxiang \0Nanjing University\03 years.".replace("\0"," ")
'HuXiaoxiang  Nanjing University\x03 years.'
>>> "HuXiaoxiang \0Nanjing University\03 years.".replace(" ","@")
'HuXiaoxiang@\x00Nanjing@University\x03@years.'

Why the first & second didn't work as I excepted?
Thxs for anyone who will view my problem in advance~

Your problem is not with the replace() method but with the escaped characters in literal strings:

  • An escaped backslash "\\" is interpreted as a single backslash character in a literal string, so your first string contains a backslash character followed by the digit 0, and not the null character '\0'.
  • A backslash followed by 1, 2 or 3 octal digits is interpreted as the character which binary value has this number. For example, 'a' has order 97, which is written 141 in base 8, so the string "\141" is the same as "a" (an octal digit is 0, ..., 7). So in the second string, "\0" is interpreted as the null character but "\03" is the character with number 3, while "\09" would mean a null character followed by the digit 9, because 9 is not an octal digit.

Because they can have a variable number of digits, the octal escaped sequences are not very useful. The better way is to represent non …

vegaseat commented: nice explanation +15
Gribouillis 1,391 Programming Explorer Team Colleague

Oh boy, Jaro's tab indented code looks like dung on a shingle.

An old trick to reindent your code is to use Tim Peters' reindent script http://pypi.python.org/pypi/Reindent/0.1.0 .

Gribouillis 1,391 Programming Explorer Team Colleague

Using the key argument of sorted() or list.sort(), you can sort a list of items according to a score function. The score of an item could be its price, name, age, mark, length, distance to a point, etc depending on what the items are.

from functools import partial

def dist_to_target(tx, ty, item):
    name, sx, sy = item
    return sqrt((int(sx) - tx)**2 + (int(sy) - ty)**2)

score = partial(dist_to_target, targetx, targety)
# score is now a function score(item) --> distance to target

sorted_items = sorted(citiescomp, key = score)
print sorted_items
vegaseat commented: nice code +15
Gribouillis 1,391 Programming Explorer Team Colleague

Oops It's me again. I just ran the code you posted and it still gives an error:

Traceback (most recent call last):
  File "soup.py", line 7, in <module>
    soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
  File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1499, in __init__
    BeautifulStoneSoup.__init__(self, *args, **kwargs)
  File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1230, in __init__
    self._feed(isHTML=isHTML)
  File "/usr/lib/pymodules/python2.6/BeautifulSoup.py", line 1263, in _feed
    self.builder.feed(markup)
  File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
    self.goahead(0)
  File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
    k = self.parse_starttag(i)
  File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
    endpos = self.check_for_whole_start_tag(i)
  File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
    self.error("malformed start tag")
  File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
    raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: malformed start tag, at line 1477, column 15

This is strange, it works well for me (python 2.6.5 on linux with BeautifulSoup 3.0.8). Perhaps you could try to clean the code with a markupMassage argument

import re
def repl_func(mo):
    print "occurrence found !"
    return 'target="_blank"'
myMassage = [(re.compile(r'target\"_blank\"'), repl_func)]
soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=myMassage)
Gribouillis 1,391 Programming Explorer Team Colleague

Hi, like I said, this is an unofficial API that is why I can't correct the web page.
When I used beautiful soup, I followed the documentation and it only points that the class only uses one parameter, which is the html. This second parameter, what are you using it for? Is there a web page with full documentation on BS?

Thanks for your help.

The documentation is here http://www.crummy.com/software/BeautifulSoup/documentation.html#Entity%20Conversion. Otherwise, here is the documentation for the initializer, obtained with pydoc

|  __init__(self, markup='', parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo='xml', convertEntities=None, selfClosingTags=None, isHTML=False)
     |      The Soup object is initialized as the 'root tag', and the
     |      provided markup (which can be a string or a file-like object)
     |      is fed into the underlying parser.
     |      
     |      sgmllib will process most bad HTML, and the BeautifulSoup
     |      class has some tricks for dealing with some HTML that kills
     |      sgmllib, but Beautiful Soup can nonetheless choke or lose data
     |      if your data uses self-closing tags or declarations
     |      incorrectly.
     |      
     |      By default, Beautiful Soup uses regexes to sanitize input,
     |      avoiding the vast majority of these problems. If the problems
     |      don't apply to you, pass in False for markupMassage, and
     |      you'll get better performance.
     |      
     |      The default parser massage techniques fix the two most common
     |      instances of invalid HTML that choke sgmllib:
     |      
     |       <br/> (No space between name of closing tag and tag close)
     |       <! --Comment--> (Extraneous whitespace in declaration)
     | …
Gribouillis 1,391 Programming Explorer Team Colleague

Hi, Thanks that really works. I'am glad my code was easy understandable.

The first I tried was BeautifulSoup, since a read it was easier. but when i run it i get: "HTMLParseError: malformed start tag, at line 1475, column 15"

I know HTMLParser is also giving me errors but at least I can still work with the document while BS is not. Maybe this has something to do with the fact that am using python 2.6?

The malformed starttag is

<area shape="rect" coords="324, 28, 445, 41" href="mailto:contacto@cinepolis.com" 

        target"_blank" />

There is a missing = sign between 'target' and "_blank" in the tag.

I was able to parse the file with beautifulsoup without errors

from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup

url = 'http://cinepolis.com.mx/index.aspx'
req = urlopen(url)
data = req.read()
soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
stuff = soup.findAll(id="ctl00_ddlCiudad")[0]
opts = stuff.findAll("option")
cities = [x.contents[0] for x in opts]
for x in cities:
    print x

"""  my output -->
Acapulco
Aguascalientes
Cabo San Lucas
Cancún
Cd. Acuña
Cd. Cuauhtémoc 
Cd. Juárez
Cd. Obregón
Cd. Victoria
Celaya
Chetumal
Chihuahua
Chilpancingo
Coatzacoalcos
etc
"""
Gribouillis 1,391 Programming Explorer Team Colleague

You can add this method to handle accented characters

def handle_charref(self, name):
    if self.this_is_the_tag and not self.end_of_city:
      print "charref", repr(name)
      self.this_city += unichr(int(name))

There is still a problem with your web page. HTMLparser exits with an error (after finding the cities). You may consider using a parser for invalid html, like beautifulsoup (or lxml + beautifulsoup)

Gribouillis 1,391 Programming Explorer Team Colleague

I know but I am doing this :

text=file.read()                      
pickled_text=pickle.dumps(text, -1)                               
compressed_text=zlib.compress(pickled_text)

That is why I asked.And please, could you tell me how to edit the code so that is shows the number of the line?Like you did.
LE: found how

Pickling a string does not seem to be a good idea. Your combination of pickle and compress may be less efficient than a single compression.

>>> from pickle import dumps
>>> s = "hello world"
>>> p = dumps(s, -1)
>>> len(p)
18 # > len(s) !
>>> len(s)
11
>>> repr(p)
"'\\x80\\x02U\\x0bhello worldq\\x00.'"

pickling the string only added some noise (the info needed to tell python that the pickled object is a string).

Gribouillis 1,391 Programming Explorer Team Colleague

Thank you, did that, I'm sorry for wasting your time, I should have said that is used zlib.One question about this , is it possible that pickling the text read from the file might increase it's size?

Yes I think it is possible, but not significantly. Pickle is not a compression algorithm, it's a persistence algorithm adapted to python data structures. It has nothing to do with zlib or gzip.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you could compress the text first to reduce its size

import zlib
text = open("file_to_be_encrypted.txt").read()
data = zlib.compress(text) # normaly much shorter than text

# ... encrypt data with your AES code
# text can be retrieved with zlib.decompress(data)

This technique won't help if your data is already in compressed format (.zip, .jpg, ...)

Gribouillis 1,391 Programming Explorer Team Colleague

any package of python ....

Let's start with something simple that will allow you to intall packages from the python package index. I don't use windows 7, but it should work here too

First, you must install setuptools from here http://pypi.python.org/pypi/setuptools#using-setuptools-and-easyinstall . If you have a 32 bits windows simply select and run the .exe installer coresponding to your version of python. If you have a 64 bits windows, download and run the ez_setup.py python script instead as described in the windows section of the installation instructions.

Then we'll try the command easy_install to install a package from pypi. For this,
open a windows cmd tool and type easy_install unidecode . If it works, start a python interpreter and type the statement import unidecode . If this works (no error occurs), it means that you managed installing the 'unidecode' third party module.

Then post again in this thread for more...

Gribouillis 1,391 Programming Explorer Team Colleague

which package ?

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

There are 2 slightly different things that you might want to do

  • execute a script xxx.py from your main program. This can be done with exec open("xxx.py").read()
  • import xxx.py as a module, which is done with import xxx or mod = __import__("xxx")

If you import the module, the script xxx.py is only executed the first time the module is imported, and a module object is stored in sys.modules["xxx"] .
If you choose the exec solution, a good idea is to execute the script in a separate dictionary to avoid polluting your namespace, like this

mydict = dict()
exec open("xxx.py").read() in mydict
# or in python 3: exec(open("xxx.py").read(), mydict)

It is unusual to choose a module to import through interaction with the user. A more logical way is that the user chooses an action to execute and this choice results in selecting a function to call. For example

action = raw_input("what should I do ? ").strip()
if action == "go to hell":
    import xxx
    xxx.gotohell()
elif action == "quit":
    import yyy
    yyy.quit()
# etc
Gribouillis 1,391 Programming Explorer Team Colleague

how to convert 'a->b' into Py??

a.b
Gribouillis 1,391 Programming Explorer Team Colleague

Or without modules:

def callable(f):
    try:
        f()
        return True
    except AttributeError:
        return False
    except TypeError:
        return False

Or you can try to call it and catch exception in your code. But there is the collections.Callable, like vegaseat said.

callable(f), whatever it is, should not actually call f().

Gribouillis 1,391 Programming Explorer Team Colleague

I think it is best to avoid the use of the built in function callable , because Guido van Rossum thought it was a mistake in the python language (perhaps because of similar questions, what does callable actually means). That's why it was removed in python 3. I like the hasattr(x, __call__) , which is not ambiguous. You could also define your own callable like this

from functools import partial

def my_callable(x):
  try:
    partial(x) # this fails if x is not callable
    return True
  except TypeError:
    return False
Gribouillis 1,391 Programming Explorer Team Colleague

You can use string formating operations

["ma%d" % n for n in range(2, 5)]
Gribouillis 1,391 Programming Explorer Team Colleague

There are different libraries for big floating numbers in python, most of them based on the gnu multiprecision library see bigfloat and gmpy and also clnum.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a slower way to do it. Actually, there was an error in list2

>>> adict = {}
>>> list1 = range(6)
>>> list2 = range(10,16)
>>> for i, item in enumerate(list1):
...  adict[item] = list2[i]
... 
>>> adict
{0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15}
Gribouillis 1,391 Programming Explorer Team Colleague

Hi,
I want to do something like this:
I have two lists:

list1 = range(6)
list2 = range(10,15)

i want a dictionary like this:

adict ={0:10,
1:11,
2:12,
3:13,
4:14,
5:15
}

I did the following:

list1 = range(6)
list2 = range(10,15)
adict = dict(zip(list1,list2))

i get :
TypeError: list objects are unhashable
it didn't work.. any help pls..

Same for me, I tried with 2.5, 2.6 and 3.1 and it works.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes, python is extremely permissive. Any function can call any other function in any module, including the module where it is defined.

Gribouillis 1,391 Programming Explorer Team Colleague

i think it is the problem with data types. am not sure :( how can i convert a result of pysnmp get into an unsigned char??

unsigned char, signed, unsigned int, unsigned char array... do all these things differ and cause the code to go astray....

there is no way to predefine data type of any variable right?

You don't really need to worry about this: python is not C. In an array.array() defined with type 'B', you can only store integers in the range [0, 256[. Python will complain if you try to give another value to an array element

>>> import array
>>> a = array.array('B', [0]*10)
>>> a[3] = 300
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: unsigned byte integer is greater than maximum
>>> a[3] = -23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: unsigned byte integer is less than minimum
>>> a[3] = 45 # ok
>>>

All you have to do is to convert your pysnmp results into ordinary python integers.

In any case, these datatype issues cannot lead to 'List index out of range'.

Ene Uran commented: agree +13
Gribouillis 1,391 Programming Explorer Team Colleague

Ok :)

I used the following:

import array
bit_map_len = array.array('B',[0]*764)

still it is giving the error, now after 513 runs...

no I am not changing the size anywhere, and not accessing index out of interval :)

You could avoid creating a list each time by storing an array of zeroes

import array
from copy import copy
zeroes = array.array('B',[0]*764)
...
bit_map_len = copy(zeroes)

Otherwise the error is somewhere in the code that you did NOT post, so it's difficult to guess. What you could do is add assert statements here and then in your program, like

assert len(bit_map_len) == 764
assert 0 <= index < 764
Gribouillis 1,391 Programming Explorer Team Colleague

If each entry contains 8 bits of data, you may consider using the array module instead of a list. Otherwise the code that you wrote above doesn't produce list index out of range error. This error does not occur randomly, so your program must have changed the size of the list somewhere, or you are accessing an index outside of the interval [0, 95[ . Also please use code tags for python code :)

Gribouillis 1,391 Programming Explorer Team Colleague

Using Counter looks good, but it will work only with python >= 2.7. The problem with your question is that there is no python code. Hint: start with a program which prints each list item on a different line.

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

You can also do it with PIL instead of ImageMagick

cv.postscript(file="circles.eps")
    from PIL import Image
    img = Image.open("circles.eps")
    img.save("circles.png", "png")
vegaseat commented: I like that soluion +14
TrustyTony commented: You are maestro! +13
Gribouillis 1,391 Programming Explorer Team Colleague

I was exploring random art and modified this nice example from vegaseat:

# random circles in Tkinter
# a left mouse double click will idle action for 5 seconds
# modified vegaseat's code from:
# http://www.daniweb.com/software-development/python/code/216626

import random as rn
import time
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def idle_5sec(event=None):
    """freeze the action for 5 seconds"""
    root.title("Idle for 5 seconds")
    time.sleep(5)
    root.title("Happy Circles ...")

# create the window form
root = tk.Tk()
# window title text
root.title("Happy Circles (click on window to idle for 5 seconds)")
# set width and height
w = 640
h = 480
# create the canvas for drawing
cv = tk.Canvas(width=w, height=h, bg='black')
cv.pack()
# endless loop to draw the random circles
while True:
    # random center (x,y) and radius r
    x = rn.randint(0, w)
    y = rn.randint(0, h)
    r = rn.randint(5, 50)
    # pick a random color
    # Tkinter color format is "#rrggbb"
    color = '#' + "".join("%02x"%rn.randrange(256) for x in range(3))
    # now draw the circle
    cv.create_oval(x, y, x+r, y+r, fill=color)
    # update the window
    root.update()
    # bind left mouse double click, idle for 5 seconds
    cv.bind('<Double-1>', idle_5sec)

# start the program's event loop
root.mainloop()

What I would like to do is to save the double clicked canvas to an image file like .jpg or .png format. Does anyone know how to do this?

I was able to do it by saving the canvas as encapsulated postscript and then using ImageMagick to convert …

Gribouillis 1,391 Programming Explorer Team Colleague

See itertools.product("daniweb", repeat=3) .

Gribouillis 1,391 Programming Explorer Team Colleague

You are using a variable row_num which was only defined in the function row() and does not exist outside this function. It's better to write separate functions with return value to get user input, like this

# -*-coding: utf8-*-
#created by Jaron Graveley
#April 26th, 2011
#This program completes reservations for Jon Von Poechman’s airline in an easy to use program
#variable list:
#i=counter used to limit the number of seats present on the diagram
#n= counter to display the row number on the diagram
#num_booked=counts the number of booked seats so the program stops 
#m=counter used to seperate the rows in the plane
#r=row counter
#p=position counter
#plane=list of seats on the plane showing taken and empty seats
#plane_name=same list as plane except it shows names for management use only
#seat=shows the letter o for an open seat
#name=the users name
#row_num= the row number that the passenger wants to sit in
#position= the position that the passenger wants to sit in
#request= the users requested seat
#taken= the equation used to bok the seat
#exit= restarts the  loop for the next person to book
#number= the employee number of the management member
i=0
n=1
num_booked=0
m=0
r=1
p=0
plane=[]
plane_name=[]
while r<21:
    if m==4:
        r+=1
        m=0
    p+=1
    if p==5:
        p=1
    m+=1
    seat="r"+str(r)+"p"+str(p)
    if seat=="r21p1":
        break
    else:
        seat='o'
        plane_name.append(seat)
        plane.append(seat)

def diagram():
    i=0
    n=1
    print "Below is a list of available seats marked with a 'o'. Those marked with an 'x' are taken:"
    print "  A    B    C …
Gribouillis 1,391 Programming Explorer Team Colleague

Gribouillis could you explain that a little please

line.strip() returns a string with white space removed at both ends (white space is a space or tabulation or newline character). line.split() splits the line into pieces separated by white space and returns a list of the pieces. For example

>>> line = "John\t000000000000000\n"
>>> print( line.strip().split() )
['John', '000000000000000']

Then name, number = ['John', '000000000000000'] defines 2 string variables, name has value 'John' and number has value '000000000000000'.

Gribouillis 1,391 Programming Explorer Team Colleague

You can use

name, number = line.strip().split()
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for the excellent description.

Perfect. Is ther anyway to use lognormal in the same way as randn? to choose sample from log normal distribution.

I suppose so. Write numpy.random.lognormal(mean, sigma, (100,20)) . But can you explain what your matrix is and why you want to add random samples, and also why should the result be in [-1,1] ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you only want to add some random noise to your data, you could add a normal random sample with a small standard deviation and clip the result in the interval [-1.0, 1.0] like this

sigma = 0.1
a = numpy.clip(X + sigma * randn(100, 20), -1.0, 1.0)

However, due to the clipping, your array won't exactly be a normal perturbation of the initial array, and this distorsion increases with the value of sigma. Mathematically speaking, it is impossible to require both a normal distribution and bounds on the possible values, but if sigma is small enough, the amount of clipped values will be small and the distorsion can be neglected.

vegaseat commented: goog explanation +14
pythonbegin commented: short and sweet +2
Gribouillis 1,391 Programming Explorer Team Colleague

This works with Python 2.7

class B:
    def __init__(self, arg):
        print(arg)

class C(B):
    def __init___(self, arg):
        super(C, self).__init__(arg)

c = C('abc')  # abc

Here super() gives a TypeError: must be type, not classobj

from math import pi

class Circle:
    """with Python3 object is inherited automagically"""
    def __init__(self, r):
        self.r = r

    def area(self):
        """a method of class Circle, first arg is self"""
        area = pi * self.r**2
        return area


class Cone(Circle):
    """class Cone inherits class Circle"""
    def __init__(self, r, h):
        super(Cone, self).__init__(r)
        # Python27 gives TypeError: must be type, not classobj
        self.r = r
        self.h = h

    def volume(self):
        """a method of class Cone, first arg is self"""
        # notice how to call the method of class Circle
        vol = 1.0/3 * self.h * Circle.area(self)
        sf = "Cone of height = %s and radius = %s has volume = %0.2f"
        print(sf % (self.h, self.r, vol))


cone = Cone(r=4, h=10)
# methods of class Box are dot connected to the instance box
cone.volume()

In the "working" example, you wrote __init__ with 3 underscores on the right. It was probably not called. To me, super is useless. It's a purist's detail in the python language which only adds noise in your code. Better call Circle.__init__(self, r) :)

HiHe commented: thank you +4
Ene Uran commented: I agree +13
Gribouillis 1,391 Programming Explorer Team Colleague

The with statement applies to instances having 2 methods: "__enter__" and "__exit__". When the with statement is encountered, the instance's __enter__ method is called and its return value is used for the 'as' part of the statement. When the block exits, the instance's __exit__ method is called to perform cleanup action. In the case of a file object, the __exit__ method closes the file.

class A(object):
    def __enter__(self):
        print("entering block")
        return "block value"
    def __exit__(self, *args):
        print("exiting block")
        
with A() as value:
    print(value)

"""
my output -->
entering block
block value
exiting block
"""

An alternative to writing a class to create such 'context' instances is to write a function with a single "yield" statement and use the contextmanager decorator like this

from contextlib import contextmanager

@contextmanager
def B():
    print("entering block")
    yield "block value"
    print("exiting block")
    
with B() as value:
    print(value)

""" my output -->
entering block
block value
exiting block
"""

As a more useful example, here is a context which executes a block of statement in a given directory and comes back to the initial directory at the end of the block

@contextmanager
def working_directory(path):
    import os
    old = os.getcwd()
    try:
        os.chdir(path)
        yield # this is where the code in the "with" block will be executed
    finally:
        os.chdir(old)

import os.path

with working_directory(os.path.expanduser("~")):
    print(os.getcwd())

Here are 2 more funny contexts: http://www.daniweb.com/software-development/python/code/317854

Gribouillis 1,391 Programming Explorer Team Colleague

I know a very simple system called py-notify. See here http://home.gna.org/py-notify. It define 'signals' emitted by your code, which can be 'connected' to callback functions.

Gribouillis 1,391 Programming Explorer Team Colleague
for((word  = wordlist[-2]) in ['ar','er',ir']):
    print word

Riechieking, you should test your code before posting. This can't work in python because word = wordlist[2] is not an expression but a statement. This is a C idiom, not a python one.

bumsfeld commented: thanks +7
Gribouillis 1,391 Programming Explorer Team Colleague

You can write verb[-2:] . Another helpful function is verb.endswith("ar") which returns True or False. Also read the documentation on string methods http://docs.python.org/library/stdtypes.html#string-methods

Gribouillis 1,391 Programming Explorer Team Colleague

The worst looking line is line 25: PyArg_ParseTuple takes addresses. It should be

if (!PyArg_ParseTuple(args, "ii", &lower, &upper))

See if it runs this way.

Gribouillis 1,391 Programming Explorer Team Colleague
a = [[1,2,3],
     [4,5,6],
     [7,8,9]]
a = [[1,4,7],
     [2,5,8],
     [3,6,9]]

Okay, now which way should I organize the list? The first way or the second way? PRobably the first way if I'm changing to col and row.

There is no rule, think about your list as a table, it all depends on the semantics of your rows and colums. For example if your table contains students marks, the logical way to organize the table would be that each item of the list contains all the marks for a given student, so there would be a row for each student with the list of his/her marks. That's the way tables are designed in relational databases.