woooee 814 Nearly a Posting Maven

There is no reason to reinvent the wheel. You can use the identify program from ImageMagick to do that for you.

Gribouillis commented: indeed! +14
woooee 814 Nearly a Posting Maven

Running this stripped down version works on my machine

from tkinter import *
root = Tk()
calc = Frame(root)
calc.grid()

root.title("Calculator")
text_box = Entry(calc, justify=RIGHT)
text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)
text_box.insert(0, "0") 

root.mainloop()
woooee 814 Nearly a Posting Maven

You have to pass the list to the function using it i.e.

numbers = get_values()
do_analysis(numbers)
woooee 814 Nearly a Posting Maven

Geometry managers, pack, grid, and place return None

canvas = Canvas(mainGUI, width=c_width, height=c_height, bg= 'white').place(x=(4.5*(widthOfScreen/12)),y= (2*(heightOfScreen/5)))
print canvas

Take a look at Vegas's code again and I'm sure you will find that the geometry manager is on a separate line.

canvas = Canvas(mainGUI, width=c_width, height=c_height, bg= 'white')
print canvas
print canvas.place(x=(4.5*(widthOfScreen/12)),y= (2*(heightOfScreen/5)))
CodingCabbage commented: Thankyou, very helpful +0
woooee 814 Nearly a Posting Maven

Take a look at the docs for os.stat()

def file_permissions( fname ) :
    st = os.stat(fname)
    ##--- st = tuple, in format
    ##      0    1   2    3    4   5    6    7     8     9
    ##    (mode,ino,dev,nlink,uid,gid,size,atime,mtime,ctime)
    mode = st[0]

    if mode :
        print "st_mode = ", mode
    if mode & stat.S_ISLNK(st[stat.ST_MODE]) :
        print "is link"
    else :
        print "is NOT link"     
    if mode & stat.S_IREAD :
        print "readable"
    if mode & stat.S_IWRITE :
        print "writable"
    if mode & stat.S_IEXEC:
        print "executable"
woooee 814 Nearly a Posting Maven

You have to pass the "numbers" list to do_analysis. Now it is using the "numbers" from the import numbers statement. This is not a complete solution but should get you started: passing parameters to a function

def main ():
    # create empty list
    intro()
    numbers = get_values()
    ## get_values()         Huh!!
    do_analysis(numbers)
    input("press enter to continue.") # required
woooee 814 Nearly a Posting Maven

Note that you don't use the "j" variable. It is not necessary. Just iterate through the the list up to the next to last element. You do this over and over until there are no more swaps. In your code you loop enough times to do all of the swaps but this is not an efficient way to do it. Also using letters like i, l, and O is not a good idea as they look too much like numbers.

import random

test_list = [random.randint(1, 10) for ctr in range(20)]
print "original", test_list
found = True
swaps_ctr = 0
while found:
    swaps_ctr += 1
    found = False       ## initial state
    for ctr in range(0, len(test_list)-1):
        if test_list[ctr] > test_list[ctr+1]:
            test_list[ctr+1], test_list[ctr] = test_list[ctr], test_list[ctr+1]
            found = True     ## loop again

print swaps_ ctr, "swaps"
print test_list
for num in set(test_list): ## reduce to one entry per number
    print num, test_list.count(num)

## another way
print "-" * 20
previous_num = -1
for num in test_list: 
    if num != previous_num:
        print num, test_list.count(num)
        previous_num = num
woooee 814 Nearly a Posting Maven

I am trying to write a program which, overall takes the names of the files that haven't completed, works out the names of those that haven't run and writes all of these into a batch file.

I would agree. You are perhaps making it too complicated. Write/store the file name when it's processing has finished. If a file in a directory is not in the finished list then process it.

When c does not equal 1.00, extend the list GULP to include gulp < ' + AaBbCc.dat + ' > ' + AaBbCc.out. This must always happen, except when a == 0.3 and b == 0.2 and when a == 0.8 and c == 0.6.

