sneekula 969 Nearly a Posting Maven

Numpy handles only numeric arrays, not object arrays.
I think VPython actually uses numpy/numeric internally.

sneekula 969 Nearly a Posting Maven

Generally you write a function for that, something like this:

# check the input of an integer between given limits

def check_input(low, high):
    """
    check the input to be an integer number within a given range
    """
    prompt = "Enter an integer number between %d and %d: " % (low, high)
    while True:
        try:
            a = int(raw_input(prompt))
            if low <= a <= high:
                return a
        except ValueError:
            print("Hey, I said integer number!")

# test the function ...
# expecting an integer number between 1 and 50
num_test = check_input(1, 50)
print(num_test)

The function loops until the correct input has been received.

sneekula 969 Nearly a Posting Maven

Use something like this that only moves files:

# move files from one directory to another
# if files alrady exist there, they will be overwritten
# retains original file date/time

import os
import shutil

# make sure that these directories exist
dir_src = "C:\\Python25\\ATest1\\"
dir_dst = "C:\\Python25\\ATest2\\" 

for file in os.listdir(dir_src):
    print file  # testing
    src_file = os.path.join(dir_src, file)
    dst_file = os.path.join(dir_dst, file)
    shutil.move(src_file, dst_file)
sneekula 969 Nearly a Posting Maven

I have a company scanner but very often people forget to remove scanned (confidencial documents)

I want to create a script which will once day check a "/home/scanner" folder and if there are any files it moves them to my /home/Administrator folder.

I dont really dont know how to start. For now I create this:

import shutil

src = "/home/scanner/."
dst = "/home/Administrator/"

shutil.move(src, dst)

