woooee 814 Nearly a Posting Maven

You have to kill the process, and how you do that is dependent on the OS you are using. You should use subprocess instead (see os.kill() at Doug Hellmann's site).

woooee 814 Nearly a Posting Maven

There are several different ways to do this. One is a dictionary pointing to a list that contains the number of records found for the key, and the thresholds found to test if greater than (if I am reading the question correctly). You could also use two dictionaries, one as the counter, and one to hold the thresholds if that is easier to understand. An SQL file would be in order if this is a large data set. You could also create a class instance for each unique name, but that is probably more trouble and more confusing than the other solutions. A simple example:

test_list = [
"john steve 0.67588",
"john matt 1.00",
"red blue 0.90",
"yellow steve 0.02" ]

test_dict = {}
for rec in test_list:
    substrs = rec.split()
    key = substrs[0]
    if key not in test_dict:
        ## add the new key, counter=1, and a list containing the threshold
        test_dict[key] = [1, [float(substrs[2])]]
    else:
        test_dict[key][0] += 1     ## add one to counter (zero location in list
        test_dict[key][1].append(float(substrs[2]))   ## interaction strength

for key in test_dict:
    ## are any > 0.5
    values = test_dict[key][1]
    for v in values:
        if v > 0.5:
            print key, v, test_dict[key][0]
woooee 814 Nearly a Posting Maven

Please mark the thread "Solved". Be aware that some people do not like using update_idletasks(), and there are at least two other ways; using .after() which does not require an update, or a Tkinter StringVar() which updates whenever the text is changed.

import time
from Tkinter import *
 
class MyApp:
    def __init__(self, parent):
        self.myParent = parent  ### (7) remember my parent, the root
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()
 
        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="Button")
        self.button1.pack()
        self.button1.bind("<Button-1>", self.button1Click)
 
        self.lbl = Label(self.myContainer1)
        self.lbl.pack()
 
        self.lbl2_text = StringVar()
        self.lbl2_text.set("lbl2")
        self.lbl2 = Label(self.myContainer1, textvariable=self.lbl2_text)
        self.lbl2.pack()
 
        self.lbl3 = Label(self.myContainer1)
        self.lbl3.pack()
 
        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Quit", background="red")
        self.button2.pack()
        self.button2.bind("<Button-1>", self.button2Click)
 
 
    def button1Click(self, event):    ### (3)
        # expensive process here
        # simulated by time.sleep
        self.lbl2_text.set("updated also")
        self.myContainer1.after(100, self.lbl3.configure(text='lbl3 Running'))

        self.lbl.configure(text='Running command...')
        self.myContainer1.update_idletasks()
        time.sleep(4)
        self.lbl.configure(text='Finished running command...')
 
    def button2Click(self, event):  ### (5)
        self.myParent.destroy()     ### (6)
 
 
root = Tk()
myapp = MyApp(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

You can use update_idletasks()

import time
from Tkinter import *
 
class MyApp:
    def __init__(self, parent):
        self.myParent = parent  ### (7) remember my parent, the root
        self.myContainer1 = Frame(parent)
        self.myContainer1.pack()
 
        self.button1 = Button(self.myContainer1)
        self.button1.configure(text="Button")
        self.button1.pack()
        self.button1.bind("<Button-1>", self.button1Click)
 
        self.lbl = Label(self.myContainer1)
        self.lbl.pack()
 
        self.button2 = Button(self.myContainer1)
        self.button2.configure(text="Quit", background="red")
        self.button2.pack()
        self.button2.bind("<Button-1>", self.button2Click)
 
 
    def button1Click(self, event):    ### (3)
        # expensive process here
        # simulated by time.sleep
        self.lbl.configure(text='Running command...')
        self.myContainer1.update_idletasks()
        time.sleep(4)
        self.lbl.configure(text='Finished running command...')
 
    def button2Click(self, event):  ### (5)
        self.myParent.destroy()     ### (6)
 
 
root = Tk()
myapp = MyApp(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

See this link for a tutorial on input http://www.pasteur.fr/formation/infobio/python/ch04s03.html and then test the integer for >0 and <6 to break from the while() loop.

woooee 814 Nearly a Posting Maven

Let's create a continuing thread to program Crazy 8's from scratch for learning purposes!

DECK/CARD IDEA'S

My simple starting suggestion:

deck = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC',
        '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD',
        '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH',
        '2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS',]

Start by downloading one of the existing packages, like http://duo.tuxfamily.org/lang/en/about and look at the code. If you don't understand something, then post the question and code. I don't think there are many who volunteer their time here, who want to spend it coding a solution for you when many already exist.

doffing81 commented: good link +1
woooee 814 Nearly a Posting Maven

You could use concepts from this vegaseats post of clickable shapes:
http://www.daniweb.com/forums/post1322031.html#post1322031

You could tag all squares as named shapes and change another tag between '','X' and 'O' to mark what shape must be drawn there, when clicked, if square has been clicked you can remove the 'clickable' tag from it.

Good find. And Vegas does code some cherries.

woooee 814 Nearly a Posting Maven

Take a look at the trackback docs. You possibly want traceback.format_exc() or extract_tb(traceback[, limit])

woooee 814 Nearly a Posting Maven

But I don't want a StringVar; I want a Canvas image.

To place text on a canvas ('X' or 'O'), you use create_text(), not buttons, which may be why the text is not showing up in the correct place. You will have to use mouse position when clicked to determine where to place the 'X' or 'O'. And keep track of what is placed where to determine the winner of course.

from Tkinter import *

root = Tk()
root.title('Canvas Test')

##----------------------------------------------------------------------------
##--- generally, you only have on3 canvas object
canvas = Canvas(root, width =300, height=300)
##----------------------------------------------------------------------------

##----------------------------------------------------------------------------
##--- from here on, the single Canvas instance is used
##----------------------------------------------------------------------------
canvas.create_line(1, 100, 300, 100, width=3)
canvas.create_line(1, 200, 300, 200, width=3)
canvas.create_line(100, 1, 100, 300, width=3)
canvas.create_line(200, 1, 200, 300, width=3)

canvas.create_text(50,50, text='0', fill='blue', font=('verdana', 36))
canvas.create_text(150,150, text='X', fill='yellow', font=('verdana', 36))

canvas.pack()
root.mainloop()
woooee 814 Nearly a Posting Maven

Because it hasn't been defined. You defined (and should use)
return self.hasFlush()

self.xxx means that it is a member of the class

return hasFlush(self)
is passing self to a hasFlush function outside of the class.

woooee 814 Nearly a Posting Maven

You don't have
if 1 in self.myranks[kitten] and 1 in self.myranks[kat]:
in any of the code you posted. Is there more than one version of this program?

It apparently thinks that self.myranks[kitten] or [kat] is an integer. Do a
print type(self.myranks[kitten])
before the offending line and see what prints. Then you will have to try and discover where self.myranks[x] is set to an integer if it indeed is one now. Note that you initialize it to a list of integers, not a list of lists, i.e. a list would be
if 1 in self.myranks

How should I fix it?

Don't create it in the first place. Don't write long blocks of code without testing and ask someone else to clean up your mess. At a minimum, test each function after you write it.

def evaluateHand(self):
 
        if self.hasStraightFlush():
            return "Straight Flush"
        elif self.hasFourOfAKind():
            return "Four of a kind"
        elif self.hasFullHouse():
            return "Full House"
        elif self.hasFlush():
            return "Flush"
        elif self.hasStraight():
            return "Straight"
        elif self.hasThreeOfAKind():
            return "Three of a kind"
        elif self.hasTwoPair():
            return "Two pair"
        elif self.hasPair():
            return "Pair"
        else:
            return "Nothing"

The above function can be optimized by testing for a pair, and not testing for 3 or 4 of a kind if a pair isn't found. along the lines of:

def evaluateHand(self):
        return_lit = 'Nothing'
        if self.hasStraight():
            return_lit = "Straight"
            if self.hasStraightFlush():
                return_lit = "Straight Flush"
        elif self.hasPair():
            return_lit = "Pair"
            if self.hasThreeOfAKind():
                return_lit = "Three of a kind"
                if self.hasFourOfAKind():
                    return_lit = …
woooee 814 Nearly a Posting Maven

You want to associate each button with a Tkinter StringVar. That way, you set (change) the contents of the StringVar and it is automatically displayed on the screeen. This is the start of a Tic-Tac_Toe game, to test button use, that I never finished. It uses a dictionary to keep track of the buttons and displays "X" or "O" via a StringVar, but doesn't have a scoring system.

from Tkinter import *

class ButtonsTest:
   def __init__(self, top):
      self.button_dic = {}
      top.title('Buttons Test')
      self.top_frame = Frame(top, width =500, height=500)
      self.buttons()
      self.top_frame.grid(row=0, column=1)
      exit = Button(self.top_frame, text='Exit', command=top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   ##-------------------------------------------------------------------         
   def buttons(self):
      b_row=1
      b_col=0
      for j in range(1, 10):
         self.button_dic[j] = StringVar()
         self.button_dic[j].set(str(j))
         b = Button(self.top_frame, textvariable = self.button_dic[j])
         b.grid(row=b_row, column=b_col)

         def handler ( event, self=self, button_num=j ):
                return self.cb_handler( event, button_num )
         b.bind ( "<Button-1>", handler )

         b_col += 1
         if b_col > 2:
            b_col = 0
            b_row += 1

   ##----------------------------------------------------------------
   def cb_handler( self, event, cb_number ):
      print "cb_handler", cb_number, self.button_dic[cb_number]                
      if self.player:          ## True = "X", False = "O"
         self.button_dic[cb_number].set("X")
      else:
         self.button_dic[cb_number].set("O")
      self.player = not self.player

##===================================================================
root = Tk()
BT=ButtonsTest(root)
root.mainloop()
woooee 814 Nearly a Posting Maven

Another beginner tutorial that might make more sense is Learning To Program http://www.freenetpages.co.uk/hp/alan.gauld/tutcont.htm but note that every print statement becomes print() on Python 3.X for that code as well.

woooee 814 Nearly a Posting Maven

Try either destroy or withdraw on the old label and see if it does what you want.

woooee 814 Nearly a Posting Maven

HelloCallBack is first defined as a variable, then as a function.

class Application(Frame):
    helloCallBack = None
 
    def helloCallBack():
        tkMessageBox.showinfo ("Hello", "Hello, do you like my application?")

Neither is correct, you want it to be a member of the class. Note also that you can not use both grid and pack, so pick one, see the Warning here http://effbot.org/tkinterbook/grid.htm

from tkinter import *
 
class Application(Frame):
##    helloCallBack = None
 
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()
 
    def helloCallBack(self):
        tkMessageBox.showinfo ("Hello", "Hello, do you like my application?")
 
    def createWidgets(self):
        self.helloButton = Button (self, text='Hello', command=self.helloCallBack)
        self.helloButton.pack()
        self.helloButton.grid()
        self.menuFile = Menubutton (self, text='File')
        self.menuFile.grid()
        self.menuFile.hiAgain = Menu (self.menuFile, tearoff = 0)
        self.menuFile["HiAgain"] = self.menuFile.hiAgain
        self.menuFile.hiAgain.add_command(label="Hello", command=self.helloCallBack)
 
 
app = Application()
app.master.title("My Attempt at python")
app.mainloop()
woooee 814 Nearly a Posting Maven

The book teaches Python 2.x. In Python 3.x, print is a function, so the last line would be
print(buildConnectionString(myParams))
In the future please include the actual error message, as it is almost impossible to debug when a program is larger, without knowing exactly what is wrong. Dive Into Python 3 is the only online book on Python 3.X that I know of.

Tenck commented: Thanks +0
woooee 814 Nearly a Posting Maven

I would suggest learning file read/write. Then you can put 101 numbers in the file and read the file to test, instead of entering 100 numbers every time you want to test.

woooee 814 Nearly a Posting Maven

For starters, break your code into smaller pieces and test each piece before moving on. As you have found out, debugging 96 lines of code is not easy. This line should be tested first as it does not do what you think.

##--- test this with a known value (word='the')
if (word != ('the'and'on'and'and'and'are'and'years'and'the')):
##
##--- I think you want something like (but can't tell from the code)
if (word not in ['the', 'on', 'and', 'are', 'years']):
woooee 814 Nearly a Posting Maven

"/ 730" has to be a float (or you have to convert somehow).

##1.0 - 2.718281828**(-(23**2)/730)
a = 23**2
print a
a *= -1
print a
print "---------------"
print a/730
a /= 730.0
print a
print "---------------"
b =  2.718281828**a
print b
print 1.0 - b
woooee 814 Nearly a Posting Maven

As you probably have guessed by now, regular expression are considered bad style by some and so learning them is possibly a complete waste of time. If you aren't aware of Jamie Zawinski's (in)famous quote
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
http://regex.info/blog/2006-09-15/247

woooee 814 Nearly a Posting Maven

Create 2 lists, one per column, and use the shuffle function of random on both,

woooee 814 Nearly a Posting Maven

Print the list fenceLines. It should contain the length of each line which you can add up or do whatever else you want. Add you probably want to use linenum+1 so it starts with one instead of zero.

fenceLines = []
for linenum in range(int(input("Enter number of lines of fence. "))):
    fenceLines.append(int(input("Enter line %s lineal feet. " % linenum+1)))
woooee 814 Nearly a Posting Maven

All variables in create_mail are local to create_mail and can not be used in send_mail. One solution is to use one function only, which simplifies things. See here for a starter on how to use funtions.

def create_mail(message):
 
        themail = MIMEMultipart()
        recipient = "xxxxxxx@hotmail.com"
        gmail_user = "asdassdsaadssd"
        gmail_pwd = "asdasdasasdasasd"
        subject = "assadasdasasdass"
	themail['Subject']=subject
	themail['From']=gmail_user
	themail['To']=recipient
 
	themail.attach(MIMEText(message)) 
 
## comment out so everything is now part of create_mail()
##def send_mail():
	smtpserver = smtplib.SMTP("smtp.gmail.com",587)
	smtpserver.ehlo()
	smtpserver.starttls()
	smtpserver.ehlo
	smtpserver.login(gmail_user, gmail_pwd)
	print "Connection established."
	smtpserver.sendmail(gmail_user, recipient, themail.as_string())
	print "Your mail has been sent."
	smtpserver.close()
woooee 814 Nearly a Posting Maven

I would start with Scripy You can also use subprocess. Doug Hellmann has a nice write-up covering input and output pipes amount other things http://www.doughellmann.com/PyMOTW/subprocess/index.html#module-subprocess

woooee 814 Nearly a Posting Maven

You can/should use a dictionary for the values, although the code you have is fine if it works and you understand it. An example:

## replace the later code with a dictionary

# A dictionary of lists.  List elements are
# position 0=price,  1=hinges,  2=latch,  3=stop
#          4=screw gate,  5=eight foot,  6=ten foot,  7=post
eight_gate_dict ={}
eight_gate_dict[1] = [100, 4, 1, 1, 24, 4, 2, -1]
## and so forth for the others
print "gate type 1"
print "     price =", eight_gate_dict[1][0]
print "     screw gate =",eight_gate_dict[1][4]
#
# which replaces
if eightGate == 1:
    Price = 100
    eightHinges = 4
    eightGateLatch = 1
    eightGateStop = 1
    eightScrewGate = 24
    eightEightFooters = 4
    eightTenFooters = 2
    post = -1
woooee 814 Nearly a Posting Maven
longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len)
    #get longest sentence -list format with every word of sentence being an actual element-
 
    longestSent=[longestSentence]
 
    for word in longestSent:#convert the list longestSentence to an actual string

Break down the list comprehension into something readable. Perhaps splitting on the sentence break, ". ", and sending each sentence to a function which checks for the trigger word, and then returns the length of the sentence if the trigger is found, or zero if not found.

woooee 814 Nearly a Posting Maven

Store the "short" line and blank it after writing. If there isn't a short line, the store variable will be empty.

in_file = open('myhugetextfile.txt')
out_file = open('mycleaneduptextfile.txt','w')
 
#go through the file line by line
repaired_line = "" 
for line in in_file:
 
     #split on ;; and check if the length is less than 11 entries long
     #if length is less than 11, it means the line has an unnecessary newline in it
 
     if len(line.split(';;')) < 11:
          #strip the unneeded newline char off the end of the line
          line = line.strip('\n')
 
          #  store this value
          repaired_line = line
 
      else:
         out_file.write(repaired_line + line)
         
         ## blank repaired_line after every write
         repaired_line = ""
woooee 814 Nearly a Posting Maven

I would try render first, but I have never tried it. From the docs at http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qgraphicsview.html

QGraphicsView.render (self, QPainter, QRectF target = QRectF(), QRect source = QRect(), Qt.AspectRatioMode mode = Qt.KeepAspectRatio)

Renders the source rect, which is in view coordinates, from the scene into target, which is in paint device coordinates, using painter. This function is useful for capturing the contents of the view onto a paint device, such as a QImage (e.g., to take a screenshot), or for printing to QPrinter.

You could also try the PyQt Forum

woooee 814 Nearly a Posting Maven

QImage has a save function. See "Reading and Writing Image Files" here

woooee 814 Nearly a Posting Maven

File "C:\Python26\lib\site-packages\pymysql-0.2-py2.6.egg\pymysql\connections.py"

We'll eliminate the easy stuff first. Do you have MySQL installed and is the MySQL server running?

woooee 814 Nearly a Posting Maven

The error is:
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

There isn't any "+" sign in the code you posted. How about posting the entire error message including the offending line of code,

woooee 814 Nearly a Posting Maven

Python usually has ways of replacing a bunch of if/elif/else statements.

for field in infos:
        if field.startswith('AC'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('ID'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('FA'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('OS'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('SF'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('BS'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('GE'):
            f_out.write('%s\t\n' % field[3:])

    ## ---------  replace with  ----------
    for field in infos:
        test_2 = field[0:2]
        if test_2 in ["AC", "ID", "FA", "OS", "SF", "BS", "GE"]:  
            f_out.write('%s\t\n' % field[3:])
woooee 814 Nearly a Posting Maven

I want make relation with gsm modem.

We don't know what this means. If you want to communicate via a serial port, check out USPP and PySerial, but however the signal enters your computer, you will have to have an interface to the port.

woooee 814 Nearly a Posting Maven

This should be:

## changed to s[0] and d1, di.keys() is not necessary
        if s[0] not in d1:
woooee 814 Nearly a Posting Maven

Use a function and pass the file name to it. Some pseudo-code:

def mapper_dict(fname, word_dict):
    ## assumes word is first element after split()
    fp = open(fname, "r")
    for rec in fp:
        substrs = rec.split()
        word = substrs[0]
        if word not in word_dict:
            word_dict[word] = 0
        word_dict[word] += 1
    return word_dict

word_dict = {}
for fname in ["/a/b/abc", "/d/e/def", "/g/h/ghi"]:
    word_dict = mapper_dict(fname, word_dict)
woooee 814 Nearly a Posting Maven

Personal preference here is to use a dictionary, with the key being the word, pointing to the number. Convert the first list to a dictionary, loop through the second list and if the word is found in the dictionary, add to the number http://www.greenteapress.com/thinkpython/html/book012.html#toc120 Post back with any code you are having coding problems with for additional help.

woooee 814 Nearly a Posting Maven

You would have to name it yourself via a class variable (shared by all instances of the class)

class TestClass(object):
    class_name = "TestClass"  ##  class variable
    def __init__(self):
        print "class instantiated"
 
print TestClass.class_name
ins = TestClass()
print TestClass.class_name
woooee 814 Nearly a Posting Maven

You can use the id also since you only want a name that is unique. Perhaps a dictionary with name/id --> class + args as well.

class TestClass(object):
    def __init__(self):
        print "class instantiated"
 
ins = TestClass()
unique_name = str(id(ins))
print unique_name
woooee 814 Nearly a Posting Maven

It is simple to use EasyGUI to get the data instead of keying in the entire file path, elevation, and pointbuff. Also, making one pass through the input file list and converting to floats will save doing that every time you access each record. An example follows with some sample code to print elevation differences that exceed the elevation input.

def convert_arg(arg_in):
    """ return a float if arg_in will convert, otherwise return zero
    """
    try:
        ret_arg = float(arg_in)
        return ret_arg
    except:  ## will catch anything, like "" that will not convert
        return 0


def get_file_name(dir_in = ""):
    """ example of choosing a file and entering data via EasyGUI
        http://easygui.sourceforge.net/
    """
    import easygui
    file_name_and_path = easygui.fileopenbox( \
                     "Double Click", "Choose your file", "/home/", "*")

    title = "pointbuff and elevation"
    msg = "Enter Now"
    field_names = ["Point Buff","Elevation"]
    field_values = []   ## start with no default values
    field_values = easygui.multenterbox(msg, title, field_names, field_values )

    # make sure that none of the fields was left blank
    while 1:
         if type(field_values) == None:
            field_values = [ -1, -1 ]
	    break
         errmsg = ""
         for x in range(len(field_names)):
            if field_values[x].strip() == "":
               errmsg = errmsg + ('"%s" is a required field.\n\n' % field_names[x])
         if errmsg == "": 
            break # no problems found
         field_values = easygui.multenterbox(errmsg, title, field_names, field_values)
    return file_name_and_path, field_values[0], field_values[1]


def read_file(filename):
    """ read the file, convert {1]. [2]. and [3] to floats and return
        the new list
    """
    converted_list = []
##    read1 = csv.reader(open(filename, 'rb'))
    read1 …
woooee 814 Nearly a Posting Maven

I essentially need to compare each Item in a list to every other item in the list.

Generally speaking, to compare you start with the first item in the list and compare to item #2, #3, etc. Then the same for the second item through n-1, as there is nothing to compare the last item to. A simple example to illustrate:

test_list = ["abc", "def", "abf", "abc", "abf", "xyz" ]

stop_y = len(test_list)
stop_x = stop_y -1
for x in range(0, stop_x):   ## stop at end-1
    ##  start at the next element and go through the end
    for y in range(x+1, stop_y):
        if test_list[x] == test_list[y]:
            print "2 are equal", test_list[x], x

Note that this brute force method can take some time with a large file (60,000 recs = 59,999 passes through the [smaller each time] list). A faster way is to use a set or dictionary indexed on the key element(s).

You should use a function instead of all of this code doing the same thing.

x2 = test[1]
        if x2 == "":
            x2 = 0
        else:
            x2 = float(x2)
        y2 = test[2]
        if y2 == "":
            y2 = 0
        else:
            y2= float(y2)
 
        elev2 = test[3]
        if elev2 == "":
            elev2 = 0
        else:
            elev2 = float(elev2)
##
##---------- use instead
def convert_arg(arg_in):
    """ return a float if arg_in will convert, otherwise return zero
    """
    try:
        ret_arg = float(arg_in)
        return ret_arg
    except:  ## will catch anything, like "" that will not convert
        return 0

x2 = …
woooee 814 Nearly a Posting Maven

You should be able to read the 100 bytes, split and write. The following code uses 25 bytes and splits from 10 through 20 (11 bytes) for simplicity.

alpha = "abcdefghijklmnopqrstuvwxy"
print alpha
print alpha[9:20]
woooee 814 Nearly a Posting Maven

Here is a link to simple on-line tutorial. See the explanation under "Functions". You should book mark this link for future reference http://hetland.org/writing/instant-python.html

woooee 814 Nearly a Posting Maven

Perhaps I am missing something, but the following code should work. But once you get past the precision of floating point numbers you will have to use the decimal module whichever way you do it.

import decimal
x = decimal.Decimal("2.4999999999999999999999999")
whole, remain = divmod(x, 1)
if remain >= decimal.Decimal("0.5"):
    whole += 1
print whole
woooee 814 Nearly a Posting Maven

I prefer to bind the button to a function that returns the desired variable, but it is somewhat personal preference.

from Tkinter import *

class ChooseVideoFiles:
    def __init__(self, root):
        canv = Toplevel(root)
        canv.geometry("+150+250")
        title = Label(canv, 
              text = "Select 3 videos with specified or a bit longer length",
              font = ("Helvetica", 10, "bold")).grid()
        self.buttons(canv)
        exit = Button(canv, text='Exit', command=top.quit).grid(row=5,column=0)

    ##-------------------------------------------------------------------         
    def buttons(self, canv):
        b_row=1
        b_col=0
        parameter_list = [ [2, "2 minutes", "Line 1"], \
                           [3, "3 minutes", "Line 2"], \
                           [5, "5+ minutes", "Line 3"] ]

        for param in parameter_list:
            b = Button(canv, text=param[1])
            b.grid(padx=3, pady=5, row=b_row, column=b_col, sticky=W)
            lab = Label(canv, text=param[2]).grid(padx=93, pady=5, 
                        row=b_row, column=b_col, sticky=W)

            def handler ( event, self=self, button_num=param[0] ):
                return self.cb_handler( event, button_num )
            b.bind ( "<Button-1>", handler )

            b_row += 1

    ##----------------------------------------------------------------
    def cb_handler( self, event, cb_number ):
        print "cb_handler", cb_number                

top = Tk()
CV = ChooseVideoFiles(top)
top.mainloop()
woooee 814 Nearly a Posting Maven

Use root.withdraw

from tkinter import *
##from tkinter import ttk
from tkinter import messagebox

root = Tk()
root.withdraw()
answer = messagebox.askyesno(message="Are you thinking of the " + "data " + "?"
                             ,icon='question' ,title="My guess")
print(answer)
woooee 814 Nearly a Posting Maven

You have to find some unique combination that you can split on. If SV= is always the final string then you can split on that. You could also split on finding X number of capital letters in a row.

## an easy way to create the string from the post
seq = ["sp|P20905|5HT1R_DROME 5-hydroxytryptamine receptor 1", 
"OS=Drosophila melanogaster GN=5-HT7 PE=2 SV=1 ",
"MALSGQDWRRHQSHRQHRNHRTQGNHQKLISTATLTLFVLFLSSWIAYAAGKATVPAPLV",
"EGETESATSQDFNSSSAFLGAIASASSTGSGSGSGSGSGSGSGSGSYGLASMNSSPIAIV",
"SYQGITSSNLGDSNTTLVPLSDTPLLLEEFAAGEFVLPPLTSIFVSIVLLIVILGTVVGN",
"VLVCIAVCMVRKLRRPCNYLLVSLALSDLCVALLVMPMALLYEVLEKWNFGPLLCDIWVS",
"FDVLCCTASILNLCAISVDRYLAITKPLEYGVKRTPRRMMLCVGIVWLAAACISLPPLLI",
"LGNEHEDEEGQPICTVCQNFAYQIYATLGSFYIPLSVMLFVYYQIFRAARRIVLEEKRAQ",
"THLQQALNGTGSPSAPQAPPLGHTELASSGNGQRHSSVGNTSLTYSTCGGLSSGGGALAG",
"HGSGGGVSGSTGLLGSPHHKKLRFQLAKEKKASTTLGIIMSAFTVCWLPFFILALIRPFE",
"TMHVPASLSSLFLWLGYANSLLNPIIYATLNRDFRKPFQEILYFRCSSLNTMMRENYYQD",
"QYGEPPSQRVMLGDERHGARESFLD"]

seq_str = "".join(seq)
result = seq_str.find("SV=")
if result > -1:     ## 'SV=' found 
    result += 5     ## skip over SV=
    print seq_str[:result]
    print
    print seq_str[result:]
woooee 814 Nearly a Posting Maven

To get a matrix, you would have to split each record in the file. The file will be read in as a single dimension list if each record has a newline. You then have to split each record on the individual fields to get a matrix that you can access. This program creates a file first, with comma delimited fields and then reads it back in, splits into fields on the commas, and then looks up individuals. If you only want to look up first name you would use a dictionary instead of a list-of-lists/matrix.

def print_name(rec):
    print
    print "first name =", rec[0]
    print "last name = ", rec[1]
    print "street =    ", rec[2]
    print "city =      ", rec[3]
    print "state =     ", rec[4]


## output the file
fname = "./test_name"
fp_out = open(fname, "w")
fp_out.write("Bill,Smith,132 Main St.,Anytown,MI\n")
fp_out.write("Mary,Jones,456 Elm Ave.,Metropolis,NY\n")
fp_out.write("Jered,Weaver,2000 Gene Autry Way,Anaheim,CA")
fp_out.close()

## read it using readlines to get a list of records
fp = open(fname, "r")
single_list = fp.readlines()
print single_list

## split each record and store in a separate list
list_of_items = []
for rec in single_list:
    rec = rec.strip()
    one_rec_list = rec.split(",")
    print one_rec_list
    list_of_items.append(one_rec_list)

## look up first name = "Mary"
for rec in list_of_items:
    if rec[0] == "Mary":
        print_name(rec)

## look up city = "Anaheim"
for rec in list_of_items:
    if rec[3] == "Anaheim":
        print_name(rec)
woooee 814 Nearly a Posting Maven
woooee 814 Nearly a Posting Maven

The following part of your code doesn't make sense. You should go back to where ever the code came from and double check that it was copied correctly, and that you copied all of the code supplied. Also, print the dictionary to see what it contains.

clist= {}
for word in wordsdict:
    if word in times:
       average = wordsdict[word] / times[word]
       clist = {word:average} [

Edit: This probably doesn't do what you think either. Start by breaking it down into simple steps and then code each step.

if word not in wordsdict:
             wordsdict[word] = cvalue
             times[word] = 1
         else:
             times[word] = 1
             wordsdict[word] = sum([cvalue,wordsdict[word]]) 
             times[word] = times[word] + 1
woooee 814 Nearly a Posting Maven

Using EasyGUI http://easygui.sourceforge.net/download/current_version/tutorial/ is a simple solution and should solve the problem