Go to Post If I was making this I would want to not have to use anything smaller than a 3/16" end mill, but 1/8" would be acceptable. Anything smaller and I'd tell the designer to go play in traffic. - Cory [more]
Home
Go Back   Chief Delphi > Technical > Programming
CD-Media   CD-Spy  
portal register members calendar search Today's Posts Mark Forums Read FAQ rules

 
Closed Thread
Thread Tools Rate Thread Display Modes
  #1   Spotlight this post!  
Unread 27-08-2010, 23:09
Robototes2412's Avatar
Robototes2412 Robototes2412 is offline
1 * 4 != 14
FRC #2412 (Robototes)
Team Role: Programmer
 
Join Date: Jan 2010
Rookie Year: 2007
Location: Bellevue
Posts: 312
Robototes2412 is on a distinguished road
Im doing something wrong here (python)

I'm working on a scouting gui and framework for my team. I have the following files (in a spoiler):
[spoiler]
teamLib.py:
Code:
#!/usr/bin/python

import os

toCommit = list()

class team:
    """
    Its a object to hold team data
    """
    def __init__(self, name = "", number = 0, robotName = "", robotType = 0):
        self.name = name
        self.number = number
        self.robotName = robotName
        self.robotType = robotType

def newTeam(name, number, robotName, robotType):
    """
    Wrote this before i found out about constructors, does the same thing as team.__init__()
    """
    temp = team()
    temp.number = number
    temp.name = name
    temp.robotName = robotName
    temp.robotType = robotType

    return temp

def teamFromDict(theDict):
    """
    Returns a team object based on a dictionary argument
    """
    return team(
        theDict["name"], 
        theDict["number"], 
        theDict["robotName"], 
        theDict["robotType"]
    )

def saveTeam(team_obj):
    """
    Appends the team object to the toCommit List
    """
    config = {}
    config["name"] = team_obj.name
    config["teamNumber"] = team_obj.number
    config["robotName"] = team_obj.robotName
    config["robotType"] = team_obj.robotType

    toCommit.append(config)
#    f = open("./Scouting/robot", "w+")
#    f.write(repr(config))
#    f.close()

def read():
    """
    Opens the config file, returns the superDict
    """
    try:
        f = open("./Scouting/robot", 'rt')
        try:
            content = f.read()
            config = eval(content)
            f.close()
            toCommit.insert(999,config)
            
        except:
            print "cannot read file"
    except:
        print "cannot open file"

def commit():
    """
    Writes the team values to the config file in a listed dict
    """
    f = open("./Scouting/robot", "w+")
    f.write(repr(toCommit))
    f.close()
    clearList(toCommit)

def clearList(lists):
    """
    A clever hack to kill a list
    """
    while True:
        try:
            lists.pop()
        except:
            break

def interpretList(lists, value):
    """
    Give it the list you want, and the position of the team, and it will return a team object with the dict data
    """
    return teamFromDict(lists[value])

def countListElements(lists):
    i = 0
    while True:
        try:
            lists[i]
        except:
            break
        i = i + 1
    return i
cmdlinehelpers.py:
Code:
import teamLib

numberOfTeamsInList = teamLib.countListElements(teamLib.toCommit)

def addTeam():
	teamLib.saveTeam(
		teamLib.team(
			raw_input("Team Name: "), 
			input("Team Number: "), 
			raw_input("Robot Name: "), 
			input("Robot Type: ")
		)
	)
	print "Saved to list"
	
def showTeam():
	print numberOfTeamsInList
	temp = numberOfTeamsInList
	request = input("choose a number")
	prettyify(teamLib.interpretList(teamLib.toCommit, request))

def prettyify(teamObject):
	print "Team Name: %d" %teamObject.name
	print "Team Number: %d" %teamObject.number
	print "Robot Name: %d" %teamOcject.robotName
and, finally, cmdLineTest.py:
Code:
#!/usr/bin/python

import teamLib, cmdlinehelpers

teamLib.read()

alive = True

numberOfTeamsInList = teamLib.countListElements(teamLib.toCommit)

print "There are the following number of teams in the list"
print numberOfTeamsInList

print "\nPlease enter your command:"

while alive:
	request = raw_input("$> ")
	if request == "show":
		cmdlinehelpers.showTeam()
	if request == "add":
		cmdlinehelpers.addTeam()
	if request == "help":
		print "Commands are: \n\nshow, add, save, load, help, quit"
	if request == "save":
		teamLib.commit()
		teamLib.read()
		numberOfTeamsInList = teamLib.countListElements(teamLib.toCommit)
		print "Saved :D"
	if request == "load":
		teamLib.read()
		numberOfTeamsInList = teamLib.countListElements(teamLib.toCommit)
		print "Found %d teams" %numberOfTeamsInList
	if request == "quit":
		print "bye"
		alive = False
