woooee 814 Nearly a Posting Maven

Python has a CSV reader/writer http://docs.python.org/release/2.5.2/lib/csv-examples.html. I would suggest you start with reading the file and printing individual rows and columns so you discover how to access them individually. Google is your friend here.

woooee 814 Nearly a Posting Maven

Somebody should Google disk cache. This is the doc for flushing write commands.

file.flush()

Flush the internal buffer, like stdio‘s fflush(). This may be a no-op on some file-like objects.
Note: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.

A RAM cache used for reading would probably be OS specific and so you would have to turn it off via the OS( in Linux you can clear it by writing to proc/sys/vm/drop_caches) but I don't know how to turn it off. A cache is also part of the drive itself for relatively recent drives. This is a random choice just to see what size of a cache a modern drive has; this one is 32MB (500 Gig is only $59.99. Damn) http://www.tigerdirect.com/applications/SearchTools/item-details.asp?EdpNo=4914330&CatId=2459

woooee 814 Nearly a Posting Maven

You use the same StringVar() if I understand what you want to do. Take a look at the following code and note how the StringVar() is declared and then attached to the second Label() and the Entry() box. Note that when the Entry() box changes the second Label() changes because they both use the same StringVar(), so no refreshing is required.

import Tkinter

class EntryTest:
   """ shows using the same StringVar in the second list box
       and in the entry box
   """
   def __init__(self):
      self.top = Tkinter.Tk()
      self.top.title("Test of Entry")
      self.top.geometry("200x125+10+10")

      self.str_1 = Tkinter.StringVar()
      label_lit = Tkinter.StringVar()

      label_1 = Tkinter.Label(self.top, textvariable = label_lit )
      label_1.pack()
      label_lit.set( "Test of Label")

      label_2 = Tkinter.Label(self.top, textvariable = self.str_1 )
      label_2.pack()

      entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1)
      entry_1.pack()
      self.str_1.set( "Entry Initial Value" )

      print_button = Tkinter.Button(self.top, text='PRINT CONTENTS',
                     command=self.getit, bg='blue', fg='white' )
      print_button.pack(fill=Tkinter.X, expand=1)

      exit_button= Tkinter.Button(self.top, text='EXIT',
                   command=self.top.quit, bg='red', fg='white' )
      exit_button.pack(fill=Tkinter.X, expand=1)

      entry_1.focus_set()
      self.top.mainloop()

   ##-----------------------------------------------------------------
   def getit(self) :
      print "getit: variable passed =", self.str_1.get()


##===============================================================
if "__main__" == __name__  :
   ET=EntryTest()
   print "under __main__ =", ET.str_1.get()

You can manually update a label also. This example is from somewhere on the web and should use a class like above, but should show you the technique to be used.

from Tkinter import *
root=Tk()

def changeLabel():
    myString.set("I'm, a-fraid we're fresh out of red Leicester, sir. ")
    
myString=StringVar()
Label(root,textvariable=myString).pack()
myString.set("Well, eh, how about a little red Leicester.")
Button(root,text='Click Me',command=changeLabel).pack()
root.mainloop()
woooee 814 Nearly a Posting Maven

Actually this is more a function of the desktop, each of which has wrappers to perform this function. KDocker for KDE is only one that comes to mind right now but there are sure to be more, perhaps one or two that are not desktop specific.

woooee 814 Nearly a Posting Maven

A simple test of the following code posted above shows that it will only find 'DTP' if it is at the beginning of the line. It should read as indicated.

f_in = ["xyz", "abcDTPxyz", "DTPabc"]
for line in f_in:

    ## the if statement should read
    ## if line.find('DTP') > -1: as line.find() returns the position found
    if line.find('DTP') == 0:
        print "DTP found in", line

""" 
prints
DTP found in DTPabc
only
"""
woooee 814 Nearly a Posting Maven

The answer is to develop good habits, one of which is to always use the complete path. It makes everything obvious. This also helps when you come back years later to debug a program because someone has moved something.

lrh9 commented: Answer is not correct. +0
woooee 814 Nearly a Posting Maven

From the PySQLite docs, a rather dated example; it allows case insensitive column access by name:

Highly optimized row_factory for column access by name
======================================================

A new function has been implemented that allows for case-insensitive
column access by name with minimal performance and memory impact,
unlike a dictionary or db_row-based approach.

To enable it, set the row_factory attribute of your connection to
sqlite.Row:

from pysqlite2 import dbapi2 as sqlite
    con = sqlite.connect(...)
    con.row_factory = sqlite.Row
    cur = con.cursor()
    cur.execute("select name_last, age from people")
    for row in cur:
        print row["Name_Last"], row[1]
woooee 814 Nearly a Posting Maven

The string "127558161.23" would not convert using the time module because it is not a 9 digit integer. Truncating the decimals yields the following result using gmtime() but is not close to the desired date and time. So it appears that the format is not "epoch second" which means a custom conversion routine will have to be used. I don't know if this comes from a Symbian platform or not, but the question should probably be asked on the phone maker's forum. Once the format is known, it can then be converted using Python or any other programming language.

time.struct_time(tm_year=1974, tm_mon=1, tm_mday=16, tm_hour=8, tm_min=49, tm_sec=21, tm_wday=2, tm_yday=16, tm_isdst=0)

woooee 814 Nearly a Posting Maven

The problem you pointed out, woooee, wasn't actually a problem. It recognizes both sticky=E and sticky="e" as valid, and they both work in exactly the same way.

E is recognized if you do a
from tkinter import *
which you can not rely on as normally "import tkinter" is used in my experience, especially if you are modifying someone else's code, and you are betting that E was not declared as a variable somewhere else in the program. "e" is always a good bet. Effbot's grid doc is a good reference http://effbot.org/tkinterbook/grid.htm And consider a function for all of those labels, passing the text, row, column, etc. to it. The same for the entry boxes, or one function to create the label and entry since entry column is always label column+1.

woooee 814 Nearly a Posting Maven

Look up the docs for sticky (you have to learn to help yourself). A hint is that there are no variables in your program named E, NE, etc.

woooee 814 Nearly a Posting Maven

Try adding some print statements as below.

def file1(filename):
    d1 = dict()
    fp = open(filename)
    for line in fp:
        print "processing file1 line =", line
        process_line1(line, d1)
        return d1
 
def file2(filename):
    d2 = dict()
    fp = open(filename)
    for line in fp:
        print "processing file2 line =", line
        process_line(line, d2)
        return d2
Gribouillis commented: good idea ! +3
woooee 814 Nearly a Posting Maven

Pass the class instance to the GUI program. An example with all classes in the same program.

import random
 
class GUIClass:
 
    def __init__(self, class_instance):
        # create a text area named "textArea"
        # bind the function "OnEnterDown" to the Enter key
        self.ci = class_instance
        print self.ci.my_number, self.ci.my_word
        print "\n calling on_enter_down() within the class"
        self.on_enter_down()

    def on_enter_down(self):
        # Call the function 'combine' in MyScript.py
        self.ci.combine()
        
class MyClass:
 
    def __init__(self):
        self.my_number = random.randint(1, 10)
        self.my_word = "Hello"
 
    def combine(self): # I want this function to be called when the Enter key is pressed
        phrase = "%s %d" % (self.my_word, self.my_number)
        print phrase

MC = MyClass()
GC = GUIClass(MC)
print "\n calling on_enter_down() outside the class"
GC.on_enter_down()
woooee 814 Nearly a Posting Maven

Mechanize is an easier way IMHO to do this. This link explains how to log in with a user name and password to a remote site
http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/

woooee 814 Nearly a Posting Maven

I've added a print statement which should clarify what you are actually doing.

p = [1, 2, 0, -1, 3, 4, 5]
smaller = 0
bigger = 0
 
i = 0
while i < len(p):  
  print "comparing", p[1], p
  if p[i] >= p:
    bigger += 1  
    print bigger
  i += 1

I think you want two for loops. Note that the logic is different if the list is sorted first.

stop = len(p)
for x in range(0, stop):
    greater_list = []
    for y in range(0, stop):
        if p[x] < p[y]:
            greater_list.append(p[y])
    print p[x], "greater =", greater_list
woooee 814 Nearly a Posting Maven

You can read the entire file into a list, process the list once appending the record number to a dictionary of lists, with the "QA" field as the key. So if record #1 has QA=123 the dictionary would then be
index_dict[123] = [1]
for record #2 QA = 12
index dict[12] = 2
record #3 QA = 123 again
index_dict[123] = [1, 3]
You can then look up a specific QA value in the dictionary and know which records in the list to print. And how are you defining "duplicate record"? If it is subsequent records with the same QA value, then you can just store the original record in the dictionary instead of the record number. Post back if you want some help with this, or want to use SQLite which is the best solution for this.

woooee 814 Nearly a Posting Maven

The number of groups that need to rotate and the step size is based on user input.

The OP is asking how to use a variable for range and step, based on user input, specifically

rotationarray[rotation][3] contains the whole rotation range and
rotationarray[rotation][4] contains the step size

OMG?? (this isn't high school).

woooee 814 Nearly a Posting Maven

You can use variables for this, if that is what you are after (untested code).

rotation_in = int(raw_input("Enter rotation "))
for el in rotationarray:
    if rotation_in == el[3]:
        print el
        for x in range(0, el[3]+1, el[4]):     ## start, stop, step
            print x
woooee 814 Nearly a Posting Maven

Dictionary doesn't allow to sort the keys or values so in that case I need to transfer it to the list. Is it correct to do it this way?

That is the way that it is usually done. In fact I can't think of any other way to order keys in an existing dictionary. Note that you are re-using the same variable here
h=histogram(h)
In this case it doesn't matter but it is not a good habit to form. Also, when you start debugging code you will learn the importance of descriptive variable names.

woooee 814 Nearly a Posting Maven

If you are calling the programs from a Python program, you can simply pass the parameter as an arg to the program or to the function being called within the program. Subprocess works fine for this http://www.doughellmann.com/PyMOTW/subprocess/index.html#module-subprocess

woooee 814 Nearly a Posting Maven
def sort(self, x):

It is bad form to re-define reserved words like "sort" so use a more descriptive name (sort what?) and avoid the confusion. Also, you should include one function at a time and test it, then add another, etc. And why are all of the functions staticMethods? Perhaps I just don't understand the logic.

thanks... do you know how i can fix it now though?

"thanks... do you know how i can fix it now though?"
Re-post the code as a new reply with code tags around it.

Looks like there is a problem with the new page form, i.e ["QUOTE"] does not work.

woooee 814 Nearly a Posting Maven

I think you want to join() everything after the first sub-string if destination does indeed contain spaces, or simply split on the colon if you know that there is never more than one in the file.

for x in ["Branch: ltm_7.4\n", "Destination: Test 5\n"]:
    x = x.strip()
    substrs = x.split()
    ## Note that join() concatenates the remaining strings
    print substrs[0], "----->", " ".join(substrs[1:])
woooee 814 Nearly a Posting Maven

I tried to add more entry boxes and make them a difference size then the rest but using the width= under the if ipos: changes them all -__-.

Just use a separate block of code to add the additional entry boxes that are a different size, or add a width parameter to the info list.

woooee 814 Nearly a Posting Maven

For future reference, a Google for "python find from one list in another list" listed this link among others http://www.daniweb.com/code/post968722.html

woooee 814 Nearly a Posting Maven

Try mechanize and see if that is any easier http://wwwsearch.sourceforge.net/mechanize

woooee 814 Nearly a Posting Maven

No testing is necessary. SQLite has been up and running for years and is fully reliable. Just write your code and go.

woooee 814 Nearly a Posting Maven

As far as I can tell, both of these options work.

x=16
backslash = chr(92)
part1 = '\x03\xa2'
part2 = hex(x)[1:]
 
command2 = "%s%s%s" % (part1, backslash, part2)
command3 = part1 + backslash + part2
woooee 814 Nearly a Posting Maven

sorry wrong error this is the error
AttributeError: Application instance has no attribute 'toggle'

"toggle" is no longer a member of Tkinter. You re-defined it as a member of your Application class.

woooee 814 Nearly a Posting Maven

I've tried everything and it gives me all types of errors.

It worked find for me. I clicked button 8 and it displayed "button 8 clicked", so you'll have to include the error message(s) for any further help.

woooee 814 Nearly a Posting Maven

I'm not sure I quite understand this. I only want a function to display text in the field depending upon what is checked. Is there anyway to do this within the function using if/elif/elif/else/

Thank you

What you display would depend on the button number sent to the function. A convenient way would use a dictionary with the button number as key pointing to the text, so it would be
self.pp_txt = desc_dict[cb_number]

If you run the code, you will see that a different number prints for each different button checked.

woooee 814 Nearly a Posting Maven

set.defference() would be the easiest if record order doesn't matter, otherwise you would have to index by record number and search the next x records to determine if a record was not found, and then go back to the original point. And you could probably delete records that were just " </group>", "<user>", "</user>", etc.

file_input_1 = [ "record 1\n",
                 "record 2\n",
                 "deleted from 2nd file\n",
                 "record 3\n",
                 "record 4\n",
                 "record 5\n" ]

file_input_2 = [ "record 1\n",
                 "record 2\n",
                 "record 3\n",
                 "record 4\n",
                 "added to 2nd file\n",
                 "record 5\n" ]

set_1 = set(file_input_1)
set_2 = set(file_input_2)

diff_1_2 = set_1.difference(set_2)
diff_2_1 = set_2.difference(set_1)
print(diff_1_2)
print(diff_2_1)
woooee 814 Nearly a Posting Maven

You have to define "different" before you begin. Do you want to compare the first record in the first file to the first record in the second file, and the second record to second record, etc.? What happens if one of the files has one record more than the other file, or is that detail not to be considered. Generally you would read the files into lists using readlines and then check first to first, second to second, etc. for a one to one check. You could also read both files, compare the records, read both files, rinse and repeat. Linux provides this with diff (man diff) if you are running one the the Linux distros.

woooee 814 Nearly a Posting Maven

I generally use a dictionary to store the buttons, but in any case you pass the button number to a callback bound to the specific button. You should also use one function to create a button, and pass the button's text, etc. to the function. Note that this does not use a grid, but you should get the idea.

def one_button(txt, var):
      b = Checkbutton(self.frame, text = txt, variable=var)
      b.pack()
      def handler ( event, self=self, button_num=self.button_num ):
          return self.cb_handler( event, button_num )
      b.bind ( "<Button-1>", handler )
      self.button_num += 1

      return b

   ##-------------------------------------------------------------------
   def cb_handler( self, event, cb_number ):
       print cb_number, "button pressed"
woooee 814 Nearly a Posting Maven

You would have to test each record for the specific info you want to keep, "Ship", "start_time", etc., and store it, probably in a dictionary. If the example you posted has not been "improved" for our readability then you can start writing once you hit *END*, headers first and then each record in turn. You would probably want a comma delimited file, if there isn't any commas in the records themselves, to import in Excel. Start with reading one file, one record at a time. Next, initialize a dictionary with the keys you want to search for. It appears that you can search the dictionary using the first word in each record, (strip non-letters and split). Post back with some code for more assistance and see 10.8, Text Files, here http://openbookproject.net/thinkcs/python/english2e/ch10.html

woooee 814 Nearly a Posting Maven

I tried adding in where you had edited.. but it doesn't seem to work still.

Test each function individually and post what "doesn't work" means for each individual function.

woooee 814 Nearly a Posting Maven

You should not be using "string" as a variable name as it is used by Python. Also, "i", "l" and "o" are not good choices for single letter variable names as they can look like numbers. Test each function individuallty and see comments in the code.

def searchAuthor(dataList, string):
   print"\n"
   print"Search results:"
   i = -1
   for listIndex, subList in enumerate(dataList):
      try:
         ind = subList.index(string, i+1)

         ##   test for a successful find, -1 == not found
         if ind > -1:

             ## you are searching through subList but sending 
             ## authorsList to the print function
             ## Make sure they are properly aligned
             print authorNameOutput(authorsList[listIndex]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
             break
      except ValueError:
         print "\n Please search again"
         break 
##
##-----------------------------------------------------------------------------
def search(dataList, string):
   """This is the search function that searches the defined
      string within its respective list"""
   print "\n"
   print "Search results:"
   i = -1
   for value in dataList:
      try:

         ##   while loop is not necessary and is an
         ##   infinite loop that will only stop if string is found
         while 1:

            ## do you want to look in dataList or value?
            ind = dataList.index(string, i+1)

            ##   same thing here
            if ind > _1:

                ## you are searching through dataList but sending 
                ## authorsList to the print function
                print authorNameOutput(authorsList[i]),". (",papersList[i][0],"). ",papersList[i][1],". ",journalsList[i],"."
                break
      except ValueError:
         print "\n Please search again"
         break
woooee 814 Nearly a Posting Maven

Add some print statements to ferret out what's happening, for example:
And Idle (comes with Python) is much easier to use than the Python shell/command line.

word=str(raw_input("Please enter a string:"))
##   Don't use 'string' as a variable name
input_string ="word"
word_rev =word[::-1]

print "comparing", input_string, word
if (input_string == word_rev):
    print "The word your have entered is a palindrome"
else:
   print"The word you have entered is not a palindrome"

And note that "banana" is not a palindrome, so you should use another word like "racecar".

woooee 814 Nearly a Posting Maven

What method are you using to access the office computer from home and can you sign in and get the necessary permissions so as to execute files from home?

2. Check if the latest nightly build has been successful. If it is successful, deploy it on a test environment by clicking on 'Deploy this build' link.

It should be simple to have a cron job that runs a program to test for a successful nightly build, using name, time written, or seeing a new file, and then run whatever you want to run, but I don't know what it is that determines if the build has been successful or not, so can't really say.

woooee 814 Nearly a Posting Maven

This is a tricky one (note the parens in the statement).

L = [ [4,5,6] , [2,4,5] ]
new_L = [ (y if ctr > 1 else y*y) for x in L for ctr, y in enumerate(x)]
print new_L
woooee 814 Nearly a Posting Maven

Yo write what you want to keep to a separate file. Start here http://www.greenteapress.com/thinkpython/html/book015.html#toc154

woooee 814 Nearly a Posting Maven

The "standard" way does not use regular expressions. When "<test>" is found, start appending records to a list. When "</test> " is found, print or do whatever with list and re-define it as an empty list, and continue down the line.

woooee 814 Nearly a Posting Maven

A Google of "Perl to Python" will yield some of the programs that will do this for you. If the translation is incomplete, post the offending code, with an explanation of what it should do, and someone will help. Note that this code appears to call other functions, so just translating this portion will probably not work.

woooee 814 Nearly a Posting Maven

File "./firstpython", line 6, in <module>
input()
File "<string>", line 0

You want to use raw_input() for the Python version you are using, or enter an integer.

woooee 814 Nearly a Posting Maven

It appears that you did not test this code as you only read the first rec. Also you can use
for rec in inFile
instead of the while loop. And string.split() is deprecated, use line.split() instead.

line = inFile.readline()

   ##---------------------------------------------------------------
   ##   this is an infinite loop unless the 1st rec = ""
   ##---------------------------------------------------------------
    while line != "":
        name, num = string.split(line)
        total = total + eval(num)
        count = count + 1
        avg = total/count
        outFile.write('%d' %(avg))
woooee 814 Nearly a Posting Maven

For x in row 2, col 1, append to empty list[]. Now look to see if there is an x above it....No? well now is there an x to the left.....No? well now look to right....Yes? right, append it to the list[]. Is there now an x underneath this x.....Tes? right well append it to the list[].

Now look to see if there is an x above it (row-1)
well now is there an x to the left (col-1)
well now look to right (col+1)
Is there now an x underneath this x (row+1)

woooee 814 Nearly a Posting Maven

I know there is a better way to write that last line,
but I'm too lazy to look into it

I think you could convert to a list and just pass a pair of index counters, but it is more than I want to do as well.

woooee 814 Nearly a Posting Maven

What i am trying to do is take the list of strings, which must be of equal length, and use a nested for loop to go over each character and its neighbours for creation of the relevant equations.

This solution is similar to a tic-tac-toe game, except the board can be any size. One way to do it is to index a dictionary using a tuple containing the row & column number. The neighbors then would be a row, column tuple for row+1, row-1, col+1, and col-1.

shape=[
    '    ',
    '++++',
    'xxxx',
    'xxxx',
    'xxxx',
    '----',
    '    ']

shape_dict = {}
for row, rec in enumerate(shape):
    for col, ch in enumerate(rec):
        shape_dict[(row, col)] = ch

print shape_dict[(2,2)]   ## print one as an example
woooee 814 Nearly a Posting Maven

See the Student class under "Key Functions" here http://wiki.python.org/moin/HowTo/Sorting if you are talking about a list of classes. Also, see the "The Old Way Using the cmp Parameter" on the same page.

woooee 814 Nearly a Posting Maven

You can use a one to one dictionary
"ą" --> "a"
or use the ord/decimal value if there are codec conversion problems. A decimal value conversion dictionary would be something like:

conv_dict = {}
conv_dict[ord("ą")] = "a"
#
# and to convert
test_ch = "ą"
if ord(test_ch) in conv_dict:
    test_ch = conv_dict[ord(test_ch)]
woooee 814 Nearly a Posting Maven

Use a function.

def download_url(channel_num):
    url = 'http://192.168.1.6:8008/schedule.html?channel=%s' % (channel_num)
    texto = urllib.urlopen(url).read()
    index = texto.find('<td class="topaligned "><div class="withmargin nowrap"')
    h1 = index+55
    index = texto[h1:].find('><span class="title">')
    pi1 = h1 + index + 21
    index = texto[pi1:].find('</span><br')
    pf1 = pi1 + index
    index = texto[pf1:].find('<td class="topaligned "><div class="withmargin nowrap"')
    h2 = pf1+index+55
    index = texto[h2:].find('><span class="title">')
    pi2 = h2 + index + 21
    index = texto[pi2:].find('</span><br')
    pf2 = pi2 + index
    print texto[h1:h1+19]+'   '+texto[pi1:pf1]+'\n'+texto[h2:h2+19]+'   '+texto[pi2:pf2]

if __name__ == '__main__':
    download_url("120")
    download_url("121")
woooee 814 Nearly a Posting Maven
def main():
      maze= open('maze.txt','r+')
      for line in maze:
          line = line.strip()
          print line
       maze.close()
print
start(maze,x,y)
print maze[y][x]

This code won't run. You don't call main() and neither maze, x, or y are defined before calling the start(maze, x, y) function. "How To Think Like A Computer Scientist" is a good learning tool; "Functions" Chapter (3.5) = http://www.greenteapress.com/thinkpython/html/book004.html