def test_validator_age_valid_1(self): val = Validator() test_data = 23 expected_result = True actual_result = val.Validate_Age(test_data)[0] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def test_validator_age_invalid_string(self): val = Validator() test_data = "Blah" expected_result = False actual_result = val.Validate_Age(test_data)[0] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def test_file_input(self): self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.myModel.toDataSet() self.failIfEqual(self.myModel.get_data_set(), None)
def __init__(self, matrix, alpha, beta, p, ants_n, t_max, Q): self.validator = Validator() self.subject = matrix self.alpha = alpha self.beta = beta self.p = p self.Q = Q self.L = self.INFINITY self.path = list() self.ants_n = ants_n self.t_max = t_max self.cities = len(self.subject) self.ants = list() for i in range(0, self.ants_n): a = Ant(self.cities) self.ants.append(a) self.pheromones = list() for i in range(0, len(self.subject)): self.pheromones.append(list()) for j in range(0, len(self.subject[i])): if i == j: self.pheromones[i].append(0) else: self.pheromones[i].append(1.0)
def test_validator_empid_false_2(self): val = Validator() employee_place_holder = '' test_data = '3201' actual_result, error_message = val.val_empid(employee_place_holder, test_data) self.assertFalse(actual_result, error_message)
def test_date(): dates = ( # valid "22.05.1988", "01.01.2000", "1.1.0001", "1.1.9999", "27.02.2000", "28.2.2000", "29.02.2000", # 29.02. is a valid date in 2000 # not valid "1.1.10000", # biggest possible year is 9999 "1.1.0", # smallest possible year is 1 "1.1.0000", "1.1." "1", "30.02.2000", "31.02.2000", "31.04.2000", "29.02.2001", ) validator = Validator() for date in dates: if validator.validate_date(date, "%d.%m.%Y"): validated = "valid" else: validated = "not valid" print ("{0:32} {1:10}".format(date, validated))
def can_host_flavor(args): if is_admin(): f = validator.validate_flavor(args.flavor) s = validator.validate_server(args.machine_name) Controller.can_host_flavor(f, s) else: raise Exception(exp.ADMIN_PRIVILEGE_REQUIRED)
def test_validator_empid_true(self): val = Validator() employee_place_holder = '' test_data = 'A201' actual_result = val.val_empid(employee_place_holder, test_data) self.assertTrue(actual_result)
def __init__(self, dir_path, file_name=None): self.validator = Validator() self.validator.is_folder(dir_path) self.file_name = file_name self.dir_path = dir_path self.delimiter = ';' self.sep = ';'
def test_validator_sales(self): self.myValidator = Validator() self.result = self.myValidator.match_sales("235") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_sales("FED") self.expected = None self.failUnlessEqual(self.result, self.expected)
def test_validator_weight(self): self.myValidator = Validator() self.result = self.myValidator.match_weight("Normal") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_weight("F") self.expected = None self.failUnlessEqual(self.result, self.expected)
def test_validator_gender(self): self.myValidator = Validator() self.result = self.myValidator.match_gender("M") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_gender("G") self.expected = None self.failUnlessEqual(self.result, self.expected)
def test_validator_id(self): self.myValidator = Validator() self.result = self.myValidator.match_id("D003") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_id("DDD03") self.expected = None self.failUnlessEqual(self.result, self.expected)
def test_csv_file_input(self): self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.expected = 12 self.myModel.toDataSet() self.failUnlessEqual(self.myModel.get_data_set().__len__(), self.expected)
def test_validator_birthday_valid(self): val = Validator() test_data_1 = "25-11-1991" test_data_2 = 26 expected_result = True actual_result = val.Validate_Birthday(test_data_1, test_data_2)[0] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def test_validator_birthday_invalid_wrong_age_error_message(self): val = Validator() test_data_1 = "25-11-1991" test_data_2 = 27 expected_result = "The age given and birthday do not line up" actual_result = val.Validate_Birthday(test_data_1, test_data_2)[1] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def test_validator_age(self): self.myValidator = Validator() self.result = self.myValidator.match_age("13") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_age("F") self.expected = None self.failUnlessEqual(self.result, self.expected)
def test_validator_birthday_invalid_string_age(self): val = Validator() test_data_1 = "11-25-1991" test_data_2 = "Yahhh" expected_result = False actual_result = val.Validate_Birthday(test_data_1, test_data_2)[0] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def test_validator_birthday_invalid_not_date_error_message(self): val = Validator() test_data_1 = "11-25-1991" test_data_2 = 27 expected_result = "Birthday is not a valid date" actual_result = val.Validate_Birthday(test_data_1, test_data_2)[1] self.assertEqual(actual_result, expected_result, "actaul_result should equal" + str(expected_result))
def __init__ (self, training_data=None, target=None): self.epsilon = Constants().get_rbfn_deafult_epsilon() self.k = Constants().get_rbfn_default_k() self.base_function_type = Constants().get_rbfn_gaussian_abbreviation() self.training_data = training_data self.target = target self.solver = Constants().get_solver_ls_abbreviation() self.validator = Validator()
def __init__(self, file_path, file_name): self.validator = Validator() self.validator.is_folder(file_path) self.normalized = False self.norm = None self.file_name = file_name self.file_path = file_path self.data, self.header = self.set_data() self.rbfn = RBFN()
def test_washing_data(self): # There are 5 errors so length should be cut down to 7 after washing self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.expected = 8 self.myModel.toDataSet() self.failUnlessEqual(self.myModel.wash_data().__len__(), self.expected)
class Algorithm: INFINITY = 999999 def __init__(self, matrix): self.validator = Validator() self.subject = matrix self.results = list() self.matrixes = list() def run(self): self.validator.set_subject(self.subject) if not self.validator.validate(): print('Validation error. Please check source file.\n') return for i in range(len(self.subject)): m = list() for row in self.subject: m.append(list(row)) self.matrixes.append(m) self.processMatixes() def processMatixes(self): i = 0 for m in self.matrixes: way = list() rate = 0 current = i for j in range(len(m) - 1): for k in range(len(m)): m[k][current] = self.INFINITY way.append(current) v = min(m[current]) current = numpy.argmin(m[current]) rate += v self.results.append(Result(way, rate)) i += 1 def findMinResult(self): m = self.results.pop() while len(self.results): p = self.results.pop() if p.rate < m.rate: m = p return m def print_result(self): o = self.findMinResult() print('Length: ' + str(o.rate) + '\n') result = '' for i in o.path: result += str(i + 1) + ' -> ' result += str(o.path[0] + 1) print(result)
def sendData(self): '''Funkcja wysylajaca przechowywane dane w buforze do walidacji i ustawiajaca flagi na false''' if self.isReady(): Validator.validate([self.time[0], self.longitude[0], self.latitude[0], self.altitude[0], self.roll[0], self.pitch[0], self.heading[0]]) self.time = [0, False] self.longitude = [0, False] self.latitude = [0, False] self.altitude = [0, False] self.roll = [0, False] self.pitch = [0, False] self.heading = [0, False]
def add_machine(args): if is_admin(): Controller.add_new_machine(args.server_name, validator.validate_rack(args.rack), validator.validate_ip(args.ip), validator.validate_int_value(args.mem), validator.validate_int_value(args.disk), validator.validate_int_value(args.vcpus)) else: raise Exception(exp.ADMIN_PRIVILEGE_REQUIRED)
def create_flavors(file_name): with open(file_name, "r") as f: # The first line indicates how many flavors store flavors_cnt = f.readline().split() flavors_list = [] for i in range(int(flavors_cnt[0])): line = f.readline().split() flavor = Flavor(line[0], validator.validate_int_value(line[1]), validator.validate_int_value(line[2]), validator.validate_int_value(line[3])) flavors_list.append(flavor) dao.create_flavors(flavors_list)
def allocate(self): exec("self.allocator = " + self.allocation + "()") self.allocator.allocate(self.electors, self.data) validator = Validator() valid, allocated = validator.validate(self.electors, self.data) if not valid: raise Exception("Correct Number of Electors Not Allocated: " + str(allocated)) dq = DemocracyQuotient().calc(self.data) return self.data, dq
def Create_device(): if request.method == 'POST': data_device = Validator().Add_device(data, request.data) if data_device['status']: return jsonify({'msg': data_device['message']}), status.HTTP_200_OK else: return jsonify({'msg': data_device['message'] }), status.HTTP_400_BAD_REQUEST if request.method == 'GET': return jsonify({'msg': Validator().Display_device(data)}), status.HTTP_200_OK
def __init__(self, players, updater=None): self.players = players self.nplayers = len(players) self.state = GameState(self.nplayers) self.validator = Validator(self.state) self.logger = logging.getLogger(__name__) if updater is not None: self.update = ViewUpdater() else: self.update = updater self.delay = 0.5 self.stalematecond = 2000
def play(self): """ This method is the core of game which takes care of game's status """ won = False who = -1 board = Board(3, 3) validator = Validator(3, 3) self.first = input("First player please input your Name:\n>> ") self.second = input("Second player please input your Name:\n>> ") while (won is not True): if board.isfull() is not True: r = int( input( f"{self.first}: give row number where you want to put cross\n>> " )) c = int( input( f"{self.first}: give column number where you want to put cross\n>> " )) board.update_board(r - 1, c - 1, 1) board.print_board() won = validator.check_if_won(board.board, 1) if (won is True): who = 1 break else: print("Sorry No one won !") return if board.isfull() is not True: r = int( input( f"{self.second}: give row number where you want to put circle\n>> " )) c = int( input( f"{self.second}: give column number where you want to put circle\n>> " )) board.update_board(r - 1, c - 1, 0) board.print_board() won = validator.check_if_won(board.board, 0) if (won is True): who = 2 break else: print("Sorry No one won !") return if (who == 1): print(f"Congrats {self.first} You won the game!") else: print("Congrats {self.second} You won the game!")
def upload_workflow_input_files(self, wdl_file, json_file): """ Given workflow inputs, parse them to determine which inputs are files or files containing file paths, and upload those files to the bucket specified by the SingleBucket instance. :param wdl_file: File containing workflow description. Used to determine which workflow inputs are files. :param json_file: JSON inputs to wdl. Contains actual paths to files. :return: A list of files that were uploaded. """ v = Validator(wdl_file, json_file) # get all the wdl arguments and figure out which ones are file inputs, store them in an array. wdl_args = v.get_wdl_args() file_keys = {k: v for k, v in wdl_args.iteritems() if 'File' in v}.keys() json_dict = v.get_json() files_to_upload = list() for file_key in file_keys: # need to make sure that keys in wdl args but not json dict aren't processed as file keys. # also, need to skip gs urls since they are already uploaded. if file_key in json_dict.keys( ) and "gs://" not in json_dict[file_key]: if 'fofn' in file_key: # get files listed in the fofn and add them to list of files to upload files_to_upload.extend( get_files_from_fofn(json_dict[file_key])) """ Next don't want to upload the original fofn because it won't have the 'gs://' prefix for the files in. Therefore need to create a new fofn that has updated paths, and we add that to files_to_upload. """ new_fofn = update_fofn(json_dict[file_key], self.bucket.name) files_to_upload.append(new_fofn) else: if isinstance(json_dict[file_key], list): for f in json_dict[file_key]: if "gs://" not in f: files_to_upload.append(f) elif isinstance(json_dict[file_key], dict): file_dict = json_dict[file_key] for k, v in file_dict.iteritems( ): #assume all Map with File are Map[?,File] if "gs://" not in v: files_to_upload.append(v) else: files_to_upload.append(json_dict[file_key]) self.upload_files(files_to_upload) return files_to_upload
def test_email(): addresses = ( # valid "*****@*****.**", "cust/[email protected]", # /, = are valid characters "!def!xyz%[email protected]", # !, % "*****@*****.**", # + is allowed "!#$%&*+-/=?^_`{}|[email protected]", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", '"Abc@def"@example.com', # @ in " " '"bert\ ernie"@w00t.com', # blank allowed, if in " " and '"\ \\""@dot.org', '"()<[:@\\"-/=?^_`{}|~.a"@ab.org', '""@example.org', "a@[10.10.10.10]", # theoretically valid, but not recognized 'abc."defghi"*****@*****.**', # dot-separated quoted string, not commonly used "b@[IPv6:2001:db8:1ff::a0b:dbd0]", # IP address literal as IPv6 "postbox@com", # top-level domains are valid hostnames # not valid "A@b@[email protected]", 'a"b(c)d,e:f;g<h>i[[email protected]', 'abc"defghi"*****@*****.**', " not\ [email protected]", "*****@*****.**", "*****@*****.**", "test [email protected]", "*****@*****.**", # two consectutive dots '"bert ernie"@w00t.com', "Abc\@[email protected]", # escaping @ only in " " allowed "lulz", "foo@bar", # bar is no top-level domain "foo@bar com", "foo@hello bar.com", "foo@[hello bar].com", "abcdefghijklmno@pqrstuvwxyz", ) validator = Validator() for email in addresses: if validator.validate_email(email, False): validated = "valid" else: validated = "not valid" print ("{0:32} {1:10}".format(email, validated))
def __init__(self): wx.Frame.__init__(self, None, -1, self.title, wx.Point(30,30)) self.addressBook = AddressBook() self.saveName = "" self.create_menu() self.create_main_panel() self.validation = Validator()
class DataStream(): def __init__(self): self.buffer_stream = Queue(maxsize=0) self.error_stream = Queue(maxsize=0) self.result_stream = Queue(maxsize=0) self.val = Validator() def stream(self): while self.buffer_stream.empty() == False: #Retrieve the top value from the queue data = self.buffer_stream.get() #Validate the buffer self.val.validate(self.buffer_stream, data) #If there is an error on the buffer, move it to the error stream if data.status==4: self.error_stream.put(data) #Else, put it to the result stream else: self.result_stream.put(data)
def __init__(self, gui, mode, name='', phone='', address='', address2='', city='', state='', zipcode='', index=0): wx.Frame.__init__(self, None, -1, "Contact Information", pos=wx.Point(50,120)) self.states = ["","AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"] self.gui = gui self.mode = mode self.index = index self.create_main_panel() self.nameBox.SetValue(name) self.phoneBox.SetValue(phone) self.addressBox.SetValue(address) self.address2Box.SetValue(address2) self.cityBox.SetValue(city) self.stateBox.SetValue(self.states[self.states.index(state)]) self.zipBox.SetValue(zipcode) self.validation = Validator()
def returnBuffered(self): self.deepCounter = 0 while self.deepCounter < 10: self.bufferedData = [self.time[0],self.latitude[0],self.longitude[0],self.altitude[0],self.speed[0],self.acceleration[0],self.roll[0],self.pitch[0],self.heading[0],self.date[0],self.fullTime[0]] if Validator.validate(self.bufferedData): self.popFirstIndex() self.bufferFlag = True return self.bufferedData time.sleep(0.1) self.deepCounter += 1 self.bufferFlag = False self.popFirstIndex() print 'Skipping line' return 0
def testDNETSV(self): v = Validator() """tests if v rejects files that don't exist""" filein = 'blah.tsv' self.assertFalse(v.isValidUSPS(filein))
def testNonTSV(self): v = Validator() filein = 'testTSV/test.csv' self.assertFalse(v.isValidUSPS(filein))
class GUI(wx.Frame): title = "Jello Puddin' Pals" def __init__(self): wx.Frame.__init__(self, None, -1, self.title, wx.Point(30,30)) self.addressBook = AddressBook() self.saveName = "" self.create_menu() self.create_main_panel() self.validation = Validator() def create_menu(self): ##### Menu Bar self.Bind(wx.EVT_CLOSE, self.on_exit, self) self.menubar = wx.MenuBar() menu_file = wx.Menu() m_open = menu_file.Append(-1, "&New", "New Address Book") self.Bind(wx.EVT_MENU, self.on_new, m_open) m_open = menu_file.Append(-1, "&Open", "Open Address Book") self.Bind(wx.EVT_MENU, self.on_open, m_open) m_save = menu_file.Append(-1, "&Save", "Save Address Book") self.Bind(wx.EVT_MENU, self.on_save, m_save) m_save_as = menu_file.Append(-1, "&Save as...", "Save Address Book as...") self.Bind(wx.EVT_MENU, self.on_save_as, m_save_as) m_import = menu_file.Append(-1, "&Import", "Import Address Book") self.Bind(wx.EVT_MENU, self.on_import, m_import) m_export = menu_file.Append(-1, "&Export", "Export Address Book") self.Bind(wx.EVT_MENU, self.on_export, m_export) m_exit = menu_file.Append(-1, "&Exit", "Exit Program") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) menu_contact = wx.Menu() m_add = menu_contact.Append(-1, "&Add New Contact", "Add New Contact to Address Book") self.Bind(wx.EVT_MENU, self.on_add, m_add) m_edit = menu_contact.Append(-1, "&Edit Selected", "Edit Selected Contact") self.Bind(wx.EVT_MENU, self.on_edit, m_edit) m_remove = menu_contact.Append(-1, "&Remove Selected", "Remove Selected Contact from Address Book") self.Bind(wx.EVT_MENU, self.on_remove, m_remove) m_print = menu_contact.Append(-1, "Get Mailing Label", "Get Mailing Label for Selected Contact") self.Bind(wx.EVT_MENU, self.on_print, m_print) menu_help = wx.Menu() m_about = menu_help.Append(-1, "&About", "About this application") self.Bind(wx.EVT_MENU, self.on_about, m_about) self.menubar.Append(menu_file, "&File") self.menubar.Append(menu_contact, "&Contact") self.menubar.Append(menu_help, "&Help") self.SetMenuBar(self.menubar) self.statusbar = self.CreateStatusBar() def create_main_panel(self): self.panel = wx.Panel(self) ##### List of Contacts self.list = wx.ListCtrl(self.panel, -1, size=wx.Size(775,500), style=wx.LC_REPORT | wx.LC_SINGLE_SEL) self.list.InsertColumn(0, 'Name', width=150) self.list.InsertColumn(1, 'Phone', width=125) self.list.InsertColumn(2, 'Address', width=150) self.list.InsertColumn(3, 'Address, cont.', width=100) self.list.InsertColumn(4, 'City', width=125) self.list.InsertColumn(5, 'State', width=50) self.list.InsertColumn(6, 'Zip', width=75) self.display() ##### User Controls self.addButton = wx.Button(self.panel, -1, "+ Add", size=wx.Size(80,20)) self.Bind(wx.EVT_BUTTON, self.on_add, self.addButton) self.removeButton = wx.Button(self.panel, -1, "- Remove", size=wx.Size(80,20)) self.Bind(wx.EVT_BUTTON, self.on_remove, self.removeButton) self.editButton = wx.Button(self.panel, -1, "Edit", size=wx.Size(80,20)) self.Bind(wx.EVT_BUTTON, self.on_edit, self.editButton) self.printButton = wx.Button(self.panel, -1, "Mail Label", size=wx.Size(80,20)) self.Bind(wx.EVT_BUTTON, self.on_print, self.printButton) self.sortName = wx.Button(self.panel, -1, u"Sort by Name \u25B2", size=wx.Size(120,20)) self.Bind(wx.EVT_BUTTON, self.on_sort_name, self.sortName) self.sortZip = wx.Button(self.panel, -1, u"Sort by Zip", size=wx.Size(120,20)) self.Bind(wx.EVT_BUTTON, self.on_sort_zip, self.sortZip) ##### Layout self.vbox = wx.BoxSizer(wx.VERTICAL) self.hbox = wx.BoxSizer(wx.HORIZONTAL) flags = wx.ALIGN_LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL self.hbox.Add(self.addButton, 0, border=5, flag=flags) self.hbox.Add(self.editButton, 0, border=5, flag=flags) self.hbox.Add(self.removeButton, 0, border=5, flag=flags) self.hbox.Add(self.printButton, 0, border=5, flag=flags) self.hbox.AddStretchSpacer() self.hbox.Add(self.sortName, 0, border=5, flag=wx.ALIGN_RIGHT | wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox.Add(self.sortZip, 0, border=5, flag=wx.ALIGN_RIGHT | wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox.Add(self.hbox, 0, flag = wx.ALIGN_LEFT | wx.TOP | wx.EXPAND) self.vbox.Add(self.list, 1, border=5, flag = wx.ALL | wx.GROW) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) ##### Functionality def display(self): self.list.DeleteAllItems() for contact in self.addressBook.contacts: self.show_contact(contact) if self.saveName != "": file = self.saveName.split('/') self.SetTitle("Jello Puddin' Pals - {}".format(file[len(file)-1])) def show_contact(self, contact): index = self.list.InsertStringItem(sys.maxint, contact.getAttr('name')) self.list.SetStringItem(index, 1, contact.getAttr('phone')) self.list.SetStringItem(index, 2, contact.getAttr('address')) self.list.SetStringItem(index, 3, contact.getAttr('address2')) self.list.SetStringItem(index, 4, contact.getAttr('city')) self.list.SetStringItem(index, 5, contact.getAttr('state')) self.list.SetStringItem(index, 6, contact.getAttr('zipcode')) def on_add(self, event): cb = ContactBox(self, "add") cb.Show() def on_edit(self, event): if len(self.addressBook.contacts)>0: i = self.list.GetFirstSelected() name = self.addressBook.contacts[i].getAttr('name') phone = self.addressBook.contacts[i].getAttr('phone') address = self.addressBook.contacts[i].getAttr('address') address2 = self.addressBook.contacts[i].getAttr('address2') city = self.addressBook.contacts[i].getAttr('city') state = self.addressBook.contacts[i].getAttr('state') zipcode = self.addressBook.contacts[i].getAttr('zipcode') cb = ContactBox(self, "edit", name, phone, address, address2, city, state, zipcode, index=i) cb.Show() else: self.flash_status_message("Address book is empty") def on_remove(self, event): if len(self.addressBook.contacts)>0: i = self.list.GetFirstSelected() name = self.addressBook.contacts[i].getAttr('name') dlg = wx.MessageDialog(self, "Are you sure you want to remove {}?".format(name), "Confirm Delete", wx.OK|wx.CANCEL|wx.ICON_QUESTION) result = dlg.ShowModal() dlg.Destroy() if result == wx.ID_OK: del self.addressBook.contacts[i] self.addressBook.sort(self.addressBook.sortMethod[0],self.addressBook.sortMethod[1]) self.display() self.addressBook.changed = True self.flash_status_message("Removed {}".format(name)) else: self.flash_status_message("Address book is empty") def on_sort_name(self, event): if self.addressBook.sortMethod == ('name', False): self.addressBook.sortMethod = ('name',True) self.addressBook.sort('name',True) self.sortName.SetLabel(u"Sort by Name \u25BC") self.sortZip.SetLabel(u"Sort by Zip") self.flash_status_message("Sorted address book by last name, Z-A") else: self.addressBook.sortMethod = ('name',False) self.addressBook.sort('name',False) self.sortName.SetLabel(u"Sort by Name \u25B2") self.sortZip.SetLabel(u"Sort by Zip") self.flash_status_message("Sorted address book by last name, A-Z") self.display() def on_sort_zip(self, event): if self.addressBook.sortMethod == ('zipcode', False): self.addressBook.sortMethod = ('zipcode',True) self.addressBook.sort('zipcode',True) self.sortZip.SetLabel(u"Sort by Zip \u25BC") self.sortName.SetLabel(u"Sort by Name") self.flash_status_message("Sorted address book by zip code, 9-0") else: self.addressBook.sortMethod = ('zipcode',False) self.addressBook.sort('zipcode',False) self.sortZip.SetLabel(u"Sort by Zip \u25B2") self.sortName.SetLabel(u"Sort by Name") self.flash_status_message("Sorted address book by zip code, 0-9") self.display() ##### Menu functions def on_new(self, event): if self.addressBook.changed: if wx.MessageBox("This address book contains unsaved changes! Continue anyway?", "Are you sure?", wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO: return newGui = GUI() newGui.display() newGui.Show() self.Destroy() def on_open(self, event): if self.addressBook.changed: if wx.MessageBox("This address book contains unsaved changes! Continue anyway?", "Are you sure?", wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO: return openFileDialog = wx.FileDialog(self, "Open .tsv file", "", "", ".tsv files (*.tsv)|*.tsv", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return inFilePath = openFileDialog.GetPath() if self.validation.isValidUSPS(inFilePath): newGui = GUI() newGui.addressBook.loadTSV(inFilePath) newGui.saveName = inFilePath newGui.addressBook.sort('name',False) newGui.display() newGui.Show() newGui.flash_status_message("Opened address book {}".format(newGui.saveName)) self.Destroy() else: dlg = wx.MessageDialog(self, "Unable to open {}".format(inFilePath.split('/')[len(inFilePath.split('/'))-1]), "Invalid File", wx.OK) dlg.ShowModal() dlg.Destroy() def on_save_as(self, mode): defaultName = "" if mode != 1: default = self.saveName.split('/') if len(default) > 0: defaultName = default[len(default)-1] saveFileDialog = wx.FileDialog(self, "Save .tsv file", "", defaultName, ".tsv files (*.tsv)|*.tsv", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if saveFileDialog.ShowModal() == wx.ID_CANCEL: return self.saveName = saveFileDialog.GetPath() self.addressBook.writeTSV(self.saveName) if (mode != 2): self.display() self.addressBook.changed = False self.flash_status_message("Saved address book as {}".format(self.saveName)) def on_import(self, event): openFileDialog = wx.FileDialog(self, "Import .tsv file", "", "", ".tsv files (*.tsv)|*.tsv", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return inFilePath = openFileDialog.GetPath() if self.validation.isValidUSPS(inFilePath): temp = AddressBook() temp.loadTSV(inFilePath) for contact in temp.contacts: self.addressBook.contacts.append(contact) self.addressBook.sort(self.addressBook.sortMethod[0],self.addressBook.sortMethod[1]) self.display() self.flash_status_message("Imported address book {}".format(inFilePath)) self.addressBook.changed = True else: dlg = wx.MessageDialog(self, "Unable to import {}".format(inFilePath.split('/')[len(inFilePath.split('/'))-1]), "Invalid File", wx.OK) dlg.ShowModal() dlg.Destroy() def on_export(self, event): self.on_save_as(mode=2) def on_save(self, event): if self.saveName == "": self.on_save_as(mode=0) else: self.addressBook.writeTSV(self.saveName) self.addressBook.changed = False self.flash_status_message("Saved address book {}".format(self.saveName)) def on_print(self, event): if len(self.addressBook.contacts)>0: i = self.list.GetFirstSelected() mail = self.addressBook.contacts[i].getLabel() dlg = MessageBox(self, mail) dlg.ShowModal() dlg.Destroy() else: self.flash_status_message("Address book is empty") def on_exit(self, event): if self.addressBook.changed: if wx.MessageBox("This address book contains unsaved changes! Exit anyway?", "Are you sure?", wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO: return self.Destroy() def on_about(self, event): msg = "Bill Cosby's Eligible Bachelors of Science" dlg = wx.MessageDialog(self, msg, "About", wx.OK) dlg.ShowModal() dlg.Destroy() def flash_status_message(self, msg, flash_len_ms=3000): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('')
class UnitTest(unittest.TestCase): def test_file_input(self): self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.myModel.toDataSet() self.failIfEqual(self.myModel.get_data_set(), None) def test_csv_file_input(self): self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.expected = 12 self.myModel.toDataSet() self.failUnlessEqual(self.myModel.get_data_set().__len__(), self.expected) def test_washing_data(self): # There are 5 errors so length should be cut down to 7 after washing self.myFiler = Filer() self.myValidator = Validator() self.myModel = Model(self.myFiler,self.myValidator) self.myFiler.read("TestData.csv") self.expected = 8 self.myModel.toDataSet() self.failUnlessEqual(self.myModel.wash_data().__len__(), self.expected) def test_validator_id(self): self.myValidator = Validator() self.result = self.myValidator.match_id("D003") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_id("DDD03") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_validator_gender(self): self.myValidator = Validator() self.result = self.myValidator.match_gender("M") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_gender("G") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_validator_age(self): self.myValidator = Validator() self.result = self.myValidator.match_age("13") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_age("F") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_validator_bmi(self): self.myValidator = Validator() self.result = self.myValidator.match_bmi("235") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_bmi("F") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_validator_weight(self): self.myValidator = Validator() self.result = self.myValidator.match_weight("Normal") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_weight("F") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_validator_sales(self): self.myValidator = Validator() self.result = self.myValidator.match_sales("235") self.expected = None self.failIfEqual(self.result, self.expected) self.result = self.myValidator.match_sales("FED") self.expected = None self.failUnlessEqual(self.result, self.expected) def test_filer_read(self): self.myFiler = Filer() self.myFiler.read("TestData.csv") self.result = self.myFiler.getData() self.notExpected = None self.failIfEqual(self.result, self.notExpected)
def testGoodTSV(self): v = Validator() filein = 'testTSV/twoWord.tsv' self.assertTrue(v.isValidUSPS(filein))
def test_validator(): translation = Translation ("En","apple","Fr","hahaha") validator = Validator() assert len(validator.validateTranslation (translation)) == 0 translation = Translation ("a","apple","Fr","hahaha") assert len(validator.validateTranslation(translation)) == 1
logging.basicConfig(stream=sys.stdout, level=Config.LOG_LEVEL, format='%(asctime)s - %(levelname)s - %(message)s') ''' Test Area ''' #inputReader = InputReader() #inputReader.readData() #Data.Q = [[0 for i in range(2)] for i in range(3)] #print (Constants.timeVsTechnologyHeader) ''' ==================================== ''' print "Program execution started..." ''' Validate the configuration for the program''' validator = Validator() if validator.validateConfig() == False: exit(1) ''' Read input directory and create data file ''' inputReader = InputReader() inputReader.readPortfolioFile() for portfolio in Data.portfolios: logging.debug("Started Processing Portfolio"+ portfolio.name) Config.inputFileDirectory = portfolio.inputDirectory inputReader.readData() ''' Calculate W for the portfolio ''' calculator = Calculator() totalWForPortfolio = calculator.calculateWForPortfolio(0)
def __init__(self): self.Validator = Validator() self.uspsFields = ['Last','Delivery','Second','Recipient','Phone']
class ContactBox(wx.Frame): def __init__(self, gui, mode, name='', phone='', address='', address2='', city='', state='', zipcode='', index=0): wx.Frame.__init__(self, None, -1, "Contact Information", pos=wx.Point(50,120)) self.states = ["","AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","PR","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"] self.gui = gui self.mode = mode self.index = index self.create_main_panel() self.nameBox.SetValue(name) self.phoneBox.SetValue(phone) self.addressBox.SetValue(address) self.address2Box.SetValue(address2) self.cityBox.SetValue(city) self.stateBox.SetValue(self.states[self.states.index(state)]) self.zipBox.SetValue(zipcode) self.validation = Validator() def create_main_panel(self): self.panel = wx.Panel(self) ##### User Controls self.nameLabel = wx.StaticText(self.panel, -1, "Name: ") self.nameBox = wx.TextCtrl(self.panel, size=(200,-1)) self.phoneLabel = wx.StaticText(self.panel, -1, "Phone: ") self.phoneBox = wx.TextCtrl(self.panel, size=(200,-1)) self.addressLabel = wx.StaticText(self.panel, -1, "Address: ") self.addressBox = wx.TextCtrl(self.panel, size=(200,-1)) self.address2Label = wx.StaticText(self.panel, -1, "Address, cont.: ") self.address2Box = wx.TextCtrl(self.panel, size=(200,-1)) self.cityLabel = wx.StaticText(self.panel, -1, "City: ") self.cityBox = wx.TextCtrl(self.panel, size=(200,-1)) self.stateLabel = wx.StaticText(self.panel, -1, "State: ") self.stateBox = wx.ComboBox(self.panel, value=self.states[0], choices=self.states, style=wx.CB_READONLY) self.zipLabel = wx.StaticText(self.panel, -1, "Zip: ") self.zipBox = wx.TextCtrl(self.panel, size=(100,-1)) self.addButton = wx.Button(self.panel, -1, "Save") self.Bind(wx.EVT_BUTTON, self.on_add, self.addButton) self.cancelButton = wx.Button(self.panel, -1, "Cancel") self.Bind(wx.EVT_BUTTON, self.on_cancel, self.cancelButton) ##### Box Sizers self.window = wx.BoxSizer(wx.VERTICAL) self.info = wx.BoxSizer(wx.HORIZONTAL) self.labels = wx.BoxSizer(wx.VERTICAL) self.labels.Add(self.nameLabel, 1, border=8, flag=wx.ALL) self.labels.Add(self.phoneLabel, 1, border=7, flag=wx.ALL) self.labels.Add(self.addressLabel, 1, border=7, flag=wx.ALL) self.labels.Add(self.address2Label, 1, border=7, flag=wx.ALL) self.labels.Add(self.cityLabel, 1, border=7, flag=wx.ALL) self.labels.Add(self.stateLabel, 1, border=7, flag=wx.ALL) self.labels.Add(self.zipLabel, 1, border=7, flag=wx.ALL) self.boxes = wx.BoxSizer(wx.VERTICAL) self.boxes.Add(self.nameBox, 1, border=5, flag=wx.ALL) self.boxes.Add(self.phoneBox, 1, border=3, flag=wx.ALL) self.boxes.Add(self.addressBox, 1, border=3, flag=wx.ALL) self.boxes.Add(self.address2Box, 1, border=3, flag=wx.ALL) self.boxes.Add(self.cityBox, 1, border=3, flag=wx.ALL) self.boxes.Add(self.stateBox, 1, border=3, flag=wx.ALL) self.boxes.Add(self.zipBox, 1, border=3, flag=wx.ALL) self.errors = wx.BoxSizer(wx.VERTICAL) self.nameError = wx.StaticText(self.panel, -1, "") self.phoneError = wx.StaticText(self.panel, -1, "") self.addressError = wx.StaticText(self.panel, -1, "") self.address2Error = wx.StaticText(self.panel, -1, "") self.cityError = wx.StaticText(self.panel, -1, "") self.stateError = wx.StaticText(self.panel, -1, "") self.zipError = wx.StaticText(self.panel, -1, "") self.errors.Add(self.nameError, 1, border=8, flag=wx.ALL) self.errors.Add(self.phoneError, 1, border=7, flag=wx.ALL) self.errors.Add(self.addressError, 1, border=7, flag=wx.ALL) self.errors.Add(self.address2Error, 1, border=7, flag=wx.ALL) self.errors.Add(self.cityError, 1, border=7, flag=wx.ALL) self.errors.Add(self.stateError, 1, border=7, flag=wx.ALL) self.errors.Add(self.zipError, 1, border=7, flag=wx.ALL) flags = wx.ALIGN_LEFT | wx.ALL self.info.Add(self.labels, 1, flag=flags) self.info.Add(self.boxes, 1, flag=flags) self.info.Add(self.errors, 1, flag=flags) self.buttons = wx.BoxSizer(wx.HORIZONTAL) self.buttons.Add(self.addButton, 1, border=3, flag=wx.ALL) self.buttons.Add(self.cancelButton, 1, border=3, flag=wx.ALL) self.window.Add(self.info, 1, border=3, flag=wx.ALL) self.window.Add(self.buttons, 1, border=3, flag=wx.ALL) self.panel.SetSizer(self.window) self.window.Fit(self) self.SetSize(wx.Size(700,300)) self.SetMinSize(wx.Size(700,300)) self.SetMaxSize(wx.Size(700,300)) def on_add(self, event): self.name = str(self.nameBox.GetValue()) self.phone = str(self.phoneBox.GetValue()) self.address = str(self.addressBox.GetValue()) self.address2 = str(self.address2Box.GetValue()) self.city = str(self.cityBox.GetValue()) self.state = str(self.stateBox.GetValue()) self.zipcode = str(self.zipBox.GetValue()) if self.validation.isValidName(self.name) and \ self.validation.isValidPhone(self.phone) and \ self.validation.isValidAddress(self.address) and \ self.validation.isValidCity(self.city) and \ self.validation.isValidState(self.state) and \ self.validation.isValidZip(self.zipcode): if self.mode == "add": self.gui.addressBook.addContact(**{"name": self.name, "phone": self.phone, "address": self.address, "address2": self.address2, "city": self.city, "state": self.state, "zipcode": self.zipcode}) self.gui.addressBook.sort(self.gui.addressBook.sortMethod[0],self.gui.addressBook.sortMethod[1]) self.gui.display() self.gui.flash_status_message("Added {}".format(str(self.name))) self.gui.addressBook.changed = True self.Destroy() if self.mode == "edit": del self.gui.addressBook.contacts[self.index] self.gui.addressBook.addContact(**{"name": self.name, "phone": self.phone, "address": self.address, "address2": self.address2, "city": self.city, "state": self.state, "zipcode": self.zipcode}) self.gui.addressBook.sort(self.gui.addressBook.sortMethod[0],self.gui.addressBook.sortMethod[1]) self.gui.display() self.gui.flash_status_message("Edited {}".format(str(self.name))) self.gui.addressBook.changed = True self.Destroy() else: self.nameError.SetLabel("") self.phoneError.SetLabel("") self.addressError.SetLabel("") self.address2Error.SetLabel("") self.cityError.SetLabel("") self.stateError.SetLabel("") self.zipError.SetLabel("") if not self.validation.isValidName(self.name): self.nameError.SetLabel("Cannot be blank") if not self.validation.isValidPhone(self.phone): self.phoneError.SetLabel("Invalid phone number") if not self.validation.isValidAddress(self.address): self.addressError.SetLabel("Invalid Address") if not self.validation.isValidAddress(self.address2): self.address2Error.SetLabel("Invalid Address") if not self.validation.isValidCity(self.city): self.cityError.SetLabel("Invalid City") if not self.validation.isValidState(self.state): self.stateError.SetLabel("Invalid State") if not self.validation.isValidZip(self.zipcode): self.zipError.SetLabel("Must be ##### or #####-####") def on_cancel(self, event): self.Destroy()
class FileHandler(object): def __init__(self): self.Validator = Validator() self.uspsFields = ['Last','Delivery','Second','Recipient','Phone'] def ValidAttr(self, attrName, attr): """ Returns Empty String if Invalid, else returns sanitized attr""" if self.Validator.validateAttr(attrName, attr) : return self.Validator.sanitize(attr) return '' def splitLast(self,last): city ='' state = '' zipcode = '' row = last.split(' ') if len(row)==1: if self.Validator.isValidState(row[0]): state = row[0] elif row[0].isdigit(): zipcode = row[0] else: city = row[0] else: stateIndex = None for index, el in enumerate(row): if self.Validator.isValidState(el): stateIndex = index if stateIndex: state = row[stateIndex] if stateIndex+1 == len(row): city = ' '.join(row[0:stateIndex]) elif stateIndex == 0: zipcode = row[stateIndex+1] else: city = ' '.join(row[0:stateIndex]) state = row[stateIndex] zipcode = row[stateIndex+1] else: if row[len(row)-1].isdigit(): zipcode = row[len(row)-1] city = ' '.join(row[0:len(row)-1]) else: city = ' '.join(row) return [city,state,zipcode] def readUSPS(self,filepath): tsv = open(filepath,'r') reader = csv.DictReader(tsv, delimiter='\t',restval='') attributes =[] for row in reader: attr ={} last = self.splitLast(row['Last']) attr['name'] = row['Recipient'] attr['phone'] = self.ValidAttr('phone',row['Phone']) attr['address'] = row['Delivery'] attr['address2'] = row['Second'] attr['city'] = self.ValidAttr('city',last[0]) attr['state'] = self.ValidAttr('state',last[1]) attr['zipcode'] = self.ValidAttr('zipcode',last[2]) if attr['name']: attributes.append(attr) return attributes def writeUSPS(self,contacts, filepath): tsv = open(filepath,'w') writer = csv.DictWriter(tsv, delimiter='\t', fieldnames=self.uspsFields) writer.writeheader() for contact in contacts: attributes ={} attributes['Recipient'] = contact.getAttr('name') last = [contact.getAttr('city'),contact.getAttr('state'),contact.getAttr('zipcode')] attributes['Second'] = contact.getAttr('address2') attributes['Last'] = ' '.join(last) attributes['Delivery'] = contact.getAttr('address') attributes['Phone'] = contact.getAttr('phone') writer.writerow(attributes)
class Controller(object): def __init__(self, players, updater=None): self.players = players self.nplayers = len(players) self.state = GameState(self.nplayers) self.validator = Validator(self.state) self.logger = logging.getLogger(__name__) if updater is not None: self.update = ViewUpdater() else: self.update = updater self.delay = 0.5 self.stalematecond = 2000 def play(self): self.setup() while not self.gameEnded(): currTime = int(round(time.time() * 1000)) self.roll() #resource/bandit self.takeTurn() #actions self.nextPlayerTurn() while int(round(time.time() * 1000)) < currTime + 1000: pass self.end() def end(self): #tell everyone the game is over self.updateView() for player in self.players: player.getMove(self.state) def setup(self): # Send initial state for display self.update.sendTiles(self.state) #Decide first player randomly self.state.turn = random.randrange(0,self.nplayers) builtcount = 0 turnorder = [] for i in range(0, self.nplayers): turnorder.append((self.state.turn + i) % self.nplayers) turnorderbckwd = copy.deepcopy(turnorder) turnorderbckwd.reverse() turnorder += turnorderbckwd print "Turnorder: %s" %(str(turnorder)) for i in range(0, self.nplayers*2): self.state.turn = turnorder[i] self.state.phase = "buildsettle" self.updateView() bs_move = self.getValidMove(self.state.turn) self.doMove(bs_move) self.state.phase = "buildroad" self.updateView() move = self.getValidMove(self.state.turn) self.doMove(move) #if this is second settle built do resource init if builtcount >= self.nplayers: for rec in self.state.getSurroundingResources(bs_move.location): if rec != 'desert': self.state.addResource(self.state.turn, rec, 1) #initial resource allocation self.state.phase = 'standard' def nextPlayerTurn(self): self.state.turn = (self.state.turn + 1) % self.nplayers def takeTurn(self): #loop action (trade, build, play, buy) until turn ended while not self.turnEnded(): self.updateView() move = self.getValidMove(self.state.turn) self.doMove(move) self.state.updateAllScores() self.state.phase = 'standard' self.state.numturns += 1 def updateView(self): self.update.sendGameState(self.state) def gameEnded(self): if self.state.maxPlayerScore() >= 10: self.state.phase = 'ended' self.state.phaseinfo = 'won' return True elif self.state.numturns >= self.stalematecond: self.state.phase = 'ended' self.state.phaseinfo = 'stalemate' return True else: return False def turnEnded(self): return self.state.phase == 'endturn' def roll(self): self.state.lastroll = random.randint(1,6) + random.randint(1,6) #self.updateView() if self.state.lastroll == 7: turn = self.state.turn #resource discard for i in range(0, self.nplayers): self.state.turn = i nresources = self.state.countResources(i) if nresources > 7: reqresources = (nresources+1)/2 self.state.phase = "discard" while nresources > reqresources: # number you need to discard self.state.phaseinfo = nresources - reqresources # should we change whose turn it is in state? move = self.getValidMove(i) self.doMove(move) nresources = self.state.countResources(i) self.state.turn = turn #robber movement self.moveRobber() else: #resource collection for (r,p,b) in self.state.getBuildings(self.state.lastroll): mult = 1 if b == 'settlement' else 2 self.state.addResource(p, r, mult) #self.updateView() self.state.phase = 'standard' def moveRobber(self): self.state.phase = 'moverobber' move = self.getValidMove(self.state.turn) self.doMove(move) #list of playerid's next to robber adjplayers = self.state.getAdjacentPlayers(self.state.getRobberTile()) if self.state.turn in adjplayers: adjplayers.remove(self.state.turn) #remove players who have no cards from adjacent list for i in xrange(len(adjplayers) - 1, -1, -1): if self.state.countResources(adjplayers[i]) == 0: del adjplayers[i] # Davis says to make code concise, use empty list as test for this # if statement otherwise he will hit irakli. I like irakli, so this list # is now the test for this if statement. if adjplayers: self.state.phaseinfo = adjplayers self.state.phase = 'chooseplayer' move = self.getValidMove(self.state.turn) self.doMove(move) def getValidMove(self, player): self.updateView() move = self.players[player].getMove(self.state) # loop until valid move receied while not self.isValid(move): self.logger.error("INVALID MOVE RECEIVED: Player %d, Move: %s, Phase %s" % (player,str(move), self.state.phase)) move = self.players[player].getMove(self.state) return move def isValid(self, move): return self.validator.validateMove(move) def doMove(self, move): if move.typ == 'build': if move.structure == 'road': # 1 brick, 1 wood self.state.addRoad(move.playerid, move.location[0], move.location[1]) if self.state.phase != 'buildroad': self.state.removeResource(move.playerid, 'brick', 1) self.state.removeResource(move.playerid, 'wood', 1) else: if move.structure == 'settlement': # 1 brick, 1 wood, 1 wheat, 1 sheep settlement if self.state.phase != 'buildsettle': self.state.removeResource(move.playerid, 'wood', 1) self.state.removeResource(move.playerid, 'wheat', 1) self.state.removeResource(move.playerid, 'brick', 1) self.state.removeResource(move.playerid, 'sheep', 1) elif move.structure == 'city': # 2 wheat, 3 ore city self.state.removeResource(move.playerid, 'wheat', 2) self.state.removeResource(move.playerid, 'ore', 3) else: self.logger.error("Unrecognized build type %s" % move.structure) self.state.addBuilding(move.playerid, move.structure, move.location) # check to see if building changed longest road count l = self.state.getLongestRoads() currentlongest = 0 if self.state.longestroad is not None: currentlongest = l[self.state.longestroad] newlongestid = self.state.longestroad for i in xrange(0, self.nplayers): if l[i] > currentlongest: newlongestid = i currentlongest = l[i] #need to check if road breaking resulted in a tie if newlongestid != self.state.longestroad: if currentlongest<5: self.state.longestroad = None elif l.count(currentlongest) != 1: self.state.longestroad = None else: self.state.longestroad = newlongestid # update remaining building count self.state.updateRemaining(move.playerid) #self.updateView() elif move.typ == 'trade': self.logger.error("TRADE MOVE NOT SUPPORTED") elif move.typ == 'navaltrade': self.state.removeResource(move.playerid,move.offer,4) self.state.addResource(move.playerid,move.want,1) elif move.typ == 'robber': #set robber tile self.state.setRobberTile(move.location) elif move.typ == 'takecard': # Remove card from target, add to initiator rectoremove = self.state.getRandomResource(move.target) self.state.removeResource(move.target, rectoremove, 1) self.state.addResource(move.playerid, rectoremove, 1) #self.updateView() elif move.typ == 'playcard': #yell when things are important self.logger.error("PLAY CARD MOVE NOT SUPPORTED") elif move.typ == 'discard': # Need to add ability to discard more than one at a time self.state.removeResource(move.playerid, move.card, 1) elif move.typ == 'endturn': self.state.phase = 'endturn'
args.port = params["port"] httpport = params["httpport"] ip = params["ip"] args.flows = params["flow"] repsize = params["repsize"] args.type = params["type"] args.client_count = params["client_count"] args.size = params["size"] args.delay = params["delay"] ################################# # VALIDATION # ################################# #create a new Validator and validate Params validator = Validator() if args.endurance is not None: if validator.validate_endurance(args.endurance): endurance = int(args.endurance) #validate replysize if args.reply_size is not None: validator.validate_repsize(int(args.reply_size)) repsize = args.reply_size #validate and set Port if args.port is not None: validator.validate_port(int(args.port)) port = args.port
def testSanitize(self): v = Validator() bad = 'Hello\tRoger\n Rabbit' good = "Hello Roger Rabbit" self.assertEqual(good,v.sanitize(bad))
def __init__(self): self.buffer_stream = Queue(maxsize=0) self.error_stream = Queue(maxsize=0) self.result_stream = Queue(maxsize=0) self.val = Validator()