[/spoiler]
the problem is that when I call teamLib.read(), teamLib.toCommit, which is a list, inserts the contents of ./Scouting/robot (which is a list of dicts) into another list, or (for clarity's sake) I get this:
Code:
[[{"teamName": 'YouBots'}]]
instead of:
Code:
[{"teamName": 'YouBots'}]
any tips?
  #2   Spotlight this post!  
Unread 27-08-2010, 23:44
demosthenes2k8's Avatar
demosthenes2k8 demosthenes2k8 is offline
Graduated but not gone
AKA: Matt Soucy
FRC #0166 (Chop Shop 166)
Team Role: Mentor
 
Join Date: Jan 2009
Rookie Year: 2007
Location: Merrimack, NH
Posts: 589
demosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to beholddemosthenes2k8 is a splendid one to behold
Send a message via AIM to demosthenes2k8 Send a message via Yahoo to demosthenes2k8
Re: Im doing something wrong here (python)

If that's consistently the problem, try doing a simple
Code:
teamLib.toCommit = teamLib.toCommit[0]
That might fix up the problem.
__________________


GSR Dean's List Finalist 2011
  #3   Spotlight this post!  
Unread 28-08-2010, 03:21
AustinSchuh AustinSchuh is offline
Registered User
FRC #0971 (Spartan Robotics) #254 (The Cheesy Poofs)
Team Role: Engineer
 
Join Date: Feb 2005
Rookie Year: 1999
Location: Los Altos, CA
Posts: 803
AustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond repute
Re: Im doing something wrong here (python)

What does your "./Scouting/Robot" file look like normally? It's hard to just read your code and provide feedback without seeing the data format.

Also, have you looked at "pickling" your data instead of using eval and repr? Pickled data should be faster to load and more secure than eval (which is a giant security hole...). And easier to get working.
  #4   Spotlight this post!  
Unread 28-08-2010, 08:30
Bomberofdoom's Avatar
Bomberofdoom Bomberofdoom is offline
Biggest FIRST addict in Israel
AKA: Nir Levanon
FRC #2230 (Zcharia's Angels)
Team Role: Programmer
 
Join Date: Jan 2007
Rookie Year: 2007
Location: Israel
Posts: 471
Bomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond reputeBomberofdoom has a reputation beyond repute
Send a message via MSN to Bomberofdoom
Re: Im doing something wrong here (python)

I wasn't able to spot the problem exactly, but try to check your objects' values (print them to the interactive shell) just before/after you repr/eval them, and try to see if there was some sort of mistake in there.

Aside from that, here are a couple of tips you might wanna' use to better you program's performance a bit, and make it easier to use:

Enums:
You have yet to represent the type of robot in your outputs, such as prettyfiy(), but I already see that you defined the member robotType as a numeric one, so just in case you'll want to represnt the robot's type in text and not in numbers, you could use enums for that:

Taken from http://stackoverflow.com/questions/3...enum-in-python

Quote:
Code:
def enum(**enums):
    return type('Enum', (), enums)
Used like so:

Code:
>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
You can also easily support automatic enumeration with something like this:

Code:
def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)
Used like so:

Code:
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1

Len(object):

The Len method is used to get the length of an object holding a collection. e.g, a string can be a collection (a collection of single strings or "chars" appended).
You could use it to return the count of items in your list, like this:

Code:
def countListElements(lists):
    return len(lists)
    # if you use this method only for the toCommit list, do it like this:
    # return len(self.toCommit)
Keep us updated on how the program is progressing.
__________________
TEAM 2230 ZECHARIA'S ANGELS

2009 Microsoft Israel FRC Regional Winners!
2009 Microsoft Israel FRC Regional Chairman's Award Winners!!!
---------------------------------
2008 Microsoft Israel FRC Regional semi-finalist.
2008 Microsoft Israel FRC Regional Delphi's "Driving Tommorow's Technology" Award winner.
2008 Robot Driver
---------------------------------
2007 GM/Technion Israel FRC Regional semi-Finalist.
2007 GM/Technion Israel FRC Regional Xerox Creativity Award winner.
2007 Robot Driver.
  #5   Spotlight this post!  
Unread 29-08-2010, 23:58
Robototes2412's Avatar
Robototes2412 Robototes2412 is offline
1 * 4 != 14
FRC #2412 (Robototes)
Team Role: Programmer
 