I know that os.walk() and listdir() shoud do a job but I donk know how to write a code.;-(

Would you be able to help me ?

When moving an entire directory with shutil.move will remove this directory, since it basically uses copy and then remove.

sneekula 969 Nearly a Posting Maven

Whenever Obama does something, I think of what McCain with the help of Palin would have done.

sneekula 969 Nearly a Posting Maven

Leftover Lebkuchen from Christmas.

sneekula 969 Nearly a Posting Maven

Chile's chain of volcanoes is the second-largest in the world after Indonesia.

sneekula 969 Nearly a Posting Maven

In the Banking News:
The Swiss bank UBS, one of the largest banks in the world, has agreed to pay a fine of $780,000,000 to the US government. They admitted that over the last eight years they have helped very wealthy US citizens to move large sums of money into Switzerland in order to avoid paying US taxes. I guess the Bush taxcuts for the rich weren't good enough! UBS has also agreed to reveal the names of those rich scumbags. These folks could be due billions of Dollars in back-taxes.

sneekula 969 Nearly a Posting Maven

...
When Ronald Reagan took office, the economy was in an arguably worse state than it is now. However, his strives to limit government, and leave the private sector alone helped us to recover, and enjoy the prosperities of the 90s. Obama plans to do the very opposite... Hmmm.... I wonder what will happen...

Reagan presided over the largest US deficit increase and tax increase ever. He also sold arms to our enemy Iran (Iran Contra affair), an item he conveniently could not remember doing.

sneekula 969 Nearly a Posting Maven

Like the poet says, love is a mutual thing. If it's one sided, then it quickly turns into agony. A couple that truly loves each other doesn't need to exchange many words. I look at my mom and dad, and see love every day.

Lardmeister, God bless you, you are a hopless romantic! I think that wears off with age.

sneekula 969 Nearly a Posting Maven

These are bailouts done when 'Bush the Smaller' was US President:

$152 billion Bush stimulus package in the spring of 2008
$700 billion Troubled Asset Relief Program (TARP) in the fall of 2008
$200 billion to nationalize Fannie Mae and Freddie Mac
$42 billion for the Big Three auto manufacturers
$29 billion for Bear Stearns
$150 billion for AIG
$350 billion for Citigroup
$300 billion for the Federal Housing Administration Rescue Bill
$87 billion to pay back JPMorgan Chase for bad Lehman Brothers trades
$200 billion to banks under the Federal Reserve's Term Auction Facility (TAF)
$50 billion to short-term corporate IOUs held by money market mutual funds
$500 billion to rescue various credit markets
$620 billion for other industrial nations
like the Bank of Canada, Bank of England, Bank of Japan, National Bank of
Denmark, European Central Bank, Bank of Norway, Reserve Bank of Australia,
Bank of Sweden, and Swiss National Bank
$120 billion in aid for emerging markets
like the central banks of Brazil, Mexico, South Korea, and Singapore
trillions to guarantee the Federal Deposit Insurance Corporation's
expanded bank deposit insurance coverage from $100,000 to $250,000
$500 billion in Fed purchases of asset-backed securities
plus trillions more for other sweeping guarantees.

Grand total: Liabilities for the US taxpayer of over $9 trillion!

sneekula 969 Nearly a Posting Maven

We all have interesting little snippets lying around. Too bad we can't find some way to create some sort of central index, but it is more than I have time for.

Image Files
     tif to gif
SQLite
     database - create
     database - modify record
Homework problems
     common
          primes - find all up to a certain number
etc.

Well, there is a snippet section, but nobody ever looks there.

sneekula 969 Nearly a Posting Maven

Hi, i'm schoooler

I’m new to the forum and just saying hello.

Good grief, the forum is going nuts!

sneekula 969 Nearly a Posting Maven

Karl Benz invented the first gas powered car. The car had only three wheels. The first car with four wheels was made in France in 1901 by Panhard et LeVassor.

sneekula 969 Nearly a Posting Maven

Wonder how polyphonic gotrucculliet gets his frigging spam onto DaniWeb?

There goes another polyphonic spam, this time she calls herself vescapsvece. Please, do not support those miserable spammers!

sneekula 969 Nearly a Posting Maven

I found this short one hilarious, not quite sure why :D. http://uk.youtube.com/watch?v=N4J73AnRE5A

Wonder why Ford never offered the Ka car in the US? It's a sharp looking little city car!

sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

My suggestion is to read the file in line by line and write it out to a new file line by line in one loop. Then you can process the line in question and write it out as it comes along. This way you don't have a memory problem with very large files.

Something like this:

file_in = open("myfile.txt", "r")
file_out = open("myfile_modified.txt", "w")

search = "<Age>32</Age>"
my_line = "<Age>1200</Age>"

print("working ...")

for line in file_in:
    # strip of the trailing '\n' 
    if search in line.strip():
        file_out.write(my_line+'\n')
    else:
        file_out.write(line)

print("... done")

file_in.close()
file_out.close()
sneekula 969 Nearly a Posting Maven

One way to present highly formatted text like text with superscripts is to use wxPython's wx.html.HtmlWindow widget and simplified html code:

# exploring wxPython's
# wx.html.HtmlWindow(parent, id, pos, size, style, name)

import wx
import wx.html

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("yellow")
        
        htmlwin = wx.html.HtmlWindow(self, wx.ID_ANY, 
            pos=(10,30), size=(200,100))
        htmlwin.SetPage(html_code)


# use simple HTML code ...
html_code = """\
x<sup>3</sup> + y<sup>2</sup> - 15 = 0
"""

app = wx.App(0)
# create a frame, no parent, default ID, title, size
caption = "superscript text with wx.html.HtmlWindow"
frame = wx.Frame(None, wx.ID_ANY, caption, size=(400, 210))
MyPanel(frame)
frame.Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

My semi-educated guess is that a primitive GUI toolkit like Tkinter does not have a superscripting option. For that you need wxPython, it has widgets like wx.lib.fancytext or wx.html.HtmlWindow that use simplified xml or html code. For an example see:
http://www.daniweb.com/forums/post782156-106.html

sneekula 969 Nearly a Posting Maven

My question is, how do you determine the values for f.seek() in such a large file?

sneekula 969 Nearly a Posting Maven

I just happen to have it handy:

# convert all .tif file in a directory to .gif files
# needs Python Image Library (PIL) free from:
# http://www.pythonware.com/products/pil/index.htm

import os
from PIL import Image

# give the directory the TIF files are in
path = 'C:/temp/test/'
# make it the working directory
os.chdir(path)

for file in os.listdir(path):
    # assumes '.tif' is lower case
    if file.endswith('.tif'):
        img = Image.open(file)
        # change name *.tif to *.gif
        gif_file = file[:-4]+'.gif'
        img.save(gif_file)
        # indicate progress
        print( "%s converted and saved to %s" % (file, gif_file) )
sneekula 969 Nearly a Posting Maven

Thanks for the lead AD, there are a whole slew of other rather funny banned commercials! I like the girl on the copier.

http://www.youtube.com/watch?v=nI2y4s3vzgk&NR=1

Ancient Dragon commented: LOL :) +36
sneekula 969 Nearly a Posting Maven

i would rather coal ash than radioactive sludge lol

Yeah, all that arsenic, cadmium and lead in coal ash is good for the neighbourhood!

sneekula 969 Nearly a Posting Maven

I didn't know that 'Stars and Stripes' is printed in Germany. Good find there Dude!

sneekula 969 Nearly a Posting Maven

When is the bird going to drop something on the guy or bring down an airplane?

sneekula 969 Nearly a Posting Maven

It is very obvious that I am from Mars. Everybody looks like this -->

sneekula 969 Nearly a Posting Maven

Wonder how polyphonic gotrucculliet gets his frigging spam onto DaniWeb?

sneekula 969 Nearly a Posting Maven

I would avoid using Python26 with wxPython. I had problems and went back to Python25.

sneekula 969 Nearly a Posting Maven

A lot of editors written with Python in mind automaticaly replace tabs with spaces, but again it depends on the tab settings original versus present.

sneekula 969 Nearly a Posting Maven

Actually, Portable Python comes also with IDLE that will use the portable version.

sneekula 969 Nearly a Posting Maven

I was looking over some code for an open source project and I saw some strange whitespace stuff that I didn't even think would run. The thing is, it runs just fine. I was wondering if someone could explain what I'm missing.

I don't want to copy the exact code, so I'll simplify...
It starts with a class definition, easy enough
class KevinsClass:

the next line is indented four space...
__init__(self, name):

The next line is indented eight spaces....
self.name = name

the next line is indented with one tab
<tab>self.othername = name

I would think that python would bark about the whitespace not being correct. I thought that if you start a block of code, like a class, then every line of that class has to be indented the same way as the first line. So if I indented four spaces, I thought that everything else in the class needed to be indented four spaces.

What am I missing?

If I would be running this code from my editor, I would have a royal mess on my hand because my editor is set to a tab width of four spaces! You just lucked out with your tab setting. The moral is, for heaven sake don't mix tabs and spaces in your code! Use spaces only!

sneekula 969 Nearly a Posting Maven

I got curious, so I timed the 'just Python' and 'module re' approaches:

# timing characer count by type
# compare 'module re' and 'just Python' approches

import timeit
import re

def count_char1(text):
    """
    count upper case char, lower case char, digits and spaces in a text
    """
    regexes = [ re.compile(x) for x in
        (r"[^A-Z]+", r"[^a-z]+", r"[^0-9]+", r"[^\ ]+")]
    counts = [len(s) for s in (r.sub("", text) for r in regexes)]
    return tuple(counts)

def count_char2(text):
    """
    count upper case char, lower case char, digits and spaces in a text
    """    
    upper = lower = digit = space = 0
    for c in text:
        if c.isupper():
            upper += 1
        elif c.islower():
            lower += 1
        elif c.isdigit():
            digit += 1
        elif c.isspace():
            space += 1
    return (upper, lower, digit, space)


text = """
There is one rule for the industrialist and that is: 
Make the best quality of goods possible at the lowest 
cost possible, paying the highest wages possible.

Henry Ford 1924
"""

# for longer text uncomment line below
#text = text*10

stmt = 'count_char1(text)'
t = timeit.Timer(stmt, setup="from __main__ import count_char1, text")
#  doing 10000 passes * 100 gives the time in microseconds/pass
elapsed = (100 * t.timeit(number=10000))
print( "Function %s takes %0.3f micro-seconds/pass" % (stmt, elapsed) )

stmt = 'count_char2(text)'
t = timeit.Timer(stmt, setup="from __main__ import count_char2, text")
#  doing 10000 passes * 100 gives the time in microseconds/pass
elapsed = (100 * t.timeit(number=10000))
print( "Function %s takes %0.3f micro-seconds/pass" % (stmt, elapsed) )

"""
my …
Gribouillis commented: good idea +2
mn_kthompson commented: Damn fine analysis +2
sneekula 969 Nearly a Posting Maven

I would like to learn regular expressions. I have no Idea what it is (I always see people here using). Can someone explain a litle and suggest good tutorial?

Didn't mean to deviate the thread, so keep your first focus on the thread, then you can answer my question

There is also:
http://www.amk.ca/python/howto/regex/

sneekula 969 Nearly a Posting Maven

There is a very good free online book "A Byte Of Python" by C.H. Swaroop at:
http://www.swaroopch.com/notes/Python_en:Table_of_Contents

sneekula 969 Nearly a Posting Maven

To transpose a 2d array (list of lists) see:
http://www.daniweb.com/forums/showpost.php?p=778261&postcount=161

sneekula 969 Nearly a Posting Maven

The Python function zip() can be used to transpose a twodimensional array (list of lists). The initial result would be a list of tuples, so a list comprehension is used to change the tuples to lists:

# transpose a 2D_array (list of lists) from 4x6 to 6x4

arr_4x6 = [
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0],
]

# the * unpacks the array
arr_6x4 = [list(q) for q in zip(*arr_4x6)]

for row in arr_4x6:
    print(row)

print('-'*20)

for row in arr_6x4:
    print(row)

"""
my transpose result -->
[0, 0, 0, 0, 0, 0]
[0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 0]
[0, 1, 0, 1, 1, 0]
--------------------
[0, 0, 0, 0]
[0, 1, 0, 1]
[0, 1, 0, 0]
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 0, 0, 0]
"""
sneekula 969 Nearly a Posting Maven

One of the ways to do this is to flatten the nested list. Here is an example:

# flatten a nested list

def flatten(q):
    """
    a recursive function that flattens a nested list q
    """
    flat_q = []
    for x in q:
        # may have nested tuples or lists
        if type(x) in (list, tuple):
            flat_q.extend(flatten(x))
        else:
            flat_q.append(x)
    return flat_q

template = [[0, 0, 0, 0],
            [0, 1, 1, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 0]]

target = [[0, 0, 0, 0],
          [0, 1, 1, 0],
          [0, 1, 1, 0],
          [0, 0, 1, 0]]

flat_template = flatten(template)
flat_target = flatten(target)

# test it
print(flat_template)
print(flat_target)

"""
my test result -->
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0]
"""

The code you are using to calculate the score is straight forward, simply go head an use it on the flattened list.

Another way to to add the score would be to zip the two lists:

template =  [0, 0, 1, 1, 0, 1, 0]
target =    [0, 0, 0, 1, 1, 1, 0]

print(template)
print(target)

print(zip(template, target))

score = 0
for x in zip(template, target):
    a = x[0] + x[1] + 1
    if a == 2:
        score -= 1
    else:
        score += a

print(score)

"""
my result -->
[0, 0, 1, 1, 0, 1, 0]
[0, 0, 0, 1, 1, 1, 0]
[(0, 0), (0, 0), (1, 0), (1, 1), (0, 1), (1, 1), (0, 0)]
7
"""

Notice that I am using 'print(template)' rather than 'print template'. This way the code works both with Python25 and the new Python30.

sneekula 969 Nearly a Posting Maven

Without the __init__() class constructor this class would behave strange:

class DoesNothing():
    print 'I have been initialized'
sneekula 969 Nearly a Posting Maven

Yeap I knw hw beautfl it looks bt thng is I dnt knw much abt progmng...ie y I askd help...

Pretty goofy English there!

At first you need to help yourself by studying the manual a little.

sneekula 969 Nearly a Posting Maven

Wow!
The address bar of your browser window can be used to run javascript.
What is the javascript to wipe out the hard disk? :)

sneekula 969 Nearly a Posting Maven

Seven is the average number of days a German goes without washing his or her underwear.

sneekula 969 Nearly a Posting Maven

It looks more and more like the first $300,000,000,000 of the US financial bailout went to friends of Hank Paulson without any trace. Bush has triumphed again!

sneekula 969 Nearly a Posting Maven

How about Local Warming? Could stand some right now!

sneekula 969 Nearly a Posting Maven

A blonde and a brunette are running a ranch together in Texas. They decide they need a bull to mate with their cows to increase their herd. The brunette takes their life savings of $600 dollars and goes to Arizona, where the bulls are cheap, to buy a bull.

She finds an old cowboy that will sell her a bull. "It’s the only one I got for $599, take it or leave it."

She buys the bull and goes to the local telegram office and says, "I’d like to send a telegram to my friend in Texas that says HAVE FOUND THE STUD BULL FOR OUR RANCH, BRING THE TRAILER."

The man behind the counter tells her, "Telegrams to anywhere in the U.S. are $.75 per word."

She thinks about it for a moment and decides. "I’d like to send one word, please."

"And what word would that be?" inquires the man.

"COMFORTABLE." replies the brunette.

The man asks, "I’m sorry miss, but how is your friend gonna understand this telegram?"

The brunette replies, "My friend is blonde and reads real slow, when she gets this, she will read out loud COM-FOR-DA-BULL."

sneekula 969 Nearly a Posting Maven

Q: "Have you heard about the lawyers' word processor?"
A: "No matter what font you select, everything comes out in fine print."

sneekula 969 Nearly a Posting Maven

The stock market is full of bears right now, enough to scare everyone.

sneekula 969 Nearly a Posting Maven

RIGHT NOW? I am just drinking the rest of the Diet DR Pepper I had with dinner...

I had tacos (ground turkey, and the seasoning I mix myself because I like more heat and less salt than the packaged mixes offer).

Topped with: lettuce, tomato, diced onion, minced up jalapeno (makes them hotter) and grated white new york cheddar cheese.

Stuffed in: Old ElPaso (I think) Stand N Stuff shells, toasted.

and the Diet Dr. Pepper (I'm getting used to it)

I have a Snickers Bar in the refrigerator...

Wow, your tacos sound good!

I am making a pot full of chili and some homemade bread for a bunch of my friends tonight.

sneekula 969 Nearly a Posting Maven

Installing python 2.5.4 over version 2.5.2 should not bother any third party modules like wxPython. Version 2.5.4 is simply a bug upgrade within the 2.5 series. Don't uninstal version 2.5.2, the new version will simply overwrite it.

sneekula 969 Nearly a Posting Maven

Wow, the Fatso patrol! Would it lower the cost of healthcare?

Of course Japan has a lot of rather crowded puplic transport, too many fat folks would just make it worse.

The last flight I took, the guy next to me was so fat that he literally overflowed into my seat. Maybe the airlines should charge by the pound.