You can extend the list by all names in a directory "except when a == 0.3 and b == 0.2 and when a == 0.8 and c == 0.6" and not have to worry about which ones have run. If the program exits before all files have run then the program name is not in the stored list and will run next time this program is run.

If I understand what you want to do, you will use something like the subprocess modules to run the "bash" commands and when it finishes, and returns to the calling program, write the name of the file to where ever it is being stored.

woooee 814 Nearly a Posting Maven

but it returns : _iNone

The "None" is returned by the function so apparently you are calling it with "print function_name()" instead of "function_name". If that does not help then post the entire code including how you call it.

woooee 814 Nearly a Posting Maven

Your code is a good example of why we use the Python Style Guide You use an upper and lower case "L" for the same field name so the code you posted does not run. The style guide says to use lower_case_with_underscores so to avoid that problem and make your code more readable by others. Try the following code and see if it does the random part. It does not matter if you have the keys in 2 lists or use [0][1] and [2][3] so it is up to you if you want to divide it into two lists or use as is. Note on the first print that the keys are in "dictionary order" not the order they were added.

import random
test_dict = {'One': 3, 'Two': 5, 'Three': 1, 'Four': 4, 'Five':7 }
dict_keys = test_dict.keys()
print dict_keys
random.shuffle(dict_keys)
print dict_keys
TrustyTony commented: clear thinking +12
woooee 814 Nearly a Posting Maven

Now that you have posted the complete error message we know which line is causing it.

level=PhotoImage(file='images\0.gif')

does not look like a valid file name. It is perhaps "/images/0.gif". But that probably is not enough either as you have to provide the complete file name "/path/to/file/images/0.gif". You also must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object. You might want to use something like this just to be on the safe side

fname="/path/to/file/images/0.gif"
if os.path.isfile(fname):
    level=PhotoImage(file=fname)
else:
    print "File not found", fname

If that still doesn't work, then download a gif image from the web to test with as it may be the image that is causing the problem.

Gribouillis commented: good help +14
woooee 814 Nearly a Posting Maven

64 bit, Python 2.7 is predictably twice the memory, except for the string???

"""
Size of empty tuple = 56
Size of empty list = 72
Size of empty dictionary = 280
Size of empty string = 37
"""
woooee 814 Nearly a Posting Maven

There is a little hiccup for stars with 3 and 4 sides. You can divide 360 by the number of sides for stars with 5 sides and up, but for 3 or 4 sides this gives an angle greater than or equal to 90 which will not work. I will leave this conundrum up to the OP to solve for now. Both star_angle and left_angle have to be calculated differently for angles >= 90. Draw it out on a piece of paper and measure the angles and you should be fine.

def draw_star(number_of_sides):
    star_angle=360.0/number_of_sides  ## float for Python 2.X
    left_angle = star_angle*2
    print number_of_sides, star_angle
    turtle.penup()
    turtle.goto(-150, -100)
    turtle.pendown()
    for _ in range(number_of_sides):
        turtle.forward(100)
        turtle.right(star_angle)
        turtle.forward(100)
        turtle.left(left_angle)

    raw_input("Press a key")
    turtle.clear()

for num_sides in range(3, 8):
    draw_star(num_sides)
woooee 814 Nearly a Posting Maven

set a StringVar or IntVar in the command callback, "get" example here but set works the same way. Start at "This example creates an Entry widget, and a Button that prints the current contents:"

woooee 814 Nearly a Posting Maven

This works per your example. However you don't have a queue.put() so you won't get anything from the get() call. I don't think that is what you want however. Look up shared data perhaps a dictionary or list would be easiest to understand depending on the size of the data. Also please try to conform to the Python Style Guide (CamelCase is for classes, lower_case_with_underscore for functions) as it makes you code easier for others to understand.

import multiprocessing as mp
import time

DELAY_SIZE = 1

def Worker(q):
    sleep_for = DELAY_SIZE / 2.0
    for ctr in range(10):       
        print "I'm working... %s"  % (ctr)
        time.sleep(sleep_for)

def Process(): 
    print "          I'm processing.."

queue = mp.Queue(maxsize=DELAY_SIZE)
p = mp.Process(target=Worker, args=(queue,))
p.start()

while p.is_alive():
  time.sleep(DELAY_SIZE)
  Process()
woooee 814 Nearly a Posting Maven

You can send a tuple to startswith

 ## note that opt is never set back to "" or "n"
 if s.startwith(('Total number of defects', 'Total charge on defect', etc.))

Are you saying that you want to stop looking after the second if s=='**** Optimisation achieved ****':

if s=='**** Optimisation achieved ****':
    if opt=='y':
        opt='n'
    else:
        opt="y"            
Gribouillis commented: I forgot about the tuple ! +14
woooee 814 Nearly a Posting Maven

That is more code than I want to trudge through for a simple question, so will just say that generally you use Toplevels as the code below illustrates. If there is more that you wish to know, post back. Note that you can use a function or third class to call (separate instance) each class as many times as you want, with individual parameters.

class one():
    def __init__(self, root):
        self.root = root
        top = tk.Toplevel(root)
        top.title("First")
        top.geometry("150x75+10+10")

        tk.Button(top, text="open new window", command=self.openit).grid()
        tk.Button(top, text="Quit", command=self.root.quit).grid(row=1)

    def openit(self):
        two = Two(self.root)

class Two():
    def __init__(self, root):
        self.root = root
        top = tk.Toplevel(root)
        top.title("Second")
        top.geometry("150x50+10+125")

        tk.Label(top, text="second window").grid()

root = tk.Tk()
root.withdraw()
one(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

I do not know of water being used in the generation process. But perhaps that is in another type of thermal solar plant. This uses some kind of "salt" that melts when heated (I think to something like 1000 degrees F which leaves water out). The salt then heats a tank of some type of mixture that produces steam and turns a turbine, but that is a closed system meaning an extremely small amout is lost. Another advantage is that the heated salts can be stored to generate power at night.

woooee 814 Nearly a Posting Maven

There has been a solar thermal plant in the Mohave since the '80s I think and no problems with water. There aren't that many workers who are physically at the plant so a relatively small amount a water covers their drinking, bathroom, etc. requirements, but it probably has to be trucked in.

woooee 814 Nearly a Posting Maven

Those who can make you believe absurdities can make you commit atrocities.
--Voltaire

woooee 814 Nearly a Posting Maven

“The liar's punishment is, not in the least that he is not believed, but that he cannot believe anyone else.”
― George Bernard Shaw,

woooee 814 Nearly a Posting Maven

I would just add both directories to the PYTHONPATH variable in .bashrc. You can also add something like
export PYTHONSTARTUP=$HOME/.pythonstartup
to .bashrc to execute a given file when python starts.

Edit: Sorry, I see now from the "7" and "xp" that you are probably using a windows OS, but am going to leave the reply for any future searchers

woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

That comes out to June 10th, 14 days off. There would be something like 28 leap years which is too far off to be a possibility. "41401,250002" comes back as May 9th at 6:00 AM (providing January 1, 1900 is correct).

import datetime
x=datetime.datetime(1900, 1, 1, 0, 0, 0) + datetime.timedelta(days=41433.662413)
print x.year, x.month, x.day, x.hour, x.minute, x.second
woooee 814 Nearly a Posting Maven

UnicodeDecodeError: 'utf16' codec can't decode byte 0x20 in position 108: truncated data

I assume your are using Python 2.x so try something like this.
book = open_workbook(os.path.join(folder_to_import, file_to_import), coding='utf-16')

If you have unicode file names then use
l_files_to_import = os.listdir(u"/Location/DATA")

woooee 814 Nearly a Posting Maven

Always use complete names. The program is not looking in the directory that the file is located in. Also, you should be able to use a slash, /directory_name on any OS.

##-------------------------------------------------------------
## Assumes this code is now indented to run under the for() loop
##-------------------------------------------------------------
folder_to_import = '/Location/DATA'
l_files_to_import = os.listdir(folder_to_import)
for file_to_import in l_files_to_import:
    if file_to_import.endswith('.XLS'):

            column_count=10

        # Open entire workbook
        book = open_workbook(os.path.join(folder_to_import, file_to_import))
woooee 814 Nearly a Posting Maven

The easiest way to eat crow is while it's still warm. The colder it gets, the harder it is to swallow.

woooee 814 Nearly a Posting Maven

2nd hit on Google pyusb backend not accessible. You have to install an additional lib that pyusb depends on, and it's also on the pyusb site but the web site isn't real clear saying that you have to install one of the library dependencies. Please mark this as solved.

woooee 814 Nearly a Posting Maven

You write one ('HBHB', 0xcafe, *ssd) and multiple ('HH', chunk) and then read one ('HBHB', 0xcafe, *ssd) and only one ('HH', chunk), then one ('HBHB', 0xcafe, *ssd) and one ('HH', chunk), etc. In addition to ('HBHB', 0xcafe, *ssd) write the number of items (length) written so you know how many to read.

woooee 814 Nearly a Posting Maven

You have not declared log_size or log1_size anywhere and it appears the indentation is off under the while True, which is an infinite loop since you don't ever exit it. There is no reason from the code you posted to append to "packed" and then write each value from packed instead of just writing to the file directly. Other than that the error message is self explanatory and we of course don't know what the values of the variables are so there is no further way to help.

woooee 814 Nearly a Posting Maven

Tkinter does not have a Circle class; you use create_oval with circle dimensions. Note that you call the function once and have it call itself recursively for as many times as you want.

try:
    import Tkinter as tk
except:
    import tkinter as tk

class TestAfter():
    def __init__(self):
        self.root=tk.Tk()
        self.ctr = 3
        self.canvas = tk.Canvas(self.root, width=500, height=500)
        self.canvas.grid()
        self.root.after(750, self.update)

        self.root.mainloop()

    def update(self):
        colors = ["black", "red", "green", "blue"]

        if self.ctr > 0:
            start = 50*self.ctr  ## use same values for x & y
            end = start+50
            self.canvas.create_oval(start, start, end, end,
                               fill=colors[self.ctr], width=2)
            self.ctr -= 1
            self.root.after(750, self.update)

TA=TestAfter()
woooee 814 Nearly a Posting Maven

GUI's have their own "sleep" type methods that should be used. However each GUI uses a different function name so it depends on the GUI toolkit you are using.

woooee 814 Nearly a Posting Maven

I agree that you are doing it the hard way. Note that dollars is multiplied by two after the print and the addition to total

#get the ending limit
days = int(raw_input('How manys days were worked? '))
total = 0
dollars = 0.02
#print table headings
print('\nDays\tDollars')
print('------------------------------')


#print the days and the amount of money that was earned that day
for today in range(days):
    total += dollars  ## 0.02 on first pass
    print(today+1, '\t', '$',format(dollars,',.2f'))
    dollars *=  2  ## set for next pass
print('the total amount of money you earned is: $',format(total,',.2f'))
woooee 814 Nearly a Posting Maven

Does the file have more than one taxon? In the example you posted there is only one so all of the solutions are for one only. Try this as a hint, although there are other ways to do it.

handle = open(fname, "r")
all_data = handle.read()
print all_data.split("taxon")
woooee 814 Nearly a Posting Maven

Once you get the value it is a normal variable and you can do anything with it that you can do to a normal variable. I would suggest that you consider putting everything under one class instead of here's a function, there's a class, here's another function, etc.

try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

def another_function(input_var):
    print "another function", input_var

class TestClass():
    def __init__(self):
        root1 = tk.Tk()
        root1.title("Vreme")
        naziv = "Vreme"
        L1 = tk.Label(root1, text="Zadržavanje: ")
        L1.place(x=10, y=30)
        self.E1 = tk.Entry(root1, bd = 2)
        self.E1.insert(0, "Test string")
        self.E1.place(x=100, y=30)
        root1.geometry("300x100+300+200")
##    tk.Button(root1, text="OK", command = lambda: izmeni(E1.get(),root1,vreme1,naziv), width=10).place(x=130, y=65)
        tk.Button(root1, text="OK", command = self.izmeni, width=10).place(x=130, y=65)
        root1.mainloop()

    def izmeni(self):
        value = self.E1.get()
        print "izmeni -->", value
        another_function(value)
        self.function_in_class(value)

    def function_in_class(self, input_var):
        print "functionin_class -->", input_var

TC=TestClass()
woooee 814 Nearly a Posting Maven

You should be able to come up with a generic function that takes any number of dictionaries of any length and calculates the average.

a = {1:[1, 2, 3],
     2:[3,4,5],
     3:[6,7,8]
     }

b = {1:[3,7,4],
     2:[8,2,9]
     }

c = {1:[4,7,1],
     2:[5,5,9],
     3:[2,3,7],
     4:[9, 10, 11]
     }


def average(tuple_of_dicts):  ## or list of dicts
    """ receives a tuple of one or more dictionaries and
        averages the grades
    """
    total_grades=0
    total_num=0
    for each_dictionary in tuple_of_dicts:
        for key in each_dictionary:
            grades_list = each_dictionary[key]
            for grade in grades_list:
                total_grades += grade
                total_num += 1
    return float(total_grades)/total_num

print "One dictionary =", average([a])  ## can use a tuple or list
print "Two dictionaries =", average((a, b))
print "Three dictionaries =", average([a, b, c])
woooee 814 Nearly a Posting Maven

I would suggest that you use a button instead of a label, which can execute a funtion when it is clicked. Also, the name "list" is already used by Python so you should not override it, although you never use the variable "list" in the code posted so the "list" code can just be deleted.

woooee 814 Nearly a Posting Maven

There is a typo in get_average that you should be able to run down from the error messages, or at least begin to learn how. Using descriptive variable names would help you with this, as well as help us understand the program. Print the return from get_average and see if it can be summed. Note that get_average returns a kind of sum of averages, not the average. Also, you should loop through containers like a dictionary so your funtion can handle containers that have any number of items instead of

return average(p[1]) + average(p[2]) + average(p[3])

Usually we test programs with known values that should produce known results to tell if the program is calculating correctly or not, so what are the results supposed to be?.

woooee 814 Nearly a Posting Maven

First, remove punctuation (? , . etc). Next all words should be lower() case as an upper case word is different to the computer than a lower case word. To print use the dictionary's key as below, although this code does not do any of the other above suggestions

data="""I love the python programming
 How love the python programming?
 We love the python programming
 Do you like python for kids?
 I like Hello World Computer Programming for Kids and Other Beginners."""

count = {}
for word in data.split():
    if word not in count:
        count[word] = 0
    count[word] += 1

## access the dictionary by key
for word in count:
    print "The word", word, "was found", count[word], "times"

print "\nThere are %d unique words (if Upper and lower case," % (len(count))
print "and words with punctuation, are different words)"
woooee 814 Nearly a Posting Maven

You do not test for the password for the user so if any user's password is found it will return True. This works for me but again will accept any user's password (and note the added print statements to see what is happening).

import crypt

line="victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh"
cryptPass = line.split(':')[1].strip(' ')
salt = cryptPass[0:2]
print "cryptPass",  cryptPass, salt

test_file="""apple
orange
egg
lemon
grapes
secret
strawberry
password"""

dictFile = test_file.split("\n")  
for word in dictFile:
    cryptWord = crypt.crypt(word, salt)
    print "     ", cryptWord, cryptPass,
    if cryptWord == cryptPass:
        print "FOUND",
    print
woooee 814 Nearly a Posting Maven

That is a little complicated because I get an error on the first test lookup at

e = self.shelve[key]

because the keys are not correct. If it works for you then there is possibly a difference because of the Python version being used. If it does not work for you, take another look at Doug Hellmann's page as to how he adds data to a shelve object. Deleting is just del self.shelve[key], but you also have to set writeback=True for the changes to take place in the db. Also, Python is already using "string" and "list" and so using them in your program "redefines" them so you can not convert something to a list for example because "list" no longer points to a function. Finally, "b" will never equal 4 because it is set to one on the previous line

    def phonemenu(b):
        b = 1
        if b != 4:
jeremywduncan commented: Thank you. This homework is hard without a tutor! +0
woooee 814 Nearly a Posting Maven

You don't ever print tempStr.

TrustyTony commented: Observant +12
woooee 814 Nearly a Posting Maven

The following code does the same lookups using a list and a dictionary. Lists are sequential in memory, meaning that the program has to get the offset for the beginning of the item it wants to use, go to that offset, compare to what it wants to find, and go back and do it all over again for each element in the list. A dictionary uses a hash which creates small groups, for lack of a better term, so there is a relatively small number of lookups. For each tenfold increase in data, the dictionary's time increases by ten times also, but is still pretty fast. The list's lookup time increases by 100+ times for the same increase. One would expect the same increases for a tenfold increase in the size of each individual item being stored as that would also increase the anount of memory that has to be traversed. So it appears that you can't really decide on using a list vs. dictionary based on the number of items but have to consider the total amount of memory to be consumed.

import datetime

def add_to_list(num):
    a_list=[]
    start_time=datetime.datetime.now()
    for ctr in xrange(num):
        ##  lookup up each time to show the "cost" of lookups
        if ctr not in a_list:
            a_list.append(ctr)

    print "elapsed time:", datetime.datetime.now()-start_time


def add_to_dict(num):
    a_dict={}
    start_time=datetime.datetime.now()
    for ctr in xrange(num):
        ##  lookup up each time to show the "cost" of lookups
        if ctr not in a_dict:
            a_dict[ctr]=ctr

    print "elapsed time:", datetime.datetime.now()-start_time


for num in [1000, 10000, 100000]: …
woooee 814 Nearly a Posting Maven

For future reference, the error was eliminated because you added the plus signs. Also, include the entire error message in the future.

print('Ok,'chara,
print('Ok, '+ chara +
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

A hint

from string import ascii_lowercase as letters
print letters[-1:]
print letters[-2:]

print
location=25
print letters[location:]
location -= 1
print letters[location:]
woooee 814 Nearly a Posting Maven

Two from Einstein

“Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.”

“If a cluttered desk is a sign of a cluttered mind, of what, then, is an empty desk a sign?”

woooee 814 Nearly a Posting Maven

10 Great Headlines courtesy of the 2013 Farmer's Almanac
1. Hospitals Sued by 7 Foot Doctors
2. Police Begin Campaign to Run Down Jaywalkers
3. Panda Mating Fails: Veterinarian Takes Over
4. War Dims Hope For Peace
5. Astronaut Takes Blame for Gas in Spacecraft
6. Juvenile Court to Try Shooting Defendant
7. Something Went Wrong in Jet Crash
8. New Study of Obesity Looks for Larger Test Group
9. Cold Wave Linked to Temperatures
10. Typhoon Rips Through Cemetery: Hundreds Dead

diafol commented: funny +0
woooee 814 Nearly a Posting Maven

The early bird gets the worm, but the second mouse gets the cheese.

woooee 814 Nearly a Posting Maven

You don't have a [0, 15] in the example you posted, you have [0, 0] through [3, 3]. If you have a
board = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] --> 16 zeros
then you can access the 15th. Show us some code, especially the code that creates the board, for more info.