Join Date: Jan 2010
Rookie Year: 2007
Location: Bellevue
Posts: 312
Robototes2412 is on a distinguished road
Re: Im doing something wrong here (python)

here is ./Scouting/robot: (whitespaced in json-like format for your readability)

Code:
{
    'robotName': 'The lord', 
    'robotType': 2, 
    'name': 'Bacon Scouts', 
    'teamNumber': 1233
}, 
{
    'robotName': "CheeseLord", 
    'robotType': 2, 
    'name': "The Guys", 
    'teamNumber': 2345
}
  #6   Spotlight this post!  
Unread 30-08-2010, 01:50
AustinSchuh AustinSchuh is offline
Registered User
FRC #0971 (Spartan Robotics) #254 (The Cheesy Poofs)
Team Role: Engineer
 
Join Date: Feb 2005
Rookie Year: 1999
Location: Los Altos, CA
Posts: 803
AustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond repute
Re: Im doing something wrong here (python)

That's your issue. (assuming I'm internally evaluating that correctly...) Python is going to interpret that as an array, and then you are inserting that array into a list. Hence your double packed list.

I'd highly recommend learning how pickling works. It's very easy and better than using eval in that location.

Code:
#!/usr/bin/python
import pickle

filename = "p.txt"

f = open(filename, "w")
pickle.dump({1:"a", 2:"b", 3:"c"}, f)
f.close()

f = open(filename, "r")
print pickle.load(f)
f.close()
You could also edit the code to instead use += instead of append. That'll solve your problem as well, but still leaves a security vulnerability.
  #7   Spotlight this post!  
Unread 30-08-2010, 19:44
Robototes2412's Avatar
Robototes2412 Robototes2412 is offline
1 * 4 != 14
FRC #2412 (Robototes)
Team Role: Programmer
 
Join Date: Jan 2010
Rookie Year: 2007
Location: Bellevue
Posts: 312
Robototes2412 is on a distinguished road
Re: Im doing something wrong here (python)

how would you reccomend i proceed with as little security vulnerabilities as possible?
  #8   Spotlight this post!  
Unread 30-08-2010, 20:58
AustinSchuh AustinSchuh is offline
Registered User
FRC #0971 (Spartan Robotics) #254 (The Cheesy Poofs)
Team Role: Engineer
 
Join Date: Feb 2005
Rookie Year: 1999
Location: Los Altos, CA
Posts: 803
AustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond repute
Re: Im doing something wrong here (python)

Quote:
Originally Posted by Robototes2412 View Post
how would you reccomend i proceed with as little security vulnerabilities as possible?
Web searches recommend JSON, which makes a lot of sense given how the format is put together. Use the cjson module or another similar module to parse JSON rather than eval as you have above. That will do sanity checks rather than blindly trust the code. I was going to recommend pickling until I started reading about the security of pickling. The format is designed for ease of use over security, sadly. It's an interesting read if you are interested in that type of thing.
  #9   Spotlight this post!  
Unread 30-08-2010, 23:18
Robototes2412's Avatar
Robototes2412 Robototes2412 is offline
1 * 4 != 14
FRC #2412 (Robototes)
Team Role: Programmer
 
Join Date: Jan 2010
Rookie Year: 2007
Location: Bellevue
Posts: 312
Robototes2412 is on a distinguished road
Re: Im doing something wrong here (python)

I am intending this to be a library that i can implement in many different ui's (symbian was the origional target, but I am going to write a gtk+ ui for linux and a tkinter one if you really want me to), so i need a 100% python solution. I am most likely going to go with http://pypi.python.org/pypi/simplejson/ as the json parser.
  #10   Spotlight this post!  
Unread 31-08-2010, 00:05
AustinSchuh AustinSchuh is offline
Registered User
FRC #0971 (Spartan Robotics) #254 (The Cheesy Poofs)
Team Role: Engineer
 
Join Date: Feb 2005
Rookie Year: 1999
Location: Los Altos, CA
Posts: 803
AustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond reputeAustinSchuh has a reputation beyond repute
Re: Im doing something wrong here (python)

Sounds reasonable.
Closed Thread


Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
What am I doing wrong? grrrrrrr techplex CAN 5 05-08-2010 19:40
Something Wrong with usfirst! Eric W. Jones General Forum 5 09-01-2007 02:01
Something wrong with this picture sanddrag Chit-Chat 2 30-04-2006 12:41


All times are GMT -5. The time now is 17:20.

The Chief Delphi Forums are sponsored by Innovation First International, Inc.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi